<?php
session_start();

// 1. Validasi session - Manager & Operasional
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true) {
    header("Location: ../../index.html?error=session");
    exit;
}

$userRole = strtoupper(trim($_SESSION['role'] ?? ''));
$allowedRoles = ['M', 'O', 'A']; // Manager, Operasional, Admin

if (!in_array($userRole, $allowedRoles)) {
    header("Location: ../../index.html?error=forbidden");
    exit;
}

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

// Tentukan nama role untuk display
$roleNames = [
    'M' => 'Manager',
    'O' => 'Operasional',
    'A' => 'Admin'
];
$displayRole = $roleNames[$userRole] ?? 'User';
$userName = $_SESSION['username'] ?? 'Pengguna';

// 2. Logika Filter yang Lebih Lengkap
$start_date = isset($_GET['start']) ? mysqli_real_escape_string($conn, $_GET['start']) : '';
$end_date = isset($_GET['end']) ? mysqli_real_escape_string($conn, $_GET['end']) : '';
$filter_kantor = isset($_GET['kantor']) ? mysqli_real_escape_string($conn, $_GET['kantor']) : '';
$filter_kategori = isset($_GET['kategori']) ? mysqli_real_escape_string($conn, $_GET['kategori']) : '';
$filter_status = isset($_GET['status']) ? mysqli_real_escape_string($conn, $_GET['status']) : '';

$whereClause = "1=1";
if (!empty($start_date) && !empty($end_date)) {
    $whereClause .= " AND tanggal_perolehan BETWEEN '$start_date' AND '$end_date'";
}
if (!empty($filter_kantor)) {
    $whereClause .= " AND kantor = '$filter_kantor'";
}
if (!empty($filter_kategori)) {
    $whereClause .= " AND kategori = '$filter_kategori'";
}
if (!empty($filter_status)) {
    $whereClause .= " AND status = '$filter_status'";
}

// 3. Data untuk Filter Options
$kantorList = [];
$qKantor = mysqli_query($conn, "SELECT DISTINCT kantor FROM inventory WHERE kantor IS NOT NULL ORDER BY kantor");
while($r = mysqli_fetch_assoc($qKantor)) { $kantorList[] = $r['kantor']; }

$kategoriList = [];
$qKat = mysqli_query($conn, "SELECT DISTINCT kategori FROM inventory WHERE kategori IS NOT NULL ORDER BY kategori");
while($r = mysqli_fetch_assoc($qKat)) { $kategoriList[] = $r['kategori']; }

// 4. Pengambilan Data (Query)
// Statistik Utama
$queryTotal = "SELECT COUNT(*) as total, SUM(harga_perolehan) as total_nilai FROM inventory WHERE $whereClause";
$resultTotal = mysqli_query($conn, $queryTotal);
$rowTotal = mysqli_fetch_assoc($resultTotal);
$totalAset = $rowTotal['total'] ?? 0;
$totalNilai = $rowTotal['total_nilai'] ?? 0;

// Data Kondisi - Skip jika kolom tidak ada
$dataKondisi = [];
$checkKondisi = mysqli_query($conn, "SHOW COLUMNS FROM inventory LIKE 'kondisi'");
if (mysqli_num_rows($checkKondisi) > 0) {
    $queryKondisi = "SELECT kondisi, COUNT(*) as jumlah FROM inventory WHERE $whereClause GROUP BY kondisi";
    $resKondisi = mysqli_query($conn, $queryKondisi);
    while($row = mysqli_fetch_assoc($resKondisi)) { $dataKondisi[] = $row; }
}

// Data Status
$dataStatus = [];
$queryStatus = "SELECT status, COUNT(*) as jumlah FROM inventory WHERE $whereClause GROUP BY status";
$resStatus = mysqli_query($conn, $queryStatus);
while($row = mysqli_fetch_assoc($resStatus)) { $dataStatus[] = $row; }

