<?php
session_start();
require_once __DIR__ . '/config/config.php';

/* =========================
   PROTEKSI LOGIN
========================= */
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    die("Akses ditolak!");
}

if (!isset($_SESSION['role'])) {
    die("Role tidak ditemukan, silakan login ulang.");
}

$role = $_SESSION['role'];

/* =========================
   TAMBAHAN ADMIN: FILTER SEKOLAH
========================= */
$npsn_filter = '';
if ($role === 'admin' && isset($_GET['npsn']) && $_GET['npsn'] !== '') {
    $npsn_filter = $_GET['npsn'];
}

/* =========================
   QUERY SESUAI ROLE
========================= */
if ($role === 'admin') {

    if ($npsn_filter !== '') {
        // ADMIN → filter sekolah tertentu
        $sql = "SELECT * FROM kwitansi WHERE npsn = ? ORDER BY id_kw DESC";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("s", $npsn_filter);
    } else {
        // ADMIN → semua data
        $sql = "SELECT * FROM kwitansi ORDER BY id_kw DESC";
        $stmt = $conn->prepare($sql);
    }

    if (!$stmt) {
        die("Prepare error: " . $conn->error);
    }

} else {

    // SEKOLAH → data sesuai NPSN LOGIN
    if (!isset($_SESSION['npsn'])) {
        die("NPSN tidak ditemukan di session, silakan login ulang.");
    }

    $npsn = trim($_SESSION['npsn']);

       $sql = "SELECT * FROM kwitansi
            WHERE TRIM(npsn) = ?
            ORDER BY id_kw DESC";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        die("Prepare error: " . $conn->error);
    }

    $stmt->bind_param("s", $npsn);
}

$stmt->execute();
$data = $stmt->get_result();
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Data Kwitansi</title>
<link rel="icon" href="assets/images/logomu.ico">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">

