<?php
// Total Produk
$qProduk = $conn->query("SELECT COUNT(*) AS total FROM tabel_produk");
$totalProduk = $qProduk->fetch_assoc()['total'];

// Total Pelanggan
$qPelanggan = $conn->query("SELECT COUNT(*) AS total FROM tabel_pelanggan");
$totalPelanggan = $qPelanggan->fetch_assoc()['total'];

// Total Transaksi
$qTransaksi = $conn->query("SELECT COUNT(*) AS total FROM tabel_transaksi");
$totalTransaksi = $qTransaksi->fetch_assoc()['total'];

// Total Pendapatan
$qPendapatan = $conn->query("SELECT SUM(total) AS total FROM tabel_transaksi");
$totalPendapatan = $qPendapatan->fetch_assoc()['total'] ?? 0;

// Total Pengeluaran
$qPengeluaran = $conn->query("SELECT SUM(jumlah) AS total FROM tabel_pengeluaran");
$totalPengeluaran = $qPengeluaran->fetch_assoc()['total'] ?? 0;

// Saldo
$saldo = $totalPendapatan - $totalPengeluaran;

// Stok Rendah
$qStok = $conn->query("SELECT nama_produk, stok FROM tabel_produk WHERE stok < 5");

// Penjualan per bulan
$penjualanBulanan = array_fill(1, 12, 0);
$qBulanan = $conn->query("SELECT MONTH(tanggal) AS bulan, SUM(total) AS total 
                          FROM tabel_transaksi GROUP BY MONTH(tanggal)");
while ($row = $qBulanan->fetch_assoc()) {
    $penjualanBulanan[(int)$row['bulan']] = (int)$row['total'];
}

// Pengeluaran per bulan
$pengeluaranBulanan = array_fill(1, 12, 0);
$qPengeluaranBulanan = $conn->query("SELECT MONTH(tanggal) AS bulan, SUM(jumlah) AS total 
                                     FROM tabel_pengeluaran GROUP BY MONTH(tanggal)");
while ($row = $qPengeluaranBulanan->fetch_assoc()) {
    $pengeluaranBulanan[(int)$row['bulan']] = (int)$row['total'];
}

// 10 Produk Terlaris
$qTerlaris = $conn->query("
    SELECT p.nama_produk, SUM(d.qty) AS total_qty 
    FROM tabel_transaksi_detail d
    JOIN tabel_produk p ON p.id = d.produk_id
    GROUP BY d.produk_id
    ORDER BY total_qty DESC
    LIMIT 10
");
?>
<h2 class="mb-4">Dashboard</h2>

<div class="row">
    <!-- Kartu Produk -->
    <div class="col-md-2">
        <div class="card text-white bg-primary mb-3">
            <div class="card-body p-2">
                <h6 class="card-title">Produk</h6>
                <p class="h4"><?= $totalProduk ?></p>
            </div>
        </div>
    </div>

    <!-- Kartu Pelanggan -->
    <div class="col-md-2">
        <div class="card text-white bg-success mb-3">
            <div class="card-body p-2">
                <h6 class="card-title">Pelanggan</h6>
                <p class="h4"><?= $totalPelanggan ?></p>
            </div>
        </div>
    </div>

    <!-- Kartu Transaksi -->
    <div class="col-md-2">
        <div class="card text-white bg-warning mb-3">
            <div class="card-body p-2">
                <h6 class="card-title">Transaksi</h6>
                <p class="h4"><?= $totalTransaksi ?></p>
            </div>
        </div>
    </div>

    <!-- Kartu Pendapatan -->
    <div class="col-md-2">
        <div class="card text-white bg-danger mb-3">
            <div class="card-body p-2">
                <h6 class="card-title">Pendapatan</h6>
                <p class="h6">Rp <?= number_format($totalPendapatan, 0, ',', '.') ?></p>
            </div>
        </div>
    </div>

    <!-- Kartu Pengeluaran -->
    <div class="col-md-2">
        <div class="card text-white bg-dark mb-3">
            <div class="card-body p-2">
                <h6 class="card-title">Pengeluaran</h6>
                <p class="h6">Rp <?= number_format($totalPengeluaran, 0, ',', '.') ?></p>
            </div>
        </div>
    </div>

    <!-- Kartu Saldo -->
    <div class="col-md-2">
        <div class="card text-white bg-info mb-3">
            <div class="card-body p-2">
                <h6 class="card-title">Saldo</h6>
                <p class="h6">Rp <?= number_format($saldo, 0, ',', '.') ?></p>
            </div>
        </div>
    </div>
</div>

<!-- Chart Penjualan & Pengeluaran -->
<div class="card mt-4">
    <div class="card-header">Statistik Penjualan & Pengeluaran per Bulan</div>
    <div class="card-body">
        <canvas id="chartPenjualan" style="width:100%; height:400px;"></canvas>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('chartPenjualan').getContext('2d');
new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Agu','Sep','Okt','Nov','Des'],
        datasets: [
            {
                label: 'Total Penjualan',
                data: <?= json_encode(array_values($penjualanBulanan)) ?>,
                backgroundColor: '#0d6efd'
            },
            {
                label: 'Total Pengeluaran',
                data: <?= json_encode(array_values($pengeluaranBulanan)) ?>,
                backgroundColor: '#dc3545'
            }
        ]
    },
    options: {
        responsive: true,
        maintainAspectRatio: false, // biar proporsional dengan tinggi CSS
        plugins: { legend: { position: 'top' } },
        scales: { 
            y: { 
                beginAtZero: true,
                ticks: {
                    callback: function(value) {
                        return 'Rp ' + value.toLocaleString('id-ID');
                    }
                }
            }
        }
    }
});
</script>

<!-- Tabel Stok Rendah -->
<div class="card mt-4">
    <div class="card-header">Produk Stok Rendah ( < 5 )</div>
    <div class="card-body">
        <table class="table table-bordered">
            <thead><tr><th>Nama Produk</th><th>Stok</th></tr></thead>
            <tbody>
                <?php if($qStok->num_rows > 0): ?>
                    <?php while($row = $qStok->fetch_assoc()): ?>
                        <tr><td><?= $row['nama_produk'] ?></td><td><?= $row['stok'] ?></td></tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="2" class="text-center">Semua stok aman 👍</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Tabel 10 Produk Terlaris -->
<div class="card mt-4">
    <div class="card-header">10 Produk Terlaris</div>
    <div class="card-body">
        <table class="table table-bordered">
            <thead><tr><th>Nama Produk</th><th>Jumlah Terjual</th></tr></thead>
            <tbody>
                <?php if($qTerlaris->num_rows > 0): ?>
                    <?php while($row = $qTerlaris->fetch_assoc()): ?>
                        <tr><td><?= $row['nama_produk'] ?></td><td><?= $row['total_qty'] ?></td></tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr><td colspan="2" class="text-center">Belum ada penjualan</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
