<?php
session_start();
require_once __DIR__ . '/../../DataBase/koneksi.php';

if (!$conn) {
    die("Koneksi database gagal!");
}

// Ambil data untuk filter
$kategoriList = $conn->query("SELECT * FROM kategori ORDER BY nama_kategori ASC");
$sumberDanaList = $conn->query("SELECT * FROM sumber_dana ORDER BY nama_sumber ASC");

// Cek apakah tabel lokasi ada
$lokasiExists = false;
$lokasiList = null;
$checkTable = $conn->query("SHOW TABLES LIKE 'lokasi'");
if ($checkTable && $checkTable->num_rows > 0) {
    $lokasiExists = true;
    $lokasiList = $conn->query("SELECT * FROM lokasi ORDER BY nama_lokasi ASC");
}

$kondisiList = ['Baik', 'Rusak Ringan', 'Rusak Berat', 'Hilang'];

// Filter parameters
$filter_kategori = isset($_GET['kategori']) ? $_GET['kategori'] : '';
$filter_sumber = isset($_GET['sumber']) ? $_GET['sumber'] : '';
$filter_lokasi = isset($_GET['lokasi']) ? $_GET['lokasi'] : '';
$filter_kondisi = isset($_GET['kondisi']) ? $_GET['kondisi'] : '';
$filter_tanggal_dari = isset($_GET['tanggal_dari']) ? $_GET['tanggal_dari'] : '';
$filter_tanggal_sampai = isset($_GET['tanggal_sampai']) ? $_GET['tanggal_sampai'] : '';

// Build query dengan JOIN
$query = "SELECT 
    b.id,
    b.kode_barang,
    b.nama_barang,
    b.merk,
    b.tanggal_pembelian,
    b.harga_satuan,
    b.jumlah,
    b.kondisi,
    b.keterangan,
    k.nama_kategori,
    sd.nama_sumber" . ($lokasiExists ? ",\n    l.nama_lokasi" : "") . "
FROM barang b
LEFT JOIN kategori k ON b.kategori_id = k.id
LEFT JOIN sumber_dana sd ON b.sumber_dana_id = sd.id" . 
($lokasiExists ? "\nLEFT JOIN lokasi l ON b.lokasi_id = l.id" : "") . "
WHERE 1=1";

$params = [];
$types = "";

if (!empty($filter_kategori)) {
    $query .= " AND b.kategori_id = ?";
    $params[] = $filter_kategori;
    $types .= "i";
}

if (!empty($filter_sumber)) {
    $query .= " AND b.sumber_dana_id = ?";
    $params[] = $filter_sumber;
    $types .= "i";
}

if (!empty($filter_lokasi) && $lokasiExists) {
    $query .= " AND b.lokasi_id = ?";
    $params[] = $filter_lokasi;
    $types .= "i";
}

if (!empty($filter_kondisi)) {
    $query .= " AND b.kondisi = ?";
    $params[] = $filter_kondisi;
    $types .= "s";
}

if (!empty($filter_tanggal_dari)) {
    $query .= " AND b.tanggal_pembelian >= ?";
    $params[] = $filter_tanggal_dari;
    $types .= "s";
}

if (!empty($filter_tanggal_sampai)) {
    $query .= " AND b.tanggal_pembelian <= ?";
    $params[] = $filter_tanggal_sampai;
    $types .= "s";
}

$query .= " ORDER BY b.tanggal_pembelian DESC, b.kode_barang ASC";

// Execute query
if (!empty($params)) {
    $stmt = $conn->prepare($query);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query($query);
}

$barangList = [];
$total_nilai = 0;
$total_barang = 0;

if ($result) {
    while ($row = $result->fetch_assoc()) {
        $barangList[] = $row;
        $total_nilai += ($row['harga_satuan'] * $row['jumlah']);
        $total_barang += $row['jumlah'];
    }
}

