<?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']) : '';
$sumber_dana_filter = isset($_GET['sumber_dana']) ? $conn->real_escape_string($_GET['sumber_dana']) : '';

// Gunakan WHERE 1=1 agar penyambungan string AND lebih fleksibel
$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";
}

if (!empty($sumber_dana_filter)) {
    $whereClause .= " AND sumber_dana='$sumber_dana_filter'";
    $urlParams .= "&sumber_dana=$sumber_dana_filter";
}

// 4. Handle Export Excel
if (isset($_GET['export']) && $_GET['export'] == 'excel') {
    header('Content-Type: application/vnd.ms-excel; charset=utf-8');
    header('Content-Disposition: attachment;filename="Laporan_Inventory_' . date('Ymd') . '.xls"');
    
    // Tambahkan BOM agar Excel membaca UTF-8 dengan benar
    echo "\xEF\xBB\xBF"; 
    
    $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 nama kolom yang benar: kode_aset atau kode_asset
        $kode = isset($r['kode_aset']) ? $r['kode_aset'] : (isset($r['kode_asset']) ? $r['kode_asset'] : '-');
        
        echo '<tr>
                <td>'.$n++.'</td>
                <td>'.$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 & Grafik
$stats_query = $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");
$stats = $stats_query ? $stats_query->fetch_assoc() : ['total_item'=>0, 'total_nilai'=>0, 'total_kat'=>0, 'total_lok'=>0];

// Query Pengeluaran Bulanan
$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 = [];
if ($resultBulanan) {
    while($rowB = $resultBulanan->fetch_assoc()) { $dataBulanan[] = $rowB; }
}

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

// Query dropdown
$sumberDanaList = $conn->query("SELECT DISTINCT sumber_dana FROM inventory WHERE sumber_dana IS NOT NULL AND sumber_dana != '' ORDER BY sumber_dana");
?>

<!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 small { color: #64748b; font-weight: 700; font-size: 10px; display: block; margin-bottom: 5px; }
        .stat-item .val { font-size: 22px; font-weight: 800; color: var(--primary); }
        
        .filter-section { background: white; padding: 20px; border-radius: 12px; margin-bottom: 20px; }
        .filter-grid { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 15px; }
        .filter-input { width: 100%; padding: 10px; border: 1.5px solid #e2e8f0; border-radius: 8px; font-size: 14px; box-sizing: border-box; }
        
        table { width: 100%; border-collapse: collapse; font-size: 13px; }
        th { background: #f1f5f9; color: var(--primary); padding: 12px 8px; text-align: left; border-bottom: 2px solid #e2e8f0; }
        td { padding: 10px 8px; border-bottom: 1px solid #f1f5f9; }
        
        .kode-asset { font-family: monospace; font-weight: bold; color: var(--primary); background: #f8f4ff; padding: 3px 6px; border-radius: 4px; }
        .btn { padding: 10px 16px; border-radius: 8px; font-weight: 600; cursor: pointer; text-decoration: none; border: none; display: inline-flex; align-items: center; gap: 8px; }
        .btn-primary { background: var(--primary); color: white; }
        .btn-success { background: #10b981; color: white; }
        .btn-outline { border: 1px solid #cbd5e1; background: white; color: #64748b; }

        .print-only { display: none; }
        @media print {
            .no-print { display: none !important; }
            .print-only { display: block !important; }
            body { padding: 0; background: white; }
            .card { box-shadow: none; border: 1px solid #ccc; }
            table { font-size: 10px; }
        }
    </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 Aset</h1>
            <p style="color:#64748b; margin:0;">Manajemen & Monitoring Inventory</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> PDF</button>
            <a href="?export=excel<?= $urlParams ?>" class="btn btn-success"><i class="fas fa-file-excel"></i> Excel</a>
        </div>
    </div>

    <form method="GET" class="filter-section no-print card">
        <div class="filter-grid">
            <div>
                <label style="font-size:12px; font-weight:700;">Mulai</label>
                <input type="date" name="start" class="filter-input" value="<?= $start_date ?>">
            </div>
            <div>
                <label style="font-size:12px; font-weight:700;">Selesai</label>
                <input type="date" name="end" class="filter-input" value="<?= $end_date ?>">
            </div>
            <div>
                <label style="font-size:12px; font-weight:700;">Sumber Dana</label>
                <select name="sumber_dana" class="filter-input">
                    <option value="">Semua Sumber Dana</option>
                    <?php while($sd = $sumberDanaList->fetch_assoc()): ?>
                        <option value="<?= $sd['sumber_dana'] ?>" <?= $sumber_dana_filter == $sd['sumber_dana'] ? 'selected' : '' ?>><?= $sd['sumber_dana'] ?></option>
                    <?php endwhile; ?>
                </select>
            </div>
        </div>
        <div style="text-align: right; margin-top: 15px;">
            <a href="?" class="btn btn-outline">Reset</a>
            <button type="submit" class="btn btn-primary">Filter</button>
        </div>
    </form>

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

    <div class="no-print" style="display: grid; grid-template-columns: 2fr 1fr; gap: 20px; margin-bottom: 20px;">
        <div class="card">
            <h3>Grafik Bulanan</h3>
            <div style="height: 250px;"><canvas id="chartBulanan"></canvas></div>
        </div>
        <div class="card">
            <h3>Ringkasan</h3>
            <table>
                <thead><tr><th>Bulan</th><th style="text-align:right;">Total</th></tr></thead>
                <tbody>
                    <?php if(!empty($dataBulanan)): 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; else: echo "<tr><td colspan='2'>No data</td></tr>"; endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <div class="card">
        <h3>📋 Detail Inventory</h3>
        <div style="overflow-x: auto;">
            <table>
                <thead>
                    <tr>
                        <th>No</th>
                        <th>Kode Asset</th>
                        <th>Tanggal</th>
                        <th>Kategori</th>
                        <th>Barang</th>
                        <th>Kantor</th>
                        <th style="text-align:right;">Harga</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    $n = 1; $total = 0;
                    if ($dataInventory && $dataInventory->num_rows > 0):
                        while($row = $dataInventory->fetch_assoc()): 
                            $total += $row['harga_perolehan'];
                            $kode = isset($row['kode_aset']) ? $row['kode_aset'] : (isset($row['kode_asset']) ? $row['kode_asset'] : '-');
                    ?>
                    <tr>
                        <td><?= $n++ ?></td>
                        <td><span class="kode-asset"><?= $kode ?></span></td>
                        <td><?= date('d/m/Y', strtotime($row['tanggal_perolehan'])) ?></td>
                        <td><?= $row['kategori'] ?></td>
                        <td><strong><?= $row['jenis_barang'] ?></strong></td>
                        <td><?= $row['kantor'] ?></td>
                        <td style="text-align:right;"><?= number_format($row['harga_perolehan'], 0, ',', '.') ?></td>
                    </tr>
                    <?php endwhile; endif; ?>
                    <tr style="background:#f1f5f9; font-weight:bold;">
                        <td colspan="6" style="text-align:right;">TOTAL</td>
                        <td style="text-align:right;"><?= number_format($total, 0, ',', '.') ?></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
    const ctxB = document.getElementById('chartBulanan').getContext('2d');
    const dataBulanan = <?= json_encode($dataBulanan) ?>;
    
    new Chart(ctxB, {
        type: 'bar',
        data: {
            labels: dataBulanan.map(d => {
                const date = new Date(d.bulan_tahun + "-01");
                return date.toLocaleString('id-ID', { month: 'short', year: 'numeric' });
            }),
            datasets: [{
                label: 'Pengeluaran',
                data: dataBulanan.map(d => d.total_biaya),
                backgroundColor: '#8B4789',
                borderRadius: 4
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } }
        }
    });
</script>
</body>
</html>