<?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 = [];
$fotoList  = [];
$fileList  = [];

if ($edit) {
    $data = Database::fetchOne("SELECT * FROM kegiatan_pendampingan WHERE id=?", [$id]);
    if (!$data) { setFlash('error','Kegiatan tidak ditemukan.'); redirect(BASE_URL.'/modules/kegiatan/index.php'); }
    $fotoList = Database::fetchAll("SELECT * FROM foto_kegiatan WHERE kegiatan_id=? ORDER BY urutan", [$id]);
    $fileList = Database::fetchAll("SELECT * FROM file_laporan WHERE kegiatan_id=? ORDER BY created_at", [$id]);
}

$sekolahList = Database::fetchAll("SELECT id, nama_sekolah FROM sekolah WHERE aktif=1 ORDER BY nama_sekolah");
$programList = Database::fetchAll("SELECT id, nama_program FROM program_kerja ORDER BY nama_program");
$errors = [];

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

    $fields = [
        'sekolah_id'       => (int)($_POST['sekolah_id'] ?? 0),
        'program_kerja_id' => (int)($_POST['program_kerja_id'] ?? 0) ?: null,
        'tanggal_kegiatan' => sanitize($_POST['tanggal_kegiatan'] ?? ''),
        'nama_kegiatan'    => sanitize($_POST['nama_kegiatan'] ?? ''),
        'materi'           => sanitize($_POST['materi'] ?? ''),
        'sasaran'          => sanitize($_POST['sasaran'] ?? ''),
        'peserta'          => (int)($_POST['peserta'] ?? 0) ?: null,
        'hasil_kegiatan'   => sanitize($_POST['hasil_kegiatan'] ?? ''),
        'narasi'           => $_POST['narasi'] ?? '',
        'tindak_lanjut'    => sanitize($_POST['tindak_lanjut'] ?? ''),
        'status'           => sanitize($_POST['status'] ?? 'Draft'),
    ];

    if (!$fields['sekolah_id'])       $errors[] = 'Sekolah wajib dipilih.';
    if (empty($fields['tanggal_kegiatan'])) $errors[] = 'Tanggal wajib diisi.';
    if (empty($fields['nama_kegiatan']))    $errors[] = 'Nama kegiatan wajib diisi.';
    if (empty($fields['materi']))           $errors[] = 'Materi wajib diisi.';
    if (empty($fields['hasil_kegiatan']))   $errors[] = 'Hasil kegiatan wajib diisi.';

    if (empty($errors)) {
        if ($edit) {
            $set  = implode(',', array_map(fn($k) => "{$k}=?", array_keys($fields)));
            $vals = array_values($fields); $vals[] = $id;
            Database::execute("UPDATE kegiatan_pendampingan SET {$set} WHERE id=?", $vals);
            $kegId = $id;
        } else {
            $cols = implode(',', array_keys($fields));
            $pls  = implode(',', array_fill(0, count($fields), '?'));
            Database::execute("INSERT INTO kegiatan_pendampingan ({$cols}) VALUES ({$pls})", array_values($fields));
            $kegId = (int)Database::lastInsertId();
        }

        // Upload foto (multiple)
        if (!empty($_FILES['foto_kegiatan']['name'][0])) {
            $urutan = 1;
            foreach ($_FILES['foto_kegiatan']['tmp_name'] as $i => $tmp) {
                $fotoFile = [
                    'name'     => $_FILES['foto_kegiatan']['name'][$i],
                    'tmp_name' => $tmp,
                    'size'     => $_FILES['foto_kegiatan']['size'][$i],
                    'error'    => $_FILES['foto_kegiatan']['error'][$i],
                ];
                if ($fotoFile['error'] !== UPLOAD_ERR_OK) continue;
                $up = uploadFile($fotoFile, 'foto_kegiatan', ALLOWED_IMAGE, MAX_IMAGE_SIZE);
                if ($up['success']) {
                    Database::execute(
                        "INSERT INTO foto_kegiatan (kegiatan_id,nama_file,keterangan,urutan) VALUES (?,?,?,?)",
                        [$kegId, $up['filename'], sanitize($_POST['ket_foto'][$i] ?? ''), $urutan++]
                    );
                }
            }
        }

        // Upload file laporan PDF
        if (!empty($_FILES['file_laporan']['name'])) {
            $up = uploadFile($_FILES['file_laporan'], 'dokumen', ALLOWED_PDF, MAX_FILE_SIZE);
            if ($up['success']) {
                Database::execute(
                    "INSERT INTO file_laporan (kegiatan_id,nama_file,nama_asli,ukuran) VALUES (?,?,?,?)",
                    [$kegId, $up['filename'], $_FILES['file_laporan']['name'], $_FILES['file_laporan']['size']]
                );
            }
        }

        auditLog($edit?'UPDATE':'INSERT', 'kegiatan_pendampingan', $kegId, $fields['nama_kegiatan']);
        setFlash('success', 'Kegiatan berhasil ' . ($edit?'diperbarui':'ditambahkan') . '.');
        redirect(BASE_URL . '/modules/kegiatan/index.php');
    }
    $data = array_merge($data, $fields);
}

