<?php
session_start();

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

// 2. Koneksi Database & Helper
require_once __DIR__ . '/../../DataBase/koneksi.php';

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

// 3. Logika Filter
$start_date = isset($_GET['start']) ? $conn->real_escape_string($_GET['start']) : '';
$end_date = isset($_GET['end']) ? $conn->real_escape_string($_GET['end']) : '';

$whereClause = "status='aktif'";
$urlParams = "";
if (!empty($start_date) && !empty($end_date)) {
    $whereClause .= " AND tanggal_perolehan BETWEEN '$start_date' AND '$end_date'";
    $urlParams = "&start=$start_date&end=$end_date";
}

// 4. Handle Export Excel
if (isset($_GET['export']) && $_GET['export'] == 'excel') {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="Laporan_Inventory_' . date('Ymd') . '.xls"');
    
    $resEx = $conn->query("SELECT * FROM inventory WHERE $whereClause ORDER BY tanggal_perolehan ASC");
    echo '<table border="1">
            <tr><th colspan="9" style="background:#8B4789; color:white; font-size:14pt; padding:10px;">LAPORAN INVENTORY ACF EDU HUB</th></tr>
            <tr style="background:#eee; font-weight:bold;">
                <th>No</th>
                <th>Kode Asset</th>
                <th>Tanggal</th>
                <th>Kategori</th>
                <th>Sumber Dana</th>
                <th>Kantor</th>
                <th>Jenis Barang</th>
                <th>Jenis Inventory</th>
                <th>Harga</th>
            </tr>';
    $n = 1; $totalE = 0;
    while($r = $resEx->fetch_assoc()){
        // Cek apakah ada kolom kode_asset
        $kode = isset($r['kode_asset']) && !empty($r['kode_asset']) ? $r['kode_asset'] : '-';
        
        echo '<tr>
                <td>'.$n++.'</td>
                <td style="font-weight:bold; color:#8B4789;">'.$kode.'</td>
                <td>'.date('d/m/Y', strtotime($r['tanggal_perolehan'])).'</td>
                <td>'.$r['kategori'].'</td>
                <td>'.$r['sumber_dana'].'</td>
                <td>'.$r['kantor'].'</td>
                <td>'.$r['jenis_barang'].'</td>
                <td>'.$r['jenis_inventory'].'</td>
                <td>'.$r['harga_perolehan'].'</td>
              </tr>';
        $totalE += $r['harga_perolehan'];
    }
    echo '<tr style="font-weight:bold;"><td colspan="8">TOTAL</td><td>'.$totalE.'</td></tr></table>';
    exit;
}

// 5. Query Data Statistik
$stats = $conn->query("SELECT COUNT(*) as total_item, SUM(harga_perolehan) as total_nilai, COUNT(DISTINCT kategori) as total_kat, COUNT(DISTINCT kantor) as total_lok FROM inventory WHERE $whereClause")->fetch_assoc();

// Query Pengeluaran Bulanan (Untuk Grafik & Tabel)
$resultBulanan = $conn->query("SELECT DATE_FORMAT(tanggal_perolehan, '%Y-%m') as bulan_tahun, SUM(harga_perolehan) as total_biaya, COUNT(*) as jumlah_item FROM inventory WHERE $whereClause GROUP BY bulan_tahun ORDER BY bulan_tahun ASC");
$dataBulanan = [];
while($rowB = $resultBulanan->fetch_assoc()) {
    $dataBulanan[] = $rowB;
}

// Query Kategori (Top 5)
$dataKategori = $conn->query("SELECT kategori, SUM(harga_perolehan) as total_nilai FROM inventory WHERE $whereClause GROUP BY kategori ORDER BY total_nilai DESC LIMIT 5")->fetch_all(MYSQLI_ASSOC);

