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

if (!isset($_SESSION['login'])) die("Akses ditolak");

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

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

if ($role !== 'admin') {
    $npsn = $npsn_login;
}

/* ================= BULAN SEBELUMNYA ================= */
$prev_bulan = (int)$bulan - 1;
$prev_tahun = $tahun;
if ($prev_bulan == 0) {
    $prev_bulan = 12;
    $prev_tahun--;
}

/* ================= QUERY ================= */
$sql = "
SELECT
    rm.kode_rekening,
    rm.nama_rekening,
    k.uraian,
    k.satuanb,

    /* SALDO AWAL */
    SUM(
        CASE 
            WHEN (YEAR(k.tanggal) < '$tahun')
              OR (YEAR(k.tanggal) = '$tahun' AND MONTH(k.tanggal) < '$bulan')
            THEN k.jumb - k.pengeluaran
            ELSE 0
        END
    ) AS saldo_awal_qty,

    /* MASUK BULAN INI */
    SUM(
        CASE 
            WHEN MONTH(k.tanggal) = '$bulan' AND YEAR(k.tanggal) = '$tahun'
            THEN k.jumb
            ELSE 0
        END
    ) AS masuk_qty,

    /* DIGUNAKAN BULAN INI */
    SUM(
        CASE 
            WHEN MONTH(k.tanggal) = '$bulan' AND YEAR(k.tanggal) = '$tahun'
            THEN k.pengeluaran
            ELSE 0
        END
    ) AS keluar_qty

FROM kwitansi k
JOIN rekening_map rm ON rm.kode_rekening = k.kode_rekening
WHERE rm.kelompok = 'BHP'
";

if ($npsn != '') {
    $sql .= " AND k.npsn = '$npsn'";
}

$sql .= "
GROUP BY rm.kode_rekening, k.uraian, k.satuanb
ORDER BY rm.kode_rekening, k.uraian
";

$q = mysqli_query($conn, $sql);
if (!$q) die(mysqli_error($conn));

$data = [];
while ($r = mysqli_fetch_assoc($q)) {
    $data[$r['kode_rekening']]['nama'] = $r['nama_rekening'];
    $data[$r['kode_rekening']]['item'][] = $r;
}

/* ================= NAMA BULAN ================= */
$nama_bulan = [
    '01'=>'Januari','02'=>'Februari','03'=>'Maret','04'=>'April',
    '05'=>'Mei','06'=>'Juni','07'=>'Juli','08'=>'Agustus',
    '09'=>'September','10'=>'Oktober','11'=>'November','12'=>'Desember'
];
?>
<!DOCTYPE html>
<html>
<head>
<title>Stok Opname BHP</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<style>
body{font-size:12px}
.table th,.table td{padding:4px}
.bg-induk{background:#e9f2ff;font-weight:600}
@media print{.no-print{display:none}}
</style>
</head>
<body>

<div class="container mt-3">

<!-- FILTER -->
<div class="no-print mb-3">
<form class="row g-2">
    <div class="col-md-3">
        <select name="bulan" class="form-select form-select-sm">
            <?php foreach($nama_bulan as $k=>$v): ?>
            <option value="<?= $k ?>" <?= $k==$bulan?'selected':'' ?>><?= $v ?></option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="col-md-2">
        <select name="tahun" class="form-select form-select-sm">
            <?php for($t=date('Y')-5;$t<=date('Y');$t++): ?>
            <option value="<?= $t ?>" <?= $t==$tahun?'selected':'' ?>><?= $t ?></option>
            <?php endfor; ?>
        </select>
    </div>

    <?php if($role==='admin'): ?>
    <div class="col-md-3">
        <input type="text" name="npsn" value="<?= $npsn ?>"
               class="form-control form-control-sm" placeholder="NPSN">
    </div>
    <?php endif; ?>

    <div class="col-md-2">
        <button class="btn btn-primary btn-sm">Tampilkan</button>
    </div>
    <div class="col-md-2">
        <button onclick="window.print()" type="button"
                class="btn btn-success btn-sm">🖨 Cetak</button>
    </div>
</form>
</div>

<h6 class="text-center fw-bold">
STOK OPNAME BHP<br>
Bulan <?= $nama_bulan[$bulan] ?> Tahun <?= $tahun ?>
</h6>

<table class="table table-bordered table-sm mt-3">
<thead class="text-center table-light">
<tr>
    <th rowspan="2">No</th>
    <th rowspan="2">Uraian</th>
    <th colspan="3">Saldo Awal</th>
    <th colspan="1">Masuk</th>
    <th colspan="1">Digunakan</th>
    <th colspan="2">Saldo Akhir</th>
</tr>
<tr>
    <th>Qty</th><th></th><th></th>
    <th>Qty</th>
    <th>Qty</th>
    <th>Qty</th><th></th>
</tr>
</thead>
<tbody>
<?php
$no=1;
foreach($data as $kode=>$g):
?>
<tr class="bg-induk">
    <td colspan="9"><?= $kode ?> | <?= $g['nama'] ?></td>
</tr>
<?php foreach($g['item'] as $d):
$akhir_qty = $d['saldo_awal_qty'] + $d['masuk_qty'] - $d['keluar_qty'];
?>
<tr>
    <td class="text-center"><?= $no++ ?></td>
    <td><?= $d['uraian'] ?></td>
    <td class="text-center"><?= $d['saldo_awal_qty'] ?></td>
    <td></td><td></td>
    <td class="text-center"><?= $d['masuk_qty'] ?></td>
    <td class="text-center"><?= $d['keluar_qty'] ?></td>
    <td class="text-center"><?= $akhir_qty ?></td>
    <td></td>
</tr>
<?php endforeach; endforeach; ?>
</tbody>
</table>

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