// Data Kantor (Untuk Chart)
$dataKantor = [];
$queryKantor = "SELECT kantor, COUNT(*) as jumlah, SUM(harga_perolehan) as nilai FROM inventory WHERE $whereClause GROUP BY kantor ORDER BY jumlah DESC";
$resKantor = mysqli_query($conn, $queryKantor);
while($row = mysqli_fetch_assoc($resKantor)) { $dataKantor[] = $row; }

// Data Kategori
$dataKategori = [];
$queryKategori = "SELECT kategori, COUNT(*) as jumlah, SUM(harga_perolehan) as nilai FROM inventory WHERE $whereClause GROUP BY kategori ORDER BY jumlah DESC LIMIT 8";
$resKat = mysqli_query($conn, $queryKategori);
while($row = mysqli_fetch_assoc($resKat)) { $dataKategori[] = $row; }

// Data Trend Perolehan per Bulan (6 bulan terakhir)
$dataTrend = [];
$queryTrend = "SELECT DATE_FORMAT(tanggal_perolehan, '%Y-%m') as bulan, 
               COUNT(*) as jumlah, 
               SUM(harga_perolehan) as nilai 
               FROM inventory 
               WHERE $whereClause 
               GROUP BY DATE_FORMAT(tanggal_perolehan, '%Y-%m') 
               ORDER BY bulan DESC 
               LIMIT 6";
$resTrend = mysqli_query($conn, $queryTrend);
while($row = mysqli_fetch_assoc($resTrend)) { $dataTrend[] = $row; }
$dataTrend = array_reverse($dataTrend);

// Detail Inventory dengan Pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

$queryCount = "SELECT COUNT(*) as total FROM inventory WHERE $whereClause";
$resultCount = mysqli_query($conn, $queryCount);
$totalRecords = mysqli_fetch_assoc($resultCount)['total'];
$totalPages = ceil($totalRecords / $perPage);

$queryInventory = "SELECT * FROM inventory WHERE $whereClause ORDER BY tanggal_perolehan DESC LIMIT $offset, $perPage";
$resultInventory = mysqli_query($conn, $queryInventory);

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

