<?php
$pageTitle = 'Data Siswa';
require_once __DIR__ . '/includes/header.php';

$db = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'delete') {
        $id = (int) ($_POST['id'] ?? 0);
        $stmt = $db->prepare('DELETE FROM siswa WHERE id = ?');
        $stmt->execute([$id]);
        flash('success', 'Data siswa berhasil dihapus.');
        header('Location: siswa.php');
        exit;
    }

    if ($action === 'bulk_delete') {
        $ids = array_values(array_filter(array_map('intval', $_POST['ids'] ?? []), static fn ($id) => $id > 0));
        if (!empty($ids)) {
            $placeholders = implode(',', array_fill(0, count($ids), '?'));
            $stmt = $db->prepare("DELETE FROM siswa WHERE id IN ($placeholders)");
            $stmt->execute($ids);
            $count = $stmt->rowCount();
            flash('success', "$count data siswa berhasil dihapus.");
        } else {
            flash('error', 'Pilih minimal satu data siswa untuk dihapus.');
        }
        header('Location: siswa.php');
        exit;
    }
}

$limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
$validLimits = [10, 20, 50, 100, 300, 500];
if (!in_array($limit, $validLimits)) {
    $limit = 10;
}
$page = isset($_GET['p']) ? (int)$_GET['p'] : 1;
$offset = ($page - 1) * $limit;

$sql = 'SELECT * FROM siswa';
$sql .= ' ORDER BY id DESC';

// Get total count for pagination
$countSql = str_replace('SELECT *', 'SELECT COUNT(*)', $sql);
$countStmt = $db->prepare($countSql);
$countStmt->execute();
$totalRows = $countStmt->fetchColumn();
$totalPages = ceil($totalRows / $limit);

// Add pagination to main query
$sql .= " LIMIT $limit OFFSET $offset";

$stmt = $db->prepare($sql);
$stmt->execute();
$siswaList = $stmt->fetchAll();

$success = flash('success');
$viewSiswa = null;
if (isset($_GET['view'])) {
    $vid = (int) $_GET['view'];
    $st = $db->prepare('SELECT * FROM siswa WHERE id = ?');
    $st->execute([$vid]);
    $viewSiswa = $st->fetch();
}
?>

<div class="page-header">
  <h1>Data Siswa</h1>
