<?php
session_start();

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

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

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

// Helper Function untuk nilai aman
if (!function_exists('safeValue')) {
    function safeValue($value, $default = '-') {
        return ($value !== null && $value !== '') ? $value : $default;
    }
}

// Ambil filter dari URL
$search = $_GET['search'] ?? '';
$kantor_filter = $_GET['kantor'] ?? '';
$kategori_filter = $_GET['kategori'] ?? '';

// Query dengan filter
$sql = "SELECT * FROM inventory WHERE 1=1";
$params = [];
$types = "";

if (!empty($search)) {
    $sql .= " AND (jenis_barang LIKE ? OR jenis_inventory LIKE ? OR kantor LIKE ? OR kode_aset_auto LIKE ? OR kode_aset LIKE ?)";
    $searchParam = "%$search%";
    $params[] = $searchParam; 
    $params[] = $searchParam; 
    $params[] = $searchParam; 
    $params[] = $searchParam;
    $params[] = $searchParam;
    $types .= "sssss";
}

if (!empty($kantor_filter)) {
    $sql .= " AND kantor = ?";
    $params[] = $kantor_filter;
    $types .= "s";
}

if (!empty($kategori_filter)) {
    $sql .= " AND kategori = ?";
    $params[] = $kategori_filter;
    $types .= "s";
}

$sql .= " ORDER BY tanggal_perolehan DESC, id DESC";

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

// Hitung statistik
$totalData = $result->num_rows;
$totalNilai = 0;
$data = [];

