<?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();

// Build JSON payload for QZ Tray ZPL printing
$zplLabels = [];
foreach ($cands as $c) {
    $barcode     = strtoupper(trim($c['barcode'] ?: $c['candidate_number']));
    $candNum     = strtoupper(trim($c['candidate_number']));
    $name        = mb_strimwidth(trim($c['name']), 0, 28, '...');

    $bits = array_filter([
        $c['facility_code'] ?: $c['facility_name'],
        $c['cohort_year'],
        $c['section'] ? 'Sec ' . $c['section'] : null,
    ]);
    $subline = mb_strimwidth(implode(' · ', $bits), 0, 32, '');

    // ZPL for 60mm x 40mm @ 203dpi = 480 x 320 dots
    $zpl  = "^XA\n";
    $zpl .= "^PW480\n";           // label width  60mm @ 203dpi
    $zpl .= "^LL320\n";           // label length 40mm @ 203dpi
    $zpl .= "^LH0,0\n";           // label home origin
    $zpl .= "^CI28\n";            // UTF-8 character set

    // Barcode — Code-39, centred, bars 80 dots tall
    $zpl .= "^FO20,10^BY2,3,60\n";
    $zpl .= "^B3N,N,60,Y,N\n";
    $zpl .= "^FD{$barcode}^FS\n";

    // Candidate number — bold, centred
    $zpl .= "^FO20,110^A0N,26,26^FB440,1,0,C^FD{$candNum}^FS\n";

    // Name
    $zpl .= "^FO20,142^A0N,22,22^FB440,1,0,C^FD{$name}^FS\n";

    // Sub-line (facility · year · section)
    $zpl .= "^FO20,170^A0N,18,18^FB440,1,0,C^FD{$subline}^FS\n";

    $zpl .= "^XZ\n";

    $zplLabels[] = $zpl;
}
$zplJson = json_encode($zplLabels, JSON_UNESCAPED_UNICODE);
?>

<!-- QZ Tray JS library (loaded from CDN) -->
<script src="https://cdn.jsdelivr.net/npm/qz-tray@2.2.4/qz-tray.min.js"></script>

<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.
    Use <strong>🖨 Print (Browser)</strong> for any printer, or <strong>⚡ Direct to Zebra</strong> for instant 60×40mm label printing via QZ Tray.
</p>

<div class="mb-2 no-print flex" style="gap:10px; align-items:center; flex-wrap:wrap;">
    <form method="get" style="display:contents;">
        <?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-secondary" onclick="window.print()">🖨 Print (Browser)</button>
    </form>

    <button type="button" class="btn btn-primary" id="btnZebraPrint" onclick="printZebra()">
        ⚡ Direct to Zebra
    </button>
    <span class="muted"><?php echo count($cands); ?> candidate(s)</span>
    <span id="qzStatus" class="muted" style="font-size:12px;"></span>
</div>

<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>

<script>
// ZPL data generated server-side
const ZPL_LABELS = <?php echo $zplJson; ?>;
const ZEBRA_PRINTER = 'ZDesigner ZD220-203dpi ZPL';

async function printZebra() {
    const btn    = document.getElementById('btnZebraPrint');
    const status = document.getElementById('qzStatus');

    if (!ZPL_LABELS.length) {
        status.textContent = 'No candidates to print.';
        return;
    }

    btn.disabled = true;
    status.textContent = 'Connecting to QZ Tray…';

    try {
        // Connect — use WSS (secure) since site is HTTPS; QZ Tray listens on 8183 for WSS
        if (!qz.websocket.isActive()) {
            await qz.websocket.connect({
                host: 'localhost',
                port: { secure: [8183, 8282], insecure: [8182, 8181] },
                usingSecure: true
            });
        }
        status.textContent = 'Connected. Finding printer…';

        // Verify printer exists
        const printers = await qz.printers.find(ZEBRA_PRINTER);
        if (!printers || (Array.isArray(printers) && printers.length === 0)) {
            throw new Error('Printer "' + ZEBRA_PRINTER + '" not found. Check it is on and QZ Tray is running.');
        }

        const printer = Array.isArray(printers) ? printers[0] : printers;
        status.textContent = `Printing ${ZPL_LABELS.length} label(s) to "${printer}"…`;

        // Build one print config — RAW ZPL
        const cfg  = qz.configs.create(printer, { raw: true });
        const data = ZPL_LABELS.map(zpl => ({ type: 'raw', format: 'plain', data: zpl }));

        await qz.print(cfg, data);
        status.textContent = `✅ Sent ${ZPL_LABELS.length} label(s) to printer.`;

    } catch (err) {
        console.error('QZ Tray error:', err);
        status.textContent = '❌ ' + (err.message || err);
    } finally {
        btn.disabled = false;
    }
}
</script>

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