<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/config/config.php';

if (!isset($_SESSION['id_user'])) {
    header("Location: index.php");
    exit;
}

$nama_lengkap = $_SESSION['nama_lengkap'] ?? 'User';
$role = $_SESSION['role'] ?? '-';
$npsn = $_SESSION['npsn'] ?? null;
?>
<?php
// ===============================
// AMBIL NAMA SEKOLAH UNTUK NAVBAR
// ===============================
$nama_sekolah = 'Nama Sekolah';

if (!empty($npsn)) {
    $qSekolah = mysqli_query($conn, "
        SELECT nama_sekolah 
        FROM sekolah 
        WHERE npsn = '$npsn'
        LIMIT 1
    ");
    if ($qSekolah && mysqli_num_rows($qSekolah) > 0) {
        $rSekolah = mysqli_fetch_assoc($qSekolah);
        $nama_sekolah = $rSekolah['nama_sekolah'];
    }
}
?>

<?php
require_once __DIR__ . '/config/config.php';

/* =====================
   TOTAL ANGGARAN
===================== */
if ($role === 'admin') {
    $qAnggaran = mysqli_query($conn,"
        SELECT SUM(total) AS total_anggaran
        FROM penganggaran
    ");
} else {
    $qAnggaran = mysqli_query($conn,"
        SELECT SUM(total) AS total_anggaran
        FROM penganggaran
        WHERE npsn = '$npsn'
    ");
}
$rAnggaran = mysqli_fetch_assoc($qAnggaran);
$total_anggaran = $rAnggaran['total_anggaran'] ?? 0;

/* =====================
   TOTAL PENGELUARAN
===================== */
if ($role === 'admin') {
    $qPengeluaran = mysqli_query($conn,"
        SELECT SUM(pengeluaran) AS total_pengeluaran
        FROM kwitansi
    ");
} else {
    $qPengeluaran = mysqli_query($conn,"
        SELECT SUM(pengeluaran) AS total_pengeluaran
        FROM kwitansi
        WHERE npsn = '$npsn'
    ");
}
$rPengeluaran = mysqli_fetch_assoc($qPengeluaran);
$total_pengeluaran = $rPengeluaran['total_pengeluaran'] ?? 0;

/* =====================
   SALDO BANK (OPSIONAL)
===================== */
if ($role === 'admin') {
    $qBank = mysqli_query($conn,"
        SELECT SUM(saldo_akhir) AS saldo_bank
        FROM rekening_koran
    ");
} else {
    $qBank = mysqli_query($conn,"
        SELECT SUM(saldo_akhir) AS saldo_bank
        FROM rekening_koran
        WHERE npsn = '$npsn'
    ");
}
$rBank = mysqli_fetch_assoc($qBank);
$saldo_bank = $rBank['saldo_bank'] ?? 0;

/* =====================
   SALDO TUNAI
===================== */
$saldo_tunai = $total_anggaran - $total_pengeluaran - $saldo_bank;

/* =====================
   REKAP PERJENIS BELANJA
===================== */


if ($role === 'admin') {
    $qTotal = mysqli_query($conn, "
        SELECT
            SUM(honor) AS total_honor,
            SUM(habis_pakai) AS total_habis_pakai,
            SUM(barjas) AS total_barjas,
            SUM(modal_mesin + modal_lainnya) AS total_modal
        FROM penganggaran
    ");
} else {
    $qTotal = mysqli_query($conn, "
        SELECT
            SUM(honor) AS total_honor,
            SUM(habis_pakai) AS total_habis_pakai,
            SUM(barjas) AS total_barjas,
            SUM(modal_mesin + modal_lainnya) AS total_modal
        FROM penganggaran
        WHERE npsn = '$npsn'
    ");
}

$total = mysqli_fetch_assoc($qTotal);
$total_honor       = $total['total_honor'] ?? 0;
$total_habis_pakai = $total['total_habis_pakai'] ?? 0;
$total_barjas      = $total['total_barjas'] ?? 0;
$total_modal       = $total['total_modal'] ?? 0;


$notif = null;

/* =========================
   PRIORITAS 1: MASIH MENUNGGU
========================= */
$qMenunggu = mysqli_query($conn,"
    SELECT bulan, tahun, status_verifikasi, catatan_admin
    FROM upload_laporan
    WHERE npsn = '".mysqli_real_escape_string($conn,$npsn)."'
      AND LOWER(status_verifikasi) = 'menunggu'
    ORDER BY tgl_lapor DESC
    LIMIT 1
");

if($qMenunggu && mysqli_num_rows($qMenunggu) > 0){

    $notif = mysqli_fetch_assoc($qMenunggu);
    $notif['pesan_custom'] = 
        "📌 Laporan masih diajukan kembali, mohon tunggu verifikasi admin.";

}else{

    /* =========================
       PRIORITAS 2: DITOLAK
    ========================= */
    $qTolak = mysqli_query($conn,"
        SELECT bulan, tahun, status_verifikasi, catatan_admin
        FROM upload_laporan
        WHERE npsn = '".mysqli_real_escape_string($conn,$npsn)."'
          AND LOWER(status_verifikasi) = 'ditolak'
        ORDER BY tgl_verifikasi DESC
        LIMIT 1
    ");

    if($qTolak && mysqli_num_rows($qTolak) > 0){

        $notif = mysqli_fetch_assoc($qTolak);

    }else{

        /* =========================
           PRIORITAS 3: DISETUJUI
        ========================= */
        $qSetuju = mysqli_query($conn,"
            SELECT bulan, tahun, status_verifikasi, catatan_admin
            FROM upload_laporan
            WHERE npsn = '".mysqli_real_escape_string($conn,$npsn)."'
              AND LOWER(status_verifikasi) = 'disetujui'
            ORDER BY tgl_verifikasi DESC
            LIMIT 1
        ");

        if($qSetuju){
            $notif = mysqli_fetch_assoc($qSetuju);
        }
    }
}

?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Dashboard e-BOS</title>
    <!-- Favicon (logo di tab browser) -->
    <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 rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <link rel="icon" href="assets/images/logomu.ico">
    <style>
        body {
            margin: 0;
            overflow-x: hidden;
            background-color: #f4f6f9;
        }

        /* NAVBAR */
        .navbar {
            height: 56px;
        }

        /* SIDEBAR */
        .sidebar {
            position: fixed;
            top: 56px;
            left: 0;
            width: 240px;
            height: calc(100vh - 56px);
            background: #0d6efd; /* biru seperti app guru */
            color: #fff;
            overflow-y: auto;
        }

        .sidebar .title {
            font-weight: bold;
            padding: 15px;
            font-size: 15px;
            background: #0b5ed7;
            text-align: center;
        }

        .sidebar ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar ul li a {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 12px 18px;
            color: #eaeaea;
            text-decoration: none;
            font-size: 14px;
            transition: 0.2s;
        }

        .sidebar ul li a:hover {
            background: rgba(255,255,255,0.15);
            color: #fff;
        }

		.sidebar ul li a.active {
			background: transparent;
			color: #ffffff;
			font-weight: 700;
		}

       /* CONTENT */
	
.content {
    margin-left: 240px;
    margin-top: 66px;        /* navbar + jarak aman */
    padding: 20px 25px;
}

.dashboard-divider {
    border-bottom: 1px solid #dee2e6; /* garis tipis abu bootstrap */
    margin-top: 10px;
    margin-bottom: 10px;
}
/* HEADER DASHBOARD – RAPAT */
.dashboard-header h4 {
    margin-bottom: 2px;   /* rapatkan judul ke subjudul */
    line-height: 1.2;
}

.dashboard-header p {
    margin-bottom: 0;    /* hilangkan jarak bawah */
    line-height: 1.3;
}
.sidebar ul {
    list-style: none;
    padding: 0;
    margin: 0;
}

.sidebar ul li {
    margin: 2px 0; /* 🔽 jarak antar menu dirapatkan */
}

.sidebar ul li a {
    display: block;
    padding: 8px 12px; /* 🔽 sebelumnya biasanya 12–15px */
    font-size: 14px;
    line-height: 1.3;
    color: #fff;
    text-decoration: none;
    border-radius: 6px;
}

.sidebar ul li a:hover {
    background: rgba(255,255,255,0.15);
}

.sidebar ul li a.active {
    background: #0d6efd;
}
/* =========================
   DASHBOARD CARD RAPAT & LURUS
========================= */
.dashboard-cards {
    margin-left: -6px;   /* 🔽 tarik sedikit ke kiri */
    margin-right: -6px;  /* 🔽 samakan kanan */
}

.dashboard-cards .card {
    height: 100%;
    border-radius: 10px;
}

.dashboard-cards .card-body {
    min-height: 95px; /* 🔒 samakan tinggi semua card */
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 14px;
}

.dashboard-cards h6 {
    font-size: 14px;
    margin-bottom: 6px;
    white-space: nowrap;
}

.dashboard-cards h4 {
    font-weight: 700;
    margin-bottom: 0;
}
/* =========================
   HOVER EFFECT DASHBOARD CARD
========================= */
.dashboard-cards .card {
    transition: 
        transform 0.25s ease,
        box-shadow 0.25s ease,
        border-color 0.25s ease;
    border: 1px solid #e5e7eb;
    cursor: pointer;
}

.dashboard-cards .card::before {
    content: "";
    position: absolute;
    inset: 0;
    border-radius: 10px;
    border-top: 4px solid transparent;
    transition: border-color 0.25s ease;
}

.dashboard-cards .card:hover {
    transform: scale(1.04);
    box-shadow: 0 12px 25px rgba(0,0,0,0.12);
}

/* WARNA AKSEN SAAT HOVER */
.dashboard-cards .card:hover::before {
    border-top-color: #0d6efd; /* biru bootstrap */
}

/* WARNA TEKS SEDIKIT HIDUP */
.dashboard-cards .card:hover h4 {
    color: #0d6efd !important;
}
.dashboard-cards .card {
    position: relative;
}
/* RUNNING TEXT */
.running-text{
    position:fixed;
    bottom:0;
    left:240px; /* menyesuaikan sidebar */
    right:0;
    background:#ffffff;        /* putih mengikuti background */
    color:#000000;             /* teks hitam */
    font-size:13px;
    padding:8px 0;
    overflow:hidden;
    border-top:1px solid #ddd; /* garis tipis biar rapi */
    z-index:999;
}

.running-text span{
    display:inline-block;
    padding-left:100%;
    white-space:nowrap;
    animation: scrollText 36s linear infinite;
}

@keyframes scrollText{
    0%   { transform: translateX(0); }
    100% { transform: translateX(-100%); }
}
.menu-upload {
    font-weight: 700;
}
.menu-upload {
    font-weight: 700;
    color: #ffffff;
}
.sidebar li a {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 15px;
    color: #333;
    text-decoration: none;
    border-radius: 8px;
    transition: 0.2s;
}

.sidebar li a:hover {
    background: #f0f4ff;
    color: #0d6efd;
}

.sidebar li a i {
    width: 18px;
    text-align: center;
}
.navbar-brand img {
    object-fit: cover;
}

.sidebar .title {
    font-weight: 600;
    padding: 15px;
    font-size: 14px;
}
.navbar-brand span {
    font-weight: 600;
}

.dropdown-menu {
    border-radius: 10px;
    font-size: 14px;
}

.dropdown-item:hover {
    background: #f1f5ff;
}
.menu-logout {
    display: flex;
    align-items: center;
    gap: 10px;
    font-weight: 600;
    background: #0d6efd;
    color: #fff !important;
    padding: 10px 14px;
    border-radius: 8px;
    text-decoration: none;
    transition: 0.2s;
}

.menu-logout:hover {
    background: #0b5ed7;
}

.menu-logout i {
    width: 18px;
    text-align: center;
}
    </style>
</head>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<body>

<!-- NAVBAR -->
<nav class="navbar navbar-dark bg-primary fixed-top">
    <div class="container-fluid">

        <!-- KIRI : LOGO + NAMA APP -->
        <a class="navbar-brand d-flex align-items-center gap-2" href="dashboard_admin.php">
            <img src="assets/images/logomu.ico" alt="Logomu" width="30" height="30" style="border-radius:6px;">
            <span>Aplikasi e-BOS</span>
        </a>

        <!-- KANAN : NAMA SEKOLAH + DROPDOWN -->
        <div class="dropdown">
            <a class="d-flex align-items-center gap-2 text-white text-decoration-none dropdown-toggle"
               href="#"
               role="button"
               data-bs-toggle="dropdown"
               aria-expanded="false">

                <i class="fa fa-school"></i>
                <?= htmlspecialchars($nama_sekolah) ?>
            </a>

            <ul class="dropdown-menu dropdown-menu-end shadow">
                <li class="px-3 py-2 text-muted" style="font-size:13px;">
                    <i class="fa fa-user"></i> <?= htmlspecialchars($nama_lengkap ?? 'User') ?>
                </li>

                <li><hr class="dropdown-divider"></li>

                <li>
                    <a class="dropdown-item text-danger d-flex align-items-center gap-2" href="logout.php">
                        <i class="fa fa-sign-out-alt"></i> Logout
                    </a>
                </li>
            </ul>
        </div>

    </div>
</nav>

<!-- SIDEBAR -->
<div class="sidebar">
    <div class="title d-flex align-items-center gap-2">
        <img src="assets/images/logomu.ico" width="28" style="border-radius:6px;">
        APP-e-BOS 2026 V.1
    </div>

    <ul>

        <!-- MENU UMUM (ADMIN & USER) -->
        <li>
            <a href="dashboard.php" class="<?= basename($_SERVER['PHP_SELF'])=='dashboard.php'?'active':'' ?>">
                <i class="fas fa-house"></i> Dashboard
            </a>
        </li>

            <?php if ($role === 'admin') { ?>
                <!-- MENU KHUSUS ADMIN -->
                <li><a href="users.php"><i class="fa fa-user"></i> Users</a></li>
                <li><a href="list_rekening_map.php"><i class="fa fa-file-invoice"></i> Input Rekening Belanja</a></li>
                <li><a href="list_sekolah.php"><i class="fa fa-school"></i> Profil Sekolah</a></li>
                <li><a href="list_penganggaran.php"><i class="fa fa-chart-bar"></i> Penganggaran</a></li>
                <li><a href="list_kwitansi.php"><i class="fa fa-print"></i> Cetak Kwitansi</a></li>
                <li><a href="rekap_bku_proses.php"><i class="fa fa-book"></i> Rekap BKU</a></li>
                <li><a href="list_rekap_kib.php"><i class="fa fa-tags"></i> Rekap KIB</a></li>
                <li><a href="list_rekap_bhp.php"><i class="fa fa-boxes"></i> Rekap BHP</a></li>
                <li><a href="list_rekening_koran.php"><i class="fa fa-university"></i> Upload Rekening Koran</a></li>
                <li><a href="list_stokopname.php"><i class="fa fa-clipboard-check"></i> Stok Opname</a></li>
                <li><a href="list_laporan.php" class="menu-upload"><i class="fa fa-upload"></i> Upload Laporan</a></li>
            <?php } else { ?>
                <!-- MENU KHUSUS USER -->
                <li><a href="list_sekolah.php"><i class="fa fa-school"></i> Profil Sekolah</a></li>
                <li><a href="list_penganggaran.php"><i class="fa fa-chart-bar"></i> Penganggaran</a></li>
                <li><a href="list_kwitansi.php"><i class="fa fa-print"></i> Cetak Kwitansi</a></li>
                <li><a href="rekap_bku_proses.php"><i class="fa fa-book"></i> Rekap BKU</a></li>
                <li><a href="list_rekap_kib.php"><i class="fa fa-tags"></i> Rekap KIB</a></li>
                <li><a href="list_rekap_bhp.php"><i class="fa fa-boxes"></i> Rekap BHP</a></li>
                <li><a href="list_rekening_koran.php"><i class="fa fa-university"></i> Upload Rekening Koran</a></li>
                <li><a href="list_stokopname.php"><i class="fa fa-clipboard-check"></i> Stok Opname</a></li>
                <li><a href="list_laporan.php" class="menu-upload"><i class="fa fa-upload"></i> Upload Laporan</a></li>
            <?php } ?>

        <!-- LOGOUT -->
        <li class="mt-3">
            <a href="logout.php" class="menu-logout">
                <i class="fa fa-sign-out-alt"></i>
                Logout
            </a>
        </li>

    </ul>
</div>


<!-- CONTENT -->
<div class="content">
    <div class="dashboard-header">
    <h4>Selamat Datang di e-BOS Dinas Pendidikan Kab. Situbondo</h4>
    <p class="text-muted mb-1">Sistem Pengelolaan Dana BOS</p>
    <div class="dashboard-divider"></div>
</div>

	<div class="row g-3 mt-3 dashboard-cards">
    <div class="col-md-3">
        <div class="card shadow-sm text-center">
            <div class="card-body">
                <h6>Total Anggaran</h6>
                <h4 class="text-success">
                    Rp <?= number_format($total_anggaran,0,',','.') ?>
                </h4>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="card shadow-sm text-center">
            <div class="card-body">
                <h6>Total Pengeluaran</h6>
                <h4 class="text-danger">
                    Rp <?= number_format($total_pengeluaran,0,',','.') ?>
                </h4>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="card shadow-sm text-center">
            <div class="card-body">
                <h6>Saldo Bank</h6>
                <h4 class="text-primary">
                    Rp <?= number_format($saldo_bank,0,',','.') ?>
                </h4>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="card shadow-sm text-center">
            <div class="card-body">
                <h6>Saldo Tunai</h6>
                <h4 class="<?= $saldo_tunai < 0 ? 'text-danger' : 'text-dark' ?>">
                    Rp <?= number_format($saldo_tunai,0,',','.') ?>
                </h4>
            </div>
        </div>
    </div>
</div>
	
   <div class="row g-3 mt-3 dashboard-cards">
    <div class="col-md-3">
        <div class="card shadow-sm text-center">
            <div class="card-body">
                <h6>Total Honor</h6>
                <h4 class="text-success">
                    Rp <?= number_format($total_honor,0,',','.') ?>
                </h4>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="card shadow-sm text-center">
            <div class="card-body">
                <h6>Total Habis Pakai</h6>
                <h4 class="text-danger">
                    Rp <?= number_format($total_habis_pakai,0,',','.') ?>
                </h4>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="card shadow-sm text-center">
            <div class="card-body">
                <h6>Total Barjas</h6>
                <h4 class="text-primary">
                    Rp <?= number_format($total_barjas,0,',','.') ?>
                </h4>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="card shadow-sm text-center">
            <div class="card-body">
                <h6>Total Modal</h6>
                <h4 class="text-dark">
                    Rp <?= number_format($total_modal,0,',','.') ?>
                </h4>
            </div>
        </div>
    </div>

	
	<?php
		require_once __DIR__ . '/config/config.php';

		// ambil total dari tabel penganggaran
		$qTotal = mysqli_query($conn, "
			SELECT
				SUM(honor) AS total_honor,
				SUM(habis_pakai) AS total_habis_pakai,
				SUM(barjas) AS total_barjas,
				SUM(modal_mesin + modal_lainnya) AS total_modal
			FROM penganggaran
		");

		$total = mysqli_fetch_assoc($qTotal);

		$total_honor       = $total['total_honor'] ?? 0;
		$total_habis_pakai = $total['total_habis_pakai'] ?? 0;
		$total_barjas      = $total['total_barjas'] ?? 0;
		$total_modal       = $total['total_modal'] ?? 0;
		?>

</div>
	
<div class="row g-2 mt-3 dashboard-cards">
<?php if (!empty($notif)): ?>
<?php
    $status = strtolower($notif['status_verifikasi']);
    if ($status === 'disetujui') {
    $warna = 'success';
    $judul = '✅ LAPORAN DISETUJUI';
    $isi   = 'Laporan telah diverifikasi dan disetujui.';
}
elseif ($status === 'menunggu') {
    $warna = 'info';
    $judul = '📤 LAPORAN MENUNGGU VERIFIKASI';
    $isi   = 'Laporan sudah dikirim dan sedang menunggu verifikasi admin.';
}
elseif ($status === 'diajukan_ulang') {
    $warna = 'warning';
    $judul = '🔁 LAPORAN DIAJUKAN ULANG';
    $isi   = 'Laporan diperbaiki dan diajukan ulang, mohon tunggu verifikasi admin.';
}
else { // ditolak
    $warna = 'danger';
    $judul = '❌ LAPORAN DITOLAK';
    $isi   = trim($notif['catatan_admin']) !== ''
        ? nl2br(htmlspecialchars($notif['catatan_admin']))
        : '<i>Belum ada catatan dari admin.</i>';
}
   
?>

<div class="col-12">
    <div class="alert alert-<?= $warna ?> py-2 px-3 mb-0" style="font-size:11px">
        <div class="d-flex justify-content-between align-items-center">
            <strong><?= $judul ?></strong>
            <span>
                <?= htmlspecialchars($notif['bulan']) ?> <?= htmlspecialchars($notif['tahun']) ?>
            </span>
        </div>

        <hr class="my-1">

        <div>
            <?= $isi ?>
        </div>
    </div>
</div>

<?php endif; ?>
</div>


</div>
<!-- RUNNING TEXT -->
<div class="running-text">
    <span>
		<?php if($role == 'admin'){ ?>
			📢 Informasi Admin: Mohon cek kembali laporan anda.
		<?php }else{ ?>
			📢 Informasi dari Admin: Silakan lengkapi Laporan BOS Sekolah anda sesuai dengan aplikasi yang ada di ARKAS.
		<?php } ?>
</span>
</div>
<script>
function showRiwayat(el){
    const box = document.getElementById('riwayatBox');

    if(el.value === ''){
        box.classList.add('d-none');
        return;
    }

    const status = el.options[el.selectedIndex].dataset.status;
    let alertClass = 'alert-secondary';
    let judul = '';
    let isi   = '';

    if(status === 'disetujui'){
        alertClass = 'alert-success';
        judul = '✅ LAPORAN DISETUJUI';
        isi   = 'Laporan telah diverifikasi dan disetujui.';
    }
    else if(status === 'menunggu'){
        alertClass = 'alert-warning';
        judul = '⏳ LAPORAN DIAJUKAN KEMBALI';
        isi   = 'Laporan masih diajukan kembali, mohon tunggu verifikasi admin.';
    }
    else{
        alertClass = 'alert-danger';
        judul = '❌ LAPORAN DITOLAK';
        isi   = el.value ? el.value.replace(/\n/g,'<br>') : '-';
    }

    box.className = 'alert ' + alertClass;
    box.style.fontSize = '12px';

    box.innerHTML = `
        <strong>${judul}</strong><hr class="my-1">
        ${isi}
    `;

    box.classList.remove('d-none');
}
</script>

</body>
</html>
