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

$pageTitle  = 'Agenda Kegiatan';
$activePage = 'agenda';

// Handle POST (add/edit) – admin only
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isAdmin()) {
    if (!csrf_verify()) { setFlash('error','Token tidak valid.'); redirect(BASE_URL.'/modules/agenda/index.php'); }

    $editId = (int)($_POST['edit_id'] ?? 0);
    $fields = [
        'tanggal'       => sanitize($_POST['tanggal'] ?? ''),
        'waktu_mulai'   => sanitize($_POST['waktu_mulai'] ?? '') ?: null,
        'waktu_selesai' => sanitize($_POST['waktu_selesai'] ?? '') ?: null,
        'nama_kegiatan' => sanitize($_POST['nama_kegiatan'] ?? ''),
        'tempat'        => sanitize($_POST['tempat'] ?? ''),
        'penyelenggara' => sanitize($_POST['penyelenggara'] ?? ''),
        'keterangan'    => sanitize($_POST['keterangan'] ?? ''),
        'status'        => sanitize($_POST['status'] ?? 'Terjadwal'),
    ];

    if (!empty($fields['tanggal']) && !empty($fields['nama_kegiatan']) && !empty($fields['tempat'])) {
        if ($editId) {
            $set  = implode(',', array_map(fn($k) => "{$k}=?", array_keys($fields)));
            $vals = array_values($fields); $vals[] = $editId;
            Database::execute("UPDATE agenda_kegiatan SET {$set} WHERE id=?", $vals);
            auditLog('UPDATE','agenda_kegiatan',$editId,$fields['nama_kegiatan']);
            setFlash('success','Agenda berhasil diperbarui.');
        } else {
            $cols = implode(',', array_keys($fields));
            $pls  = implode(',', array_fill(0, count($fields), '?'));
            Database::execute("INSERT INTO agenda_kegiatan ({$cols}) VALUES ({$pls})", array_values($fields));
            auditLog('INSERT','agenda_kegiatan',(int)Database::lastInsertId(),$fields['nama_kegiatan']);
            setFlash('success','Agenda berhasil ditambahkan.');
        }
    } else {
        setFlash('error','Tanggal, nama, dan tempat wajib diisi.');
    }
    redirect(BASE_URL.'/modules/agenda/index.php');
}

// Handle delete
if (isset($_GET['del']) && isAdmin()) {
    $del = (int)$_GET['del'];
    $row = Database::fetchOne("SELECT * FROM agenda_kegiatan WHERE id=?", [$del]);
    if ($row) {
        Database::execute("DELETE FROM agenda_kegiatan WHERE id=?", [$del]);
        auditLog('DELETE','agenda_kegiatan',$del,$row['nama_kegiatan']);
        setFlash('success','Agenda dihapus.');
    }
    redirect(BASE_URL.'/modules/agenda/index.php');
}

// Fetch untuk edit
$editData = [];
if (isset($_GET['edit']) && isAdmin()) {
    $editData = Database::fetchOne("SELECT * FROM agenda_kegiatan WHERE id=?", [(int)$_GET['edit']]);
}

// List dengan filter
$bulan  = sanitize($_GET['bulan'] ?? '');
$tahun  = sanitize($_GET['tahun'] ?? date('Y'));
$status = sanitize($_GET['status'] ?? '');
$search = sanitize($_GET['q'] ?? '');
$page   = max(1,(int)($_GET['page'] ?? 1));

$where  = ['1=1'];
$params = [];
if ($bulan)  { $where[] = 'MONTH(tanggal) = ?'; $params[] = $bulan; }
if ($tahun)  { $where[] = 'YEAR(tanggal) = ?'; $params[] = $tahun; }
if ($status) { $where[] = 'status = ?'; $params[] = $status; }
if ($search) { $where[] = '(nama_kegiatan LIKE ? OR tempat LIKE ?)'; $params[] = "%$search%"; $params[] = "%$search%"; }

$whereStr = implode(' AND ', $where);
$sql      = "SELECT * FROM agenda_kegiatan WHERE {$whereStr} ORDER BY tanggal DESC";
$pag      = paginate($sql, $params, 15, $page);
$baseUrl  = BASE_URL.'/modules/agenda/index.php?bulan='.urlencode($bulan).'&tahun='.urlencode($tahun).'&status='.urlencode($status).'&q='.urlencode($search);

require_once ROOT_PATH . '/views/layouts/header.php';
?>

