<?php
session_start();
require_once __DIR__ . '/../../DataBase/koneksi.php';

// Cek login dan role
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    echo '<script>
        var redirectUrl = "../../index.html";
        if (window.self !== window.top) {
            window.top.location.href = redirectUrl;
        } else {
            window.location.href = redirectUrl;
        }
    </script>';
    exit;
}

if (!function_exists('checkRole')) {
    function checkRole($roles) {
        if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], $roles)) {
            echo '<script>
                var redirectUrl = "../../index.html";
                if (window.self !== window.top) {
                    window.top.location.href = redirectUrl;
                } else {
                    window.location.href = redirectUrl;
                }
            </script>';
            exit;
        }
    }
}
// Support both 'D' and 'director' role format
checkRole(['D', 'director', 'DIRECTOR']);

if (!function_exists('formatRupiah')) {
    function formatRupiah($angka) {
        return "Rp " . number_format($angka, 0, ',', '.');
    }
}

if (!function_exists('formatTanggalIndonesia')) {
    function formatTanggalIndonesia() {
        $hari = ['Minggu', 'Senin', 'Selasa', 'Rabu', 'Kamis', 'Jumat', 'Sabtu'];
        $bulan = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];
        
        $hariIni = $hari[date('w')];
        $tanggal = date('d');
        $bulanIni = $bulan[date('n') - 1];
        $tahun = date('Y');
        
        return "$hariIni, $tanggal $bulanIni $tahun";
    }
}

$userName = $_SESSION['nama'] ?? $_SESSION['username'] ?? 'Direktur';
$tanggalSekarang = formatTanggalIndonesia();

// STATISTIK UTAMA - Menggunakan query yang sama seperti admin
$totalAset = $conn->query("SELECT COUNT(*) as total FROM inventory WHERE status='aktif'")->fetch_assoc()['total'];
$totalNilai = $conn->query("SELECT SUM(harga_perolehan) as total FROM inventory WHERE status='aktif'")->fetch_assoc()['total'] ?? 0;
$totalKantor = $conn->query("SELECT COUNT(DISTINCT kantor) as total FROM inventory WHERE status='aktif'")->fetch_assoc()['total'];
$totalKategori = $conn->query("SELECT COUNT(DISTINCT kategori) as total FROM inventory WHERE status='aktif'")->fetch_assoc()['total'];

// Aset bermasalah (bukan aktif)
$asetPerluPerbaikan = $conn->query("SELECT COUNT(*) as total FROM inventory WHERE status != 'aktif'")->fetch_assoc()['total'] ?? 0;

// Statistik transaksi bulan ini - menggunakan tabel inventory
$bulanIni = date('Y-m');