function formatTanggal($tanggal) {
    $bulan = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'Mei', 'Jun', 'Jul', 'Ags', 'Sep', 'Okt', 'Nov', 'Des'];
    $split = explode('-', $tanggal);
    return $split[2] . ' ' . $bulan[(int)$split[1]] . ' ' . $split[0];
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laporan Inventaris - 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://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    <style>
        :root {
            --primary-teal: #7AB2B2;
            --secondary-teal: #4D869C;
            --light-mint: #CDE8E5;
            --lightest-mint: #EEF7FF;
            --bg-body: #f8fafc;
            --text-dark: #1e293b;
            --border-color: #e2e8f0;
        }

        * { margin: 0; padding: 0; box-sizing: border-box; }

        body {
            font-family: 'Inter', 'Segoe UI', sans-serif;
            background-color: var(--bg-body);
            color: var(--text-dark);
            padding: 20px;
            line-height: 1.6;
        }

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

        /* Header Section */
        .dashboard-header {
            background: linear-gradient(135deg, var(--primary-teal) 0%, var(--secondary-teal) 100%);
            color: white;
            padding: 30px;
            border-radius: 16px;
            box-shadow: 0 8px 20px rgba(122, 178, 178, 0.3);
            margin-bottom: 25px;
        }

        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 20px;
        }

        .header-title h1 { 
            font-size: 28px; 
            font-weight: 800; 
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 12px;
        }

        .header-title p { 
            opacity: 0.9; 
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .header-actions {
            display: flex;
            gap: 12px;
            flex-wrap: wrap;
        }

        /* User Info Badge */
        .user-badge {
            background: rgba(255,255,255,0.2);
            backdrop-filter: blur(10px);
            padding: 12px 20px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            gap: 12px;
            border: 1px solid rgba(255,255,255,0.3);
        }

        .user-badge i {
            font-size: 24px;
        }

        .user-info strong {
            display: block;
            font-size: 15px;
            margin-bottom: 2px;
        }

        .user-info small {
            font-size: 12px;
            opacity: 0.9;
        }

        /* Filter Section */
        .filter-card {
            background: white;
            padding: 25px;
            border-radius: 16px;
            margin-bottom: 25px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.08);
            border: 1px solid var(--border-color);
        }

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

        .filter-header h3 {
            font-size: 18px;
            color: var(--secondary-teal);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .filter-row { 
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
            gap: 20px;
            margin-bottom: 20px;
        }

        .filter-group label { 
            display: block; 
            font-size: 12px; 
            font-weight: 700; 
            color: #64748b; 
            margin-bottom: 8px; 
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .input-with-icon { 
            position: relative; 
            display: flex; 
            align-items: center; 
        }

        .input-with-icon i { 
            position: absolute; 
            left: 14px; 
            color: var(--primary-teal); 
            font-size: 14px;
            z-index: 1;
        }
        
        .filter-control {
            width: 100%; 
            padding: 12px 14px 12px 42px;
            border: 2px solid var(--border-color); 
            border-radius: 10px;
            font-size: 14px; 
            outline: none; 
            transition: all 0.3s ease;
            background: white;
        }

        .filter-control:focus { 
            border-color: var(--primary-teal); 
            box-shadow: 0 0 0 4px rgba(122, 178, 178, 0.1); 
        }

        .filter-actions {
            display: flex;
            gap: 12px;
            align-items: flex-end;
        }

        /* Buttons */
        .btn {
            padding: 12px 24px; 
            border-radius: 10px; 
            text-decoration: none;
            font-weight: 700; 
            font-size: 14px; 
            display: inline-flex;
            align-items: center; 
            gap: 8px; 
            cursor: pointer; 
            border: none; 
            transition: all 0.3s ease;
            white-space: nowrap;
        }

        .btn-primary { 
            background: var(--primary-teal); 
            color: white; 
        }

        .btn-primary:hover { 
            background: var(--secondary-teal);
            transform: translateY(-2px); 
            box-shadow: 0 6px 20px rgba(122, 178, 178, 0.4);
        }

        .btn-outline { 
            background: white; 
            color: var(--text-dark); 
            border: 2px solid var(--border-color); 
        }

        .btn-outline:hover {
            background: var(--bg-body);
            border-color: var(--primary-teal);
        }

        .btn-secondary {
            background: var(--light-mint);
            color: var(--text-dark);
            border: 2px solid var(--primary-teal);
        }

        .btn-secondary:hover {
            background: var(--primary-teal);
            color: white;
            transform: translateY(-2px);
        }

        /* Grid Stats */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 20px; 
            margin-bottom: 30px;
        }

        .stat-card {
            background: white; 
            padding: 24px; 
            border-radius: 16px;
            display: flex; 
            align-items: center; 
            gap: 18px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.06);
            border: 1px solid var(--border-color);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-4px);
            box-shadow: 0 8px 24px rgba(0,0,0,0.12);
        }

        .stat-icon {
            width: 60px; 
            height: 60px; 
            border-radius: 14px;
            display: flex; 
            align-items: center; 
            justify-content: center; 
            font-size: 26px;
            flex-shrink: 0;
        }

        .stat-content {
            flex: 1;
        }

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

        .stat-value {
            font-size: 24px; 
            font-weight: 800;
            color: var(--text-dark);
            line-height: 1;
        }

        .stat-unit {
            font-size: 13px;
            font-weight: 400;
            color: #64748b;
            margin-left: 4px;
        }

        /* Content Layout */
        .content-row { 
            display: grid; 
            grid-template-columns: 1.5fr 1fr; 
            gap: 20px; 
            margin-bottom: 25px; 
        }

        .card-panel { 
            background: white; 
            padding: 28px; 
            border-radius: 16px; 
            box-shadow: 0 4px 12px rgba(0,0,0,0.06);
            border: 1px solid var(--border-color);
        }

        .card-panel h2 { 
            font-size: 18px; 
            margin-top: 0; 
            margin-bottom: 24px; 
            color: var(--secondary-teal); 
            display: flex; 
            align-items: center; 
            gap: 10px;
            font-weight: 700;
            padding-bottom: 16px;
            border-bottom: 2px solid var(--light-mint);
        }

        /* Chart Container */
        .chart-container {
            height: 340px;
            position: relative;
        }

        /* Table Style */
        .table-container { 
            overflow-x: auto;
            border-radius: 12px;
            border: 1px solid var(--border-color);
        }

        table { 
            width: 100%; 
            border-collapse: collapse;
            font-size: 13px;
        }

        table th { 
            text-align: left; 
            padding: 16px 14px; 
            background: var(--bg-body); 
            color: #64748b; 
            font-size: 11px; 
            text-transform: uppercase;
            font-weight: 700;
            letter-spacing: 0.5px;
            border-bottom: 2px solid var(--border-color);
            position: sticky;
            top: 0;
            z-index: 10;
        }

        table td { 
            padding: 16px 14px; 
            border-bottom: 1px solid var(--border-color);
        }

        table tbody tr:hover {
            background: var(--bg-body);
        }

        table tbody tr:last-child td {
            border-bottom: none;
        }
        
        .badge { 
            padding: 6px 14px; 
            border-radius: 8px; 
            font-size: 11px; 
            font-weight: 700; 
            text-transform: uppercase;
            display: inline-block;
            letter-spacing: 0.3px;
        }

        .badge-success { background: #d1fae5; color: #065f46; }
        .badge-warning { background: #fef3c7; color: #92400e; }
        .badge-danger { background: #fee2e2; color: #991b1b; }
        .badge-info { background: #dbeafe; color: #1e40af; }

        /* Pagination */
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
            margin-top: 24px;
            padding-top: 24px;
            border-top: 1px solid var(--border-color);
        }

        .pagination a,
        .pagination span {
            padding: 10px 16px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: 600;
            font-size: 13px;
            transition: all 0.3s ease;
        }

        .pagination a {
            background: white;
            color: var(--text-dark);
            border: 2px solid var(--border-color);
        }

        .pagination a:hover {
            background: var(--primary-teal);
            color: white;
            border-color: var(--primary-teal);
        }

        .pagination .active {
            background: var(--primary-teal);
            color: white;
            border: 2px solid var(--primary-teal);
        }

        /* Alert Box */
        .alert {
            padding: 16px 20px;
            border-radius: 12px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 12px;
            font-size: 14px;
        }

        .alert-info {
            background: #dbeafe;
            color: #1e40af;
            border-left: 4px solid #1e40af;
        }

        /* Summary Box */
        .summary-box {
            background: linear-gradient(135deg, var(--lightest-mint), white);
            padding: 20px;
            border-radius: 12px;
            border-left: 4px solid var(--primary-teal);
            margin-bottom: 20px;
        }

        .summary-box h4 {
            color: var(--secondary-teal);
            margin-bottom: 12px;
            font-size: 15px;
        }

        .summary-items {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 16px;
        }

        .summary-item {
            display: flex;
            justify-content: space-between;
            padding: 10px;
            background: white;
            border-radius: 8px;
            font-size: 13px;
        }

        .summary-item strong {
            color: var(--primary-teal);
            font-weight: 700;
        }

        /* Print Styles */
        @media print { 
            .no-print { display: none !important; } 
            body { background: white; padding: 0; } 
            .card-panel { 
                box-shadow: none; 
                border: 1px solid #ddd;
                page-break-inside: avoid;
            }
            .dashboard-header {
                background: white;
                color: var(--text-dark);
                border: 2px solid var(--acf-purple);
            }
            .stat-card {
                box-shadow: none;
                border: 1px solid #ddd;
            }
        }

        /* Responsive */
        @media (max-width: 1200px) { 
            .content-row { grid-template-columns: 1fr; } 
        }

        @media (max-width: 768px) {
            body { padding: 12px; }
            
            .dashboard-header { padding: 20px; }
            
            .header-title h1 { font-size: 20px; }
            
            .filter-card { padding: 18px; }
            
            .filter-row {
                grid-template-columns: 1fr;
            }

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

            .stat-card {
                padding: 18px;
            }

            .card-panel {
                padding: 20px;
            }

            .table-container {
                font-size: 12px;
            }

            table th,
            table td {
                padding: 12px 8px;
            }
        }
    </style>
</head>
<body>

<div class="container">
    <!-- Header -->
    <header class="dashboard-header no-print">
        <div class="header-content">
            <div class="header-title">
                <h1>
                    <i class="fas fa-chart-line"></i> 
                    LAPORAN INVENTARIS ASET
                </h1>
                <p>
                    <i class="fas fa-building"></i> ACF EDU HUB • 
                    <i class="fas fa-calendar"></i> <?= date('d F Y') ?>
                </p>
            </div>
            <div class="user-badge">
                <i class="fas fa-user-circle"></i>
                <div class="user-info">
                    <strong><?= htmlspecialchars($userName) ?></strong>
                    <small><?= $displayRole ?></small>
                </div>
            </div>
        </div>
        <div class="header-actions" style="margin-top: 20px;">
            <a href="<?= $userRole === 'M' ? 'home_manager.php' : ($userRole === 'O' ? 'home_operasional.php' : '../admin/home_admin.php') ?>" class="btn btn-outline">
                <i class="fas fa-arrow-left"></i> Dashboard
            </a>
            <button onclick="window.print()" class="btn btn-secondary">
                <i class="fas fa-print"></i> Cetak Laporan
            </button>
            <button onclick="exportToExcel()" class="btn btn-primary">
                <i class="fas fa-file-excel"></i> Export Excel
            </button>
        </div>
    </header>

    <!-- Filter Section -->
    <form method="GET" class="filter-card no-print">
        <div class="filter-header">
            <h3><i class="fas fa-filter"></i> Filter & Pencarian</h3>
            <span style="color: #64748b; font-size: 13px;">
                <i class="fas fa-info-circle"></i> Gunakan filter untuk mempersempit data
            </span>
        </div>
        
        <div class="filter-row">
            <div class="filter-group">
                <label><i class="fas fa-calendar-alt"></i> Tanggal Mulai</label>
                <div class="input-with-icon">
                    <i class="fas fa-calendar-alt"></i>
                    <input type="date" name="start" value="<?= htmlspecialchars($start_date) ?>" class="filter-control">
                </div>
            </div>
            
            <div class="filter-group">
                <label><i class="fas fa-calendar-check"></i> Tanggal Akhir</label>
                <div class="input-with-icon">
                    <i class="fas fa-calendar-check"></i>
                    <input type="date" name="end" value="<?= htmlspecialchars($end_date) ?>" class="filter-control">
                </div>
            </div>

            <div class="filter-group">
                <label><i class="fas fa-building"></i> Lokasi Kantor</label>
                <div class="input-with-icon">
                    <i class="fas fa-building"></i>
                    <select name="kantor" class="filter-control">
                        <option value="">-- Semua Kantor --</option>
                        <?php foreach($kantorList as $k): ?>
                        <option value="<?= htmlspecialchars($k) ?>" <?= $filter_kantor === $k ? 'selected' : '' ?>>
                            <?= htmlspecialchars($k) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="filter-group">
                <label><i class="fas fa-tags"></i> Kategori</label>
                <div class="input-with-icon">
                    <i class="fas fa-tags"></i>
                    <select name="kategori" class="filter-control">
                        <option value="">-- Semua Kategori --</option>
                        <?php foreach($kategoriList as $k): ?>
                        <option value="<?= htmlspecialchars($k) ?>" <?= $filter_kategori === $k ? 'selected' : '' ?>>
                            <?= htmlspecialchars($k) ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="filter-group">
                <label><i class="fas fa-info-circle"></i> Status</label>
                <div class="input-with-icon">
                    <i class="fas fa-info-circle"></i>
                    <select name="status" class="filter-control">
                        <option value="">-- Semua Status --</option>
                        <option value="Aktif" <?= $filter_status === 'Aktif' ? 'selected' : '' ?>>Aktif</option>
                        <option value="Tidak Aktif" <?= $filter_status === 'Tidak Aktif' ? 'selected' : '' ?>>Tidak Aktif</option>
                        <option value="Rusak" <?= $filter_status === 'Rusak' ? 'selected' : '' ?>>Rusak</option>
                    </select>
                </div>
            </div>
        </div>

        <div class="filter-actions">
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-search"></i> Terapkan Filter
            </button>
            <a href="?" class="btn btn-outline">
                <i class="fas fa-undo"></i> Reset
            </a>
        </div>
    </form>

    <!-- Alert Info jika ada filter aktif -->
    <?php if (!empty($start_date) || !empty($filter_kantor) || !empty($filter_kategori) || !empty($filter_status)): ?>
    <div class="alert alert-info no-print">
        <i class="fas fa-filter"></i>
        <span>
            <strong>Filter Aktif:</strong>
            <?php if (!empty($start_date)): ?>Periode: <?= formatTanggal($start_date) ?> - <?= formatTanggal($end_date) ?> • <?php endif; ?>
            <?php if (!empty($filter_kantor)): ?>Kantor: <?= htmlspecialchars($filter_kantor) ?> • <?php endif; ?>
            <?php if (!empty($filter_kategori)): ?>Kategori: <?= htmlspecialchars($filter_kategori) ?> • <?php endif; ?>
            <?php if (!empty($filter_status)): ?>Status: <?= htmlspecialchars($filter_status) ?><?php endif; ?>
        </span>
    </div>
    <?php endif; ?>

    <!-- Statistics Cards -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon" style="background:var(--light-mint); color:var(--primary-teal);">
                <i class="fas fa-layer-group"></i>
            </div>
            <div class="stat-content">
                <div class="stat-label">Total Aset</div>
                <div class="stat-value">
                    <?= number_format($totalAset) ?>
                    <span class="stat-unit">Unit</span>
                </div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon" style="background:#dbeafe; color:#1e40af;">
                <i class="fas fa-wallet"></i>
            </div>
            <div class="stat-content">
                <div class="stat-label">Nilai Investasi</div>
                <div class="stat-value" style="color:var(--secondary-teal); font-size: 20px;">
                    <?= formatRupiah($totalNilai) ?>
                </div>
            </div>
        </div>

        <?php 
        $kondisiAktif = 0;
        $kondisiRusak = 0;
        foreach($dataStatus as $s) {
            if (strtolower($s['status']) === 'aktif') {
                $kondisiAktif = $s['jumlah'];
            } else {
                $kondisiRusak += $s['jumlah'];
            }
        }
        ?>

        <div class="stat-card">
            <div class="stat-icon" style="background:#d1fae5; color:#16a34a;">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="stat-content">
                <div class="stat-label">Aset Aktif</div>
                <div class="stat-value">
                    <?= number_format($kondisiAktif) ?>
                    <span class="stat-unit">Unit</span>
                </div>
            </div>
        </div>

        <div class="stat-card">
            <div class="stat-icon" style="background:#fee2e2; color:#dc2626;">
                <i class="fas fa-exclamation-triangle"></i>
            </div>
            <div class="stat-content">
                <div class="stat-label">Perlu Perhatian</div>
                <div class="stat-value">
                    <?= number_format($kondisiRusak) ?>
                    <span class="stat-unit">Unit</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row -->
    <div class="content-row">
        <div class="card-panel">
            <h2><i class="fas fa-chart-bar"></i> Distribusi Aset Per Lokasi</h2>
            <div class="chart-container">
                <canvas id="chartKantor"></canvas>
            </div>
        </div>

        <div class="card-panel">
            <h2><i class="fas fa-chart-pie"></i> Top Kategori Aset</h2>
            <div class="chart-container">
                <canvas id="chartKategori"></canvas>
            </div>
        </div>
    </div>

    <!-- Trend Chart -->
    <?php if (!empty($dataTrend)): ?>
    <div class="card-panel">
        <h2><i class="fas fa-chart-line"></i> Trend Perolehan Aset (6 Bulan Terakhir)</h2>
        <div class="chart-container">
            <canvas id="chartTrend"></canvas>
        </div>
    </div>
    <?php endif; ?>

    <!-- Summary Box -->
    <?php if (!empty($dataKondisi)): ?>
    <div class="summary-box">
        <h4><i class="fas fa-clipboard-list"></i> Ringkasan Kondisi Aset</h4>
        <div class="summary-items">
            <?php foreach($dataKondisi as $k): ?>
            <div class="summary-item">
                <span><?= htmlspecialchars($k['kondisi'] ?? 'Tidak Diketahui') ?></span>
                <strong><?= number_format($k['jumlah']) ?> Unit</strong>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Detail Table -->
    <div class="card-panel">
        <h2><i class="fas fa-table"></i> Detail Inventaris Lengkap</h2>
        <div style="margin-bottom: 16px; color: #64748b; font-size: 13px;">
            <i class="fas fa-info-circle"></i> 
            Menampilkan <?= number_format($totalRecords) ?> data aset
        </div>
        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th style="width: 50px;">No</th>
                        <th>Kode Aset</th>
                        <th>Tanggal</th>
                        <th>Nama Barang</th>
                        <th>Kategori</th>
                        <th>Lokasi</th>
                        <th>Status</th>
                        <th style="text-align:right;">Harga</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $no = $offset + 1; 
                    while($row = mysqli_fetch_assoc($resultInventory)): 
                    ?>
                    <tr>
                        <td style="text-align: center; font-weight: 600;"><?= $no++ ?></td>
                        <td>
                            <strong style="color:var(--primary-teal); font-family: 'Courier New', monospace;">
                                <?= htmlspecialchars($row['kode_aset_auto'] ?? $row['kode_aset'] ?? '-') ?>
                            </strong>
                        </td>
                        <td style="white-space: nowrap;">
                            <?= date('d/m/Y', strtotime($row['tanggal_perolehan'])) ?>
                        </td>
                        <td><strong><?= htmlspecialchars($row['jenis_barang']) ?></strong></td>
                        <td><?= htmlspecialchars($row['kategori']) ?></td>
                        <td>
                            <i class="fas fa-map-marker-alt" style="color: var(--primary-teal);"></i>
                            <?= htmlspecialchars($row['kantor']) ?>
                        </td>
                        <td>
                            <?php
                            $status = strtolower($row['status'] ?? 'aktif');
                            $statusBadge = $status === 'aktif' ? 'badge-success' : 'badge-danger';
                            ?>
                            <span class="badge <?= $statusBadge ?>">
                                <?= htmlspecialchars($row['status'] ?? 'Aktif') ?>
                            </span>
                        </td>
                        <td style="text-align:right; font-weight:700; font-family: 'Courier New', monospace;">
                            <?= formatRupiah($row['harga_perolehan']) ?>
                        </td>
                    </tr>
                    <?php endwhile; ?>
                </tbody>
            </table>
        </div>

        <!-- Pagination -->
        <?php if ($totalPages > 1): ?>
        <div class="pagination no-print">
            <?php if ($page > 1): ?>
            <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page - 1])) ?>">
                <i class="fas fa-chevron-left"></i> Prev
            </a>
            <?php endif; ?>

            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <?php if ($i == $page): ?>
                    <span class="active"><?= $i ?></span>
                <?php else: ?>
                    <a href="?<?= http_build_query(array_merge($_GET, ['page' => $i])) ?>">
                        <?= $i ?>
                    </a>
                <?php endif; ?>
            <?php endfor; ?>

            <?php if ($page < $totalPages): ?>
            <a href="?<?= http_build_query(array_merge($_GET, ['page' => $page + 1])) ?>">
                Next <i class="fas fa-chevron-right"></i>
            </a>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>

    <!-- Footer Info -->
    <div style="text-align: center; margin-top: 30px; padding: 20px; color: #64748b; font-size: 13px;">
        <p>
            <strong>ACF EDU HUB</strong> - Sistem Manajemen Inventaris Aset
            <br>
            Laporan dibuat pada: <?= date('d F Y, H:i') ?> WIB oleh <?= htmlspecialchars($userName) ?> (<?= $displayRole ?>)
        </p>
    </div>
