<?php
require_once '../../config/config.php';
require_once '../../config/database.php';
require_once '../../core/helpers.php';
requireRole('admin');

$id   = (int)($_GET['id'] ?? 0);
$edit = $id > 0;
$data = [];

if ($edit) {
    $data = Database::fetchOne("SELECT * FROM pengembangan_diri WHERE id=?", [$id]);
    if (!$data) { setFlash('error','Data tidak ditemukan.'); redirect(BASE_URL.'/modules/pengembangan_diri/index.php'); }
}

$jenisList = ['Diklat','Seminar','Workshop','Webinar','Bimtek','Lokakarya','Lainnya'];
$errors    = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) { $errors[] = 'Token tidak valid.'; }

    $fields = [
        'jenis_kegiatan'     => sanitize($_POST['jenis_kegiatan'] ?? ''),
        'judul_kegiatan'     => sanitize($_POST['judul_kegiatan'] ?? ''),
        'penyelenggara'      => sanitize($_POST['penyelenggara'] ?? ''),
        'tempat'             => sanitize($_POST['tempat'] ?? ''),
        'tanggal_mulai'      => sanitize($_POST['tanggal_mulai'] ?? ''),
        'tanggal_selesai'    => sanitize($_POST['tanggal_selesai'] ?? ''),
        'jumlah_jp'          => (int)($_POST['jumlah_jp'] ?? 0) ?: null,
        'nomor_sertifikat'   => sanitize($_POST['nomor_sertifikat'] ?? ''),
        'tanggal_sertifikat' => sanitize($_POST['tanggal_sertifikat'] ?? '') ?: null,
        'resume_materi'      => $_POST['resume_materi'] ?? '',
    ];

    if (empty($fields['judul_kegiatan']))  $errors[] = 'Judul kegiatan wajib diisi.';
    if (empty($fields['penyelenggara']))   $errors[] = 'Penyelenggara wajib diisi.';
    if (empty($fields['tanggal_mulai']))   $errors[] = 'Tanggal mulai wajib diisi.';
    if (empty($fields['tanggal_selesai'])) $errors[] = 'Tanggal selesai wajib diisi.';

    if (empty($errors)) {
        // Upload sertifikat
        if (!empty($_FILES['sertifikat_file']['name'])) {
            $up = uploadFile($_FILES['sertifikat_file'], 'sertifikat', ALLOWED_PDF, MAX_FILE_SIZE);
            if (!$up['success']) { $errors[] = $up['error']; }
            else {
                if ($edit && !empty($data['sertifikat_file'])) deleteFile('sertifikat', $data['sertifikat_file']);
                $fields['sertifikat_file'] = $up['filename'];
            }
        }
    }

    if (empty($errors)) {
        if ($edit) {
            $set  = implode(',', array_map(fn($k) => "{$k}=?", array_keys($fields)));
            $vals = array_values($fields); $vals[] = $id;
            Database::execute("UPDATE pengembangan_diri SET {$set} WHERE id=?", $vals);
            auditLog('UPDATE','pengembangan_diri',$id,$fields['judul_kegiatan']);
            setFlash('success','Data berhasil diperbarui.');
        } else {
            $cols = implode(',', array_keys($fields));
            $pls  = implode(',', array_fill(0, count($fields), '?'));
            Database::execute("INSERT INTO pengembangan_diri ({$cols}) VALUES ({$pls})", array_values($fields));
            auditLog('INSERT','pengembangan_diri',(int)Database::lastInsertId(),$fields['judul_kegiatan']);
            setFlash('success','Data berhasil ditambahkan.');
        }
        redirect(BASE_URL.'/modules/pengembangan_diri/index.php');
    }
    $data = array_merge($data, $fields);
}

$pageTitle  = ($edit?'Edit':'Tambah').' Pengembangan Diri';
$activePage = 'pengembangan';
require_once ROOT_PATH . '/views/layouts/header.php';
?>

<div class="page-header">
  <div class="page-header-title">
    <h1><i class="bi bi-award me-2 text-primary"></i><?= $pageTitle ?></h1>
    <nav><ol class="breadcrumb">
      <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/modules/dashboard/index.php">Dashboard</a></li>
      <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/modules/pengembangan_diri/index.php">Pengembangan Diri</a></li>
      <li class="breadcrumb-item active"><?= $edit?'Edit':'Tambah' ?></li>
    </ol></nav>
  </div>
