<?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 program_kerja WHERE id=?", [$id]);
    if (!$data) { setFlash('error','Program tidak ditemukan.'); redirect(BASE_URL.'/modules/program_kerja/index.php'); }
}

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

    $fields = [
        'tahun_ajaran'    => sanitize($_POST['tahun_ajaran'] ?? ''),
        'nama_program'    => sanitize($_POST['nama_program'] ?? ''),
        'deskripsi'       => sanitize($_POST['deskripsi'] ?? ''),
        'target_kegiatan' => max(1,(int)($_POST['target_kegiatan'] ?? 1)),
        'waktu_mulai'     => sanitize($_POST['waktu_mulai'] ?? ''),
        'waktu_selesai'   => sanitize($_POST['waktu_selesai'] ?? ''),
        'status'          => sanitize($_POST['status'] ?? 'Belum Mulai'),
        'keterangan'      => sanitize($_POST['keterangan'] ?? ''),
    ];

    if (empty($fields['tahun_ajaran']))  $errors[] = 'Tahun ajaran wajib diisi.';
    if (empty($fields['nama_program']))  $errors[] = 'Nama program wajib diisi.';
    if (empty($fields['waktu_mulai']))   $errors[] = 'Waktu mulai wajib diisi.';
    if (empty($fields['waktu_selesai'])) $errors[] = 'Waktu selesai 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 program_kerja SET {$set} WHERE id=?", $vals);
            auditLog('UPDATE','program_kerja',$id,$fields['nama_program']);
            setFlash('success','Program berhasil diperbarui.');
        } else {
            $cols = implode(',', array_keys($fields));
            $pls  = implode(',', array_fill(0, count($fields), '?'));
            Database::execute("INSERT INTO program_kerja ({$cols}) VALUES ({$pls})", array_values($fields));
            auditLog('INSERT','program_kerja',(int)Database::lastInsertId(),$fields['nama_program']);
            setFlash('success','Program berhasil ditambahkan.');
        }
        redirect(BASE_URL.'/modules/program_kerja/index.php');
    }
    $data = array_merge($data, $fields);
}

$pageTitle  = ($edit?'Edit':'Tambah').' Program Kerja';
$activePage = 'program_kerja';
require_once ROOT_PATH . '/views/layouts/header.php';
?>

<div class="page-header">
  <div class="page-header-title">
    <h1><i class="bi bi-clipboard2-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/program_kerja/index.php">Program Kerja</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; ?>

<div class="row justify-content-center">
  <div class="col-lg-8">
    <div class="card">
      <div class="card-header"><span class="card-header-title"><i class="bi bi-clipboard2-check me-2"></i>Form Program Kerja</span></div>
      <div class="card-body">
        <form method="POST">
          <?= csrf_field() ?>
          <div class="row g-3">
            <div class="col-md-4">
              <label class="form-label">Tahun Ajaran <span class="text-danger">*</span></label>
              <input type="text" name="tahun_ajaran" class="form-control" value="<?= e($data['tahun_ajaran'] ?? '') ?>" placeholder="2024/2025" required>
            </div>
            <div class="col-md-8">
              <label class="form-label">Nama Program <span class="text-danger">*</span></label>
              <input type="text" name="nama_program" class="form-control" value="<?= e($data['nama_program'] ?? '') ?>" required>
            </div>
            <div class="col-12">
              <label class="form-label">Deskripsi Program</label>
              <textarea name="deskripsi" class="form-control" rows="3"><?= e($data['deskripsi'] ?? '') ?></textarea>
            </div>
            <div class="col-md-4">
              <label class="form-label">Target Kegiatan</label>
              <input type="number" name="target_kegiatan" class="form-control" min="1" value="<?= e($data['target_kegiatan'] ?? 1) ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label">Waktu Mulai <span class="text-danger">*</span></label>
              <input type="date" name="waktu_mulai" class="form-control" value="<?= e($data['waktu_mulai'] ?? '') ?>" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">Waktu Selesai <span class="text-danger">*</span></label>
              <input type="date" name="waktu_selesai" class="form-control" value="<?= e($data['waktu_selesai'] ?? '') ?>" required>
            </div>
            <div class="col-md-4">
              <label class="form-label">Status</label>
              <select name="status" class="form-select">
                <?php foreach(['Belum Mulai','Berjalan','Selesai'] as $st): ?>
                <option value="<?= $st ?>" <?= ($data['status']??'Belum Mulai')===$st?'selected':'' ?>><?= $st ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-8">
              <label class="form-label">Keterangan</label>
              <input type="text" name="keterangan" class="form-control" value="<?= e($data['keterangan'] ?? '') ?>">
            </div>
            <div class="col-12 pt-2 d-flex gap-2">
              <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i><?= $edit?'Simpan':'Tambah Program' ?></button>
              <a href="<?= BASE_URL ?>/modules/program_kerja/index.php" class="btn btn-outline-secondary">Batal</a>
            </div>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

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