<?php
/**
 * SisPen Snesaka - Manajemen Ekstrakurikuler
 */
require_once '../../includes/functions.php';
requireAdmin();

$pageTitle  = 'Ekstrakurikuler';
$activeMenu = 'ekstra';

// Handle tambah
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'add') {
        $nama      = sanitize($_POST['nama'] ?? '');
        $ket       = sanitize($_POST['keterangan'] ?? '');
        $pembinaId = intval($_POST['pembina_id'] ?? 0) ?: null;
        if ($nama) {
            db_insert('ekstrakurikuler', array(
                'nama'       => $nama,
                'keterangan' => $ket,
                'pembina_id' => $pembinaId,
                'status'     => 'aktif',
            ));
            setFlash('success', 'Ekstrakurikuler berhasil ditambahkan.');
        }
    } elseif ($_POST['action'] === 'edit') {
        $id        = intval($_POST['id']);
        $nama      = sanitize($_POST['nama'] ?? '');
        $ket       = sanitize($_POST['keterangan'] ?? '');
        $pembinaId = intval($_POST['pembina_id'] ?? 0) ?: null;
        $status    = $_POST['status'] ?? 'aktif';
        db_update('ekstrakurikuler',
            array('nama'=>$nama,'keterangan'=>$ket,'pembina_id'=>$pembinaId,'status'=>$status),
            'id=:id', array('id'=>$id)
        );
        setFlash('success', 'Data ekstrakurikuler diperbarui.');
    } elseif ($_POST['action'] === 'delete') {
        $id = intval($_POST['id']);
        db_query("DELETE FROM ekstrakurikuler WHERE id=?", [$id]);
        setFlash('success', 'Ekstrakurikuler dihapus.');
    }
    header('Location: list.php');
    exit;
}

