<?php
// Print label for each bin in a group
require_once __DIR__ . '/../config/db_remote.php';
require_once __DIR__ . '/../config/label_config.php';

$group_id = isset($_GET['group_id']) ? (int)$_GET['group_id'] : 0;
if ($group_id <= 0) {
    die("Missing group_id.");
}

$res = $mysqli->query("
    SELECT 
        bi.id,
        bi.lot,
        bi.date,
        gp.name AS grower,
        vl.name AS variety,
        tl.name AS type
    FROM bins_ingresso bi
    LEFT JOIN growers_list   gp ON bi.grower_id  = gp.id
    LEFT JOIN varieties_list vl ON bi.variety_id = vl.id
    LEFT JOIN bin_types_list tl ON bi.type_id    = tl.id
    WHERE bi.group_id = $group_id
    ORDER BY bi.id ASC
");
if (!$res) {
    die("Query error.");
}

$bins = [];
while ($row = $res->fetch_assoc()) {
    $bins[] = $row;
}

if (empty($bins)) {
    die("No bins found for this group.");
}

$settings    = get_label_settings($mysqli);
$printerName = $settings['printer_name'] ?? null;

$results = [];
foreach ($bins as $bin) {
    $zpl = build_full_bin_zpl($bin, $settings);
    $results[$bin['id']] = send_zpl_to_printer($zpl, $printerName);
}

header('Content-Type: text/html; charset=utf-8');
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Print Group #<?= $group_id ?> Labels</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="p-3">
<div class="container">
    <h4 class="mb-3">Group <?= $group_id ?> - Label Print</h4>

    <table class="table table-sm table-bordered align-middle">
        <thead class="table-light">
            <tr>
                <th>Bin ID</th>
                <th>Grower</th>
                <th>Variety</th>
                <th>Lot</th>
                <th>Date</th>
                <th>HTTP</th>
                <th>Error</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($bins as $bin): 
                $r = $results[$bin['id']] ?? ['http_code'=>0,'error'=>'','body'=>''];
            ?>
            <tr>
                <td><?= (int)$bin['id'] ?></td>
                <td><?= htmlspecialchars($bin['grower']) ?></td>
                <td><?= htmlspecialchars($bin['variety']) ?></td>
                <td><?= htmlspecialchars($bin['lot']) ?></td>
                <td><?= htmlspecialchars($bin['date']) ?></td>
                <td><?= (int)$r['http_code'] ?></td>
                <td class="small text-danger"><?= htmlspecialchars($r['error'] ?? '') ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <p class="small text-muted">
        The web app sent one ZPL job per bin to Zebra Print Agent at
        <code>http://localhost:9100/print</code> (printer: <?= htmlspecialchars($printerName ?? 'default') ?>).
    </p>
</div>
</body>
</html>