// Handle Export
if (isset($_GET['export']) && $_GET['export'] == 'excel') {
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="Laporan_Inventory_' . date('Y-m-d') . '.xls"');
    header('Cache-Control: max-age=0');
    
    echo '<table border="1">';
    echo '<tr style="background-color: #7AB2B2; color: white; font-weight: bold;">';
    echo '<th>No</th>';
    echo '<th>Kode Barang</th>';
    echo '<th>Nama Barang</th>';
    echo '<th>Merk</th>';
    echo '<th>Kategori</th>';
    echo '<th>Sumber Dana</th>';
    if ($lokasiExists) {
        echo '<th>Lokasi</th>';
    }
    echo '<th>Tanggal Pembelian</th>';
    echo '<th>Harga Satuan</th>';
    echo '<th>Jumlah</th>';
    echo '<th>Total Nilai</th>';
    echo '<th>Kondisi</th>';
    echo '<th>Keterangan</th>';
    echo '</tr>';
    
    foreach ($barangList as $index => $barang) {
        echo '<tr>';
        echo '<td>' . ($index + 1) . '</td>';
        echo '<td>' . htmlspecialchars($barang['kode_barang']) . '</td>';
        echo '<td>' . htmlspecialchars($barang['nama_barang']) . '</td>';
        echo '<td>' . htmlspecialchars($barang['merk'] ?: '-') . '</td>';
        echo '<td>' . htmlspecialchars($barang['nama_kategori'] ?: '-') . '</td>';
        echo '<td>' . htmlspecialchars($barang['nama_sumber'] ?: '-') . '</td>';
        if ($lokasiExists) {
            echo '<td>' . htmlspecialchars($barang['nama_lokasi'] ?: '-') . '</td>';
        }
        echo '<td>' . date('d/m/Y', strtotime($barang['tanggal_pembelian'])) . '</td>';
        echo '<td>Rp ' . number_format($barang['harga_satuan'], 0, ',', '.') . '</td>';
        echo '<td>' . $barang['jumlah'] . '</td>';
        echo '<td>Rp ' . number_format($barang['harga_satuan'] * $barang['jumlah'], 0, ',', '.') . '</td>';
        echo '<td>' . htmlspecialchars($barang['kondisi']) . '</td>';
        echo '<td>' . htmlspecialchars($barang['keterangan'] ?: '-') . '</td>';
        echo '</tr>';
    }
    
    echo '<tr style="background-color: #f8fafc; font-weight: bold;">';
    echo '<td colspan="9" style="text-align: right;">TOTAL</td>';
    echo '<td>' . $total_barang . '</td>';
    echo '<td>Rp ' . number_format($total_nilai, 0, ',', '.') . '</td>';
    echo '<td colspan="2"></td>';
    echo '</tr>';
    echo '</table>';
    exit;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laporan Inventory - 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">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', sans-serif;
            background: #f8fafc;
            padding: 25px;
            color: #1e293b;
        }

        /* HEADER */
        .header {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
            color: white;
            padding: 40px;
            border-radius: 20px;
            margin-bottom: 30px;
            box-shadow: 0 8px 25px rgba(122, 178, 178, 0.25);
        }

        .header h1 {
            font-size: 32px;
            font-weight: 800;
            margin-bottom: 8px;
        }

        .header p {
            font-size: 16px;
            opacity: 0.95;
        }

        /* CARD */
        .card {
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            margin-bottom: 30px;
        }

        .card-header {
            margin-bottom: 25px;
            padding-bottom: 20px;
            border-bottom: 2px solid #f1f5f9;
        }

        .card-title {
            font-size: 20px;
            font-weight: 700;
            color: #1e293b;
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 15px;
        }

        .card-title i {
            color: #7AB2B2;
            font-size: 24px;
        }

        /* FILTER FORM */
        .filter-form {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .form-group {
            display: flex;
            flex-direction: column;
        }

        .form-group label {
            font-size: 13px;
            font-weight: 600;
            color: #475569;
            margin-bottom: 6px;
        }

        .form-group select,
        .form-group input {
            padding: 10px 14px;
            border: 2px solid #e2e8f0;
            border-radius: 8px;
            font-size: 14px;
            font-family: 'Inter', sans-serif;
            transition: all 0.3s ease;
        }

        .form-group select:focus,
        .form-group input:focus {
            outline: none;
            border-color: #7AB2B2;
            box-shadow: 0 0 0 3px rgba(122, 178, 178, 0.1);
        }

        .filter-actions {
            display: flex;
            gap: 10px;
            margin-top: 20px;
        }

        /* BUTTON */
        .btn {
            padding: 12px 24px;
            border-radius: 10px;
            border: none;
            cursor: pointer;
            font-weight: 600;
            font-size: 14px;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-family: 'Inter', sans-serif;
            text-decoration: none;
        }

        .btn-primary {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
            color: white;
            box-shadow: 0 4px 15px rgba(122, 178, 178, 0.3);
        }

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

        .btn-secondary {
            background: #64748b;
            color: white;
        }

        .btn-secondary:hover {
            background: #475569;
        }

        .btn-success {
            background: #10b981;
            color: white;
        }

        .btn-success:hover {
            background: #059669;
        }

        /* SUMMARY CARDS */
        .summary-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }

        .summary-card {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
            color: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(122, 178, 178, 0.2);
        }

        .summary-card h3 {
            font-size: 14px;
            font-weight: 600;
            opacity: 0.9;
            margin-bottom: 10px;
        }

        .summary-card .value {
            font-size: 28px;
            font-weight: 800;
        }

        /* TABLE */
        .table-container {
            overflow-x: auto;
            border-radius: 10px;
            margin-bottom: 20px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            min-width: 1000px;
        }

        table thead {
            background: linear-gradient(135deg, #7AB2B2 0%, #4D869C 100%);
        }

        table th {
            color: white;
            padding: 16px 12px;
            text-align: left;
            font-weight: 600;
            font-size: 13px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            white-space: nowrap;
        }

        table th:first-child {
            border-radius: 10px 0 0 0;
        }

        table th:last-child {
            border-radius: 0 10px 0 0;
        }

        table td {
            padding: 14px 12px;
            border-bottom: 1px solid #f1f5f9;
            font-size: 14px;
            color: #334155;
        }

        table tbody tr {
            transition: all 0.3s ease;
        }

        table tbody tr:hover {
            background: #f8fafc;
        }

        table tbody tr:last-child td {
            border-bottom: none;
        }

        .badge {
            display: inline-block;
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .badge-baik {
            background: #dcfce7;
            color: #166534;
        }

        .badge-rusak-ringan {
            background: #fef3c7;
            color: #92400e;
        }

        .badge-rusak-berat {
            background: #fee2e2;
            color: #991b1b;
        }

        .badge-hilang {
            background: #f3f4f6;
            color: #374151;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #94a3b8;
        }

        .empty-state i {
            font-size: 64px;
            margin-bottom: 20px;
            opacity: 0.3;
        }

        /* FOOTER TOTAL */
        .table-footer {
            background: #f8fafc;
            padding: 20px;
            border-radius: 10px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-weight: 600;
        }

        .print-hide {
            display: flex;
            gap: 10px;
        }

        /* PRINT STYLES */
        @media print {
            body {
                padding: 0;
                background: white;
            }

            .header {
                box-shadow: none;
                page-break-after: avoid;
            }

            .card {
                box-shadow: none;
                page-break-inside: avoid;
            }

            .print-hide,
            .filter-form,
            .filter-actions,
            .btn {
                display: none !important;
            }

            table {
                page-break-inside: auto;
            }

            tr {
                page-break-inside: avoid;
                page-break-after: auto;
            }

            thead {
                display: table-header-group;
            }

            tfoot {
                display: table-footer-group;
            }
        }

        /* RESPONSIVE */
        @media (max-width: 768px) {
            body {
                padding: 15px;
            }

            .header {
                padding: 25px;
            }

            .header h1 {
                font-size: 24px;
            }

            .card {
                padding: 20px;
            }

            .filter-form {
                grid-template-columns: 1fr;
            }

            .filter-actions {
                flex-direction: column;
            }

            .filter-actions .btn {
                width: 100%;
                justify-content: center;
            }

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

            .table-footer {
                flex-direction: column;
                gap: 15px;
                align-items: flex-start;
            }

            .print-hide {
                width: 100%;
                flex-direction: column;
            }

            .print-hide .btn {
                width: 100%;
                justify-content: center;
            }
        }
    </style>
</head>
<body>

    <!-- HEADER -->
    <div class="header">
        <h1><i class="fas fa-chart-bar"></i> Laporan Inventory</h1>
        <p>Laporan Lengkap Data Barang Inventory ACF EDU HUB</p>
    </div>

    <!-- FILTER CARD -->
    <div class="card">
        <div class="card-header">
            <div class="card-title">
                <i class="fas fa-filter"></i>
                Filter Laporan
            </div>
        </div>

        <form method="GET" class="filter-form">
            <div class="form-group">
                <label>Kategori</label>
                <select name="kategori">
                    <option value="">Semua Kategori</option>
                    <?php 
                    $kategoriList->data_seek(0);
                    while ($kat = $kategoriList->fetch_assoc()): 
                    ?>
                        <option value="<?= $kat['id'] ?>" <?= $filter_kategori == $kat['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($kat['nama_kategori']) ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <div class="form-group">
                <label>Sumber Dana</label>
                <select name="sumber">
                    <option value="">Semua Sumber Dana</option>
                    <?php 
                    $sumberDanaList->data_seek(0);
                    while ($sumber = $sumberDanaList->fetch_assoc()): 
                    ?>
                        <option value="<?= $sumber['id'] ?>" <?= $filter_sumber == $sumber['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($sumber['nama_sumber']) ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>

            <?php if ($lokasiExists): ?>
            <div class="form-group">
                <label>Lokasi</label>
                <select name="lokasi">
                    <option value="">Semua Lokasi</option>
                    <?php 
                    $lokasiList->data_seek(0);
                    while ($lok = $lokasiList->fetch_assoc()): 
                    ?>
                        <option value="<?= $lok['id'] ?>" <?= $filter_lokasi == $lok['id'] ? 'selected' : '' ?>>
                            <?= htmlspecialchars($lok['nama_lokasi']) ?>
                        </option>
                    <?php endwhile; ?>
                </select>
            </div>
            <?php endif; ?>

            <div class="form-group">
                <label>Kondisi</label>
                <select name="kondisi">
                    <option value="">Semua Kondisi</option>
                    <?php foreach ($kondisiList as $kondisi): ?>
                        <option value="<?= $kondisi ?>" <?= $filter_kondisi == $kondisi ? 'selected' : '' ?>>
                            <?= $kondisi ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="form-group">
                <label>Tanggal Dari</label>
                <input type="date" name="tanggal_dari" value="<?= $filter_tanggal_dari ?>">
            </div>

            <div class="form-group">
                <label>Tanggal Sampai</label>
                <input type="date" name="tanggal_sampai" value="<?= $filter_tanggal_sampai ?>">
            </div>

            <div class="filter-actions" style="grid-column: 1 / -1;">
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-search"></i>
                    Tampilkan
                </button>
                <a href="?" class="btn btn-secondary">
                    <i class="fas fa-redo"></i>
                    Reset Filter
                </a>
                <a href="?<?= $_SERVER['QUERY_STRING'] ?>&export=excel" class="btn btn-success">
                    <i class="fas fa-file-excel"></i>
                    Export Excel
                </a>
                <button type="button" onclick="window.print()" class="btn btn-primary">
                    <i class="fas fa-print"></i>
                    Cetak
                </button>
            </div>
        </form>
    </div>

    <!-- SUMMARY -->
    <div class="summary-grid print-hide">
        <div class="summary-card">
            <h3>Total Barang</h3>
            <div class="value"><?= count($barangList) ?> Item</div>
        </div>
        <div class="summary-card">
            <h3>Total Kuantitas</h3>
            <div class="value"><?= number_format($total_barang, 0, ',', '.') ?> Unit</div>
        </div>
        <div class="summary-card">
            <h3>Total Nilai Aset</h3>
            <div class="value">Rp <?= number_format($total_nilai, 0, ',', '.') ?></div>
        </div>
    </div>

    <!-- DATA TABLE -->
    <div class="card">
        <div class="card-header">
            <div class="card-title">
                <i class="fas fa-table"></i>
                Data Inventory
            </div>
        </div>

        <div class="table-container">
            <table>
                <thead>
                    <tr>
                        <th style="width: 50px;">No</th>
                        <th>Kode</th>
                        <th>Nama Barang</th>
                        <th>Merk</th>
                        <th>Kategori</th>
                        <th>Sumber Dana</th>
                        <?php if ($lokasiExists): ?>
                        <th>Lokasi</th>
                        <?php endif; ?>
                        <th>Tgl Beli</th>
                        <th>Harga</th>
                        <th>Qty</th>
                        <th>Total</th>
                        <th>Kondisi</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($barangList)): ?>
                        <tr>
                            <td colspan="12">
                                <div class="empty-state">
                                    <i class="fas fa-inbox"></i>
                                    <p>Tidak ada data yang sesuai dengan filter</p>
                                </div>
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($barangList as $index => $barang): ?>
                        <tr>
                            <td><strong><?= $index + 1 ?></strong></td>
                            <td><?= htmlspecialchars($barang['kode_barang']) ?></td>
                            <td><strong><?= htmlspecialchars($barang['nama_barang']) ?></strong></td>
                            <td><?= htmlspecialchars($barang['merk'] ?: '-') ?></td>
                            <td><?= htmlspecialchars($barang['nama_kategori'] ?: '-') ?></td>
                            <td><?= htmlspecialchars($barang['nama_sumber'] ?: '-') ?></td>
                            <?php if ($lokasiExists): ?>
                            <td><?= htmlspecialchars($barang['nama_lokasi'] ?: '-') ?></td>
                            <?php endif; ?>
                            <td><?= date('d/m/Y', strtotime($barang['tanggal_pembelian'])) ?></td>
                            <td>Rp <?= number_format($barang['harga_satuan'], 0, ',', '.') ?></td>
                            <td><?= $barang['jumlah'] ?></td>
                            <td><strong>Rp <?= number_format($barang['harga_satuan'] * $barang['jumlah'], 0, ',', '.') ?></strong></td>
                            <td>
                                <?php
                                $badgeClass = 'badge-baik';
                                if ($barang['kondisi'] == 'Rusak Ringan') $badgeClass = 'badge-rusak-ringan';
                                elseif ($barang['kondisi'] == 'Rusak Berat') $badgeClass = 'badge-rusak-berat';
                                elseif ($barang['kondisi'] == 'Hilang') $badgeClass = 'badge-hilang';
                                ?>
                                <span class="badge <?= $badgeClass ?>">
                                    <?= htmlspecialchars($barang['kondisi']) ?>
                                </span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>

        <?php if (!empty($barangList)): ?>
        <div class="table-footer">
            <div>
                <strong>Total: <?= count($barangList) ?> Item</strong> | 
                <strong><?= number_format($total_barang, 0, ',', '.') ?> Unit</strong>
            </div>
            <div>
                <strong>Total Nilai: Rp <?= number_format($total_nilai, 0, ',', '.') ?></strong>
            </div>
        </div>
        <?php endif; ?>
    </div>

</body>
</html>