<?php
require_once __DIR__ . '/includes/functions.php';
requireLogin();
$pageTitle = 'Dashboard';

$bulanIni = date('m');
$tahunIni = date('Y');

// Saldo total semua akun (saldo awal + pemasukan - pengeluaran)
$saldoAwalTotal = $pdo->query("SELECT COALESCE(SUM(saldo_awal),0) FROM akun_kas")->fetchColumn();
$totalMasukAll  = $pdo->query("SELECT COALESCE(SUM(jumlah),0) FROM transaksi WHERE tipe='pemasukan'")->fetchColumn();
$totalKeluarAll = $pdo->query("SELECT COALESCE(SUM(jumlah),0) FROM transaksi WHERE tipe='pengeluaran'")->fetchColumn();
$saldoSaatIni   = $saldoAwalTotal + $totalMasukAll - $totalKeluarAll;

// Pemasukan & pengeluaran bulan ini
$stmt = $pdo->prepare("SELECT COALESCE(SUM(jumlah),0) FROM transaksi WHERE tipe='pemasukan' AND MONTH(tanggal)=:b AND YEAR(tanggal)=:t");
$stmt->execute(['b'=>$bulanIni,'t'=>$tahunIni]);
$masukBulanIni = $stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COALESCE(SUM(jumlah),0) FROM transaksi WHERE tipe='pengeluaran' AND MONTH(tanggal)=:b AND YEAR(tanggal)=:t");
$stmt->execute(['b'=>$bulanIni,'t'=>$tahunIni]);
$keluarBulanIni = $stmt->fetchColumn();

// Tunggakan SPP
$tunggakan = $pdo->query("SELECT COALESCE(SUM(nominal - jumlah_dibayar),0) FROM tagihan_spp WHERE status='belum_lunas'")->fetchColumn();
$jumlahSiswaNunggak = $pdo->query("SELECT COUNT(DISTINCT siswa_id) FROM tagihan_spp WHERE status='belum_lunas'")->fetchColumn();

// Grafik 6 bulan terakhir
$labelsBulan = []; $dataMasuk = []; $dataKeluar = [];
for ($i = 5; $i >= 0; $i--) {
    $ts = strtotime("-$i month");
    $b = date('m', $ts); $t = date('Y', $ts);
    $labelsBulan[] = namaBulan($b) . ' ' . $t;
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(jumlah),0) FROM transaksi WHERE tipe='pemasukan' AND MONTH(tanggal)=:b AND YEAR(tanggal)=:t");
    $stmt->execute(['b'=>$b,'t'=>$t]); $dataMasuk[] = (float)$stmt->fetchColumn();
    $stmt = $pdo->prepare("SELECT COALESCE(SUM(jumlah),0) FROM transaksi WHERE tipe='pengeluaran' AND MONTH(tanggal)=:b AND YEAR(tanggal)=:t");
    $stmt->execute(['b'=>$b,'t'=>$t]); $dataKeluar[] = (float)$stmt->fetchColumn();
}

