<?php
session_start();

// Validasi session - Dept Head only
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    echo '<script>
        var redirectUrl = "../../index.html?error=session";
        if (window.self !== window.top) {
            window.top.location.href = redirectUrl;
        } else {
            window.location.href = redirectUrl;
        }
    </script>';
    exit;
}

$userRole = strtolower(trim($_SESSION['role'] ?? ''));

// ✅ FIX 1: Debug dengan console.log (tidak ganggu user)
// echo '<script>console.log("ROLE:", ' . json_encode($userRole) . ');</script>';

// ✅ FIX 2: Validasi role dengan benar
if ($userRole !== 'dept_head' && $userRole !== 'dh') {
    // ✅ FIX 3: Encoding URL yang aman
    $encodedRole = htmlspecialchars($userRole, ENT_QUOTES, 'UTF-8');
    echo '<script>
        var redirectUrl = "../../index.html?error=forbidden_' . $encodedRole . '";
        if (window.self !== window.top) {
            window.top.location.href = redirectUrl;
        } else {
            window.location.href = redirectUrl;
        }
    </script>';
    exit;
}

require_once __DIR__ . '/../../DataBase/koneksi.php';

// Query statistik
$totalBarang   = $conn->query("SELECT COUNT(*) total FROM inventory")->fetch_assoc()['total'] ?? 0;
$totalKategori = $conn->query("SELECT COUNT(DISTINCT kategori) total FROM inventory")->fetch_assoc()['total'] ?? 0;
$totalKantor   = $conn->query("SELECT COUNT(DISTINCT kantor) total FROM inventory")->fetch_assoc()['total'] ?? 0;

// Chart data - Top kategori
$chartData = [];
$q = $conn->query("SELECT kategori, COUNT(*) jumlah FROM inventory WHERE kategori IS NOT NULL AND kategori!='' GROUP BY kategori ORDER BY jumlah DESC LIMIT 5");
while ($r = $q->fetch_assoc()) { $chartData[] = $r; }