while($row = $result->fetch_assoc()) {
    $data[] = $row;
    $totalNilai += $row['harga_perolehan'];
}
?>
<!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>
    <style>
        @page {
            size: A4 landscape;
            margin: 15mm;
        }
        
        * { margin: 0; padding: 0; box-sizing: border-box; }
        
        body {
            font-family: Arial, sans-serif;
            font-size: 10pt;
            line-height: 1.4;
        }
        
        .header {
            text-align: center;
            margin-bottom: 20px;
            border-bottom: 3px solid #8B4789;
            padding-bottom: 15px;
        }
        
        .header h1 {
            color: #8B4789;
            font-size: 20pt;
            margin-bottom: 5px;
        }
        
        .header p {
            color: #666;
            font-size: 10pt;
        }
        
        .info-section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 10px;
            margin-bottom: 20px;
            background: #f8f9fa;
            padding: 10px;
            border-radius: 5px;
        }
        
        .info-item {
            font-size: 9pt;
        }
        
        .info-item strong {
            color: #8B4789;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
            font-size: 8pt;
        }
        
        thead {
            background: #8B4789;
            color: white;
        }
        
        th {
            padding: 8px 5px;
            text-align: left;
            font-weight: bold;
            font-size: 8pt;
        }
        
        td {
            padding: 6px 5px;
            border-bottom: 1px solid #e0e0e0;
        }
        
        tbody tr:nth-child(even) {
            background: #f8f9fa;
        }
        
        tbody tr:hover {
            background: #e9ecef;
        }
        
        .kode-new {
            background: #667eea;
            color: white;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
            font-size: 7pt;
            font-weight: bold;
        }
        
        .kode-old {
            background: #e9ecef;
            color: #495057;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
            font-size: 7pt;
        }
        
        .kode-none {
            background: #fff5f5;
            color: #c92a2a;
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 7pt;
        }
        
        .status-badge {
            padding: 2px 6px;
            border-radius: 3px;
            font-size: 7pt;
            font-weight: bold;
            text-transform: uppercase;
        }
        
        .status-aktif { background: #d4edda; color: #155724; }
        .status-lelang { background: #fff3cd; color: #856404; }
        .status-rusak { background: #f8d7da; color: #721c24; }
        .status-hilang { background: #e2e3e5; color: #383d41; }
        
        .footer {
            margin-top: 30px;
            padding-top: 15px;
            border-top: 2px solid #8B4789;
            text-align: center;
            font-size: 8pt;
            color: #666;
        }
        
        .summary-box {
            background: #fff3cd;
            border: 1px solid #ffc107;
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        
        .summary-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 15px;
            text-align: center;
        }
        
        .summary-item h3 {
            color: #8B4789;
            font-size: 18pt;
            margin-bottom: 5px;
        }
        
        .summary-item p {
            color: #666;
            font-size: 8pt;
            text-transform: uppercase;
        }
        
        @media print {
            body { margin: 0; }
            .no-print { display: none !important; }
            @page { margin: 15mm; }
        }
    </style>
</head>
<body>
    
    <div class="header">
        <h1>LAPORAN INVENTORY ASET</h1>
        <p><strong>ACF EDU HUB</strong></p>
        <p style="font-size: 8pt; margin-top: 5px;">
            Dicetak pada: <?= date('d F Y, H:i:s') ?> WIB
        </p>
    </div>

    <?php if (!empty($search) || !empty($kantor_filter) || !empty($kategori_filter)): ?>
    <div class="info-section">
        <div class="info-item">
            <strong>Filter Aktif:</strong><br>
            <?php if (!empty($search)): ?>
                • Pencarian: "<?= htmlspecialchars($search) ?>"<br>
            <?php endif; ?>
            <?php if (!empty($kantor_filter)): ?>
                • Kantor: <?= htmlspecialchars($kantor_filter) ?><br>
            <?php endif; ?>
            <?php if (!empty($kategori_filter)): ?>
                • Kategori: <?= htmlspecialchars($kategori_filter) ?><br>
            <?php endif; ?>
        </div>
        <div class="info-item" style="text-align: right;">
            <strong>Total Data:</strong> <?= number_format($totalData) ?> item<br>
            <strong>Total Nilai:</strong> <?= formatRupiah($totalNilai) ?>
        </div>
    </div>
    <?php else: ?>
    <div class="summary-box">
        <div class="summary-grid">
            <div class="summary-item">
                <h3><?= number_format($totalData) ?></h3>
                <p>Total Unit Aset</p>
            </div>
            <div class="summary-item">
                <h3 style="font-size: 14pt;"><?= formatRupiah($totalNilai) ?></h3>
                <p>Total Nilai Investasi</p>
            </div>
            <div class="summary-item">
                <h3><?= date('Y') ?></h3>
                <p>Periode Laporan</p>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <table>
        <thead>
            <tr>
                <th style="width: 30px;">NO</th>
                <th style="width: 100px;">KODE ASET</th>
                <th>JENIS BARANG</th>
                <th>JENIS INVENTORY</th>
                <th>KATEGORI</th>
                <th>KANTOR</th>
                <th style="width: 70px;">TGL PEROLEHAN</th>
                <th style="width: 90px; text-align: right;">HARGA</th>
                <th style="width: 80px;">SUMBER DANA</th>
                <th style="width: 60px;">STATUS</th>
            </tr>
        </thead>
        <tbody>
            <?php if (count($data) > 0): 
                $no = 1;
                foreach ($data as $row): 
                    // Deteksi kode
                    $kode_display = '';
                    $kode_class = '';
                    
                    if (!empty($row['kode_aset_auto'])) {
                        $kode_display = $row['kode_aset_auto'];
                        $kode_class = 'kode-new';
                    } elseif (!empty($row['kode_aset'])) {
                        $kode_display = $row['kode_aset'];
                        $kode_class = 'kode-old';
                    } else {
                        $kode_display = 'NO-CODE';
                        $kode_class = 'kode-none';
                    }
                    
                    // Status badge class
                    $status = strtolower($row['status']);
                    $status_class = 'status-' . $status;
            ?>
            <tr>
                <td><?= $no++ ?></td>
                <td><span class="<?= $kode_class ?>"><?= htmlspecialchars($kode_display) ?></span></td>
                <td><strong><?= htmlspecialchars($row['jenis_barang']) ?></strong></td>
                <td><?= htmlspecialchars(safeValue($row['jenis_inventory'])) ?></td>
                <td><?= htmlspecialchars($row['kategori']) ?></td>
                <td><?= htmlspecialchars($row['kantor']) ?></td>
                <td><?= date('d/m/Y', strtotime($row['tanggal_perolehan'])) ?></td>
                <td style="text-align: right; font-weight: bold;"><?= number_format($row['harga_perolehan'], 0, ',', '.') ?></td>
                <td style="font-size: 7pt;"><?= htmlspecialchars(safeValue($row['sumber_dana'])) ?></td>
                <td><span class="status-badge <?= $status_class ?>"><?= strtoupper($status) ?></span></td>
            </tr>
            <?php endforeach; else: ?>
            <tr>
                <td colspan="10" style="text-align: center; padding: 30px; color: #999;">
                    Tidak ada data yang ditemukan
                </td>
            </tr>
            <?php endif; ?>
        </tbody>
    </table>

    <div class="footer">
        <p><strong>ACF EDU HUB - Sistem Manajemen Inventory Aset</strong></p>
        <p>Dokumen ini digenerate secara otomatis oleh sistem pada <?= date('d F Y H:i:s') ?> WIB</p>
        <p style="margin-top: 10px; font-size: 7pt; color: #999;">
            Halaman ini dapat dicetak atau disimpan sebagai PDF menggunakan fungsi Print Browser (Ctrl+P)
        </p>
    </div>

    <script>
        // Auto print saat halaman dibuka
        window.onload = function() {
            // Tunggu sebentar untuk memastikan semua konten sudah dimuat
            setTimeout(function() {
                window.print();
            }, 500);
        }
        
        // Tutup window setelah print dialog ditutup (opsional)
        window.onafterprint = function() {
            // Uncomment baris berikut jika ingin auto-close setelah print
            // window.close();
        }
    </script>

</body>
</html>