</div>

<?php if($errors): ?>
<div class="alert alert-danger border-0 mb-3"><ul class="mb-0 ps-3"><?php foreach($errors as $e): ?><li><?= e($e) ?></li><?php endforeach; ?></ul></div>
<?php endif; ?>

<form method="POST" enctype="multipart/form-data">
  <?= csrf_field() ?>
  <div class="row g-3">
    <div class="col-lg-8">
      <div class="card mb-3">
        <div class="card-header"><span class="card-header-title"><i class="bi bi-info-circle me-2"></i>Informasi Kegiatan</span></div>
        <div class="card-body">
          <div class="row g-3">
            <div class="col-md-4">
              <label class="form-label">Jenis Kegiatan</label>
              <select name="jenis_kegiatan" class="form-select">
                <?php foreach($jenisList as $j): ?>
                <option value="<?= $j ?>" <?= ($data['jenis_kegiatan']??'')===$j?'selected':'' ?>><?= $j ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-8">
              <label class="form-label">Judul Kegiatan <span class="text-danger">*</span></label>
              <input type="text" name="judul_kegiatan" class="form-control" value="<?= e($data['judul_kegiatan'] ?? '') ?>" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Penyelenggara <span class="text-danger">*</span></label>
              <input type="text" name="penyelenggara" class="form-control" value="<?= e($data['penyelenggara'] ?? '') ?>" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Tempat</label>
              <input type="text" name="tempat" class="form-control" value="<?= e($data['tempat'] ?? '') ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label">Tanggal Mulai <span class="text-danger">*</span></label>
              <input type="date" name="tanggal_mulai" class="form-control" value="<?= e($data['tanggal_mulai'] ?? '') ?>" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">Tanggal Selesai <span class="text-danger">*</span></label>
              <input type="date" name="tanggal_selesai" class="form-control" value="<?= e($data['tanggal_selesai'] ?? '') ?>" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">Jumlah JP</label>
              <div class="input-group">
                <input type="number" name="jumlah_jp" class="form-control" min="0" value="<?= e($data['jumlah_jp'] ?? '') ?>">
                <span class="input-group-text">JP</span>
              </div>
            </div>
            <div class="col-12">
              <label class="form-label">Resume Materi</label>
              <textarea name="resume_materi" class="form-control" rows="5" placeholder="Tuliskan resume/ringkasan materi yang diikuti…"><?= e($data['resume_materi'] ?? '') ?></textarea>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-lg-4">
      <!-- Sertifikat -->
      <div class="card mb-3">
        <div class="card-header"><span class="card-header-title"><i class="bi bi-patch-check me-2"></i>Sertifikat</span></div>
        <div class="card-body">
          <div class="mb-3">
            <label class="form-label">Nomor Sertifikat</label>
            <input type="text" name="nomor_sertifikat" class="form-control" value="<?= e($data['nomor_sertifikat'] ?? '') ?>">
          </div>
          <div class="mb-3">
            <label class="form-label">Tanggal Sertifikat</label>
            <input type="date" name="tanggal_sertifikat" class="form-control" value="<?= e($data['tanggal_sertifikat'] ?? '') ?>">
          </div>
          <div>
            <label class="form-label">Upload Sertifikat (PDF)</label>
            <label class="upload-zone w-100" style="cursor:pointer">
              <div class="upload-icon"><i class="bi bi-patch-check"></i></div>
              <p class="mb-1 fw-600" style="font-size:.82rem">Pilih file sertifikat</p>
              <p class="text-muted mb-0" style="font-size:.73rem">PDF • Maks 10MB</p>
              <input type="file" name="sertifikat_file" accept=".pdf" class="d-none" id="sertInput">
            </label>
            <?php if($edit && !empty($data['sertifikat_file'])): ?>
            <div class="mt-2 text-muted" style="font-size:.78rem"><i class="bi bi-paperclip me-1"></i>Sudah ada sertifikat</div>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <div class="d-flex flex-column gap-2">
        <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i><?= $edit?'Simpan':'Tambah' ?></button>
        <a href="<?= BASE_URL ?>/modules/pengembangan_diri/index.php" class="btn btn-outline-secondary">Batal</a>
      </div>
    </div>
  </div>
</form>

<?php require_once ROOT_PATH . '/views/layouts/footer.php'; ?>