// Transaksi terbaru
$transaksiTerbaru = $pdo->query("
    SELECT t.*, k.nama as kategori_nama, a.nama_akun
    FROM transaksi t
    JOIN kategori k ON k.id = t.kategori_id
    JOIN akun_kas a ON a.id = t.akun_id
    ORDER BY t.id DESC LIMIT 8
")->fetchAll();

// Distribusi pengeluaran per kategori (untuk pie chart) - bulan ini
$stmt = $pdo->prepare("
    SELECT k.nama, SUM(t.jumlah) as total
    FROM transaksi t JOIN kategori k ON k.id = t.kategori_id
    WHERE t.tipe = 'pengeluaran' AND MONTH(t.tanggal)=:b AND YEAR(t.tanggal)=:t
    GROUP BY k.id ORDER BY total DESC
");
$stmt->execute(['b'=>$bulanIni,'t'=>$tahunIni]);
$pieData = $stmt->fetchAll();

include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="mb-0">Dashboard Keuangan</h5>
    <span class="text-muted small"><?= tanggalIndo(date('Y-m-d')) ?></span>
</div>

<div class="row g-3 mb-3">
    <div class="col-md-3 col-6">
        <div class="card stat-card p-3">
            <div class="d-flex align-items-center gap-3">
                <div class="icon-box bg-primary-subtle text-primary"><i class="bi bi-wallet2"></i></div>
                <div>
                    <div class="text-muted small">Saldo Saat Ini</div>
                    <div class="fw-bold"><?= rupiah($saldoSaatIni) ?></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 col-6">
        <div class="card stat-card p-3">
            <div class="d-flex align-items-center gap-3">
                <div class="icon-box bg-success-subtle text-success"><i class="bi bi-arrow-down-circle"></i></div>
                <div>
                    <div class="text-muted small">Pemasukan Bulan Ini</div>
                    <div class="fw-bold"><?= rupiah($masukBulanIni) ?></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 col-6">
        <div class="card stat-card p-3">
            <div class="d-flex align-items-center gap-3">
                <div class="icon-box bg-danger-subtle text-danger"><i class="bi bi-arrow-up-circle"></i></div>
                <div>
                    <div class="text-muted small">Pengeluaran Bulan Ini</div>
                    <div class="fw-bold"><?= rupiah($keluarBulanIni) ?></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-3 col-6">
        <div class="card stat-card p-3">
            <div class="d-flex align-items-center gap-3">
                <div class="icon-box bg-warning-subtle text-warning"><i class="bi bi-exclamation-circle"></i></div>
                <div>
                    <div class="text-muted small">Tunggakan SPP (<?= $jumlahSiswaNunggak ?> siswa)</div>
                    <div class="fw-bold"><?= rupiah($tunggakan) ?></div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row g-3">
    <div class="col-lg-8">
        <div class="card">
            <div class="card-header">Tren Pemasukan vs Pengeluaran (6 Bulan Terakhir)</div>
            <div class="card-body"><canvas id="chartTren" height="110"></canvas></div>
        </div>
    </div>
    <div class="col-lg-4">
        <div class="card">
            <div class="card-header">Distribusi Pengeluaran Bulan Ini</div>
            <div class="card-body"><canvas id="chartPie" height="180"></canvas></div>
        </div>
    </div>
</div>

<div class="card mt-3">
    <div class="card-header">Transaksi Terbaru</div>
    <div class="card-body p-0">
        <table class="table table-hover mb-0">
            <thead><tr><th class="ps-3">No. Transaksi</th><th>Tanggal</th><th>Kategori</th><th>Akun</th><th>Jumlah</th><th class="pe-3"></th></tr></thead>
            <tbody>
            <?php foreach ($transaksiTerbaru as $t): ?>
                <tr>
                    <td class="ps-3"><?= htmlspecialchars($t['no_transaksi']) ?></td>
                    <td><?= tanggalIndo($t['tanggal']) ?></td>
                    <td><?= htmlspecialchars($t['kategori_nama']) ?></td>
                    <td><?= htmlspecialchars($t['nama_akun']) ?></td>
                    <td class="<?= $t['tipe']==='pemasukan' ? 'text-success' : 'text-danger' ?> fw-semibold">
                        <?= $t['tipe']==='pemasukan' ? '+' : '-' ?> <?= rupiah($t['jumlah']) ?>
                    </td>
                    <td class="pe-3"></td>
                </tr>
            <?php endforeach; ?>
            <?php if (empty($transaksiTerbaru)): ?>
                <tr><td colspan="6" class="text-center text-muted py-4">Belum ada transaksi</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php
$extraJs = '<script>
const ctxTren = document.getElementById("chartTren");
new Chart(ctxTren, {
    type: "line",
    data: {
        labels: ' . json_encode($labelsBulan) . ',
        datasets: [
            { label: "Pemasukan", data: ' . json_encode($dataMasuk) . ', borderColor:"#2f5d50", backgroundColor:"rgba(47,93,80,.1)", tension:.3, fill:true },
            { label: "Pengeluaran", data: ' . json_encode($dataKeluar) . ', borderColor:"#c0392b", backgroundColor:"rgba(192,57,43,.1)", tension:.3, fill:true }
        ]
    },
    options: { responsive:true, plugins:{legend:{position:"bottom"}} }
});

const ctxPie = document.getElementById("chartPie");
new Chart(ctxPie, {
    type: "doughnut",
    data: {
        labels: ' . json_encode(array_column($pieData, 'nama')) . ',
        datasets: [{ data: ' . json_encode(array_map('floatval', array_column($pieData, 'total'))) . ', backgroundColor:["#2f5d50","#d4a857","#c0392b","#3498db","#9b59b6","#16a085","#e67e22","#7f8c8d"] }]
    },
    options: { responsive:true, plugins:{legend:{position:"bottom"}} }
});
</script>';
include __DIR__ . '/includes/footer.php';
?>
