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

/* ========================
   AUTH STAFF
======================== */
if (!isset($_SESSION['login']) || $_SESSION['login'] !== true || $_SESSION['role'] !== 'S') {
    header("Location: ../../index.html?error=unauthorized");
    exit;
}

/* ========================
   FILTER LOGIC
======================== */
$filter_status = $_GET['status'] ?? '';
$filter_dari = $_GET['tanggal_dari'] ?? '';
$filter_sampai = $_GET['tanggal_sampai'] ?? '';
$search = trim($_GET['search'] ?? '');

$where = ["t.tipe_transaksi != 'Masuk'"];
$params = [];
$types = "";

if ($filter_status) {
    $where[] = "t.tipe_transaksi = ?";
    $params[] = $filter_status;
    $types .= "s";
}
if ($filter_dari) {
    $where[] = "t.tanggal_transaksi >= ?";
    $params[] = $filter_dari;
    $types .= "s";
}
if ($filter_sampai) {
    $where[] = "t.tanggal_transaksi <= ?";
    $params[] = $filter_sampai;
    $types .= "s";
}
if ($search) {
    $where[] = "(i.no LIKE ? OR i.jenis_barang LIKE ? OR t.keterangan LIKE ?)";
    $search_p = "%$search%";
    array_push($params, $search_p, $search_p, $search_p);
    $types .= "sss";
}

/* ========================
   MAIN QUERY
======================== */
$sql = "SELECT t.*, i.no, i.jenis_barang, i.kategori, i.harga_perolehan, k.nama_kantor as tujuan_kantor 
        FROM transaksi t 
        JOIN inventory i ON t.inventory_id = i.id 
        LEFT JOIN kantor k ON t.ke_kantor_id = k.id 
        WHERE " . implode(" AND ", $where) . " 
        ORDER BY t.tanggal_transaksi DESC";

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

