<?php
require_once __DIR__ . '/header.php';
require_login();

$user    = current_user();
$isSuper = perms_is_super($user);

$facF = v_int($_GET['facility_id'] ?? 0, 0);
$facilities = $isSuper ? $pdo->query('SELECT id, name, code FROM facilities WHERE deleted_at IS NULL ORDER BY name')->fetchAll() : [];

$params = [];
$where  = ['c.deleted_at IS NULL'];
if (!$isSuper && $user['facility_id']) { $where[] = 'c.facility_id = ?'; $params[] = $user['facility_id']; }
elseif ($isSuper && $facF > 0)         { $where[] = 'c.facility_id = ?'; $params[] = $facF; }

$stmt = $pdo->prepare("
    SELECT c.id, c.candidate_number, c.name, c.barcode, c.section, c.circuit_type, c.cohort_year,
           f.name AS facility_name, f.code AS facility_code
    FROM candidates c JOIN facilities f ON c.facility_id = f.id
    WHERE " . implode(' AND ', $where) . "
    ORDER BY c.candidate_number
");
$stmt->execute($params);
$cands = $stmt->fetchAll();
?>
<h2>Printable Barcode Labels</h2>
<p class="muted no-print">
    These are <strong>Code-39 SVG</strong> barcodes — scannable by any USB / wedge barcode reader and printable by any label printer (Brother, Zebra, DYMO, Bixolon, etc.). No font installation needed on the print machine.
</p>

<form method="get" class="mb-2 no-print flex">
    <?php if ($isSuper): ?>
    <label>Facility:
        <select name="facility_id" onchange="this.form.submit()">
            <option value="0">All</option>
            <?php foreach ($facilities as $f): ?>
                <option value="<?php echo (int)$f['id']; ?>" <?php if ($facF==(int)$f['id']) echo 'selected'; ?>>
                    <?php echo h($f['name']); ?><?php if ($f['code']) echo ' [' . h($f['code']) . ']'; ?>
                </option>
            <?php endforeach; ?>
        </select>
    </label>
    <?php endif; ?>
    <button type="button" class="btn btn-primary" onclick="window.print()">🖨 Print</button>
    <span class="muted"><?php echo count($cands); ?> candidate(s)</span>
</form>

<div class="barcode-grid">
    <?php foreach ($cands as $c): ?>
        <div class="barcode-card">
            <div style="margin-bottom:6px;"><?php echo code39_svg($c['barcode'], 50, 2, 3, true); ?></div>
            <div class="num"><?php echo h($c['candidate_number']); ?></div>
            <div class="name"><?php echo h($c['name']); ?></div>
            <div class="muted" style="font-size:11px; margin-top:4px;">
                <?php
                $bits = array_filter([
                    $c['facility_code'] ?: $c['facility_name'],
                    $c['cohort_year'],
                    $c['section'] ? 'Sec ' . $c['section'] : null,
                    $c['circuit_type'],
                ]);
                echo h(implode(' · ', $bits));
                ?>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<?php require __DIR__ . '/footer.php'; ?>
