<?php
require_once __DIR__ . '/../config/db_remote.php';
require_once __DIR__ . '/zpl_renderer.php';
require_once __DIR__ . '/printer_manager.php';

$id   = intval($_GET["id"]   ?? 0);
$auto = intval($_GET["auto"] ?? 0);
if ($id <= 0) die("Invalid ID");

// ===== LOAD SETTINGS =====
$settingsFile = __DIR__ . '/../config/printer_settings.json';
$cfg = file_exists($settingsFile) ? json_decode(file_get_contents($settingsFile), true) : [];

$fields   = $cfg['label_fields']      ?? [];
$layout   = $cfg['full_bins_layout']  ?? 'layout_a';
$dpi      = intval($cfg['full_bins_dpi'] ?? 203);
$preview  = !empty($cfg['full_bins_preview']); // toggle preview ON/OFF da settings

// Override layout/dpi da query string (per editor grafico)
$layoutGet = $_GET['layout'] ?? '';
if (in_array($layoutGet, ['layout_a', 'layout_b', 'layout_c'])) {
    $layout = $layoutGet;
}
$dpiGet = intval($_GET['dpi'] ?? 0);
if (in_array($dpiGet, [203, 300])) {
    $dpi = $dpiGet;
}

// ===== LOAD BIN DATA (con JOIN su growers e varieties) =====
$sql = "
    SELECT 
        b.*,
        g.name AS grower_name,
        v.name AS variety_name
    FROM bins_ingresso b
    LEFT JOIN growers   g ON g.id = b.grower_id
    LEFT JOIN varieties v ON v.id = b.variety_id
    WHERE b.id = $id
    LIMIT 1
";
$res = $mysqli->query($sql);
if (!$res) {
    die("DB error: " . $mysqli->error);
}
$row = $res->fetch_assoc();
if (!$row) die("Bin not found");

// PAYLOAD
$payload = [
    "id"         => $id,
    "grower"     => $row["grower_name"]   ?? "",
    "variety"    => $row["variety_name"]  ?? "",
    "date"       => $row["date"]          ?? "",
    "bins_total" => $row["quantity"]      ?? 0,
    "lot"        => $row["lot"]           ?? "",
    "barcode"    => "FBIN-" . str_pad($id, 6, "0", STR_PAD_LEFT)
];

// ===== GENERATE ZPL =====
$zpl = renderBinLabel($layout, $payload, $fields, $dpi);

// ====================================================
//  BRANCH 1: STAMPA REALE (auto=1 OR preview disattivata)
// ====================================================
if ($auto === 1 || !$preview) {
    $result = printer_send($zpl);

    header("Content-Type: text/plain; charset=utf-8");
    echo "PRINT RESULT for BIN #{$id}\n\n";
    echo $result . "\n\n";
    echo "=== ZPL SENT ===\n\n";
    echo $zpl;
    exit;
}