$pageTitle  = ($edit?'Edit':'Tambah') . ' Kegiatan Pendampingan';
$activePage = 'kegiatan';
require_once ROOT_PATH . '/views/layouts/header.php';
?>

<div class="page-header">
  <div class="page-header-title">
    <h1><i class="bi bi-journal-plus 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/kegiatan/index.php">Kegiatan</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">
    <!-- LEFT: Data Utama -->
    <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-8">
              <label class="form-label">Sekolah <span class="text-danger">*</span></label>
              <select name="sekolah_id" class="form-select" required>
                <option value="">— Pilih Sekolah —</option>
                <?php foreach($sekolahList as $s): ?>
                <option value="<?= $s['id'] ?>" <?= ($data['sekolah_id']??0)==(int)$s['id']?'selected':'' ?>><?= e($s['nama_sekolah']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-4">
              <label class="form-label">Tanggal Kegiatan <span class="text-danger">*</span></label>
              <input type="date" name="tanggal_kegiatan" class="form-control" value="<?= e($data['tanggal_kegiatan'] ?? '') ?>" required>
            </div>
            <div class="col-12">
              <label class="form-label">Nama Kegiatan <span class="text-danger">*</span></label>
              <input type="text" name="nama_kegiatan" class="form-control" value="<?= e($data['nama_kegiatan'] ?? '') ?>" required>
            </div>
            <div class="col-md-8">
              <label class="form-label">Program Kerja</label>
              <select name="program_kerja_id" class="form-select">
                <option value="">— Tidak terkait program —</option>
                <?php foreach($programList as $p): ?>
                <option value="<?= $p['id'] ?>" <?= ($data['program_kerja_id']??0)==(int)$p['id']?'selected':'' ?>><?= e($p['nama_program']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-4">
              <label class="form-label">Jumlah Peserta</label>
              <input type="number" name="peserta" class="form-control" min="0" value="<?= e($data['peserta'] ?? '') ?>">
            </div>
            <div class="col-md-6">
              <label class="form-label">Materi Pendampingan <span class="text-danger">*</span></label>
              <textarea name="materi" class="form-control" rows="3" required><?= e($data['materi'] ?? '') ?></textarea>
            </div>
            <div class="col-md-6">
              <label class="form-label">Sasaran Kegiatan <span class="text-danger">*</span></label>
              <input type="text" name="sasaran" class="form-control" value="<?= e($data['sasaran'] ?? '') ?>" required placeholder="Guru, Kepala Sekolah, Siswa…">
            </div>
            <div class="col-12">
              <label class="form-label">Hasil Kegiatan <span class="text-danger">*</span></label>
              <textarea name="hasil_kegiatan" class="form-control" rows="3" required><?= e($data['hasil_kegiatan'] ?? '') ?></textarea>
            </div>
            <div class="col-12">
              <label class="form-label">Tindak Lanjut</label>
              <textarea name="tindak_lanjut" class="form-control" rows="2"><?= e($data['tindak_lanjut'] ?? '') ?></textarea>
            </div>
          </div>
        </div>
      </div>

      <!-- Narasi -->
      <div class="card mb-3">
        <div class="card-header"><span class="card-header-title"><i class="bi bi-text-paragraph me-2"></i>Narasi Kegiatan</span></div>
        <div class="card-body">
          <textarea name="narasi" class="form-control" rows="6" placeholder="Deskripsikan kegiatan secara detail…"><?= e($data['narasi'] ?? '') ?></textarea>
        </div>
      </div>
    </div>

    <!-- RIGHT: Upload & Status -->
    <div class="col-lg-4">
      <!-- Status -->
      <div class="card mb-3">
        <div class="card-header"><span class="card-header-title"><i class="bi bi-flag me-2"></i>Status Laporan</span></div>
        <div class="card-body">
          <select name="status" class="form-select">
            <?php foreach(['Draft','Terkirim','Disetujui'] as $st): ?>
            <option value="<?= $st ?>" <?= ($data['status']??'Draft')===$st?'selected':'' ?>><?= $st ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      </div>

      <!-- Upload Foto -->
      <div class="card mb-3">
        <div class="card-header"><span class="card-header-title"><i class="bi bi-images me-2"></i>Foto Kegiatan</span></div>
        <div class="card-body">
          <label class="upload-zone w-100" style="cursor:pointer">
            <div class="upload-icon"><i class="bi bi-camera"></i></div>
            <p class="mb-1 fw-600">Pilih / seret foto</p>
            <p class="text-muted mb-2" style="font-size:.78rem">JPG, PNG, WEBP • Maks 5MB per foto</p>
            <input type="file" name="foto_kegiatan[]" accept="image/*" multiple class="d-none">
          </label>

          <?php if($fotoList): ?>
          <div class="foto-grid mt-3">
            <?php foreach($fotoList as $foto): ?>
            <div class="foto-item">
              <img src="<?= BASE_URL ?>/uploads/foto_kegiatan/<?= e($foto['nama_file']) ?>" alt="">
              <div class="foto-item-overlay">
                <a href="<?= BASE_URL ?>/modules/kegiatan/delete_foto.php?id=<?= $foto['id'] ?>&keg=<?= $id ?>"
                   class="btn btn-sm btn-danger"
                   data-confirm="Hapus foto ini?"><i class="bi bi-trash"></i></a>
              </div>
            </div>
            <?php endforeach; ?>
          </div>
          <?php endif; ?>
        </div>
      </div>

      <!-- Upload PDF -->
      <div class="card mb-3">
        <div class="card-header"><span class="card-header-title"><i class="bi bi-file-pdf me-2"></i>File Laporan PDF</span></div>
        <div class="card-body">
          <label class="upload-zone w-100" style="cursor:pointer">
            <div class="upload-icon"><i class="bi bi-file-earmark-pdf"></i></div>
            <p class="mb-1 fw-600">Pilih file PDF</p>
            <p class="text-muted mb-0" style="font-size:.78rem">Maks 10MB</p>
            <input type="file" name="file_laporan" accept=".pdf" class="d-none">
          </label>

          <?php foreach($fileList as $fl): ?>
          <div class="mt-2 d-flex align-items-center justify-content-between p-2 bg-light rounded">
            <div class="d-flex align-items-center gap-2" style="font-size:.82rem">
              <i class="bi bi-file-pdf text-danger fs-5"></i>
              <span class="text-truncate" style="max-width:140px"><?= e($fl['nama_asli']) ?></span>
              <span class="text-muted">(<?= formatBytes($fl['ukuran'] ?? 0) ?>)</span>
            </div>
            <a href="<?= BASE_URL ?>/modules/kegiatan/delete_file.php?id=<?= $fl['id'] ?>&keg=<?= $id ?>"
               class="btn btn-sm btn-outline-danger" data-confirm="Hapus file ini?"><i class="bi bi-x"></i></a>
          </div>
          <?php endforeach; ?>
        </div>
      </div>

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

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