// Query Detail Inventory
$dataInventory = $conn->query("SELECT * FROM inventory WHERE $whereClause ORDER BY tanggal_perolehan DESC");
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Laporan Statistik - ACF EDU HUB</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root { --primary: #8B4789; --secondary: #F4B840; --bg: #f8fafc; }
        body { font-family: 'Inter', sans-serif; background: var(--bg); margin: 0; padding: 20px; }
        .container { max-width: 1400px; margin: 0 auto; }
        .card { background: white; border-radius: 12px; padding: 20px; box-shadow: 0 4px 6px rgba(0,0,0,0.05); margin-bottom: 20px; border: 1px solid #e2e8f0; }
        
        .stats-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; margin-bottom: 20px; }
        .stat-item { background: white; padding: 20px; border-radius: 12px; border-left: 5px solid var(--primary); }
        .stat-item .val { font-size: 24px; font-weight: 800; color: var(--primary); }
        
        table { width: 100%; border-collapse: collapse; font-size: 13px; }
        th { background: #f1f5f9; color: var(--primary); padding: 12px 8px; text-align: left; font-size: 11px; text-transform: uppercase; border-bottom: 2px solid #e2e8f0; font-weight: 700; }
        td { padding: 10px 8px; border-bottom: 1px solid #f1f5f9; }
        
        /* Style khusus untuk kode asset */
        .kode-asset { 
            font-family: 'Courier New', monospace; 
            font-weight: 700; 
            color: var(--primary); 
            background: #f8f4ff;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            letter-spacing: 0.5px;
        }

        .btn { padding: 10px 16px; border-radius: 8px; text-decoration: none; font-size: 14px; font-weight: 600; cursor: pointer; display: inline-flex; align-items: center; gap: 8px; border:none; }
        .btn-success { background: #10b981; color: white; }
        .btn-outline { border: 1px solid #cbd5e1; background: white; color: #64748b; }
        .btn-outline:hover { background: #f8fafc; }

        .print-only { display: none; }

        @media print {
            @page { size: A4 landscape; margin: 10mm; }
            .no-print, .stats-grid, canvas { display: none !important; }
            .print-only { display: block !important; }
            body { background: white; padding: 0; }
            .card { border: none; box-shadow: none; padding: 0; }
            th { background: #eee !important; color: black !important; border: 1px solid #000 !important; font-size: 9px !important; }
            td { border: 1px solid #000 !important; font-size: 9px !important; padding: 6px !important; }
            .kode-asset { background: transparent !important; padding: 2px !important; }
        }
    </style>
</head>
<body>

<div class="container">
    <div class="page-header no-print" style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px;">
        <div>
            <h1 style="margin:0; color:var(--primary);">Laporan Analisis Aset</h1>
            <p style="color:#64748b; margin:0;">Dashboard Statistik & Pengeluaran Bulanan</p>
        </div>
        <div style="display:flex; gap:10px;">
            <button onclick="window.history.back()" class="btn btn-outline"><i class="fas fa-arrow-left"></i> Kembali</button>
            <button onclick="window.print()" class="btn btn-outline"><i class="fas fa-print"></i> Print PDF</button>
            <a href="?export=excel<?= $urlParams ?>" class="btn btn-success"><i class="fas fa-file-excel"></i> Export Excel</a>
        </div>
    </div>

    <div class="print-only" style="text-align:center; margin-bottom:20px;">
        <h1 style="margin:0;">LAPORAN INVENTORY ACF EDU HUB</h1>
        <p style="margin:5px 0;">Periode: <?= !empty($start_date) ? date('d/m/Y', strtotime($start_date)).' - '.date('d/m/Y', strtotime($end_date)) : 'Semua Data' ?></p>
        <hr>
    </div>

    <div class="stats-grid no-print">
        <div class="stat-item">
            <small>TOTAL ITEM</small>
            <div class="val"><?= number_format($stats['total_item']) ?></div>
        </div>
        <div class="stat-item" style="border-left-color: var(--secondary);">
            <small>TOTAL INVESTASI</small>
            <div class="val"><?= formatRupiah($stats['total_nilai']) ?></div>
        </div>
        <div class="stat-item">
            <small>KATEGORI</small>
            <div class="val"><?= $stats['total_kat'] ?></div>
        </div>
        <div class="stat-item">
            <small>LOKASI KANTOR</small>
            <div class="val"><?= $stats['total_lok'] ?></div>
        </div>
    </div>

    <div class="no-print" style="display: grid; grid-template-columns: 2fr 1fr; gap: 20px; margin-bottom: 20px;">
        <div class="card">
            <h3><i class="fas fa-chart-bar"></i> Grafik Pengeluaran Bulanan</h3>
            <div style="height: 300px;"><canvas id="chartBulanan"></canvas></div>
        </div>
        <div class="card">
            <h3><i class="fas fa-list"></i> Ringkasan Biaya</h3>
            <table style="font-size: 12px;">
                <thead>
                    <tr>
                        <th>Bulan</th>
                        <th style="text-align:right;">Total Biaya</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach(array_reverse($dataBulanan) as $b): ?>
                    <tr>
                        <td><?= date('M Y', strtotime($b['bulan_tahun']."-01")) ?></td>
                        <td style="text-align:right; font-weight:bold;"><?= number_format($b['total_biaya'], 0, ',', '.') ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="card">
        <h3 class="no-print">📋 Detail Data Inventory Lengkap</h3>
        <div style="overflow-x: auto;">
            <table>
                <thead>
                    <tr>
                        <th style="width: 40px;">No</th>
                        <th style="width: 140px;">Kode Asset</th>
                        <th style="width: 90px;">Tanggal</th>
                        <th>Kategori</th>
                        <th>Sumber Dana</th>
                        <th>Kantor</th>
                        <th>Jenis Barang</th>
                        <th>Jenis Inventory</th>
                        <th style="text-align:right; width: 120px;">Harga (Rp)</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $n = 1; $total = 0;
                    $dataInventory->data_seek(0);
                    while($row = $dataInventory->fetch_assoc()): 
                        $total += $row['harga_perolehan'];
                        
                        // Cek apakah ada kode_asset
                        $kode_display = '-';
                        if (isset($row['kode_asset']) && !empty($row['kode_asset'])) {
                            $kode_display = $row['kode_asset'];
                        }
                    ?>
                    <tr>
                        <td><?= $n++ ?></td>
                        <td><span class="kode-asset"><?= $kode_display ?></span></td>
                        <td><?= date('d/m/Y', strtotime($row['tanggal_perolehan'])) ?></td>
                        <td><?= $row['kategori'] ?></td>
                        <td><?= $row['sumber_dana'] ?></td>
                        <td><?= $row['kantor'] ?></td>
                        <td><strong><?= $row['jenis_barang'] ?></strong></td>
                        <td><?= $row['jenis_inventory'] ?></td>
                        <td style="text-align:right;"><?= number_format($row['harga_perolehan'], 0, ',', '.') ?></td>
                    </tr>
                    <?php endwhile; ?>
                    <tr style="background:#f9f9f9; font-weight:bold;">
                        <td colspan="8" style="text-align:right;">TOTAL KESELURUHAN</td>
                        <td style="text-align:right;"><?= number_format($total, 0, ',', '.') ?></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
    
    <!-- Info Footer -->
    <div class="no-print" style="text-align:center; color:#94a3b8; font-size:12px; margin-top:30px; padding:20px; border-top:1px solid #e2e8f0;">
        <p><i class="fas fa-info-circle"></i> Data kode asset akan otomatis muncul untuk inventory yang baru ditambahkan menggunakan sistem baru</p>
    </div>
</div>

<script>
    const ctxB = document.getElementById('chartBulanan').getContext('2d');
    new Chart(ctxB, {
        type: 'bar',
        data: {
            labels: <?= json_encode(array_map(function($d){ return date('M Y', strtotime($d['bulan_tahun']."-01")); }, $dataBulanan)) ?>,
            datasets: [{
                label: 'Total Pengeluaran (Rp)',
                data: <?= json_encode(array_column($dataBulanan, 'total_biaya')) ?>,
                backgroundColor: '#8B4789',
                borderRadius: 5
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                y: { beginAtZero: true, ticks: { callback: v => v.toLocaleString('id-ID') } }
            },
            plugins: {
                legend: { display: false }
            }
        }
    });
</script>
</body>
</html>