// ====================================================
//  FUNZIONE: genera PNG dell'etichetta con righelli
// ====================================================
function generate_label_png($payload, $fields, $layout, $dpi) {

    if (!function_exists('imagecreatetruecolor')) {
        return null; // GD non disponibile
    }

    // 4x2 inches
    $width  = intval(4 * $dpi);
    $height = intval(2 * $dpi);

    $img = imagecreatetruecolor($width, $height);

    $white = imagecolorallocate($img, 255, 255, 255);
    $black = imagecolorallocate($img, 0, 0, 0);
    $gray  = imagecolorallocate($img, 180, 180, 180);

    imagefill($img, 0, 0, $white);

    // Bordo esterno
    imagerectangle($img, 2, 2, $width - 3, $height - 3, $gray);

    // ---------- RIGHELLO INCH (sopra) ----------
    $inchCount = 4;
    for ($i = 0; $i <= $inchCount; $i++) {
        $x = intval($i * $dpi);
        imageline($img, $x, 0, $x, 12, $black);
        imagestring($img, 2, $x + 2, 12, $i . '"', $black);

        if ($i < $inchCount) {
            for ($q = 1; $q < 4; $q++) {
                $tx = intval($x + $q * ($dpi / 4));
                $h  = ($q == 2) ? 10 : 7;
                imageline($img, $tx, 0, $tx, $h, $gray);
            }
        }
    }

    // ---------- RIGHELLO MM (sinistra) ----------
    $mmMax = intval(2 * 25.4); // circa 50.8mm
    for ($mm = 0; $mm <= $mmMax; $mm += 10) {
        $y = intval(($mm / 25.4) * $dpi);
        imageline($img, 0, $y, 10, $y, $black);
        imagestring($img, 2, 12, $y - 7, $mm . "mm", $black);

        if ($mm < $mmMax) {
            $y2 = intval((($mm + 5) / 25.4) * $dpi);
            imageline($img, 0, $y2, 7, $y2, $gray);
        }
    }

    // FONT tipo Zebra
    $font   = __DIR__ . '/../assets/DejaVuSansMono.ttf';
    $hasTtf = file_exists($font);

    $zebraSize = function ($zplHeight, $dpi) {
        return $zplHeight * 72 / $dpi;
    };

    $xText = 40;
    $yText = 40;

    // GROWER
    if (!empty($fields["grower"]) && !empty($payload['grower'])) {
        $size = $zebraSize(40, $dpi);
        if ($hasTtf) {
            imagettftext($img, $size, 0, $xText, $yText, $black, $font, $payload['grower']);
        } else {
            imagestring($img, 5, $xText, $yText - 14, $payload['grower'], $black);
        }
        $yText += ($hasTtf ? $size + 8 : 28);
    }

    // VARIETY
    if (!empty($fields["variety"]) && !empty($payload['variety'])) {
        $size = $zebraSize(35, $dpi);
        if ($hasTtf) {
            imagettftext($img, $size, 0, $xText, $yText, $black, $font, $payload['variety']);
        } else {
            imagestring($img, 5, $xText, $yText - 14, $payload['variety'], $black);
        }
        $yText += ($hasTtf ? $size + 8 : 26);
    }

    // DATE
    if (!empty($fields["date"]) && !empty($payload['date'])) {
        $size = $zebraSize(30, $dpi);
        if ($hasTtf) {
            imagettftext($img, $size, 0, $xText, $yText, $black, $font, $payload['date']);
        } else {
            imagestring($img, 4, $xText, $yText - 12, $payload['date'], $black);
        }
        $yText += ($hasTtf ? $size + 6 : 22);
    }

    // BINS TOTAL
    if (!empty($fields["bins_total"])) {
        $size = $zebraSize(28, $dpi);
        $txt  = "Total bins: " . $payload['bins_total'];
        if ($hasTtf) {
            imagettftext($img, $size, 0, $xText, $yText, $black, $font, $txt);
        } else {
            imagestring($img, 4, $xText, $yText - 12, $txt, $black);
        }
        $yText += ($hasTtf ? $size + 6 : 22);
    }

    // LOT
    if (!empty($fields["lot"]) && !empty($payload['lot'])) {
        $size = $zebraSize(28, $dpi);
        $txt  = "Lot: " . $payload['lot'];
        if ($hasTtf) {
            imagettftext($img, $size, 0, $xText, $yText, $black, $font, $txt);
        } else {
            imagestring($img, 4, $xText, $yText - 12, $txt, $black);
        }
        $yText += ($hasTtf ? $size + 8 : 24);
    }

    // BARCODE
    if (!empty($fields["barcode"]) && !empty($payload["barcode"])) {
        $barHeight = ($layout === "layout_c") ? intval(1.2 * $dpi) : intval(0.9 * $dpi);
        $barY = $yText + 10;
        $module = max(1, intval($dpi / 100));

        $xBar = $xText;
        srand(crc32($payload["barcode"]));

        for ($i = 0; $i < 90; $i++) {
            $w = rand(1, 4) * $module;
            if ($i % 2 == 0) {
                imagefilledrectangle($img, $xBar, $barY, $xBar + $w, $barY + $barHeight, $black);
            }
            $xBar += $w;
            if ($xBar > $width - 30) break;
        }

        $size = $zebraSize(24, $dpi);
        $textY = $barY + $barHeight + ($hasTtf ? 30 : 20);
        if ($hasTtf) {
            imagettftext($img, $size, 0, $xText, $textY, $black, $font, $payload["barcode"]);
        } else {
            imagestring($img, 4, $xText, $textY - 12, $payload["barcode"], $black);
        }
    }

    return $img;
}

// ======================================
// mode=png → restituisce PNG
// mode=download → scarica PNG
// ======================================
$mode = $_GET['mode'] ?? '';

if ($mode === 'png' || $mode === 'download') {

    $img = generate_label_png($payload, $fields, $layout, $dpi);
    if (!$img) {
        header("Content-Type: text/plain; charset=utf-8");
        echo "GD extension non disponibile, impossibile generare la preview grafica.\n\n";
        echo "ZPL:\n\n" . $zpl;
        exit;
    }

    header("Content-Type: image/png");
    if ($mode === 'download') {
        header("Content-Disposition: attachment; filename=bin_label_{$id}.png");
    }

    imagepng($img);
    imagedestroy($img);
    exit;
}