</div>

<script>
    // Chart Kantor
    const ctxKantor = document.getElementById('chartKantor').getContext('2d');
    new Chart(ctxKantor, {
        type: 'bar',
        data: {
            labels: <?= json_encode(array_column($dataKantor, 'kantor')) ?>,
            datasets: [{
                label: 'Jumlah Unit',
                data: <?= json_encode(array_column($dataKantor, 'jumlah')) ?>,
                backgroundColor: '#7AB2B2',
                borderRadius: 8,
                barThickness: 40
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { 
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        afterLabel: function(context) {
                            const nilai = <?= json_encode(array_column($dataKantor, 'nilai')) ?>[context.dataIndex];
                            return 'Nilai: Rp ' + nilai.toLocaleString('id-ID');
                        }
                    }
                }
            },
            scales: {
                y: { 
                    beginAtZero: true, 
                    grid: { color: '#f1f5f9' },
                    ticks: { font: { size: 11 } }
                },
                x: { 
                    grid: { display: false },
                    ticks: { font: { size: 11 } }
                }
            }
        }
    });

    // Chart Kategori (Pie)
    const ctxKategori = document.getElementById('chartKategori').getContext('2d');
    const colors = ['#7AB2B2', '#4D869C', '#CDE8E5', '#16a34a', '#1e40af', '#ea580c', '#7c3aed', '#0891b2'];
    new Chart(ctxKategori, {
        type: 'doughnut',
        data: {
            labels: <?= json_encode(array_column($dataKategori, 'kategori')) ?>,
            datasets: [{
                data: <?= json_encode(array_column($dataKategori, 'jumlah')) ?>,
                backgroundColor: colors,
                borderWidth: 3,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'bottom',
                    labels: {
                        padding: 15,
                        font: { size: 11 }
                    }
                },
                tooltip: {
                    callbacks: {
                        afterLabel: function(context) {
                            const nilai = <?= json_encode(array_column($dataKategori, 'nilai')) ?>[context.dataIndex];
                            return 'Nilai: Rp ' + nilai.toLocaleString('id-ID');
                        }
                    }
                }
            }
        }
    });

    <?php if (!empty($dataTrend)): ?>
    // Chart Trend
    const ctxTrend = document.getElementById('chartTrend').getContext('2d');
    new Chart(ctxTrend, {
        type: 'line',
        data: {
            labels: <?= json_encode(array_column($dataTrend, 'bulan')) ?>,
            datasets: [{
                label: 'Jumlah Perolehan',
                data: <?= json_encode(array_column($dataTrend, 'jumlah')) ?>,
                borderColor: '#7AB2B2',
                backgroundColor: 'rgba(122, 178, 178, 0.1)',
                tension: 0.4,
                fill: true,
                pointRadius: 5,
                pointHoverRadius: 7,
                pointBackgroundColor: '#7AB2B2'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: { display: false },
                tooltip: {
                    callbacks: {
                        afterLabel: function(context) {
                            const nilai = <?= json_encode(array_column($dataTrend, 'nilai')) ?>[context.dataIndex];
                            return 'Nilai: Rp ' + nilai.toLocaleString('id-ID');
                        }
                    }
                }
            },
            scales: {
                y: { 
                    beginAtZero: true,
                    grid: { color: '#f1f5f9' }
                },
                x: { 
                    grid: { display: false }
                }
            }
        }
    });
    <?php endif; ?>

    // Export to Excel function
    function exportToExcel() {
        alert('Fitur export Excel akan segera tersedia!');
        // Implementasi export dapat ditambahkan kemudian
    }
</script>

</body>
</html>
<?php
mysqli_close($conn);
?>