</div>
<div class="page-body">
  <?php if ($success): ?><div class="alert alert-success"><?= e($success) ?></div><?php endif; ?>
  <?php $error = flash('error'); if ($error): ?><div class="alert alert-danger"><?= e($error) ?></div><?php endif; ?>

  <form method="post" id="formBulkDelete" data-confirm-delete data-skip-validation
        data-confirm-title="Hapus Data Siswa Terpilih?"
        data-confirm-text="Data yang dihapus tidak dapat dikembalikan.">
    <input type="hidden" name="action" value="bulk_delete">
  </form>

  <div class="toolbar" style="margin-bottom:1rem">
    <div class="search-box" style="flex:1">
      <i class="fas fa-search"></i>
      <input type="text" placeholder="Cari Data" data-table-search="tableSiswa">
    </div>
    <select class="form-control" style="width:auto;padding:0.5rem" onchange="location.href='siswa.php?limit='+this.value+'&p=1'">
      <option value="10" <?= $limit === 10 ? 'selected' : '' ?>>10</option>
      <option value="20" <?= $limit === 20 ? 'selected' : '' ?>>20</option>
      <option value="50" <?= $limit === 50 ? 'selected' : '' ?>>50</option>
      <option value="100" <?= $limit === 100 ? 'selected' : '' ?>>100</option>
      <option value="300" <?= $limit === 300 ? 'selected' : '' ?>>300</option>
      <option value="500" <?= $limit === 500 ? 'selected' : '' ?>>500</option>
    </select>
    <button type="submit" form="formBulkDelete" class="btn btn-danger" id="btnBulkDelete" disabled>
      <i class="fas fa-trash"></i> Hapus Terpilih
    </button>
    <a href="siswa_tambah.php" class="btn btn-outline"><i class="fas fa-plus"></i> Tambah Siswa</a>
    <a href="siswa_import.php" class="btn btn-outline"><i class="fas fa-file-excel"></i> Import Data</a>
  </div>

  <div class="card">
    <div class="card-body" style="padding-top:0">
      <div class="table-responsive">
        <table class="data-table" id="tableSiswa">
          <thead>
            <tr>
              <th class="col-check">
                <input type="checkbox" id="checkAllSiswa" class="table-checkbox" title="Pilih semua">
              </th>
              <th>No</th>
              <th>Nama</th>
              <th>Pekerjaan Orang Tua</th>
              <th>Penghasilan Orang Tua</th>
              <th>Jumlah Saudara Kandung</th>
              <th>Penerima KPS</th>
              <th>Penerima KIP</th>
              <th>Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php if (empty($siswaList)): ?>
            <tr><td colspan="9" style="text-align:center;color:var(--text-muted)">Belum ada data siswa.</td></tr>
            <?php endif; ?>
            <?php foreach ($siswaList as $i => $s): ?>
            <tr>
              <td class="col-check">
                <input type="checkbox" form="formBulkDelete" name="ids[]" value="<?= (int) $s['id'] ?>"
                       class="table-checkbox row-check-siswa">
              </td>
              <td><?= $offset + $i + 1 ?></td>
              <td><?= e($s['nama']) ?></td>
              <td><?= e($s['pekerjaan_ortu']) ?></td>
              <td><?= e($s['penghasilan_ortu']) ?></td>
              <td><?= (int) $s['jumlah_saudara'] ?></td>
              <td><?= e($s['kepemilikan_kps']) ?></td>
              <td><?= e($s['kepemilikan_kip']) ?></td>
              <td>
                <div class="action-btns">
                  <a href="siswa.php?view=<?= $s['id'] ?>" class="btn-icon" title="Lihat"><i class="fas fa-eye"></i></a>
                  <a href="siswa_edit.php?id=<?= $s['id'] ?>" class="btn-icon" title="Edit"><i class="fas fa-edit"></i></a>
                  <form method="post" style="display:inline" data-confirm-delete data-confirm-title="Hapus Data Siswa?" data-confirm-text="Data yang dihapus tidak dapat dikembalikan.">
                    <input type="hidden" name="action" value="delete">
                    <input type="hidden" name="id" value="<?= $s['id'] ?>">
                    <button type="submit" class="btn-icon delete" title="Hapus"><i class="fas fa-trash"></i></button>
                  </form>
                </div>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <?php if ($totalPages > 1): ?>
      <div class="pagination">
      <?php if ($page > 1): ?>
      <a href="siswa.php?limit=<?= $limit ?>&p=<?= $page - 1 ?>" class="btn btn-outline">&laquo; Prev</a>
      <?php endif; ?>
      
      <?php for ($i = 1; $i <= $totalPages; $i++): ?>
        <?php if ($i === $page): ?>
        <span class="btn btn-primary" style="pointer-events:none"><?= $i ?></span>
        <?php else: ?>
        <a href="siswa.php?limit=<?= $limit ?>&p=<?= $i ?>" class="btn btn-outline"><?= $i ?></a>
        <?php endif; ?>
      <?php endfor; ?>
      
      <?php if ($page < $totalPages): ?>
      <a href="siswa.php?limit=<?= $limit ?>&p=<?= $page + 1 ?>" class="btn btn-outline">Next &raquo;</a>
      <?php endif; ?>
      </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<?php if ($viewSiswa): ?>
<div class="modal-overlay show" id="modalView">
  <div class="modal">
    <div class="modal-header">
      <h3>Detail Siswa</h3>
      <a href="siswa.php" class="modal-close">&times;</a>
    </div>
    <div class="modal-body">
      <ul class="detail-list">
        <li><span>Nama</span><span><?= e($viewSiswa['nama']) ?></span></li>
        <li><span>Pekerjaan Orang Tua</span><span><?= e($viewSiswa['pekerjaan_ortu']) ?></span></li>
        <li><span>Penghasilan Orang Tua</span><span><?= e($viewSiswa['penghasilan_ortu']) ?></span></li>
        <li><span>Jumlah Saudara</span><span><?= (int) $viewSiswa['jumlah_saudara'] ?></span></li>
        <li><span>Penerima KPS</span><span><?= e($viewSiswa['kepemilikan_kps']) ?></span></li>
        <li><span>Penerima KIP</span><span><?= e($viewSiswa['kepemilikan_kip']) ?></span></li>
      </ul>
    </div>
    <div class="modal-footer">
      <a href="siswa_edit.php?id=<?= $viewSiswa['id'] ?>" class="btn btn-success">Edit</a>
      <a href="siswa.php" class="btn btn-outline">Tutup</a>
    </div>
  </div>
</div>
<?php endif; ?>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