/* ========================
   STATISTICS QUERY
======================== */
$stats_query = $conn->query("SELECT t.tipe_transaksi, COUNT(*) as jml, SUM(i.harga_perolehan) as total 
                             FROM transaksi t JOIN inventory i ON t.inventory_id = i.id 
                             WHERE t.tipe_transaksi != 'Masuk' GROUP BY t.tipe_transaksi");
$statistik = [];
while($s = $stats_query->fetch_assoc()) { $statistik[$s['tipe_transaksi']] = $s; }
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Laporan Barang Keluar - ACF EDU HUB</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        :root { --p: #764ba2; --s: #667eea; --bg: #f4f7fe; }
        body { font-family: 'Inter', sans-serif; background: var(--bg); margin: 0; padding: 20px; color: #333; }
        .container { max-width: 1300px; margin: 0 auto; }
        
        /* Header & Stats */
        .header { background: white; padding: 25px; border-radius: 15px; display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        .stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; margin-bottom: 25px; }
        .stat-card { background: white; padding: 20px; border-radius: 12px; border-left: 5px solid var(--p); box-shadow: 0 2px 10px rgba(0,0,0,0.03); }
        .stat-card h3 { margin: 0; font-size: 12px; color: #888; text-transform: uppercase; }
        .stat-card p { margin: 5px 0; font-size: 24px; font-weight: bold; color: #222; }

        /* Filter & Table */
        .filter-box { background: white; padding: 20px; border-radius: 15px; margin-bottom: 20px; display: flex; gap: 15px; align-items: flex-end; flex-wrap: wrap; }
        .input-group { display: flex; flex-direction: column; gap: 5px; }
        .input-group input, .input-group select { padding: 10px; border: 1px solid #ddd; border-radius: 8px; outline: none; }
        
        .table-container { background: white; border-radius: 15px; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.05); }
        table { width: 100%; border-collapse: collapse; }
        th { background: #f8f9fa; padding: 15px; text-align: left; font-size: 13px; color: #666; border-bottom: 2px solid #eee; }
        td { padding: 15px; border-bottom: 1px solid #eee; font-size: 14px; }
        tr:hover { background: #f9f9ff; }

        /* Badges */
        .badge { padding: 5px 12px; border-radius: 20px; font-size: 11px; font-weight: 600; }
        .badge-keluar { background: #fee2e2; color: #ef4444; }
        .badge-pindah { background: #e0e7ff; color: #4f46e5; }
        .badge-rusak { background: #fef3c7; color: #d97706; }

        /* Modal */
        .modal { display: none; position: fixed; z-index: 999; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); }
        .modal-content { background: white; width: 500px; margin: 100px auto; border-radius: 15px; overflow: hidden; animation: slideDown 0.3s; }
        .modal-header { background: var(--p); color: white; padding: 15px 20px; display: flex; justify-content: space-between; }
        .modal-body { padding: 20px; }
        .detail-row { display: flex; justify-content: space-between; padding: 10px 0; border-bottom: 1px dashed #eee; }
        .detail-label { color: #888; font-weight: 500; }

        .btn-print { background: #10b981; color: white; border: none; padding: 10px 20px; border-radius: 8px; cursor: pointer; font-weight: 600; }
        .btn-filter { background: var(--p); color: white; border: none; padding: 10px 25px; border-radius: 8px; cursor: pointer; }

        @media print { .no-print { display: none !important; } body { padding: 0; background: white; } .container { max-width: 100%; } }
        @keyframes slideDown { from { transform: translateY(-50px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
    </style>
</head>
<body>

<div class="container">
    <div class="header">
        <div>
            <h1 style="margin:0; font-size: 24px;">Laporan Barang Keluar</h1>
            <p style="color:#888; margin:5px 0;">ACF EDU HUB - Sistem Informasi Manajemen Aset</p>
        </div>
        <div class="no-print" style="display:flex; gap:10px;">
            <a href="home_staff.php" style="text-decoration:none; color:#666; padding:10px;">Kembali</a>
            <button onclick="window.print()" class="btn-print"><i class="fas fa-print"></i> Cetak Laporan</button>
        </div>
    </div>

    <div class="stats-grid no-print">
        <?php foreach(['Keluar', 'Pindah', 'Rusak'] as $t): ?>
        <div class="stat-card">
            <h3>Total <?= $t ?></h3>
            <p><?= $statistik[$t]['jml'] ?? 0 ?> <span style="font-size:14px; font-weight:normal; color:#888;">Unit</span></p>
            <small>Rp <?= number_format($statistik[$t]['total'] ?? 0, 0, ',', '.') ?></small>
        </div>
        <?php endforeach; ?>
    </div>

    <form class="filter-box no-print" method="GET">
        <div class="input-group">
            <label>Cari</label>
            <input type="text" name="search" placeholder="No Aset / Nama..." value="<?= $search ?>">
        </div>
        <div class="input-group">
            <label>Tipe</label>
            <select name="status">
                <option value="">Semua Tipe</option>
                <option value="Keluar" <?= $filter_status == 'Keluar' ? 'selected' : '' ?>>Keluar</option>
                <option value="Pindah" <?= $filter_status == 'Pindah' ? 'selected' : '' ?>>Pindah</option>
                <option value="Rusak" <?= $filter_status == 'Rusak' ? 'selected' : '' ?>>Rusak</option>
            </select>
        </div>
        <div class="input-group">
            <label>Dari Tanggal</label>
            <input type="date" name="tanggal_dari" value="<?= $filter_dari ?>">
        </div>
        <div class="input-group">
            <label>Sampai Tanggal</label>
            <input type="date" name="tanggal_sampai" value="<?= $filter_sampai ?>">
        </div>
        <button type="submit" class="btn-filter">Filter</button>
        <a href="laporan_barang_keluar.php" style="padding:10px; color:red; font-size:12px;">Reset</a>
    </form>

    <div class="table-container">
        <table>
            <thead>
                <tr>
                    <th>TGL TRANS</th>
                    <th>NO ASET</th>
                    <th>NAMA BARANG</th>
                    <th>TIPE</th>
                    <th>TUJUAN/KANTOR</th>
                    <th class="no-print">AKSI</th>
                </tr>
            </thead>
            <tbody>
                <?php if($result->num_rows > 0): while($row = $result->fetch_assoc()): ?>
                <tr>
                    <td><?= date('d/m/Y', strtotime($row['tanggal_transaksi'])) ?></td>
                    <td><strong><?= $row['no'] ?></strong></td>
                    <td><?= $row['jenis_barang'] ?></td>
                    <td><span class="badge badge-<?= strtolower($row['tipe_transaksi']) ?>"><?= $row['tipe_transaksi'] ?></span></td>
                    <td><?= $row['tujuan_kantor'] ?? '-' ?></td>
                    <td class="no-print">
                        <button onclick='showDetail(<?= json_encode($row) ?>)' style="border:none; background:none; color:var(--p); cursor:pointer;"><i class="fas fa-eye"></i> Detail</button>
                    </td>
                </tr>
                <?php endwhile; else: ?>
                <tr><td colspan="6" style="text-align:center; padding:50px; color:#888;">Tidak ada data barang keluar yang ditemukan.</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div id="detailModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3 style="margin:0;">Detail Pengeluaran Aset</h3>
            <span style="cursor:pointer;" onclick="closeModal()">&times;</span>
        </div>
        <div class="modal-body" id="modalBody"></div>
    </div>
</div>



<script>
    function showDetail(data) {
        const body = document.getElementById('modalBody');
        const price = new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR' }).format(data.harga_perolehan);
        
        body.innerHTML = `
            <div class="detail-row"><span class="detail-label">Nomor Aset</span><span>${data.no}</span></div>
            <div class="detail-row"><span class="detail-label">Jenis Barang</span><span>${data.jenis_barang}</span></div>
            <div class="detail-row"><span class="detail-label">Kategori</span><span>${data.kategori}</span></div>
            <div class="detail-row"><span class="detail-label">Harga Perolehan</span><span>${price}</span></div>
            <div style="height:15px"></div>
            <div class="detail-row"><span class="detail-label">Tipe Transaksi</span><span class="badge badge-${data.tipe_transaksi.toLowerCase()}">${data.tipe_transaksi}</span></div>
            <div class="detail-row"><span class="detail-label">Keterangan</span><span>${data.keterangan || '-'}</span></div>
            <div class="detail-row"><span class="detail-label">Tujuan Kantor</span><span>${data.tujuan_kantor || '-'}</span></div>
            <div style="height:15px"></div>
            <div class="detail-row"><span class="detail-label">Petugas (ID)</span><span>${data.created_by}</span></div>
            <div class="detail-row"><span class="detail-label">Waktu Sistem</span><span>${data.created_at}</span></div>
        `;
        document.getElementById('detailModal').style.display = 'block';
    }

    function closeModal() { document.getElementById('detailModal').style.display = 'none'; }
    window.onclick = function(e) { if(e.target == document.getElementById('detailModal')) closeModal(); }
</script>

</body>
</html>