<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/config/config.php';

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

$role       = $_SESSION['role'] ?? 'sekolah';
$npsn_login = $_SESSION['npsn'] ?? '';

$bulan = $_GET['bulan'] ?? date('m');
$tahun = $_GET['tahun'] ?? date('Y');
$npsn_filter = $_GET['npsn'] ?? '';

/* =========================
   DATA SEKOLAH (ADMIN)
========================= */
$sekolah = [];
if ($role === 'admin') {
    $qs = mysqli_query($conn, "SELECT npsn, nama_sekolah FROM sekolah ORDER BY nama_sekolah");
    while ($s = mysqli_fetch_assoc($qs)) {
        $sekolah[] = $s;
    }
}

/* =========================
   HITUNG DARI KWITANSI (FIX)
========================= */
$sql = "
SELECT
    k.npsn,
    s.nama_sekolah,

    COALESCE(SUM(CASE WHEN UPPER(TRIM(rm.kelompok))='BHP'  THEN k.pengeluaran END),0) AS bhp,
    COALESCE(SUM(CASE WHEN UPPER(TRIM(rm.kelompok))='BJJ'  THEN k.pengeluaran END),0) AS bjj,
    COALESCE(SUM(CASE WHEN UPPER(TRIM(rm.kelompok))='BMM'  THEN k.pengeluaran END),0) AS bmm,
    COALESCE(SUM(CASE WHEN UPPER(TRIM(rm.kelompok))='BMAL' THEN k.pengeluaran END),0) AS bmal

FROM kwitansi k
JOIN rekening_map rm 
    ON TRIM(rm.kode_rekening)=TRIM(k.kode_rekening)
LEFT JOIN sekolah s 
    ON s.npsn=k.npsn
WHERE MONTH(k.tanggal)='$bulan'
  AND YEAR(k.tanggal)='$tahun'
";

if ($role !== 'admin') {
    $sql .= " AND k.npsn='$npsn_login'";
} elseif ($npsn_filter !== '') {
    $sql .= " AND k.npsn='$npsn_filter'";
}

$sql .= " GROUP BY k.npsn, s.nama_sekolah ORDER BY s.nama_sekolah";

$q = mysqli_query($conn, $sql);

/* =========================
   SIMPAN & KIRIM (SEKOLAH)
========================= */
if ($role !== 'admin' && isset($_POST['simpan_kirim']) && isset($_POST['rekap'])) {

    foreach ($_POST['rekap'] as $npsn => $row) {

        $bhp  = (float)($row['bhp']  ?? 0);
        $bjj  = (float)($row['bjj']  ?? 0);
        $bmm  = (float)($row['bmm']  ?? 0);
        $bmal = (float)($row['bmal'] ?? 0);

        $total = $bhp + $bjj + $bmm + $bmal;

        mysqli_query($conn, "
            INSERT INTO rekap_bku
                (npsn, bulan, tahun, bhp, bjj, bmm, bmal, status)
            VALUES
                ('$npsn','$bulan','$tahun','$bhp','$bjj','$bmm','$bmal','menunggu_verifikasi')
            ON DUPLICATE KEY UPDATE
                bhp='$bhp',
                bjj='$bjj',
                bmm='$bmm',
                bmal='$bmal',
                status='menunggu_verifikasi'
        ");

        mysqli_query($conn, "
            UPDATE upload_laporan SET
                total_bku='$total',
                status_verifikasi='menunggu_verifikasi'
            WHERE npsn='$npsn'
              AND bulan='$bulan'
              AND tahun='$tahun'
        ");
    }

    echo "<script>
        alert('Rekap BKU berhasil dikirim ke Admin');
        location='rekap_bku_proses.php?bulan=$bulan&tahun=$tahun';
    </script>";
    exit;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Rekap BKU</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
.table{font-size:13px;white-space:nowrap}
</style>
</head>

<body class="bg-light">
<div class="container-fluid mt-4">

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

<div class="card shadow-sm">
<div class="card-body">

<!-- FILTER -->
<form method="get" class="row g-2 mb-3">
<div class="col-md-2">
<select name="bulan" class="form-select">
<?php for($i=1;$i<=12;$i++):
$m=str_pad($i,2,'0',STR_PAD_LEFT); ?>
<option value="<?= $m ?>" <?= $bulan==$m?'selected':'' ?>>
<?= date('F', mktime(0,0,0,$i,1)) ?>
</option>
<?php endfor; ?>
</select>
</div>

<div class="col-md-2">
<select name="tahun" class="form-select">
<?php for($t=date('Y')-3;$t<=date('Y')+1;$t++): ?>
<option value="<?= $t ?>" <?= $tahun==$t?'selected':'' ?>><?= $t ?></option>
<?php endfor; ?>
</select>
</div>

<?php if($role==='admin'): ?>
<div class="col-md-4">
<select name="npsn" class="form-select">
<option value="">Semua Sekolah</option>
<?php foreach($sekolah as $s): ?>
<option value="<?= $s['npsn'] ?>" <?= $npsn_filter==$s['npsn']?'selected':'' ?>>
<?= $s['npsn'] ?> - <?= $s['nama_sekolah'] ?>
</option>
<?php endforeach; ?>
</select>
</div>
<?php endif; ?>

<div class="col-md-2">
<button class="btn btn-primary">Tampilkan</button>
</div>
</form>

<!-- TABEL -->
<form method="post">
<div class="table-responsive">
<table class="table table-bordered table-sm">
<thead class="table-secondary text-center">
<tr>
<th>No</th>
<th>NPSN</th>
<th>Nama Sekolah</th>
<th>BHP</th>
<th>BJJ</th>
<th>BMM</th>
<th>BMAL</th>
<th class="bg-success text-white">TOTAL</th>
</tr>
</thead>
<tbody>
<?php
$no=1;
while($d=mysqli_fetch_assoc($q)):
$total = $d['bhp']+$d['bjj']+$d['bmm']+$d['bmal'];
?>
<tr>
<td class="text-center"><?= $no++ ?></td>
<td><?= $d['npsn'] ?></td>
<td><?= $d['nama_sekolah'] ?></td>

<?php foreach(['bhp','bjj','bmm','bmal'] as $k): ?>
<td class="text-end">
<?= number_format($d[$k],0,',','.') ?>
<input type="hidden" name="rekap[<?= $d['npsn'] ?>][<?= $k ?>]" value="<?= $d[$k] ?>">
</td>
<?php endforeach; ?>

<td class="text-end fw-bold bg-success text-white">
<?= number_format($total,0,',','.') ?>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>

<?php if ($role !== 'admin'): ?>
<button name="simpan_kirim" class="btn btn-primary">
💾 Simpan & Kirim ke Admin
</button>
<?php endif; ?>

</form>

</div>
</div>
</div>
</body>
</html>