// Barang per kantor
$kantorData = [];
$qKantor = $conn->query("SELECT kantor, COUNT(*) jumlah FROM inventory WHERE kantor IS NOT NULL AND kantor!='' GROUP BY kantor ORDER BY jumlah DESC LIMIT 5");
while ($r = $qKantor->fetch_assoc()) { $kantorData[] = $r; }
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Dept Operasional - 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>
        :root {
            --primary-teal: #7AB2B2;      
            --secondary-teal: #4D869C;    
            --light-mint: #CDE8E5;        
            --lightest-mint: #EEF7FF;     
            --text-dark: #2c3e50;
            --bg-light: #f8fafc;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Inter', sans-serif; background: var(--bg-light); color: var(--text-dark); padding: 25px; }

        .dashboard-container { max-width: 1400px; margin: 0 auto; }

        /* Header */
        .header {
            background: linear-gradient(135deg, var(--secondary-teal), var(--primary-teal));
            color: white; padding: 40px; border-radius: 20px; margin-bottom: 25px;
            box-shadow: 0 15px 30px rgba(77, 134, 156, 0.2);
        }

        /* Stats Row */
        .stats-row { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-bottom: 25px; }
        .stat-card { background: white; padding: 25px; border-radius: 15px; border: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center; }
        .stat-val { font-size: 24px; font-weight: 800; color: var(--secondary-teal); }
        .stat-icon { width: 45px; height: 45px; background: var(--lightest-mint); color: var(--primary-teal); border-radius: 12px; display: flex; align-items: center; justify-content: center; }

        /* --- Grid Side-by-Side --- */
        .main-grid {
            display: grid;
            grid-template-columns: 1fr 1fr; /* Membagi 2 kolom sama besar */
            gap: 25px;
            align-items: stretch;
        }

        .card { 
            background: white; 
            padding: 30px; 
            border-radius: 20px; 
            border: 1px solid #e2e8f0; 
            height: 100%; /* Memastikan tinggi kartu sama */
        }

        .section-title { font-size: 18px; font-weight: 800; margin-bottom: 20px; display: flex; align-items: center; gap: 10px; }
        .section-title i { color: var(--primary-teal); }

        /* Progress Bar Style */
        .location-item { margin-bottom: 20px; }
        .bar-outer { height: 10px; background: #f1f5f9; border-radius: 10px; overflow: hidden; margin-top: 8px; }
        .bar-inner { height: 100%; background: linear-gradient(90deg, var(--secondary-teal), var(--primary-teal)); border-radius: 10px; }

        /* Mobile Responsive */
        @media (max-width: 992px) {
            .main-grid { grid-template-columns: 1fr; } /* Stack ke bawah di layar kecil */
            .stats-row { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>

<div class="dashboard-container">
    <div class="header">
        <h1>Dashboard Operasional</h1>
        <p>Ringkasan status aset ACF EDU HUB secara real-time.</p>
    </div>

    <div class="stats-row">
        <div class="stat-card">
            <div><p style="font-size:12px; font-weight:700; color:#64748b;">TOTAL ASET</p><div class="stat-val"><?= number_format($totalBarang) ?></div></div>
            <div class="stat-icon"><i class="fas fa-box"></i></div>
        </div>
        <div class="stat-card">
            <div><p style="font-size:12px; font-weight:700; color:#64748b;">KATEGORI</p><div class="stat-val"><?= $totalKategori ?></div></div>
            <div class="stat-icon"><i class="fas fa-tags"></i></div>
        </div>
        <div class="stat-card">
            <div><p style="font-size:12px; font-weight:700; color:#64748b;">LOKASI</p><div class="stat-val"><?= $totalKantor ?></div></div>
            <div class="stat-icon"><i class="fas fa-map-marker-alt"></i></div>
        </div>
    </div>

    <div class="main-grid">
        <div class="card">
            <h2 class="section-title"><i class="fas fa-chart-pie"></i> Top 5 Kategori</h2>
            <div style="height: 350px;">
                <canvas id="assetChart"></canvas>
            </div>
        </div>

        <div class="card">
            <h2 class="section-title"><i class="fas fa-building"></i> Sebaran Lokasi</h2>
            <div style="margin-top: 10px;">
                <?php 
                if(!empty($kantorData)):
                    $maxVal = max(array_column($kantorData, 'jumlah'));
                    foreach($kantorData as $k): 
                        $width = ($k['jumlah'] / $maxVal) * 100;
                ?>
                <div class="location-item">
                    <div style="display:flex; justify-content:space-between; font-size:13px; font-weight:600;">
                        <span><?= htmlspecialchars($k['kantor']) ?></span>
                        <span style="color: var(--secondary-teal);"><?= $k['jumlah'] ?> Item</span>
                    </div>
                    <div class="bar-outer"><div class="bar-inner" style="width: <?= $width ?>%"></div></div>
                </div>
                <?php endforeach; else: ?>
                    <p style="color:#94a3b8; text-align:center; padding-top:100px;">Data tidak ditemukan</p>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<script>
    const ctx = document.getElementById('assetChart').getContext('2d');
    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: <?= json_encode(array_column($chartData, 'kategori')) ?>,
            datasets: [{
                data: <?= json_encode(array_column($chartData, 'jumlah')) ?>,
                backgroundColor: [
                    '#1E3A47', // Midnight Teal
                    '#4D869C', // Secondary Teal
                    '#7AB2B2', // Primary Teal
                    '#A5D7D2', // Soft Mint
                    '#CDE8E5'  // Pale Mint
                ],
                borderWidth: 3,
                borderColor: '#ffffff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { position: 'bottom', labels: { usePointStyle: true, padding: 20 } }
            },
            cutout: '70%'
        }
    });
</script>
</body>
</html>