$ekstraList = db_fetchAll("
    SELECT e.*, g.nama as nama_pembina,
           COUNT(DISTINCT ne.siswa_id) as jumlah_siswa
    FROM ekstrakurikuler e
    LEFT JOIN guru g ON g.id = e.pembina_id
    LEFT JOIN nilai_ekstra ne ON ne.ekstra_id = e.id
    GROUP BY e.id
    ORDER BY e.status DESC, e.nama
");
$guruList = db_fetchAll("SELECT id, nama FROM guru WHERE status='aktif' ORDER BY nama");

include '../../templates/header.php';
?>

<div style="display:grid;grid-template-columns:1fr 380px;gap:20px;align-items:start;">

  <!-- Daftar Ekstra -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">
        <i class="fas fa-trophy" style="color:var(--accent);margin-right:8px;"></i>
        Daftar Ekstrakurikuler
        <span class="badge badge-blue" style="margin-left:6px;"><?= count($ekstraList) ?></span>
      </span>
      <a href="nilai.php" class="btn btn-primary btn-sm">
        <i class="fas fa-star"></i> Input Nilai Ekstra
      </a>
    </div>
    <div class="table-responsive">
      <table class="table">
        <thead>
          <tr>
            <th>No</th>
            <th>Nama Ekstrakurikuler</th>
            <th>Pembina</th>
            <th style="text-align:center;">Peserta</th>
            <th style="text-align:center;">Status</th>
            <th style="text-align:center;">Aksi</th>
          </tr>
        </thead>
        <tbody>
          <?php if (empty($ekstraList)): ?>
          <tr><td colspan="6" style="text-align:center;padding:32px;color:var(--text-muted);">Belum ada ekstrakurikuler</td></tr>
          <?php else: ?>
          <?php foreach ($ekstraList as $i => $e): ?>
          <tr>
            <td style="color:var(--text-muted);"><?= $i+1 ?></td>
            <td>
              <div style="font-weight:600;"><?= htmlspecialchars($e['nama']) ?></div>
              <?php if ($e['keterangan']): ?>
              <div style="font-size:11px;color:var(--text-muted);"><?= htmlspecialchars(substr($e['keterangan'],0,60)) ?><?= strlen($e['keterangan'])>60?'...':'' ?></div>
              <?php endif; ?>
            </td>
            <td><?= $e['nama_pembina'] ? htmlspecialchars($e['nama_pembina']) : '<span style="color:var(--text-light);">-</span>' ?></td>
            <td style="text-align:center;">
              <span class="badge badge-info"><?= $e['jumlah_siswa'] ?> siswa</span>
            </td>
            <td style="text-align:center;">
              <span class="badge badge-<?= $e['status']==='aktif'?'success':'gray' ?>"><?= ucfirst($e['status']) ?></span>
            </td>
            <td style="text-align:center;">
              <button onclick="editEkstra(<?= htmlspecialchars(json_encode($e)) ?>)"
                      class="btn btn-outline btn-xs" title="Edit">
                <i class="fas fa-edit"></i>
              </button>
              <button onclick="hapusEkstra(<?= $e['id'] ?>, '<?= htmlspecialchars($e['nama']) ?>')"
                      class="btn btn-xs" style="background:#fee2e2;color:#dc2626;border:1px solid #fca5a5;" title="Hapus">
                <i class="fas fa-trash"></i>
              </button>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>

  <!-- Form Tambah/Edit -->
  <div class="card" id="formCard">
    <div class="card-header">
      <span class="card-title" id="formTitle">
        <i class="fas fa-plus-circle" style="color:var(--success);margin-right:8px;"></i>Tambah Ekstrakurikuler
      </span>
    </div>
    <div class="card-body">
      <form method="POST" id="ekstraForm">
        <input type="hidden" name="action" id="formAction" value="add">
        <input type="hidden" name="id"     id="formId"     value="">

        <div class="form-group">
          <label class="form-label">Nama Ekstrakurikuler <span class="required">*</span></label>
          <input type="text" name="nama" id="formNama" class="form-control"
                 placeholder="Contoh: Pramuka, Basket, dll" required>
        </div>
        <div class="form-group">
          <label class="form-label">Pembina</label>
          <select name="pembina_id" id="formPembina" class="form-control">
            <option value="">-- Pilih Guru Pembina --</option>
            <?php foreach ($guruList as $g): ?>
            <option value="<?= $g['id'] ?>"><?= htmlspecialchars($g['nama']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group" id="statusGroup" style="display:none;">
          <label class="form-label">Status</label>
          <select name="status" id="formStatus" class="form-control">
            <option value="aktif">Aktif</option>
            <option value="nonaktif">Nonaktif</option>
          </select>
        </div>
        <div class="form-group">
          <label class="form-label">Keterangan</label>
          <textarea name="keterangan" id="formKet" class="form-control" rows="3"
                    placeholder="Deskripsi singkat..."></textarea>
        </div>
        <div style="display:flex;gap:8px;">
          <button type="submit" class="btn btn-primary" style="flex:1;justify-content:center;">
            <i class="fas fa-save"></i> <span id="btnText">Simpan</span>
          </button>
          <button type="button" onclick="resetForm()" class="btn btn-outline">
            <i class="fas fa-times"></i>
          </button>
        </div>
      </form>
    </div>
  </div>

</div>

<!-- Form hapus tersembunyi -->
<form method="POST" id="deleteForm" style="display:none;">
  <input type="hidden" name="action" value="delete">
  <input type="hidden" name="id" id="deleteId">
</form>

<script>
function editEkstra(data) {
    document.getElementById('formAction').value  = 'edit';
    document.getElementById('formId').value      = data.id;
    document.getElementById('formNama').value    = data.nama;
    document.getElementById('formKet').value     = data.keterangan || '';
    document.getElementById('formPembina').value = data.pembina_id || '';
    document.getElementById('formStatus').value  = data.status;
    document.getElementById('statusGroup').style.display = 'block';
    document.getElementById('formTitle').innerHTML = '<i class="fas fa-edit" style="color:var(--primary);margin-right:8px;"></i>Edit Ekstrakurikuler';
    document.getElementById('btnText').textContent = 'Update';
    document.getElementById('formCard').scrollIntoView({behavior:'smooth'});
}
function resetForm() {
    document.getElementById('ekstraForm').reset();
    document.getElementById('formAction').value = 'add';
    document.getElementById('formId').value     = '';
    document.getElementById('statusGroup').style.display = 'none';
    document.getElementById('formTitle').innerHTML = '<i class="fas fa-plus-circle" style="color:var(--success);margin-right:8px;"></i>Tambah Ekstrakurikuler';
    document.getElementById('btnText').textContent = 'Simpan';
}
function hapusEkstra(id, nama) {
    if (confirm('Hapus ekstrakurikuler "'+nama+'"?\nData nilai ekstra terkait juga akan terhapus.')) {
        document.getElementById('deleteId').value = id;
        document.getElementById('deleteForm').submit();
    }
}
</script>

<?php include '../../templates/footer.php'; ?>
