<?php
require_once __DIR__ . '/../../config/session_check.php';
require_once __DIR__ . '/../../DataBase/koneksi.php';

if (!checkRole(['S', 'staff'])) {
    echo '<div style="padding: 40px; text-align: center;">
            <h2>Access Denied</h2>
            <p>Halaman ini khusus untuk Staff.</p>
          </div>';
    exit;
}

$totalBarang   = $conn->query("SELECT COUNT(*) total FROM inventory")->fetch_assoc()['total'] ?? 0;
$totalNilai    = $conn->query("SELECT SUM(harga_perolehan) 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;

$currentMonth = date('Y-m');
$barangBaru = $conn->query("
    SELECT COUNT(*) total 
    FROM inventory 
    WHERE DATE_FORMAT(tanggal_perolehan,'%Y-%m') = '$currentMonth'
")->fetch_assoc()['total'] ?? 0;

$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;
}

$barangTerbaru = $conn->query("
    SELECT jenis_barang, kantor, harga_perolehan, tanggal_perolehan
    FROM inventory
    ORDER BY tanggal_perolehan DESC, id DESC
    LIMIT 5
");
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Staff Dashboard - ACF EDU HUB</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: -apple-system, BlinkMacSystemFont, 'Inter', 'Segoe UI', sans-serif;
    background: #fafbfc;
    padding: 0;
    min-height: 100vh;
}

.dashboard-wrapper {
    padding: 24px;
    max-width: 100%;
    overflow-x: hidden;
}

.header {
    background: #8B4789;
    color: white;
    padding: 32px;
    border-radius: 16px;
    margin-bottom: 24px;
    box-shadow: 0 4px 6px -1px rgba(139, 71, 137, 0.2);
}

.header h1 {
    font-size: 28px;
    font-weight: 700;
    margin-bottom: 4px;
}

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

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    margin-bottom: 24px;
}

.stat-card {
    background: white;
    padding: 20px;
    border-radius: 12px;
    border: 1px solid #e5e7eb;
    transition: all 0.2s;
    position: relative;
    overflow: hidden;
}

.stat-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 4px;
    height: 100%;
    background: #8B4789;
}

.stat-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(139, 71, 137, 0.15);
    border-color: #8B4789;
}

.stat-label {
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    color: #9ca3af;
    margin-bottom: 8px;
}

.stat-value {
    font-size: 28px;
    font-weight: 700;
    color: #111827;
}

.stat-value.currency {
    font-size: 20px;
    color: #8B4789;
}

.section-title {
    font-size: 18px;
    font-weight: 700;
    color: #111827;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.section-title i {
    color: #8B4789;
}

.actions-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    margin-bottom: 24px;
}

.action-card {
    background: white;
    padding: 24px;
    border-radius: 12px;
    border: 2px solid #e5e7eb;
    text-align: center;
    text-decoration: none;
    color: #111827;
    transition: all 0.2s;
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 12px;
    cursor: pointer;
}

.action-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 10px 20px rgba(139, 71, 137, 0.15);
    border-color: #8B4789;
}

.action-card:hover .action-icon {
    background: #8B4789;
    color: white;
}

.action-icon {
    width: 56px;
    height: 56px;
    background: #8B478915;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: #8B4789;
    transition: all 0.2s;
}

.action-title {
    font-size: 15px;
    font-weight: 600;
}

.card {
    background: white;
    padding: 24px;
    border-radius: 12px;
    border: 1px solid #e5e7eb;
    margin-bottom: 24px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.chart-container {
    position: relative;
    height: 280px;
}

.recent-item {
    padding: 16px;
    border-bottom: 1px solid #f3f4f6;
    display: flex;
    justify-content: space-between;
    align-items: center;
    transition: background 0.2s;
}

.recent-item:hover {
    background: #fafbfc;
}

.recent-item:last-child {
    border-bottom: none;
}

.item-info {
    flex: 1;
    min-width: 0;
}

.item-name {
    font-weight: 600;
    color: #111827;
    margin-bottom: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.item-detail {
    font-size: 13px;
    color: #6b7280;
}

.item-detail i {
    color: #8B4789;
}

.item-price {
    font-weight: 700;
    color: #8B4789;
    white-space: nowrap;
    margin-left: 16px;
    font-size: 15px;
}

.empty-state {
    text-align: center;
    padding: 40px;
    color: #9ca3af;
}

.empty-state i {
    font-size: 48px;
    margin-bottom: 12px;
    display: block;
    color: #cbd5e1;
}

::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
}

::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
    background: #8B4789;
}

