<?php 
session_start();

// Block unauthorized access (same logic as dashboard)
if (!isset($_SESSION['username']) || ($_SESSION['role'] ?? '') !== 'admin') {
    header("Location: login.php?error=Unauthorized access");
    exit();
}

require 'db_connect.php';

date_default_timezone_set('Africa/Nairobi');
$page_title = "Barcode Generator";

/*
    Load products with and without barcodes
    --------------------------------------
    Table: products
    Columns: id, name, barcode, ...
*/

$productsWithBarcode    = [];
$productsWithoutBarcode = [];

// Products that already have barcodes
$sqlWith = "
    SELECT id, name, barcode
    FROM products
    WHERE barcode IS NOT NULL AND barcode <> ''
    ORDER BY name ASC
";
if ($resultWith = $conn->query($sqlWith)) {
    while ($row = $resultWith->fetch_assoc()) {
        $productsWithBarcode[] = $row;
    }
    $resultWith->free();
}

// Products that don't have barcodes yet
$sqlWithout = "
    SELECT id, name
    FROM products
    WHERE barcode IS NULL OR barcode = ''
    ORDER BY name ASC
";
if ($resultWithout = $conn->query($sqlWithout)) {
    while ($row = $resultWithout->fetch_assoc()) {
        $productsWithoutBarcode[] = $row;
    }
    $resultWithout->free();
}

include('head.php'); // <!DOCTYPE html>, <head> etc.
?>

<body>

<?php include('sidebar.php'); ?>