<div class="page-header">
  <div class="page-header-title">
    <h1><i class="bi bi-calendar3 me-2 text-primary"></i>Agenda Kegiatan</h1>
    <nav><ol class="breadcrumb"><li class="breadcrumb-item"><a href="<?= BASE_URL ?>/modules/dashboard/index.php">Dashboard</a></li><li class="breadcrumb-item active">Agenda</li></ol></nav>
  </div>
  <?php if(isAdmin()): ?>
  <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#modalAgenda">
    <i class="bi bi-plus-lg me-1"></i>Tambah Agenda
  </button>
  <?php endif; ?>
</div>

<!-- Filter -->
<div class="card mb-3">
  <div class="card-body py-2">
    <form method="GET" class="row g-2 align-items-end">
      <div class="col-sm-4"><input type="text" name="q" class="form-control form-control-sm" placeholder="Cari kegiatan, tempat…" value="<?= e($search) ?>"></div>
      <div class="col-sm-2">
        <select name="bulan" class="form-select form-select-sm">
          <option value="">Semua Bulan</option>
          <?php $bn=['','Jan','Feb','Mar','Apr','Mei','Jun','Jul','Ags','Sep','Okt','Nov','Des'];
          for($m=1;$m<=12;$m++): ?>
          <option value="<?= $m ?>" <?= $bulan==(string)$m?'selected':'' ?>><?= $bn[$m] ?></option>
          <?php endfor; ?>
        </select>
      </div>
      <div class="col-sm-2">
        <input type="number" name="tahun" class="form-control form-control-sm" value="<?= e($tahun) ?>" placeholder="Tahun" min="2020" max="2030">
      </div>
      <div class="col-sm-2">
        <select name="status" class="form-select form-select-sm">
          <option value="">Semua Status</option>
          <?php foreach(['Terjadwal','Selesai','Dibatalkan'] as $st): ?>
          <option value="<?= $st ?>" <?= $status===$st?'selected':'' ?>><?= $st ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-auto d-flex gap-2">
        <button type="submit" class="btn btn-primary btn-sm"><i class="bi bi-search"></i></button>
        <a href="<?= BASE_URL ?>/modules/agenda/index.php" class="btn btn-outline-secondary btn-sm">Reset</a>
      </div>
    </form>
  </div>
</div>

<!-- Table -->
<div class="card">
  <div class="card-header">
    <span class="card-header-title"><i class="bi bi-table me-2"></i>Daftar Agenda</span>
    <span class="badge bg-primary-subtle text-primary"><?= $pag['total'] ?> agenda</span>
  </div>
  <div class="table-responsive">
    <table class="table table-hover mb-0">
      <thead>
        <tr><th>#</th><th>Tanggal</th><th>Waktu</th><th>Nama Kegiatan</th><th>Tempat</th><th>Status</th><th width="100">Aksi</th></tr>
      </thead>
      <tbody>
        <?php if(empty($pag['data'])): ?>
        <tr><td colspan="7" class="text-center py-4 text-muted">Tidak ada agenda</td></tr>
        <?php else: ?>
        <?php $no=($pag['current']-1)*$pag['per_page']+1; ?>
        <?php foreach($pag['data'] as $row):
          $stColor=['Terjadwal'=>'info','Selesai'=>'success','Dibatalkan'=>'danger'][$row['status']]??'secondary'; ?>
        <tr>
          <td class="text-muted"><?= $no++ ?></td>
          <td style="white-space:nowrap"><?= formatTanggal($row['tanggal'],'d M Y') ?></td>
          <td style="white-space:nowrap;font-size:.82rem">
            <?= $row['waktu_mulai'] ? substr($row['waktu_mulai'],0,5) : '—' ?>
            <?= $row['waktu_selesai'] ? ' – '.substr($row['waktu_selesai'],0,5) : '' ?>
          </td>
          <td>
            <div class="fw-600"><?= e($row['nama_kegiatan']) ?></div>
            <?php if($row['keterangan']): ?>
            <div class="text-muted" style="font-size:.75rem"><?= e(mb_strimwidth($row['keterangan'],0,60,'…')) ?></div>
            <?php endif; ?>
          </td>
          <td><?= e($row['tempat']) ?></td>
          <td><span class="badge bg-<?= $stColor ?>-subtle text-<?= $stColor ?>"><?= e($row['status']) ?></span></td>
          <td>
            <?php if(isAdmin()): ?>
            <div class="d-flex gap-1">
              <a href="?edit=<?= $row['id'] ?>#formEdit" class="btn btn-sm btn-outline-warning" title="Edit"><i class="bi bi-pencil"></i></a>
              <a href="?del=<?= $row['id'] ?>" class="btn btn-sm btn-outline-danger" data-confirm="Hapus agenda ini?" title="Hapus"><i class="bi bi-trash"></i></a>
            </div>
            <?php endif; ?>
          </td>
        </tr>
        <?php endforeach; ?>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
  <?php if($pag['pages']>1): ?>
  <div class="card-footer d-flex justify-content-between align-items-center flex-wrap gap-2">
    <span class="text-muted small">Menampilkan <?= count($pag['data']) ?> dari <?= $pag['total'] ?> data</span>
    <?= renderPagination($pag,$baseUrl) ?>
  </div>
  <?php endif; ?>