// Barang masuk = inventory yang tanggal_perolehan bulan ini
$barangMasuk = $conn->query("
    SELECT COUNT(*) as total 
    FROM inventory 
    WHERE DATE_FORMAT(tanggal_perolehan, '%Y-%m') = '$bulanIni'
")->fetch_assoc()['total'] ?? 0;

// Barang keluar = inventory yang tanggal_keluar bulan ini
$barangKeluar = $conn->query("
    SELECT COUNT(*) as total 
    FROM inventory 
    WHERE tanggal_keluar IS NOT NULL 
    AND DATE_FORMAT(tanggal_keluar, '%Y-%m') = '$bulanIni'
")->fetch_assoc()['total'] ?? 0;

// Statistik Penyusutan & Nilai Buku
$totalNilaiResidu = $conn->query("
    SELECT SUM(nilai_residu) as total 
    FROM inventory 
    WHERE status='aktif'
")->fetch_assoc()['total'] ?? 0;

// Total Sumber Dana
$totalSumberDana = $conn->query("
    SELECT COUNT(DISTINCT sumber_dana) as total 
    FROM inventory 
    WHERE status='aktif' AND sumber_dana IS NOT NULL
")->fetch_assoc()['total'] ?? 0;

// TOP SUMBER DANA
$topSumberDana = [];
$result = $conn->query("
    SELECT 
        sumber_dana, 
        COUNT(*) as jumlah, 
        SUM(harga_perolehan) as nilai 
    FROM inventory 
    WHERE status='aktif' AND sumber_dana IS NOT NULL 
    GROUP BY sumber_dana 
    ORDER BY nilai DESC 
    LIMIT 5
");
while ($row = $result->fetch_assoc()) {
    $topSumberDana[] = $row;
}

// TOP KATEGORI
$topKategori = [];
$result = $conn->query("SELECT kategori, COUNT(*) as jumlah, SUM(harga_perolehan) as nilai FROM inventory WHERE status='aktif' AND kategori IS NOT NULL GROUP BY kategori ORDER BY jumlah DESC LIMIT 5");
while ($row = $result->fetch_assoc()) {
    $topKategori[] = $row;
}

// TOP KANTOR
$topKantor = [];
$result = $conn->query("SELECT kantor, COUNT(*) as jumlah, SUM(harga_perolehan) as nilai FROM inventory WHERE status='aktif' AND kantor IS NOT NULL GROUP BY kantor ORDER BY jumlah DESC");
while ($row = $result->fetch_assoc()) {
    $topKantor[] = $row;
}

// TREND PEROLEHAN (6 bulan terakhir)
$trendPerolehan = $conn->query("
    SELECT 
        DATE_FORMAT(tanggal_perolehan, '%Y-%m') as bulan,
        COUNT(*) as jumlah_aset,
        SUM(harga_perolehan) as total_nilai
    FROM inventory
    WHERE tanggal_perolehan >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH)
    GROUP BY DATE_FORMAT(tanggal_perolehan, '%Y-%m')
    ORDER BY bulan ASC
");

// ASET PERLU PERHATIAN
$asetBermasalah = $conn->query("
    SELECT 
        jenis_barang,
        status,
        kantor,
        spesifikasi
    FROM inventory
    WHERE status != 'aktif'
    ORDER BY id DESC
    LIMIT 5
");

// STATISTIK USERS
$totalUsers = $conn->query("SELECT COUNT(*) as total FROM users WHERE is_active = 1")->fetch_assoc()['total'] ?? 0;
$usersByRole = $conn->query("
    SELECT role, COUNT(*) as jumlah
    FROM users
    WHERE is_active = 1
    GROUP BY role
    ORDER BY jumlah DESC
");
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Direktur - ACF EDU HUB</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8fafc;
            color: #1e293b;
            padding: 25px;
        }

        /* HEADER */
        .header {
            background: linear-gradient(135deg, #8B5CF6 0%, #7C3AED 100%);
            color: white;
            padding: 20px 30px;
            border-radius: 12px;
            margin-bottom: 20px;
            box-shadow: 0 4px 15px rgba(139, 92, 246, 0.2);
            position: relative;
            overflow: hidden;
        }

        .header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -10%;
            width: 300px;
            height: 300px;
            background: rgba(255, 255, 255, 0.03);
            border-radius: 50%;
        }

        .header-content {
            position: relative;
            z-index: 1;
        }

        .header h1 {
            font-size: 20px;
            font-weight: 700;
            margin-bottom: 4px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .header h1 i {
            font-size: 18px;
        }

        .header p {
            font-size: 13px;
            opacity: 0.9;
        }

        .header-time {
            font-size: 12px;
            opacity: 0.85;
            margin-top: 6px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .header-time i {
            font-size: 11px;
        }

        /* STATS GRID */
        .stats-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
            gap: 12px;
            margin-bottom: 20px;
        }

        .stat-box {
            background: white;
            padding: 16px 14px;
            border-radius: 10px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.04);
            text-align: center;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .stat-box::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 3px;
        }

        .stat-box:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
        }

        .stat-box.purple::before { background: #8B5CF6; }
        .stat-box.blue::before { background: #3b82f6; }
        .stat-box.green::before { background: #10b981; }
        .stat-box.orange::before { background: #f59e0b; }
        .stat-box.red::before { background: #ef4444; }
        .stat-box.teal::before { background: #7AB2B2; }

        .stat-icon {
            width: 36px;
            height: 36px;
            margin: 0 auto 10px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
        }

        .stat-box.purple .stat-icon { background: rgba(139, 92, 246, 0.1); color: #8B5CF6; }
        .stat-box.blue .stat-icon { background: rgba(59, 130, 246, 0.1); color: #3b82f6; }
        .stat-box.green .stat-icon { background: rgba(16, 185, 129, 0.1); color: #10b981; }
        .stat-box.orange .stat-icon { background: rgba(245, 158, 11, 0.1); color: #f59e0b; }
        .stat-box.red .stat-icon { background: rgba(239, 68, 68, 0.1); color: #ef4444; }
        .stat-box.teal .stat-icon { background: rgba(122, 178, 178, 0.1); color: #7AB2B2; }

        .stat-number {
            font-size: 20px;
            font-weight: 700;
            color: #1e293b;
            line-height: 1;
            margin-bottom: 6px;
        }

        .stat-label {
            font-size: 11px;
            color: #64748b;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }

        .stat-percentage {
            font-size: 10px;
            color: #94a3b8;
            margin-top: 3px;
        }

        /* DASHBOARD GRID */
        .dashboard-grid {
            display: grid;
            grid-template-columns: repeat(12, 1fr);
            gap: 12px;
            margin-bottom: 20px;
        }

        .chart-card {
            background: white;
            padding: 18px;
            border-radius: 10px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.04);
        }

        .chart-card.span-8 { grid-column: span 8; }
        .chart-card.span-4 { grid-column: span 4; }
        .chart-card.span-6 { grid-column: span 6; }
        .chart-card.span-12 { grid-column: span 12; }

        .chart-header {
            margin-bottom: 14px;
            padding-bottom: 10px;
            border-bottom: 1px solid #f1f5f9;
        }

        .chart-title {
            font-size: 14px;
            font-weight: 700;
            color: #1e293b;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .chart-title i {
            color: #8B5CF6;
            font-size: 14px;
        }

        /* LIST ITEM */
        .list-item {
            padding: 10px;
            border-radius: 6px;
            background: #f8fafc;
            margin-bottom: 8px;
            transition: all 0.2s;
        }

        .list-item:hover {
            background: #faf5ff;
            transform: translateX(3px);
        }

        .item-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 4px;
        }

        .item-name {
            font-size: 13px;
            font-weight: 600;
            color: #1e293b;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .item-name i {
            color: #8B5CF6;
            font-size: 12px;
        }

        .item-value {
            font-size: 18px;
            font-weight: 700;
            color: #8B5CF6;
        }

        .item-detail {
            font-size: 11px;
            color: #64748b;
            margin-top: 2px;
        }

        .progress-bar-wrapper {
            margin-top: 6px;
        }

        .progress-bar {
            width: 100%;
            height: 5px;
            background: #f1f5f9;
            border-radius: 10px;
            overflow: hidden;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #8B5CF6, #7C3AED);
            border-radius: 10px;
            transition: width 0.3s ease;
        }

        /* TABLE */
        table {
            width: 100%;
            border-collapse: collapse;
        }

        table thead {
            background: linear-gradient(135deg, #8B5CF6 0%, #7C3AED 100%);
        }

        table th {
            color: white;
            padding: 8px 10px;
            text-align: left;
            font-size: 11px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.3px;
        }

        table th:first-child {
            border-radius: 8px 0 0 0;
        }

        table th:last-child {
            border-radius: 0 8px 0 0;
        }

        table td {
            padding: 8px 10px;
            border-bottom: 1px solid #f1f5f9;
            font-size: 12px;
            color: #334155;
        }

        table tbody tr {
            transition: all 0.2s;
        }

        table tbody tr:hover {
            background: #faf5ff;
        }

        table tbody tr:last-child td {
            border-bottom: none;
        }

        /* BADGE */
        .badge {
            padding: 3px 8px;
            border-radius: 10px;
            font-size: 10px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.2px;
            display: inline-flex;
            align-items: center;
            gap: 3px;
        }

        .badge i {
            font-size: 6px;
        }

        .badge.danger { background: rgba(239, 68, 68, 0.1); color: #dc2626; }
        .badge.warning { background: rgba(245, 158, 11, 0.1); color: #d97706; }
        .badge.success { background: rgba(16, 185, 129, 0.1); color: #059669; }
        .badge.info { background: rgba(59, 130, 246, 0.1); color: #2563eb; }

        /* EMPTY STATE */
        .empty-state {
            text-align: center;
            padding: 24px 16px;
            color: #94a3b8;
        }

        .empty-state i {
            font-size: 32px;
            margin-bottom: 10px;
            opacity: 0.3;
        }

        .empty-state p {
            font-size: 12px;
        }

        /* RESPONSIVE */
        @media (max-width: 1200px) {
            .chart-card.span-8,
            .chart-card.span-4,
            .chart-card.span-6 {
                grid-column: span 12;
            }
        }

        @media (max-width: 768px) {
            body {
                padding: 10px;
            }

            .header {
                padding: 16px 20px;
            }

            .header h1 {
                font-size: 16px;
            }

            .header p {
                font-size: 12px;
            }

            .stats-container {
                grid-template-columns: 1fr;
            }

            .stat-number {
                font-size: 18px;
            }
        }
    </style>
</head>
<body>

    <!-- HEADER -->
    <div class="header">
        <div class="header-content">
            <h1>Selamat Datang, <?= htmlspecialchars($userName) ?>!</h1>
            <p>Dashboard Eksekutif - Monitor dan Analisis Aset ACF EDU HUB</p>
            <div class="header-time">
                <i class="far fa-calendar-alt"></i>
                <span><?= htmlspecialchars($tanggalSekarang) ?></span>
                <span>•</span>
                <i class="far fa-clock"></i>
                <span><?= date('H:i') ?> WIB</span>
            </div>
        </div>
    </div>

    <!-- STATS OVERVIEW -->
    <div class="stats-container">
        <div class="stat-box purple">
            <div class="stat-icon">
                <i class="fas fa-boxes"></i>
            </div>
            <div class="stat-number"><?= number_format($totalAset) ?></div>
            <div class="stat-label">Total Aset Aktif</div>
            <div class="stat-percentage">Unit Terdaftar</div>
        </div>

        <div class="stat-box blue">
            <div class="stat-icon">
                <i class="fas fa-money-bill-wave"></i>
            </div>
            <div class="stat-number" style="font-size: 14px;"><?= formatRupiah($totalNilai) ?></div>
            <div class="stat-label">Nilai Total Aset</div>
            <div class="stat-percentage">Investasi</div>
        </div>

        <div class="stat-box green">
            <div class="stat-icon">
                <i class="fas fa-building"></i>
            </div>
            <div class="stat-number"><?= number_format($totalKantor) ?></div>
            <div class="stat-label">Lokasi Kantor</div>
            <div class="stat-percentage">Sebaran Aset</div>
        </div>

        <div class="stat-box teal">
            <div class="stat-icon">
                <i class="fas fa-tags"></i>
            </div>
            <div class="stat-number"><?= number_format($totalKategori) ?></div>
            <div class="stat-label">Kategori Aset</div>
            <div class="stat-percentage">Jenis Barang</div>
        </div>

        <div class="stat-box orange">
            <div class="stat-icon">
                <i class="fas fa-download"></i>
            </div>
            <div class="stat-number"><?= number_format($barangMasuk) ?></div>
            <div class="stat-label">Barang Masuk</div>
            <div class="stat-percentage">Bulan Ini</div>
        </div>

        <div class="stat-box red">
            <div class="stat-icon">
                <i class="fas fa-upload"></i>
            </div>
            <div class="stat-number"><?= number_format($barangKeluar) ?></div>
            <div class="stat-label">Barang Keluar</div>
            <div class="stat-percentage">Bulan Ini</div>
        </div>
    </div>

    <!-- DASHBOARD GRID -->
    <div class="dashboard-grid">
        <!-- TREND CHART -->
        <div class="chart-card span-8">
            <div class="chart-header">
                <div class="chart-title">
                    Trend Perolehan Aset (6 Bulan Terakhir)
                </div>
            </div>
            <canvas id="trendChart" height="20"></canvas>
        </div>

        <!-- DISTRIBUSI KATEGORI -->
        <div class="chart-card span-4">
            <div class="chart-header">
                <div class="chart-title">
                    Top 5 Kategori
                </div>
            </div>
            <canvas id="categoryChart" height="100"></canvas>
        </div>

        <!-- ASET PER KANTOR -->
        <div class="chart-card span-6">
            <div class="chart-header">
                <div class="chart-title">
                    Distribusi Per Kantor
                </div>
            </div>
            <div style="max-height: 200px; overflow-y: auto;">
                <?php if (count($topKantor) > 0): ?>
                    <?php foreach ($topKantor as $kantor): ?>
                        <div class="list-item">
                            <div class="item-header">
                                <div class="item-name">
                                    <?= htmlspecialchars($kantor['kantor']) ?>
                                </div>
                                <div class="item-value"><?= number_format($kantor['jumlah']) ?></div>
                            </div>
                            <div class="item-detail">
                                Nilai: <?= formatRupiah($kantor['nilai']) ?>
                            </div>
                            <div class="progress-bar-wrapper">
                                <div class="progress-bar">
                                    <?php $percent = $totalNilai > 0 ? ($kantor['nilai'] / $totalNilai * 100) : 0; ?>
                                    <div class="progress-fill" style="width: <?= $percent ?>%"></div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="empty-state">
                        <i class="fas fa-building"></i>
                        <p>Belum ada data kantor</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- ASET PERLU PERHATIAN -->
        <div class="chart-card span-6">
            <div class="chart-header">
                <div class="chart-title">
                    Aset Perlu Perhatian
                </div>
            </div>
            <div style="max-height: 200px; overflow-y: auto;">
                <?php if ($asetBermasalah->num_rows > 0): ?>
                    <table>
                        <thead>
                            <tr>
                                <th>Nama Barang</th>
                                <th>Status</th>
                                <th>Lokasi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php while($row = $asetBermasalah->fetch_assoc()): ?>
                                <tr>
                                    <td>
                                        <strong><?= htmlspecialchars($row['jenis_barang']) ?></strong>
                                        <?php if (!empty($row['spesifikasi'])): ?>
                                            <br><small style="color: #64748b;"><?= htmlspecialchars(substr($row['spesifikasi'], 0, 40)) ?><?= strlen($row['spesifikasi']) > 40 ? '...' : '' ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php
                                        $badgeClass = 'info';
                                        $statusText = ucfirst($row['status']);
                                        if ($row['status'] === 'rusak') {
                                            $badgeClass = 'danger';
                                        } elseif ($row['status'] === 'hilang') {
                                            $badgeClass = 'warning';
                                        } elseif ($row['status'] === 'dipinjam') {
                                            $badgeClass = 'info';
                                        }
                                        ?>
                                        <span class="badge <?= $badgeClass ?>">
                                            <i class="fas fa-circle"></i>
                                            <?= $statusText ?>
                                        </span>
                                    </td>
                                    <td><?= htmlspecialchars($row['kantor']) ?></td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <div class="empty-state">
                        <i class="fas fa-check-circle"></i>
                        <p>Semua aset dalam kondisi baik</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- BREAKDOWN SUMBER DANA -->
        <div class="chart-card span-6">
            <div class="chart-header">
                <div class="chart-title">
                    Breakdown Sumber Dana
                </div>
            </div>
            <div style="max-height: 200px; overflow-y: auto;">
                <?php if (count($topSumberDana) > 0): ?>
                    <?php foreach ($topSumberDana as $dana): ?>
                        <div class="list-item">
                            <div class="item-header">
                                <div class="item-name">
                                    <?= htmlspecialchars($dana['sumber_dana']) ?>
                                </div>
                                <div class="item-value"><?= number_format($dana['jumlah']) ?></div>
                            </div>
                            <div class="item-detail">
                                Nilai: <?= formatRupiah($dana['nilai']) ?>
                            </div>
                            <div class="progress-bar-wrapper">
                                <div class="progress-bar">
                                    <?php $percent = $totalNilai > 0 ? ($dana['nilai'] / $totalNilai * 100) : 0; ?>
                                    <div class="progress-fill" style="width: <?= $percent ?>%"></div>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="empty-state">
                        <i class="fas fa-coins"></i>
                        <p>Belum ada data sumber dana</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- STATISTIK PENGGUNA -->
        <div class="chart-card span-6">
            <div class="chart-header">
                <div class="chart-title">
                    Statistik Pengguna Sistem
                </div>
            </div>
            <div style="max-height: 200px; overflow-y: auto;">
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px;">
                    <div class="list-item">
                        <div class="item-header">
                            <div class="item-name">
                                Total Pengguna
                            </div>
                            <div class="item-value" style="font-size: 24px;"><?= number_format($totalUsers) ?></div>
                        </div>
                        <div class="item-detail">Pengguna Aktif</div>
                    </div>
                    <?php 
                    $roleNames = [
                        'A' => 'Administrator',
                        'D' => 'Direktur',
                        'KD' => 'Kepala Dept',
                        'S' => 'Staff'
                    ];
                    ?>
                    <?php while($row = $usersByRole->fetch_assoc()): ?>
                        <div class="list-item">
                            <div class="item-header">
                                <div class="item-name">
                                    <?= $roleNames[$row['role']] ?? ucfirst($row['role']) ?>
                                </div>
                                <div class="item-value" style="font-size: 20px;"><?= number_format($row['jumlah']) ?></div>
                            </div>
                            <div class="item-detail">Pengguna</div>
                        </div>
                    <?php endwhile; ?>
                </div>
            </div>
        </div>
    </div>

    <script>
        // TREND CHART
        const trendCtx = document.getElementById('trendChart').getContext('2d');
        const trendLabels = [];
        const trendData = [];
        
        <?php 
        $trendPerolehan->data_seek(0);
        $monthNames = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Agu', 'Sep', 'Okt', 'Nov', 'Des'];
        while($row = $trendPerolehan->fetch_assoc()) {
            $parts = explode('-', $row['bulan']);
            $monthLabel = $monthNames[(int)$parts[1]] . " " . $parts[0];
            echo "trendLabels.push('" . $monthLabel . "');\n";
            echo "trendData.push(" . $row['jumlah_aset'] . ");\n";
        }
        ?>

        new Chart(trendCtx, {
            type: 'line',
            data: {
                labels: trendLabels,
                datasets: [{
                    label: 'Jumlah Aset Diperoleh',
                    data: trendData,
                    borderColor: '#8B5CF6',
                    backgroundColor: 'rgba(139, 92, 246, 0.1)',
                    tension: 0.4,
                    fill: true,
                    pointBackgroundColor: '#8B5CF6',
                    pointBorderColor: '#fff',
                    pointBorderWidth: 1,
                    pointRadius: 2
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            precision: 0,
                            font: {
                                size: 9
                            }
                        },
                        grid: {
                            color: '#f1f5f9'
                        }
                    },
                    x: {
                        ticks: {
                            font: {
                                size: 9
                            }
                        },
                        grid: {
                            display: false
                        }
                    }
                }
            }
        });

        // CATEGORY CHART
        const categoryCtx = document.getElementById('categoryChart').getContext('2d');
        const categoryLabels = [];
        const categoryData = [];
        
        <?php 
        foreach($topKategori as $kat) {
            echo "categoryLabels.push('" . htmlspecialchars($kat['kategori']) . "');\n";
            echo "categoryData.push(" . $kat['jumlah'] . ");\n";
        }
        ?>

        new Chart(categoryCtx, {
            type: 'doughnut',
            data: {
                labels: categoryLabels,
                datasets: [{
                    data: categoryData,
                    backgroundColor: [
                        '#8B5CF6',
                        '#3B82F6',
                        '#10B981',
                        '#F59E0B',
                        '#EF4444'
                    ],
                    borderWidth: 0
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 8,
                            font: {
                                size: 9,
                                family: 'Inter'
                            },
                            usePointStyle: true,
                            pointStyle: 'circle',
                            boxWidth: 8,
                            boxHeight: 8
                        }
                    }
                },
                cutout: '65%'
            }
        });
    </script>

</body>
</html>