<style>
    body { font-family:"Segoe UI", Arial; }
    .card-header-primary{
        background:#0d6efd;
        color:#fff;
        font-weight:600;
    }
    .btn-aksi{
        display:inline-flex;
        align-items:center;
        justify-content:center;
        width:26px;
        height:26px;
        border-radius:6px;
        font-size:13px;
        text-decoration:none;
    }
    .btn-aksi.edit{border:1px solid #0d6efd;color:#0d6efd}
    .btn-aksi.hapus{border:1px solid #dc3545;color:#dc3545}

    /* TABLE COMPACT */
    .table-wrapper{
        max-height:380px;
        overflow-y:auto;
        border:1px solid #dee2e6;
        background:#fff;
    }
    table{width:100%;border-collapse:collapse;font-size:11px}
    thead th{
        position:sticky;
        top:0;
        background:#f1f3f5;
        z-index:2;
        text-align:center;
        padding:5px;
        border-bottom:1px solid #ccc;
    }
    td{
        padding:4px 6px;
        border-bottom:1px solid #eee;
        vertical-align:middle;
    }
    tbody tr:hover{background:#eef6ff}
	th.col-aksi, td.col-aksi{
    width:80px;
    min-width:80px;
    text-align:center;
    white-space:nowrap;
}
</style>
</head>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<body class="bg-light">

<div class="container-fluid mt-4">

    <!-- NAVIGASI -->
    <div class="mb-3">
        <a href="<?= $role==='admin'?'dashboard_admin.php':'dashboard.php' ?>"
           class="btn btn-outline-secondary btn-sm">
            ⬅ Dashboard
        </a>
    </div>

    <!-- CARD -->
    <div class="card shadow-sm">

        <!-- HEADER -->
        <div class="card-header card-header-primary">
            📊 Data Kwitansi BOS Reguler
        </div>

        <!-- BODY -->
        <div class="card-body">

            <!-- FILTER ADMIN -->
            <?php if ($role === 'admin'): ?>
            <form method="get" class="mb-3">
                <select name="npsn" class="form-select form-select-sm w-auto"
                        onchange="this.form.submit()">
                    <option value="">🔎 Semua Sekolah</option>
                    <?php
                    $qSekolah = $conn->query("
                        SELECT DISTINCT s.npsn, s.nama_sekolah
                        FROM sekolah s
                        JOIN kwitansi k ON s.npsn = k.npsn
                        ORDER BY s.nama_sekolah
                    ");
                    while ($s = $qSekolah->fetch_assoc()):
                    ?>
                    <option value="<?= $s['npsn'] ?>"
                        <?= ($npsn_filter === $s['npsn']) ? 'selected' : '' ?>>
                        <?= $s['npsn'].' | '.$s['nama_sekolah'] ?>
                    </option>
                    <?php endwhile; ?>
                </select>
            </form>
            <?php endif; ?>

            <!-- TOOLBAR -->
            <div class="mb-3 d-flex flex-wrap gap-1">
                <a href="tambah_kwitansi.php" class="btn btn-primary btn-sm">➕ Tambah</a>
                
                <a href="kwitansi_template.php" class="btn btn-outline-secondary btn-sm">📄 Template</a>

                <form action="kwitansi_import.php" method="post"
                      enctype="multipart/form-data" class="d-inline">
                    <input type="file" name="file" required style="font-size:11px">
                    <button class="btn btn-success btn-sm">⬆ Import</button>
                </form>

                <button type="button"
					class="btn btn-danger btn-sm"
					data-bs-toggle="modal"
					data-bs-target="#modalHapusSemua">
				🗑️ Hapus Semua
			</button>
            
			<!-- CETAK -->
            <form action="kwitansi_cetak_banyak.php" method="post" target="_blank">
                <input type="hidden" name="pajak" id="pajak_mode" value="on">

                <button type="submit"
                        onclick="document.getElementById('pajak_mode').value='off'"
                        class="btn btn-primary btn-sm">
                    <i class="bi bi-printer"></i> Cetak Non Pajak
                </button>

                <a href="kwitansiku.php" class="btn btn-success btn-sm">
                    ⬇ Cetak + Pajak
                </a>
			
			
			</div>

            

                <div class="table-wrapper mt-3">
                <table>
                    <thead>
                        <tr>
                            <th><input type="checkbox" id="checkAll"></th>
                            <th width="40">No</th>
                            <th style="width:95px; min-width:95px;">Tanggal</th>
                            <th>Kode Kegiatan</th>
                            <th>Kode Rekening</th>
                            <th>No Bukti</th>
                            <th>Uraian</th>
                            <th>Jml</th>
                            <th>Satuan</th>
                            <th>Pengeluaran</th>
                            <th>Penerima</th>
                            <th class="col-aksi">Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
					<?php $no = 1; ?>
                    <?php while($r = $data->fetch_assoc()): ?>
                        <tr>
                            <td class="text-center">
                                <input type="checkbox" class="cek" name="id_kw[]" value="<?= $r['id_kw'] ?>">
                            </td>
                            <td class="text-center" style="white-space:nowrap;">
                                <div style="font-size:10px;color:#6c757d;"><?= $r['npsn'] ?></div>
                                <?= date('d-m-Y', strtotime($r['tanggal'])) ?>
                            </td>
							
							</td>
                            <td><?= $r['kode_kegiatan'] ?></td>
                            <td><?= $r['kode_rekening'] ?></td>
                            <td><?= $r['nobukti'] ?></td>
                            <td><?= $r['uraian'] ?></td>
                            <td class="text-center"><?= $r['jumb'] ?></td>
                            <td class="text-center"><?= $r['satuanb'] ?></td>
                            <td class="text-end">Rp <?= number_format($r['pengeluaran'],0,',','.') ?></td>
                            <td><?= $r['yang_menerima'] ?></td>
                            <td class="col-aksi">
								<a href="edit_kwitansi.php?id=<?= $r['id_kw'] ?>" class="btn-aksi edit">✏️</a>
								<a href="hapus_kwitansi.php?id=<?= $r['id_kw'] ?>" class="btn-aksi hapus">🗑️</a>
							</td>
                        </tr>
                    <?php endwhile; ?>
					<div class="modal fade" id="modalHapusSemua" tabindex="-1">
					  <div class="modal-dialog modal-dialog-centered">
						<div class="modal-content shadow-lg border-0">

						  <div class="modal-header bg-danger text-white">
							<h5 class="modal-title">⚠️ Konfirmasi Hapus</h5>
							<button type="button" class="btn-close btn-close-white"
									data-bs-dismiss="modal"></button>
						  </div>

						  <div class="modal-body text-center">
							<p class="fw-bold text-danger mb-2">
							  Data akan dihapus permanen!
							</p>
							<small class="text-muted">
							  Semua data kwitansi tidak bisa dikembalikan.
							</small>
						  </div>

						  <div class="modal-footer justify-content-center">
							<button type="button"
									class="btn btn-secondary"
									data-bs-dismiss="modal">
								❌ Batal
							</button>

							<a href="kwitansi_hapus_semua.php"
							   class="btn btn-danger">
								🗑️ Ya, Hapus
							</a>
						  </div>

						</div>
					  </div>
					</div>
                    </tbody>
                </table>
				
				
                </div>
            </form>

        </div>
    </div>
</div>

<div class="modal fade" id="modalImport" tabindex="-1">
  <div class="modal-dialog modal-dialog-centered">
    <div class="modal-content shadow-lg border-0">

      <div class="modal-header bg-success text-white">
        <h5 class="modal-title">✅ Import Selesai</h5>
        <button type="button" class="btn-close btn-close-white"
                data-bs-dismiss="modal"></button>
      </div>

      <div class="modal-body text-center">
        <p class="mb-2">
          <strong>Berhasil:</strong>
          <span id="importBerhasil"></span> data
        </p>
        <p class="mb-0">
          <strong>Gagal:</strong>
          <span id="importGagal"></span> data
        </p>
      </div>

      <div class="modal-footer justify-content-center">
        <button type="button" class="btn btn-secondary"
                data-bs-dismiss="modal">OK</button>
      </div>

    </div>
  </div>
</div>
<?php if (isset($_SESSION['import_result'])): ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('importBerhasil').innerText =
        "<?= $_SESSION['import_result']['berhasil'] ?>";
    document.getElementById('importGagal').innerText =
        "<?= $_SESSION['import_result']['gagal'] ?>";

    const modal = new bootstrap.Modal(
        document.getElementById('modalImport')
    );
    modal.show();
});
</script>
<?php unset($_SESSION['import_result']); endif; ?>

<script>
document.getElementById('checkAll').addEventListener('click', function(){
    document.querySelectorAll('.cek').forEach(cb => cb.checked = this.checked);
});
</script>

</body>
</html>

