<?php
include 'config.php';
checkLogin();

/* ===============================
   FILTER INPUTS
================================ */
$serial = $_GET['serial'] ?? '';
$brand  = $_GET['brand'] ?? '';
$model  = $_GET['model'] ?? '';
$status = $_GET['status'] ?? ''; // '', 'printed', 'not_printed'

/* ===============================
   BUILD QUERY SAFELY
================================ */
$sql = "
SELECT 
    s.id,
    s.serial_number,
    s.printed,
    m.brand,
    m.model
FROM laptop_serials s
JOIN laptop_models m ON s.model_id = m.id
WHERE 1=1
";

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

/* Serial filter */
if (!empty($serial)) {
    $sql .= " AND s.serial_number LIKE ? ";
    $params[] = "%$serial%";
    $types .= "s";
}

/* Brand filter */
if (!empty($brand)) {
    $sql .= " AND m.brand = ? ";
    $params[] = $brand;
    $types .= "s";
}

/* Model filter */
if (!empty($model)) {
    $sql .= " AND m.model = ? ";
    $params[] = $model;
    $types .= "s";
}

/* Status filter */
if ($status === 'printed') {
    $sql .= " AND s.printed = 1 ";
} elseif ($status === 'not_printed') {
    $sql .= " AND (s.printed = 0 OR s.printed IS NULL) ";
}

$sql .= " ORDER BY s.id DESC LIMIT 300";

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

/* ===============================
   FILTER DATA FOR DROPDOWNS
================================ */
$brands = $conn->query("SELECT DISTINCT brand FROM laptop_models ORDER BY brand");
$models = $conn->query("SELECT DISTINCT model FROM laptop_models ORDER BY model");

include 'layout/header.php';
include 'layout/sidebar.php';
?>

<h3 class="mb-4">All Generated Labels</h3>

<!-- FILTER FORM -->
<div class="card p-4 mb-4">
<form method="get" class="row g-3">

    <div class="col-md-3">
        <label class="form-label">Serial Number</label>
        <input type="text" name="serial" class="form-control"
               value="<?= htmlspecialchars($serial) ?>"
               placeholder="Search serial">
    </div>

    <div class="col-md-3">
        <label class="form-label">Brand</label>
        <select name="brand" class="form-select">
            <option value="">All Brands</option>
            <?php while ($b = $brands->fetch_assoc()) { ?>
                <option value="<?= htmlspecialchars($b['brand']) ?>"
                    <?= ($brand == $b['brand']) ? 'selected' : '' ?>>
                    <?= strtoupper($b['brand']) ?>
                </option>
            <?php } ?>
        </select>
    </div>

    <div class="col-md-3">
        <label class="form-label">Model</label>
        <select name="model" class="form-select">
            <option value="">All Models</option>
            <?php while ($m = $models->fetch_assoc()) { ?>
                <option value="<?= htmlspecialchars($m['model']) ?>"
                    <?= ($model == $m['model']) ? 'selected' : '' ?>>
                    <?= strtoupper($m['model']) ?>
                </option>
            <?php } ?>
        </select>
    </div>

    <div class="col-md-3">
        <label class="form-label">Status</label>
        <select name="status" class="form-select">
            <option value="" <?= ($status === '') ? 'selected' : '' ?>>All</option>
            <option value="printed" <?= ($status === 'printed') ? 'selected' : '' ?>>Printed</option>
            <option value="not_printed" <?= ($status === 'not_printed') ? 'selected' : '' ?>>Not Printed</option>
        </select>
    </div>

    <div class="col-md-12 text-end">
        <button class="btn btn-primary">
            🔍 Apply Filters
        </button>
        <a href="recently_printed.php" class="btn btn-secondary">
            Reset
        </a>
    </div>

</form>
</div>

<!-- RESULT TABLE + MULTI SELECT PRINT -->
<div class="card p-4">

<form id="printForm" method="get" action="bulk_print_selected.php" target="_blank">
    <input type="hidden" name="ids" id="idsField">

    <table class="table table-bordered table-hover align-middle">
        <thead class="table-light">
            <tr>
                <th style="width:35px;">
                    <input type="checkbox" id="selectAll">
                </th>
                <th>#</th>
                <th>Brand</th>
                <th>Model</th>
                <th>Serial Number</th>
                <th style="width:120px;">Status</th>
                <th width="170">Action</th>
            </tr>
        </thead>
        <tbody>

        <?php
        $i = 1;
        if ($result->num_rows > 0) {
            while ($row = $result->fetch_assoc()) {
                $is_printed = (int)($row['printed'] ?? 0) === 1;
        ?>
            <tr>
                <td>
                    <input type="checkbox" class="sn-check" value="<?= (int)$row['id'] ?>">
                </td>
                <td><?= $i++ ?></td>
                <td><?= strtoupper($row['brand']) ?></td>
                <td><?= strtoupper($row['model']) ?></td>
                <td><strong><?= htmlspecialchars($row['serial_number']) ?></strong></td>
                <td>
                    <?php if ($is_printed) { ?>
                        <span class="badge bg-success">Printed</span>
                    <?php } else { ?>
                        <span class="badge bg-secondary">Not Printed</span>
                    <?php } ?>
                </td>
                <td>
                    <a href="print_barcode.php?id=<?= (int)$row['id'] ?>"
                       target="_blank"
                       class="btn btn-sm btn-outline-primary">
                       Print
                    </a>
                </td>
            </tr>
        <?php
            }
        } else {
        ?>
            <tr>
                <td colspan="7" class="text-center text-muted">
                    No serials found
                </td>
            </tr>
        <?php } ?>

        </tbody>
    </table>

    <button type="submit" class="btn btn-success mt-3">
        🖨 Print Selected
    </button>

</form>
</div>

<script>
// Select / deselect all
document.getElementById('selectAll')?.addEventListener('change', function () {
    const checked = this.checked;
    document.querySelectorAll('.sn-check').forEach(cb => cb.checked = checked);
});

// On submit, build ids CSV into hidden field
document.getElementById('printForm').addEventListener('submit', function (e) {
    const checkedBoxes = Array.from(document.querySelectorAll('.sn-check:checked'));
    if (checkedBoxes.length === 0) {
        alert("No labels selected for printing.");
        e.preventDefault();
        return;
    }
    const ids = checkedBoxes.map(cb => cb.value);
    document.getElementById('idsField').value = ids.join(',');
});
</script>

<?php include 'layout/footer.php'; ?>