<?php
session_start();

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

/* =========================
   2. DATABASE CONNECTION
========================= */
$koneksiPath = '';
$possiblePaths = [
    __DIR__ . '/../DataBase/koneksi.php',
    __DIR__ . '/../database/koneksi.php',
    __DIR__ . '/../db/koneksi.php',
    __DIR__ . '/../../DataBase/koneksi.php',
    __DIR__ . '/../../database/koneksi.php',
    __DIR__ . '/../../config/koneksi.php'
];

foreach ($possiblePaths as $path) {
    if (file_exists($path)) {
        $koneksiPath = $path;
        break;
    }
}

if (empty($koneksiPath)) {
    die("ERROR: File koneksi.php tidak ditemukan");
}

require_once $koneksiPath;

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

/* =========================
   3. CSRF TOKEN
========================= */
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

/* =========================
   4. GET FILTER PARAMETER
========================= */
$filter_kantor = $_GET['kantor'] ?? '';
$filter_status = $_GET['status'] ?? ''; // DEFAULT: SEMUA
$search         = $_GET['search'] ?? '';

/* =========================
   5. BUILD QUERY
========================= */
$sql = "
    SELECT 
        id,
        kode_aset,
        kode_aset_auto,
        jenis_barang,
        kantor,
        status,
        kategori,
        sumber_dana,
        merk
    FROM inventory
    WHERE 1=1
";

$params = [];
$types  = '';

if ($filter_status !== '') {
    $sql .= " AND status = ?";
    $params[] = $filter_status;
    $types   .= 's';
}

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

if ($search !== '') {
    $sql .= " AND (
        kode_aset LIKE ? OR
        kode_aset_auto LIKE ? OR
        jenis_barang LIKE ?
    )";
    $like = "%$search%";
    $params[] = $like;
    $params[] = $like;
    $params[] = $like;
    $types   .= 'sss';
}

$sql .= " ORDER BY id DESC";

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

/* =========================
   7. DATA DROPDOWN
========================= */
$result_kantor = $conn->query("
    SELECT DISTINCT kantor 
    FROM inventory 
    WHERE kantor IS NOT NULL AND kantor != ''
    ORDER BY kantor
");

/* =========================
   8. CEK KODE ASET KOSONG
========================= */
$check_missing = $conn->query("
    SELECT COUNT(*) AS total
    FROM inventory
    WHERE 
        (kode_aset IS NULL OR kode_aset = '')
        AND
        (kode_aset_auto IS NULL OR kode_aset_auto = '')
");
$missing_count = $check_missing->fetch_assoc()['total'];
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Panel Cetak Label</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
</head>
<body>

<h2>Panel Cetak Label</h2>

<?php if ($missing_count > 0): ?>
    <div style="color:red;">
        ⚠️ <?= $missing_count ?> item belum memiliki kode aset
    </div>
<?php endif; ?>

<form method="GET">
    <input type="text" name="search" placeholder="Cari barang..." value="<?= htmlspecialchars($search) ?>">

    <select name="kantor">
        <option value="">Semua Kantor</option>
        <?php while ($k = $result_kantor->fetch_assoc()): ?>
            <option value="<?= htmlspecialchars($k['kantor']) ?>" <?= $filter_kantor === $k['kantor'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($k['kantor']) ?>
            </option>
        <?php endwhile; ?>
    </select>

    <select name="status">
        <option value="">Semua Status</option>
        <option value="aktif" <?= $filter_status === 'aktif' ? 'selected' : '' ?>>Aktif</option>
        <option value="nonaktif" <?= $filter_status === 'nonaktif' ? 'selected' : '' ?>>Nonaktif</option>
    </select>

    <button type="submit">Filter</button>
</form>

<hr>

<p><strong>Total tampil:</strong> <?= $result->num_rows ?> data</p>

<form action="cetak_label_massal.php" method="POST" target="_blank">
    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">

    <?php while ($row = $result->fetch_assoc()): 
        $kode = $row['kode_aset'] ?: $row['kode_aset_auto'] ?: 'BELUM ADA KODE';
    ?>
        <div>
            <label>
                <input type="checkbox" name="ids[]" value="<?= $row['id'] ?>">
                <strong><?= htmlspecialchars($row['jenis_barang']) ?></strong><br>
                Kode: <?= htmlspecialchars($kode) ?><br>
                Kantor: <?= htmlspecialchars($row['kantor']) ?><br>
                Status: <?= htmlspecialchars($row['status']) ?><br>
                Merk: <?= htmlspecialchars($row['merk']) ?>
            </label>
            <hr>
        </div>
    <?php endwhile; ?>

    <button type="submit">Cetak Label</button>
</form>

</body>
</html>

<?php
$stmt->close();
$conn->close();
?>