</div>

<!-- Edit form inline if edit mode -->
<?php if($editData && isAdmin()): ?>
<div id="formEdit" class="card mt-3">
  <div class="card-header"><span class="card-header-title"><i class="bi bi-pencil-square me-2"></i>Edit Agenda: <?= e($editData['nama_kegiatan']) ?></span></div>
  <div class="card-body">
    <form method="POST">
      <?= csrf_field() ?>
      <input type="hidden" name="edit_id" value="<?= $editData['id'] ?>">
      <div class="row g-3">
        <div class="col-md-3"><label class="form-label">Tanggal</label><input type="date" name="tanggal" class="form-control" value="<?= e($editData['tanggal']) ?>" required></div>
        <div class="col-md-2"><label class="form-label">Mulai</label><input type="time" name="waktu_mulai" class="form-control" value="<?= e($editData['waktu_mulai']??'') ?>"></div>
        <div class="col-md-2"><label class="form-label">Selesai</label><input type="time" name="waktu_selesai" class="form-control" value="<?= e($editData['waktu_selesai']??'') ?>"></div>
        <div class="col-md-5"><label class="form-label">Nama Kegiatan</label><input type="text" name="nama_kegiatan" class="form-control" value="<?= e($editData['nama_kegiatan']) ?>" required></div>
        <div class="col-md-4"><label class="form-label">Tempat</label><input type="text" name="tempat" class="form-control" value="<?= e($editData['tempat']) ?>" required></div>
        <div class="col-md-4"><label class="form-label">Penyelenggara</label><input type="text" name="penyelenggara" class="form-control" value="<?= e($editData['penyelenggara']??'') ?>"></div>
        <div class="col-md-2"><label class="form-label">Status</label>
          <select name="status" class="form-select">
            <?php foreach(['Terjadwal','Selesai','Dibatalkan'] as $st): ?>
            <option value="<?= $st ?>" <?= $editData['status']===$st?'selected':'' ?>><?= $st ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-md-2"><label class="form-label">Keterangan</label><input type="text" name="keterangan" class="form-control" value="<?= e($editData['keterangan']??'') ?>"></div>
        <div class="col-12 d-flex gap-2"><button type="submit" class="btn btn-warning"><i class="bi bi-check-lg me-1"></i>Simpan</button><a href="<?= BASE_URL ?>/modules/agenda/index.php" class="btn btn-outline-secondary">Batal</a></div>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<!-- Modal Tambah -->
<?php if(isAdmin()): ?>
<div class="modal fade" id="modalAgenda" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content border-0 shadow-lg">
      <div class="modal-header border-0 pb-0">
        <h5 class="modal-title fw-700">Tambah Agenda Kegiatan</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <form method="POST">
          <?= csrf_field() ?>
          <div class="row g-3">
            <div class="col-md-3"><label class="form-label">Tanggal <span class="text-danger">*</span></label><input type="date" name="tanggal" class="form-control" required></div>
            <div class="col-md-2"><label class="form-label">Waktu Mulai</label><input type="time" name="waktu_mulai" class="form-control"></div>
            <div class="col-md-2"><label class="form-label">Waktu Selesai</label><input type="time" name="waktu_selesai" class="form-control"></div>
            <div class="col-md-5"><label class="form-label">Nama Kegiatan <span class="text-danger">*</span></label><input type="text" name="nama_kegiatan" class="form-control" required></div>
            <div class="col-md-4"><label class="form-label">Tempat <span class="text-danger">*</span></label><input type="text" name="tempat" class="form-control" required></div>
            <div class="col-md-4"><label class="form-label">Penyelenggara</label><input type="text" name="penyelenggara" class="form-control"></div>
            <div class="col-md-4"><label class="form-label">Status</label>
              <select name="status" class="form-select">
                <option value="Terjadwal">Terjadwal</option>
                <option value="Selesai">Selesai</option>
                <option value="Dibatalkan">Dibatalkan</option>
              </select>
            </div>
            <div class="col-12"><label class="form-label">Keterangan</label><textarea name="keterangan" class="form-control" rows="2"></textarea></div>
          </div>
          <div class="mt-3 d-flex gap-2">
            <button type="submit" class="btn btn-primary"><i class="bi bi-check-lg me-1"></i>Tambah Agenda</button>
            <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Batal</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

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