<!-- MAIN PAGE WRAPPER (same structure as manage_products.php) -->
<div class="content-wrapper" id="content-wrapper">

    <!-- TOP BAR (SHARED STYLE) -->
    <div class="topbar">
        <div class="topbar-left">
            <span class="menu-btn" onclick="toggleAdminSidebar()">☰</span>
            <span class="topbar-title">Admin Panel</span>
        </div>
        <div class="topbar-right">
            <button class="theme-toggle" type="button" onclick="toggleAdminTheme()">
                🌓 Theme
            </button>
            <span class="topbar-user">
                Logged in as
                <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Admin'); ?></strong>
            </span>
        </div>
    </div>

    <!-- PAGE BODY -->
    <div class="container-box page-barcode">

        <div class="page-header">
            <div class="page-header-left">
                <div class="page-header-title">
                    <span class="page-header-dot"></span>
                    <h2>Barcode Generator</h2>
                </div>
                <p>
                    Create and print barcodes for existing products (with or without barcodes) 
                    or custom items in your inventory.
                </p>
            </div>
            <span class="page-pill">
                <span class="page-pill-dot"></span>
                Tools · <?= date('d M Y'); ?>
            </span>
        </div>

        <div class="barcode-grid">

            <!-- LEFT: FORM -->
            <section class="panel-card">
                <div class="panel-title">
                    <span class="icon">🏷️</span>
                    Generate barcode
                </div>
                <div class="panel-subtitle">
                    Choose a product or enter details manually, then generate labels you can print and stick on items.
                </div>

                <form onsubmit="generateBarcode(event)">
                    <div class="form-grid">

                        <!-- MODE SWITCH -->
                        <div class="form-group">
                            <label>Mode</label>
                            <div class="mode-toggle">
                                <label class="mode-pill">
                                    <input type="radio" name="barcode_mode" value="existing_with" checked>
                                    <span>Existing product (has barcode)</span>
                                </label>
                                <label class="mode-pill">
                                    <input type="radio" name="barcode_mode" value="without">
                                    <span>Product without barcode</span>
                                </label>
                                <label class="mode-pill">
                                    <input type="radio" name="barcode_mode" value="manual">
                                    <span>Manual / custom</span>
                                </label>
                            </div>
                            <small>Select where the barcode data should come from.</small>
                        </div>

                        <!-- Existing product WITH barcode -->
                        <div class="form-group" id="existingWithBarcodeGroup">
                            <label for="product_with_barcode">Existing product (already has barcode)</label>
                            <select id="product_with_barcode" class="form-select">
                                <option value="">-- Select product --</option>
                                <?php foreach ($productsWithBarcode as $p): ?>
                                    <option
                                        value="<?= (int)$p['id']; ?>"
                                        data-name="<?= htmlspecialchars($p['name']); ?>"
                                        data-barcode="<?= htmlspecialchars($p['barcode']); ?>"
                                    >
                                        <?= htmlspecialchars($p['name'] . ' [' . $p['barcode'] . ']'); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <small>Choose a product to re-print its existing barcode labels.</small>
                        </div>

                        <!-- Product WITHOUT barcode -->
                        <div class="form-group" id="productWithoutBarcodeGroup" style="display:none;">
                            <label for="product_without_barcode">Product without barcode</label>
                            <select id="product_without_barcode" class="form-select">
                                <option value="">-- Select product --</option>
                                <?php foreach ($productsWithoutBarcode as $p): ?>
                                    <option
                                        value="<?= (int)$p['id']; ?>"
                                        data-name="<?= htmlspecialchars($p['name']); ?>"
                                    >
                                        <?= htmlspecialchars($p['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <small>Pick a product with no barcode. A new code will be generated for it.</small>
                        </div>

                        <!-- Item name -->
                        <div class="form-group">
                            <label for="item_name">Item name</label>
                            <input
                                type="text"
                                id="item_name"
                                name="item_name"
                                class="form-control"
                                placeholder="e.g. 2L Cooking Oil"
                                autocomplete="off"
                            >
                            <small>Used as the label text under the barcode.</small>
                        </div>

                        <!-- Barcode value + format -->
                        <div class="form-row-inline">
                            <div class="form-group">
                                <label for="barcode_value">Barcode number</label>
                                <input
                                    type="text"
                                    id="barcode_value"
                                    name="barcode_value"
                                    class="form-control"
                                    placeholder="e.g. 123456789012"
                                    autocomplete="off"
                                    required
                                >
                                <small>Will be filled automatically from product/mode when possible.</small>
                            </div>

                            <div class="form-group">
                                <label for="barcode_format">Barcode format</label>
                                <select id="barcode_format" name="barcode_format" class="form-select">
                                    <option value="CODE128" selected>Code 128 (recommended)</option>
                                    <option value="EAN13">EAN-13</option>
                                    <option value="UPC">UPC</option>
                                    <option value="CODE39">Code 39</option>
                                </select>
                                <small>Choose a format supported by your scanners/printers.</small>
                            </div>
                        </div>

                        <!-- Copies -->
                        <div class="form-group">
                            <label for="label_copies">Number of copies (for printing)</label>
                            <input
                                type="number"
                                id="label_copies"
                                name="label_copies"
                                class="form-control"
                                min="1"
                                value="1"
                            >
                            <small>How many labels to print for this item.</small>
                        </div>
                    </div>

                    <div class="btn-row">
                        <button type="submit" class="btn-primary">
                            <span>⚙️</span> Generate Barcode
                        </button>
                        <button type="button" class="btn-secondary" onclick="clearBarcode()">
                            <span>🧹</span> Clear
                        </button>
                    </div>

                    <p class="barcode-help">
                        Tip: After generating, use the <strong>Print Label</strong> button on the right panel and select your label printer.
                    </p>
                </form>
            </section>

            <!-- RIGHT: PREVIEW + PRINT -->
            <section class="barcode-preview-card">
                <div>
                    <div class="panel-title">
                        <span class="icon">👁️</span>
                        Barcode preview
                    </div>
                    <div class="panel-subtitle">
                        This is how the barcode will appear on the printed label.
                    </div>

                    <div id="barcodePreviewInner" class="barcode-preview-inner" style="display:none;">
                        <div id="barcodePrintArea">
                            <svg id="barcodeSvg"></svg>
                            <div class="barcode-label-main" id="barcodeCodeLabel"></div>
                            <div class="barcode-label-sub" id="barcodeItemLabel"></div>
                        </div>
                    </div>

                    <div id="barcodePlaceholder" class="barcode-preview-inner" style="opacity:0.8;">
                        <p style="font-size:13px;">
                            No barcode generated yet. Fill in the form on the left and click
                            <strong>Generate Barcode</strong> to preview it here.
                        </p>
                    </div>
                </div>

                <div class="btn-row" style="justify-content:flex-end; margin-top:12px;">
                    <button type="button" class="btn-secondary" onclick="printBarcode()" id="printButton" disabled>
                        <span>🖨️</span> Print Label
                    </button>
                </div>
            </section>

        </div>
    </div>

    <?php include('footer.php'); ?>

</div> <!-- /content-wrapper -->


<style>
    /* ----------------------------
       SIDEBAR HIDE/SHOW SUPPORT
       ---------------------------- */
    /* IMPORTANT: sidebar.php must output <div id="sidebar" class="sidebar"> */
    #sidebar.hidden {
        display: none;
    }

    /* ----------------------------
       PAGE LAYOUT (match products)
       ---------------------------- */
    .content-wrapper {
        margin-left: 250px;
        padding: 24px 26px;
        background:
            radial-gradient(circle at top left, rgba(0,255,239,0.08), transparent 55%),
            var(--bg-main, #001f3f);
        min-height: 100vh;
        box-sizing: border-box;
        transition: margin-left 0.3s ease, background 0.3s ease;
    }

    /* when sidebar is hidden: full width */
    .content-wrapper.fullwidth {
        margin-left: 0;
    }

    /* TOP BAR (uniform across pages) */
    .topbar {
        background: var(--bg-sidebar);
        padding: 14px 18px;
        margin-bottom: 20px;
        border-radius: 12px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border: 1px solid #B8860B;
        box-shadow: 0 6px 18px rgba(0,0,0,0.5);
        color: brown;
    }

    .topbar-left {
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .topbar-right {
        display: flex;
        align-items: center;
        gap: 10px;
        font-size: 13px;
    }

    .topbar-title {
        font-weight: 600;
        font-size: 15px;
        letter-spacing: 0.03em;
    }

    .menu-btn {
        font-size: 22px;
        cursor: pointer;
        color: var(--accent-gold, #f4b400);
        transition: 0.3s;
        line-height: 1;
    }

    .menu-btn:hover {
        color: #e6c34b;
    }

    .theme-toggle {
        border-radius: 999px;
        border: 1px solid rgba(184,134,11,0.7);
        padding: 6px 12px;
        background: rgba(0,0,0,0.4);
        color: #f9f9f9;
        font-size: 12px;
        cursor: pointer;
    }

    .theme-toggle:hover {
        background: rgba(0,0,0,0.65);
    }

    .topbar-user strong {
        font-weight: 600;
    }

    @media (max-width: 900px) {
        .content-wrapper {
            margin-left: 0;
            padding: 18px 14px;
        }
        .content-wrapper.fullwidth {
            margin-left: 0;
        }
        .topbar {
            flex-direction: column;
            align-items: flex-start;
            gap: 8px;
        }
    }

    /* ----------------------------
       BARCODE PAGE-SPECIFIC STYLES
       ---------------------------- */

    body[data-theme="dark"], body:not([data-theme]) {
        --cash-bg-main: #001f3f;
        --cash-bg-card: #012a57;
        --cash-panel-grad-from: #064ab8;
        --cash-panel-grad-mid: #022a6b;
        --cash-panel-grad-to:   #021d53;
        --cash-text-main: #F9FAFB;
        --cash-text-muted: #9CA3AF;
        --cash-accent: #00ffef;
        --cash-border-soft: rgba(130,238,253,0.45);
        --accent-gold: #fbbf24;
    }

    body[data-theme="light"] {
        --cash-bg-main: #f3f4f6;
        --cash-bg-card: #ffffff;
        --cash-panel-grad-from: #f9fafb;
        --cash-panel-grad-mid:  #eef2ff;
        --cash-panel-grad-to:   #e0f2fe;
        --cash-text-main: #111827;
        --cash-text-muted: #6b7280;
        --cash-accent: #0ea5e9;
        --cash-border-soft: rgba(148,163,184,0.45);
        --accent-gold: #eab308;
    }

    .container-box.page-barcode {
        max-width: 1200px;
        margin: 0 auto 20px auto;
        background: rgba(0,23,48,0.92);
        border-radius: 18px;
        padding: 20px 22px 26px;
        border: 1px solid rgba(130,238,253,0.35);
        box-shadow: 0 22px 50px rgba(0,0,0,0.65);
        backdrop-filter: blur(14px);
        color: var(--cash-text-main);
    }

    body[data-theme="light"] .container-box.page-barcode {
        background: #ffffff;
        border-color: rgba(148,163,184,0.45);
        box-shadow: 0 18px 40px rgba(15,23,42,0.12);
    }

    .page-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 16px;
        margin-bottom: 22px;
        padding-bottom: 12px;
        border-bottom: 1px solid rgba(148,163,184,0.35);
    }

    .page-header-left {
        display: flex;
        flex-direction: column;
        gap: 4px;
    }

    .page-header-title {
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .page-header-dot {
        width: 9px;
        height: 9px;
        border-radius: 999px;
        background: radial-gradient(circle at 30% 30%, #82EEFD, #00ffef);
        box-shadow: 0 0 0 6px rgba(0,255,239,0.25);
    }

    .page-header h2 {
        font-size: 22px;
        font-weight: 600;
        letter-spacing: 0.02em;
        color: var(--cash-text-main);
    }

    .page-header p {
        font-size: 13px;
        color: var(--cash-text-muted);
        max-width: 620px;
    }

    .page-pill {
        padding: 7px 16px;
        border-radius: 999px;
        border: 1px solid rgba(130,238,253,0.6);
        font-size: 12px;
        background:
            radial-gradient(circle at 0% 0%, rgba(0,255,239,0.24), transparent 60%),
            rgba(0,23,48,0.9);
        color: #82EEFD;
        white-space: nowrap;
        display: inline-flex;
        align-items: center;
        gap: 6px;
    }

    body[data-theme="light"] .page-pill {
        background: #fefce8;
        border-color: rgba(234,179,8,0.7);
        color: #854d0e;
    }

    .page-pill-dot {
        width: 7px;
        height: 7px;
        border-radius: 999px;
        background: #22c55e;
        box-shadow: 0 0 0 4px rgba(34,197,94,0.25);
    }

    .barcode-grid {
        display: grid;
        grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr);
        gap: 20px;
    }

    @media (max-width: 900px) {
        .page-header {
            flex-direction: column;
            align-items: flex-start;
        }
        .barcode-grid {
            grid-template-columns: minmax(0, 1fr);
        }
    }

    .panel-card {
        background: linear-gradient(
            135deg,
            var(--cash-panel-grad-from) 0%,
            var(--cash-panel-grad-mid) 55%,
            var(--cash-panel-grad-to) 100%
        );
        border-radius: 18px;
        padding: 16px 18px 18px;
        border: 1px solid rgba(130,238,253,0.5);
        box-shadow: 0 20px 45px rgba(0,0,0,0.6);
        color: #E9F5FF;
    }

    body[data-theme="light"] .panel-card {
        background: #ffffff;
        border-color: rgba(148,163,184,0.5);
        box-shadow: 0 12px 30px rgba(15,23,42,0.12);
        color: var(--cash-text-main);
    }

    .panel-title {
        font-size: 16px;
        font-weight: 600;
        margin-bottom: 4px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .panel-title span.icon {
        width: 22px;
        height: 22px;
        border-radius: 999px;
        background: rgba(0,0,0,0.25);
        display: inline-flex;
        align-items: center;
        justify-content: center;
        font-size: 13px;
    }

    body[data-theme="light"] .panel-title span.icon {
        background: #f3f4f6;
    }

    .panel-subtitle {
        font-size: 12px;
        color: #c3d8ff;
        margin-bottom: 12px;
    }

    body[data-theme="light"] .panel-subtitle {
        color: #4b5563;
    }

    .form-grid {
        display: grid;
        grid-template-columns: minmax(0,1fr);
        gap: 10px;
    }

    .form-row-inline {
        display: grid;
        grid-template-columns: minmax(0,1.1fr) minmax(0, 0.9fr);
        gap: 10px;
    }

    @media (max-width: 700px) {
        .form-row-inline {
            grid-template-columns: minmax(0,1fr);
        }
    }

    .form-group {
        display: flex;
        flex-direction: column;
        gap: 4px;
    }

    .form-group label {
        font-size: 12px;
        text-transform: uppercase;
        letter-spacing: 0.08em;
        color: #d1e3ff;
    }

    body[data-theme="light"] .form-group label {
        color: #6b7280;
    }

    .form-group small {
        font-size: 11px;
        color: #b0c4ff;
    }

    body[data-theme="light"] .form-group small {
        color: #6b7280;
    }

    .form-control, .form-select {
        background: rgba(0,23,64,0.9);
        border-radius: 10px;
        border: 1px solid rgba(130,238,253,0.45);
        padding: 8px 10px;
        color: #F9FAFB;
        font-size: 13px;
        outline: none;
        transition:
            border-color 0.15s ease-out,
            box-shadow 0.15s ease-out,
            background 0.15s ease-out;
    }

    .form-control::placeholder {
        color: rgba(148,163,184,0.9);
    }

    body[data-theme="light"] .form-control,
    body[data-theme="light"] .form-select {
        background: #ffffff;
        border-color: rgba(148,163,184,0.6);
        color: #111827;
    }

    body[data-theme="light"] .form-control::placeholder {
        color: #9ca3af;
    }

    .form-control:focus,
    .form-select:focus {
        border-color: var(--cash-accent);
        box-shadow: 0 0 0 1px rgba(0,255,239,0.4);
        background: rgba(0,23,64,0.98);
    }

    body[data-theme="light"] .form-control:focus,
    body[data-theme="light"] .form-select:focus {
        border-color: var(--accent-gold);
        box-shadow: 0 0 0 1px rgba(234,179,8,0.4);
        background: #f9fafb;
    }

    .btn-row {
        margin-top: 10px;
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }

    .btn-primary,
    .btn-secondary {
        border-radius: 999px;
        border: none;
        font-size: 13px;
        padding: 8px 16px;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        font-weight: 500;
        letter-spacing: 0.03em;
    }

    .btn-primary {
        background: linear-gradient(to right, #00ffef, #1e90ff);
        color: #001f3f;
        box-shadow: 0 10px 30px rgba(0,0,0,0.55);
    }

    .btn-primary:hover {
        filter: brightness(1.05);
    }

    .btn-secondary {
        background: rgba(15,23,42,0.8);
        color: #e5e7eb;
        border: 1px solid rgba(148,163,184,0.5);
    }

    .btn-secondary:hover {
        background: rgba(15,23,42,0.95);
    }

    body[data-theme="light"] .btn-secondary {
        background: #f3f4f6;
        color: #111827;
        border-color: rgba(148,163,184,0.7);
    }

    body[data-theme="light"] .btn-secondary:hover {
        background: #e5e7eb;
    }

    .barcode-preview-card {
        background: radial-gradient(circle at top left, rgba(0,255,239,0.18), transparent 60%),
                    #021226;
        border-radius: 18px;
        padding: 16px 18px;
        border: 1px solid rgba(130,238,253,0.55);
        box-shadow: 0 18px 40px rgba(0,0,0,0.7);
        text-align: center;
        min-height: 260px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        color: #E9F5FF;
    }

    body[data-theme="light"] .barcode-preview-card {
        background: #ffffff;
        border-color: rgba(148,163,184,0.6);
        box-shadow: 0 12px 30px rgba(15,23,42,0.12);
        color: #111827;
    }

    .barcode-preview-inner {
        margin-top: 10px;
    }

    #barcodeSvg {
        max-width: 100%;
    }

    .barcode-label-main {
        margin-top: 8px;
        font-size: 15px;
        font-weight: 600;
    }

    .barcode-label-sub {
        margin-top: 2px;
        font-size: 12px;
        color: #cbd5f5;
    }

    body[data-theme="light"] .barcode-label-sub {
        color: #6b7280;
    }

    .barcode-help {
        font-size: 11px;
        color: #9CA3AF;
        margin-top: 10px;
    }

    .mode-toggle {
        display: inline-flex;
        flex-wrap: wrap;
        gap: 6px;
    }

    .mode-pill {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 4px 10px;
        border-radius: 999px;
        border: 1px solid rgba(130,238,253,0.6);
        font-size: 11px;
        color: #E5E7EB;
        background: rgba(15,23,42,0.7);
        cursor: pointer;
        user-select: none;
    }

    .mode-pill input {
        accent-color: var(--cash-accent);
    }

    body[data-theme="light"] .mode-pill {
        border-color: rgba(148,163,184,0.8);
        background: #f3f4f6;
        color: #111827;
    }

    footer {
        background: transparent;
    }
</style>

<!-- JsBarcode CDN -->
<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.6/dist/JsBarcode.all.min.js"></script>

<script>
// ========== SIDEBAR TOGGLE: hide sidebar completely and make content full width ==========
function toggleAdminSidebar() {
    const sidebar = document.getElementById('sidebar');
    const wrapper = document.getElementById('content-wrapper');
    if (!sidebar || !wrapper) return;

    const nowHidden = sidebar.classList.toggle('hidden');
    if (nowHidden) {
        wrapper.classList.add('fullwidth');
    } else {
        wrapper.classList.remove('fullwidth');
    }
}

// ========== BARCODE LOGIC (same as before) ==========

function getCurrentMode() {
    const checked = document.querySelector('input[name="barcode_mode"]:checked');
    return checked ? checked.value : 'existing_with';
}

function switchMode(mode) {
    const withGroup     = document.getElementById('existingWithBarcodeGroup');
    const withoutGroup  = document.getElementById('productWithoutBarcodeGroup');
    const itemNameInput = document.getElementById('item_name');
    const barcodeInput  = document.getElementById('barcode_value');

    if (withGroup)    withGroup.style.display    = (mode === 'existing_with') ? 'block' : 'none';
    if (withoutGroup) withoutGroup.style.display = (mode === 'without')       ? 'block' : 'none';

    if (mode === 'manual') {
        itemNameInput.readOnly = false;
        barcodeInput.readOnly  = false;
        itemNameInput.value    = '';
        barcodeInput.value     = '';
    } else if (mode === 'existing_with') {
        itemNameInput.readOnly = true;
        barcodeInput.readOnly  = true;
        itemNameInput.value    = '';
        barcodeInput.value     = '';
    } else if (mode === 'without') {
        itemNameInput.readOnly = true;
        barcodeInput.readOnly  = false;
        itemNameInput.value    = '';
        barcodeInput.value     = '';
    }
}

function onProductWithBarcodeChange() {
    const select        = document.getElementById('product_with_barcode');
    const itemNameInput = document.getElementById('item_name');
    const barcodeInput  = document.getElementById('barcode_value');

    if (!select || !itemNameInput || !barcodeInput) return;

    const option = select.options[select.selectedIndex];
    if (!option || !option.value) {
        itemNameInput.value      = '';
        barcodeInput.value       = '';
        barcodeInput.readOnly    = false;
        return;
    }

    const name    = option.dataset.name    || '';
    const barcode = option.dataset.barcode || '';

    itemNameInput.value    = name;
    barcodeInput.value     = barcode;
    itemNameInput.readOnly = true;
    barcodeInput.readOnly  = true;
}

function onProductWithoutBarcodeChange() {
    const select        = document.getElementById('product_without_barcode');
    const itemNameInput = document.getElementById('item_name');
    const barcodeInput  = document.getElementById('barcode_value');

    if (!select || !itemNameInput || !barcodeInput) return;

    const option = select.options[select.selectedIndex];
    if (!option || !option.value) {
        itemNameInput.value      = '';
        barcodeInput.value       = '';
        barcodeInput.readOnly    = false;
        return;
    }

    const name = option.dataset.name || '';
    itemNameInput.value    = name;
    itemNameInput.readOnly = true;
    barcodeInput.readOnly  = false;
    barcodeInput.value     = '';
}

// simple 13-digit numeric code
function generateNewBarcodeNumber() {
    let code = '';
    for (let i = 0; i < 13; i++) {
        code += Math.floor(Math.random() * 10);
    }
    return code;
}

document.addEventListener('DOMContentLoaded', function () {
    const modeRadios = document.querySelectorAll('input[name="barcode_mode"]');
    modeRadios.forEach(radio => {
        radio.addEventListener('change', function () {
            switchMode(this.value);
        });
    });

    const withSelect = document.getElementById('product_with_barcode');
    if (withSelect) withSelect.addEventListener('change', onProductWithBarcodeChange);

    const withoutSelect = document.getElementById('product_without_barcode');
    if (withoutSelect) withoutSelect.addEventListener('change', onProductWithoutBarcodeChange);

    switchMode(getCurrentMode()); // init
});

function generateBarcode(event) {
    event.preventDefault();

    const mode       = getCurrentMode();
    const itemNameEl = document.getElementById('item_name');
    const codeEl     = document.getElementById('barcode_value');
    const format     = document.getElementById('barcode_format').value;
    const copies     = parseInt(document.getElementById('label_copies').value || '1', 10);

    if (mode === 'without' && (!codeEl.value || !codeEl.value.trim())) {
        codeEl.value = generateNewBarcodeNumber();
    }

    const itemName = itemNameEl.value.trim() || 'Unnamed Item';
    const code     = codeEl.value.trim();

    if (!code) {
        alert('Please enter or generate a barcode number.');
        return;
    }

    try {
        JsBarcode("#barcodeSvg", code, {
            format: format,
            lineColor: "#000000",
            background: "transparent",
            width: 2,
            height: 80,
            displayValue: true,
            fontSize: 16,
            margin: 6
        });

        document.getElementById('barcodeCodeLabel').textContent  = code;
        document.getElementById('barcodeItemLabel').textContent  = itemName;
        document.getElementById('barcodePreviewInner').style.display = 'block';
        document.getElementById('barcodePlaceholder').style.display  = 'none';

        const printBtn = document.getElementById('printButton');
        printBtn.dataset.copies = isNaN(copies) || copies < 1 ? 1 : copies;
        printBtn.disabled = false;
    } catch (e) {
        console.error(e);
        alert('Unable to generate barcode. Please check the value and format.');
    }
}

function clearBarcode() {
    document.getElementById('item_name').value      = '';
    document.getElementById('barcode_value').value  = '';
    document.getElementById('label_copies').value   = '1';

    const withSelect    = document.getElementById('product_with_barcode');
    const withoutSelect = document.getElementById('product_without_barcode');
    if (withSelect)    withSelect.selectedIndex    = 0;
    if (withoutSelect) withoutSelect.selectedIndex = 0;

    const defaultMode = document.querySelector('input[name="barcode_mode"][value="existing_with"]');
    if (defaultMode) defaultMode.checked = true;
    switchMode(getCurrentMode());

    document.getElementById('barcodePreviewInner').style.display = 'none';
    document.getElementById('barcodePlaceholder').style.display  = 'block';
    document.getElementById('printButton').disabled              = true;
}

function printBarcode() {
    const copies    = parseInt(document.getElementById('printButton').dataset.copies || '1', 10);
    const printArea = document.getElementById('barcodePrintArea');
    if (!printArea) return;

    const printContents = printArea.innerHTML;
    const win = window.open('', '_blank');

    win.document.write('<html><head><title>Print Barcode</title>');
    win.document.write(`
        <style>
            body {
                margin: 0;
                padding: 10px;
                background: #ffffff;
                color: #000000;
                font-family: system-ui, sans-serif;
                text-align: center;
            }
            .label-wrapper {
                display: inline-block;
                margin: 8px;
                padding: 4px 8px;
            }
            svg { max-width: 100%; }
            .barcode-label-main {
                margin-top: 4px;
                font-size: 14px;
                font-weight: 600;
            }
            .barcode-label-sub {
                margin-top: 2px;
                font-size: 11px;
            }
        </style>
    `);
    win.document.write('</head><body>');

    const n = isNaN(copies) || copies < 1 ? 1 : copies;
    for (let i = 0; i < n; i++) {
        win.document.write('<div class="label-wrapper">' + printContents + '</div>');
    }

    win.document.write('</body></html>');
    win.document.close();
    win.focus();
    win.print();
    win.close();
}
</script>

</body>
</html>