// ======================================
// DEFAULT: HTML VIEWER CON ZOOM + PAN + SELECTOR LAYOUT/DPI
// ======================================
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Full Bin Label Preview #<?= htmlspecialchars($id) ?></title>
<style>
    body {
        font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        margin: 0;
        padding: 16px;
        background: #f5f5f5;
    }
    h2 { margin-top: 0; }
    .top-bar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 16px;
        margin-bottom: 12px;
        flex-wrap: wrap;
    }
    .info {
        font-size: 13px;
        color: #555;
    }
    .btn {
        display: inline-block;
        padding: 6px 12px;
        font-size: 13px;
        border-radius: 4px;
        border: 1px solid #007bff;
        color: #007bff;
        background: #fff;
        text-decoration: none;
        cursor: pointer;
        margin-right: 6px;
    }
    .btn-primary {
        background: #007bff;
        color: #fff;
    }
    .btn-secondary {
        border-color: #6c757d;
        color: #6c757d;
    }
    .preview-wrapper {
        border: 1px solid #ddd;
        background: #fff;
        padding: 10px;
        border-radius: 6px;
    }
    .preview-frame {
        width: 100%;
        max-width: 900px;
        height: 400px;
        margin: 0 auto;
        border: 1px solid #ccc;
        background: #eee;
        overflow: hidden;
        position: relative;
        cursor: grab;
    }
    .preview-frame:active {
        cursor: grabbing;
    }
    #labelImg {
        position: absolute;
        top: 50%;
        left: 50%;
        transform-origin: center center;
        image-rendering: pixelated;
        user-select: none;
        -webkit-user-drag: none;
    }
    .hint {
        font-size: 12px;
        color: #777;
        margin-top: 6px;
        text-align: center;
    }
    .controls-row {
        display: flex;
        align-items: center;
        gap: 8px;
        flex-wrap: wrap;
        margin-top: 4px;
        font-size: 13px;
    }
    select {
        padding: 3px 6px;
        font-size: 13px;
    }
</style>
</head>
<body>

<div class="top-bar">
    <div>
        <h2>Full Bin Label Preview – BIN #<?= htmlspecialchars($id) ?></h2>
        <div class="info">
            Size: <strong>4 x 2 inches</strong>
        </div>
        <form method="get" class="controls-row">
            <input type="hidden" name="id" value="<?= htmlspecialchars($id) ?>">
            <label>
                Layout:
                <select name="layout" onchange="this.form.submit()">
                    <option value="layout_a" <?= $layout === 'layout_a' ? 'selected' : '' ?>>A (standard)</option>
                    <option value="layout_b" <?= $layout === 'layout_b' ? 'selected' : '' ?>>B (barcode left)</option>
                    <option value="layout_c" <?= $layout === 'layout_c' ? 'selected' : '' ?>>C (big barcode)</option>
                </select>
            </label>
            <label>
                DPI:
                <select name="dpi" onchange="this.form.submit()">
                    <option value="203" <?= $dpi == 203 ? 'selected' : '' ?>>203 DPI</option>
                    <option value="300" <?= $dpi == 300 ? 'selected' : '' ?>>300 DPI</option>
                </select>
            </label>
        </form>
    </div>
    <div>
        <a class="btn btn-secondary"
           href="?id=<?= urlencode($id) ?>&layout=<?= urlencode($layout) ?>&dpi=<?= (int)$dpi ?>&mode=download">
           ⬇ Download PNG
        </a>
        <a class="btn btn-primary"
           href="?id=<?= urlencode($id) ?>&layout=<?= urlencode($layout) ?>&dpi=<?= (int)$dpi ?>&auto=1"
           onclick="return confirm('Send label to printer with this layout/DPI?');">
           🖨 Print now
        </a>
    </div>
</div>

<div class="preview-wrapper">
    <div class="preview-frame" id="previewFrame">
        <img id="labelImg"
             src="?id=<?= urlencode($id) ?>&layout=<?= urlencode($layout) ?>&dpi=<?= (int)$dpi ?>&mode=png"
             alt="Label preview">
    </div>
    <div class="hint">
        Zoom: rotella del mouse · Pan: trascina con il mouse ·
        La stampa reale usa il vero barcode ^BC della Zebra.
    </div>
</div>

<script>
(function() {
    const img = document.getElementById('labelImg');
    const frame = document.getElementById('previewFrame');

    let scale = 1;
    let offsetX = 0;
    let offsetY = 0;
    let isDragging = false;
    let startX = 0;
    let startY = 0;

    function updateTransform() {
        img.style.transform = `translate(${offsetX}px, ${offsetY}px) scale(${scale})`;
    }

    img.addEventListener('load', () => {
        scale = 1;
        offsetX = 0;
        offsetY = 0;
        updateTransform();
    });

    frame.addEventListener('wheel', (e) => {
        e.preventDefault();
        const delta = e.deltaY < 0 ? 0.1 : -0.1;
        let newScale = scale + delta;
        if (newScale < 0.2) newScale = 0.2;
        if (newScale > 5)   newScale = 5;
        scale = newScale;
        updateTransform();
    });

    frame.addEventListener('mousedown', (e) => {
        isDragging = true;
        startX = e.clientX - offsetX;
        startY = e.clientY - offsetY;
    });
    window.addEventListener('mousemove', (e) => {
        if (!isDragging) return;
        offsetX = e.clientX - startX;
        offsetY = e.clientY - startY;
        updateTransform();
    });
    window.addEventListener('mouseup', () => {
        isDragging = false;
    });
    frame.addEventListener('mouseleave', () => {
        isDragging = false;
    });
})();
</script>

</body>
</html>
