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

use Dompdf\Dompdf;
use Dompdf\Options;

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

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

/* ================= PARAM BULAN ================= */
$bulan_input = $_GET['bulan'] ?? date('m-Y');
list($bulan, $tahun) = explode('-', $bulan_input);
$bulan = str_pad($bulan, 2, '0', STR_PAD_LEFT);

/* ================= NPSN ================= */
$npsn = ($role === 'admin') ? ($_GET['npsn'] ?? '') : $npsn_login;
if ($npsn == '') {
    die("Sekolah belum dipilih");
}

/* ================= AMBIL ID OPNAME ================= */
$qid = mysqli_query($conn,"
    SELECT id_opname
    FROM stok_opname
    WHERE npsn='$npsn'
      AND bulan='$bulan'
      AND tahun='$tahun'
    ORDER BY id_opname DESC
    LIMIT 1
");

if (mysqli_num_rows($qid) == 0) {
    die("Data stok opname belum ada");
}
$id_opname = mysqli_fetch_assoc($qid)['id_opname'];

/* ================= NAMA SEKOLAH ================= */
$qSek = mysqli_query($conn,"SELECT nama_sekolah FROM sekolah WHERE npsn='$npsn' LIMIT 1");
$nama_sekolah = mysqli_fetch_assoc($qSek)['nama_sekolah'] ?? 'SEKOLAH';

/* ================= DATA PEJABAT ================= */
$qPejabat = mysqli_query($conn,"
    SELECT kepala_sekolah, nip_kepsek, bendahara, nip_bendahara
    FROM sekolah
    WHERE npsn='$npsn'
    LIMIT 1
");
$pejabat = mysqli_fetch_assoc($qPejabat);

$kepsek         = $pejabat['kepala_sekolah'] ?? '';
$nip_kepsek    = $pejabat['nip_kepsek'] ?? '';
$bendahara     = $pejabat['bendahara'] ?? '';
$nip_bendahara = $pejabat['nip_bendahara'] ?? '';

/* ================= DETAIL ================= */
$sql = "
SELECT
    d.kode_rekening,
    rm.nama_rekening,
    d.nama_barang,
    d.satuan,
    d.awal_qty,
    d.awal_jumlah,
    d.masuk_qty,
    d.masuk_jumlah,
    d.keluar_qty,
    d.keluar_jumlah,
    d.akhir_qty,
    d.akhir_harga,
    d.akhir_jumlah
FROM stok_opname_detail d
LEFT JOIN rekening_map rm ON rm.kode_rekening = d.kode_rekening
WHERE d.id_opname = '$id_opname'
ORDER BY d.kode_rekening, d.nama_barang
";

$q = mysqli_query($conn,$sql);
if(mysqli_num_rows($q)==0){
    die("Detail stok opname kosong");
}

/* ================= GROUPING & TOTAL ================= */
$data = [];
$grand = ['awal'=>0,'masuk'=>0,'keluar'=>0,'akhir'=>0];

while($r = mysqli_fetch_assoc($q)){
    $kode = $r['kode_rekening'] ?? '-';

    if(!isset($data[$kode])){
        $data[$kode] = [
            'nama' => $r['nama_rekening'] ?? '',
            'item' => [],
            'tot'  => ['awal'=>0,'masuk'=>0,'keluar'=>0,'akhir'=>0]
        ];
    }

    $data[$kode]['item'][] = $r;

    $data[$kode]['tot']['awal']   += $r['awal_jumlah'];
    $data[$kode]['tot']['masuk']  += $r['masuk_jumlah'];
    $data[$kode]['tot']['keluar'] += $r['keluar_jumlah'];
    $data[$kode]['tot']['akhir']  += $r['akhir_jumlah'];

    $grand['awal']   += $r['awal_jumlah'];
    $grand['masuk']  += $r['masuk_jumlah'];
    $grand['keluar'] += $r['keluar_jumlah'];
    $grand['akhir']  += $r['akhir_jumlah'];
}

/* ================= BULAN ================= */
$bulan_nama = [
    1=>'Januari',2=>'Februari',3=>'Maret',4=>'April',5=>'Mei',6=>'Juni',
    7=>'Juli',8=>'Agustus',9=>'September',10=>'Oktober',11=>'November',12=>'Desember'
][(int)$bulan];

/* ================= HTML ================= */
$html = "
<style>
body{font-family:DejaVu Sans;font-size:9px}
table{border-collapse:collapse;width:100%}
th,td{border:1px solid #000;padding:3px}
th{text-align:center;background:#eee}
.induk{background:#d9edf7;font-weight:bold}
.subtotal{background:#f5f5f5;font-weight:bold}
.totalakhir{background:#c9e2b3;font-weight:bold}
.center{text-align:center}
.right{text-align:right}
</style>

<h2 align='center'>REKAPITULASI STOK OPNAME PERSEDIAAN</h2>
<p align='center'><b>Bulan $bulan_nama $tahun</b></p>
<p><b>Satuan Pendidikan :</b> $nama_sekolah</p>

<table>
<thead>
<tr>
<th rowspan='2'>No</th>
<th rowspan='2'>Uraian</th>
<th colspan='2'>Saldo Awal</th>
<th colspan='2'>Masuk</th>
<th colspan='2'>Digunakan</th>
<th colspan='3'>Saldo Akhir</th>
</tr>
<tr>
<th>Qty</th><th>Jumlah</th>
<th>Qty</th><th>Jumlah</th>
<th>Qty</th><th>Jumlah</th>
<th>Qty</th><th>Harga</th><th>Jumlah</th>
</tr>
</thead>
<tbody>
";

$no=1;
foreach($data as $kode=>$g){
    $html .= "
    <tr class='induk'>
        <td colspan='11'>$kode | {$g['nama']}</td>
    </tr>";

    foreach($g['item'] as $d){
        $html .= "
        <tr>
            <td class='center'>$no</td>
            <td>{$d['nama_barang']}</td>
            <td class='center'>{$d['awal_qty']}</td>
            <td class='right'>".number_format($d['awal_jumlah'],0,',','.')."</td>
            <td class='center'>{$d['masuk_qty']}</td>
            <td class='right'>".number_format($d['masuk_jumlah'],0,',','.')."</td>
            <td class='center'>{$d['keluar_qty']}</td>
            <td class='right'>".number_format($d['keluar_jumlah'],0,',','.')."</td>
            <td class='center'>{$d['akhir_qty']}</td>
            <td class='right'>".number_format($d['akhir_harga'],0,',','.')."</td>
            <td class='right'>".number_format($d['akhir_jumlah'],0,',','.')."</td>
        </tr>";
        $no++;
    }

    $t = $g['tot'];
    $html .= "
    <tr class='subtotal'>
        <td colspan='3' class='center'>Subtotal</td>
        <td class='right'>".number_format($t['awal'],0,',','.')."</td>
        <td></td>
        <td class='right'>".number_format($t['masuk'],0,',','.')."</td>
        <td></td>
        <td class='right'>".number_format($t['keluar'],0,',','.')."</td>
        <td colspan='2'></td>
        <td class='right'>".number_format($t['akhir'],0,',','.')."</td>
    </tr>";
}

/* ===== TOTAL AKHIR ===== */
$html .= "
<tr class='totalakhir'>
    <td colspan='3' class='center'>TOTAL AKHIR STOK OPNAME</td>
    <td class='right'>".number_format($grand['awal'],0,',','.')."</td>
    <td></td>
    <td class='right'>".number_format($grand['masuk'],0,',','.')."</td>
    <td></td>
    <td class='right'>".number_format($grand['keluar'],0,',','.')."</td>
    <td colspan='2'></td>
    <td class='right'>".number_format($grand['akhir'],0,',','.')."</td>
</tr>
</tbody>
</table>

<br><br>

<table width='100%' style='border:none'>
<tr>
<td width='50%' align='center'>
Mengetahui,<br>Kepala Sekolah<br><br><br><br>
<b>".strtoupper($kepsek)."</b><br>
NIP. $nip_kepsek
</td>

<td width='50%' align='center'>
Bendahara<br><br><br><br>
<b>".strtoupper($bendahara)."</b><br>
NIP. $nip_bendahara
</td>
</tr>
</table>
";

/* ================= PDF ================= */
$options = new Options();
$options->set('defaultFont','DejaVu Sans');

$pdf = new Dompdf($options);
$pdf->setPaper('A4','landscape');
$pdf->loadHtml($html);
$pdf->render();

mysqli_query($conn,"UPDATE stok_opname SET locked=1 WHERE id_opname='$id_opname'");

ob_end_clean();
$pdf->stream("stok_opname_{$npsn}_{$bulan}_{$tahun}.pdf", ["Attachment"=>false]);
exit;
