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

/* =====================
   PROTEKSI ADMIN
===================== */
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    die("⛔ Akses ditolak");
}

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) die("ID tidak valid");

/* =====================
   AMBIL DATA LAPORAN
===================== */
$stmt = $conn->prepare("SELECT * FROM upload_laporan WHERE id_laporan=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$data = $stmt->get_result()->fetch_assoc();

if (!$data) die("Data laporan tidak ditemukan");

/* KUNCI JIKA SUDAH DISETUJUI */
if ($data['status_verifikasi'] === 'disetujui') {
    die("⛔ Laporan sudah disetujui dan terkunci");
}

$npsn        = $data['npsn'];
$bulan_teks = $data['bulan'];
$tahun       = $data['tahun'];
$file_laporan = "upload/" . $data['upload_laporan'];

/* =====================
   KONVERSI BULAN
===================== */
$mapBulan = [
    'Januari'=>'01','Februari'=>'02','Maret'=>'03','April'=>'04',
    'Mei'=>'05','Juni'=>'06','Juli'=>'07','Agustus'=>'08',
    'September'=>'09','Oktober'=>'10','November'=>'11','Desember'=>'12'
];
$bulan_fix = $mapBulan[$bulan_teks] ?? null;

/* =====================
   REKENING KORAN
===================== */
$rekening_koran = null;

/* PRIORITAS 1 → upload_laporan */
if (!empty($data['upload_rekening_koran'])) {
    if (file_exists("upload/rekening_koran/".$data['upload_rekening_koran'])) {
        $rekening_koran = "upload/rekening_koran/".$data['upload_rekening_koran'];
    } elseif (file_exists("upload/".$data['upload_rekening_koran'])) {
        $rekening_koran = "upload/".$data['upload_rekening_koran'];
    }
}

/* PRIORITAS 2 → tabel rekening_koran */
if (!$rekening_koran && $bulan_fix) {
    $stmt = $conn->prepare("
        SELECT upload_file
        FROM rekening_koran
        WHERE npsn=? AND tahun=? AND bulan=?
        ORDER BY id_koran DESC
        LIMIT 1
    ");
    $stmt->bind_param("sss", $npsn, $tahun, $bulan_fix);
    $stmt->execute();
    $rk = $stmt->get_result();

    if ($rk->num_rows) {
        $f = $rk->fetch_assoc()['upload_file'];
        if (file_exists("upload/rekening_koran/$f")) {
            $rekening_koran = "upload/rekening_koran/$f";
        } elseif (file_exists("upload/$f")) {
            $rekening_koran = "upload/$f";
        }
    }
}

/* =====================
   REKAP BKU (LENGKAP)
===================== */
$bhp = $bjj = $bmm = $bmal = 0;
$total_bku = $total_kib = 0;

if ($bulan_fix) {
    $stmt = $conn->prepare("
        SELECT bhp, bjj, bmm, bmal
        FROM rekap_bku
        WHERE npsn=? AND bulan=? AND tahun=?
        LIMIT 1
    ");
    $stmt->bind_param("sss", $npsn, $bulan_fix, $tahun);
    $stmt->execute();
    $r = $stmt->get_result();

    if ($r->num_rows) {
        $x    = $r->fetch_assoc();
        $bhp  = (float)$x['bhp'];
        $bjj  = (float)$x['bjj'];
        $bmm  = (float)$x['bmm'];
        $bmal = (float)$x['bmal'];

        $total_bku = $bhp + $bjj + $bmm + $bmal;
        $total_kib = $bmm + $bmal;
    }
}

/* =====================
   SIMPAN VERIFIKASI
===================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $status  = isset($_POST['setujui']) ? 'disetujui' : 'ditolak';
    $catatan = trim($_POST['catatan_admin']);
    $file_rekom = $data['file_rekomendasi'];

    if ($status === 'ditolak' && $catatan === '') {
        echo "<script>alert('Catatan wajib diisi!');history.back();</script>";
        exit;
    }

    /* UPLOAD FILE REKOMENDASI */
    if ($status === 'disetujui' && !empty($_FILES['file_rekom']['name'])) {

        $ext = strtolower(pathinfo($_FILES['file_rekom']['name'], PATHINFO_EXTENSION));
        if ($ext !== 'pdf') {
            echo "<script>alert('File rekomendasi harus PDF');history.back();</script>";
            exit;
        }

        $dir = "upload/rekomendasi/";
        if (!is_dir($dir)) mkdir($dir, 0777, true);

        if (!empty($file_rekom) && file_exists($dir.$file_rekom)) {
            unlink($dir.$file_rekom);
        }

        $file_rekom = "rekom_{$npsn}_{$id}_" . time() . ".pdf";
        move_uploaded_file($_FILES['file_rekom']['tmp_name'], $dir.$file_rekom);
    }

    if ($status === 'disetujui') {
        $catatan = null;
    }

    $stmt = $conn->prepare("
        UPDATE upload_laporan SET
            status_verifikasi=?,
            catatan_admin=?,
            file_rekomendasi=?,
            tgl_verifikasi=NOW()
        WHERE id_laporan=?
    ");
    $stmt->bind_param("sssi", $status, $catatan, $file_rekom, $id);
    $stmt->execute();

    header("Location:list_laporan.php");
    exit;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Verifikasi Laporan</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body class="bg-light">
<div class="container mt-4">
<div class="card shadow-sm">

<div class="card-header bg-success text-white">
    <h5 class="mb-0">🔍 Verifikasi Laporan BOS</h5>
</div>

<div class="card-body">
<table class="table table-bordered align-middle text-center">

<tr>
    <th width="220" class="text-start">NPSN</th>
    <td colspan="5" class="text-start"><?= htmlspecialchars($npsn) ?></td>
</tr>

<tr>
    <th class="text-start">Nama Sekolah</th>
    <td colspan="5" class="text-start"><?= htmlspecialchars($data['nama_sekolah']) ?></td>
</tr>

<tr>
    <th class="text-start">Bulan / Tahun</th>
    <td colspan="5" class="text-start"><?= $bulan_teks ?> <?= $tahun ?></td>
</tr>

<tr>
    <th class="text-start">File Laporan</th>
    <td colspan="5" class="text-start">
        <a href="<?= $file_laporan ?>" target="_blank" class="btn btn-primary btn-sm">📄 Lihat Laporan</a>
        <?php if($rekening_koran): ?>
            <a href="<?= $rekening_koran ?>" target="_blank" class="btn btn-info btn-sm">🏦 Rekening Koran</a>
        <?php endif; ?>
    </td>
</tr>

<!-- HEADER REKAP -->
<tr class="fw-bold bg-light">
    <th class="text-start">Rekap Belanja</th>
    <th>BHP</th>
    <th>BJJ</th>
    <th>BMM</th>
    <th>BMAL</th>
    <th>BKU</th>
</tr>

<!-- ISI REKAP -->
<tr class="fw-bold">
    <td class="text-start">Total (Rp)</td>

    <td style="background:#e2f0d9">
        <?= number_format($bhp,0,',','.') ?>
    </td>

    <td style="background:#ddebf7">
        <?= number_format($bjj,0,',','.') ?>
    </td>

    <td style="background:#fce4d6">
        <?= number_format($bmm,0,',','.') ?>
    </td>

    <td style="background:#ede7f6">
        <?= number_format($bmal,0,',','.') ?>
    </td>

    <td style="background:#fff2cc">
        <?= number_format($total_bku,0,',','.') ?>
    </td>
</tr>

</table>

<form method="post" enctype="multipart/form-data">
<div class="mb-3">
    <label class="fw-bold">Catatan Admin (wajib jika ditolak)</label>
    <textarea name="catatan_admin" class="form-control" rows="3"></textarea>
</div>

<div class="mb-3">
    <label class="fw-bold">Upload File Rekomendasi (PDF)</label>
    <input type="file" name="file_rekom" class="form-control" accept="application/pdf">
</div>

<div class="d-flex gap-2">
    <button name="setujui" class="btn btn-success">✅ Setujui</button>
    <button name="tolak" class="btn btn-danger" onclick="return confirm('Tolak laporan ini?')">❌ Tolak</button>
    <a href="list_laporan.php" class="btn btn-secondary">← Kembali</a>
</div>
</form>

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