@media (max-width: 768px) {
    .dashboard-wrapper {
        padding: 16px;
    }
    
    .header {
        padding: 24px;
    }
    
    .header h1 {
        font-size: 22px;
    }
    
    .stats-grid, .actions-grid {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .stat-value {
        font-size: 24px;
    }
    
    .stat-value.currency {
        font-size: 18px;
    }
}

@media (max-width: 480px) {
    .stats-grid, .actions-grid {
        grid-template-columns: 1fr;
    }
    
    .item-detail {
        font-size: 12px;
    }
    
    .item-price {
        font-size: 14px;
    }
}
</style>
</head>
<body>

<div class="dashboard-wrapper">
    <div class="header">
        <h1>Halo, <?= htmlspecialchars($_SESSION['full_name'] ?? $_SESSION['username']) ?></h1>
        <p>Welcome back to ACF EDU HUB Inventory System</p>
    </div>

    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-label">Total Items</div>
            <div class="stat-value"><?= number_format($totalBarang) ?></div>
        </div>
        <div class="stat-card">
            <div class="stat-label">Asset Value</div>
            <div class="stat-value currency">Rp <?= number_format($totalNilai, 0, ',', '.') ?></div>
        </div>
        <div class="stat-card">
            <div class="stat-label">Categories</div>
            <div class="stat-value"><?= $totalKategori ?></div>
        </div>
        <div class="stat-card">
            <div class="stat-label">Offices</div>
            <div class="stat-value"><?= $totalKantor ?></div>
        </div>
        <div class="stat-card">
            <div class="stat-label">New This Month</div>
            <div class="stat-value"><?= $barangBaru ?></div>
        </div>
    </div>

    <h2 class="section-title">
        <i class="fas fa-bolt"></i> Quick Actions
    </h2>
    <div class="actions-grid">
        <a href="inventory_list_staff.php" class="action-card" onclick="loadPage(this.href); return false;">
            <div class="action-icon">
                <i class="fas fa-list"></i>
            </div>
            <div class="action-title">View Inventory</div>
        </a>
        <a href="barang_masuk.php" class="action-card" onclick="loadPage(this.href); return false;">
            <div class="action-icon">
                <i class="fas fa-arrow-down"></i>
            </div>
            <div class="action-title">Incoming Items</div>
        </a>
        <a href="barang_keluar.php" class="action-card" onclick="loadPage(this.href); return false;">
            <div class="action-icon">
                <i class="fas fa-arrow-up"></i>
            </div>
            <div class="action-title">Outgoing Items</div>
        </a>
        <a href="laporan_staff.php" class="action-card" onclick="loadPage(this.href); return false;">
            <div class="action-icon">
                <i class="fas fa-chart-line"></i>
            </div>
            <div class="action-title">Reports</div>
        </a>
    </div>

    <div class="card">
        <h2 class="section-title">
            <i class="fas fa-chart-pie"></i> Top 5 Categories
        </h2>
        <div class="chart-container">
            <canvas id="chartKategori"></canvas>
        </div>
    </div>

    <div class="card">
        <h2 class="section-title">
            <i class="fas fa-clock"></i> Recent Items
        </h2>
        <?php if($barangTerbaru->num_rows > 0): ?>
            <?php while($b = $barangTerbaru->fetch_assoc()): ?>
                <div class="recent-item">
                    <div class="item-info">
                        <div class="item-name"><?= htmlspecialchars($b['jenis_barang']) ?></div>
                        <div class="item-detail">
                            <i class="fas fa-building"></i> <?= htmlspecialchars($b['kantor']) ?>
                            <span style="margin: 0 8px;">•</span>
                            <i class="fas fa-calendar"></i> <?= date('d M Y', strtotime($b['tanggal_perolehan'])) ?>
                        </div>
                    </div>
                    <div class="item-price">
                        Rp <?= number_format($b['harga_perolehan'], 0, ',', '.') ?>
                    </div>
                </div>
            <?php endwhile; ?>
        <?php else: ?>
            <div class="empty-state">
                <i class="fas fa-inbox"></i>
                <p>No recent items</p>
            </div>
        <?php endif; ?>
    </div>
</div>

<script>
function loadPage(url) {
    try {
        if (window.parent && window.parent !== window) {
            window.location.href = url;
        } else {
            window.location.href = url;
        }
    } catch (e) {
        console.error('Error loading page:', e);
        window.location.href = url;
    }
}

if (typeof Chart !== 'undefined') {
    const ctx = document.getElementById('chartKategori');
    if (ctx) {
        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: <?= json_encode(array_column($chartData, 'kategori')) ?>,
                datasets: [{
                    data: <?= json_encode(array_column($chartData, 'jumlah')) ?>,
                    backgroundColor: [
                        '#8B4789',
                        '#F4B840',
                        '#6366f1',
                        '#ec4899',
                        '#10b981'
                    ],
                    borderWidth: 0,
                    hoverOffset: 8
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 20,
                            font: {
                                size: 12,
                                family: '-apple-system, BlinkMacSystemFont, Inter, Segoe UI, sans-serif'
                            },
                            usePointStyle: true,
                            pointStyle: 'circle'
                        }
                    },
                    tooltip: {
                        backgroundColor: 'rgba(0, 0, 0, 0.8)',
                        padding: 12,
                        titleFont: {
                            size: 14,
                            weight: 'bold'
                        },
                        bodyFont: {
                            size: 13
                        },
                        cornerRadius: 8
                    }
                }
            }
        });
    }
} else {
    console.error('Chart.js not loaded');
}
</script>

</body>
</html>