<?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";

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

<body data-theme="dark"><!-- default, JS will overwrite from localStorage -->

<style>
    /* THEME-SPECIFIC VARIABLES (KEEP DARK, ADD LIGHT) */
    body:not([data-theme="light"]) {
        --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; /* used if you ever want gold in dark */
    }

    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; /* warm gold for focus outlines in light mode */
    }

    body {
        background: var(--cash-bg-main);
        color: var(--cash-text-main);
        font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
        -webkit-font-smoothing: antialiased;
        margin: 0;
    }

    .main-content {
        min-height: 100vh;
        padding: 24px 26px;
        background:
            radial-gradient(circle at top left, rgba(0,255,239,0.08), transparent 55%),
            var(--cash-bg-main);
        transition: margin-left 0.3s ease, background 0.3s ease;
    }

    /* Softer, more “light mode” background highlight */
    body[data-theme="light"] .main-content {
        background:
            radial-gradient(circle at top left, rgba(56,189,248,0.15), transparent 55%),
            var(--cash-bg-main);
    }

    .main-content.collapsed {
        margin-left: 70px;
    }

    .container-box.page-barcode {
        max-width: 1200px;
        margin: 0 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);
    }

    /* Layout: form + preview */

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

    @media (max-width: 900px) {
        .main-content {
            padding: 18px 14px;
        }
        .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 styling */

    .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;
    }

    /* Focus states: dark uses accent cyan, light uses gold */
    .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 */

    .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;
    }
</style>

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

<div class="main-content" id="main">

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

    <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 items that do not have barcodes 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">
                    Enter the item name and barcode number, then generate a label you can print and stick on the product.
                </div>

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

                        <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>Optional, used as text under the barcode label.</small>
                        </div>

                        <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>Use numeric codes for EAN/UPC or any string for Code 128.</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>

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

</div>

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

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

<script>
function generateBarcode(event) {
    event.preventDefault();

    const itemName   = document.getElementById('item_name').value.trim();
    const code       = document.getElementById('barcode_value').value.trim();
    const format     = document.getElementById('barcode_format').value;
    const copies     = parseInt(document.getElementById('label_copies').value || '1', 10);

    if (!code) {
        alert('Please enter 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 || 'Unnamed Item';
        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('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 printWindow = window.open('', '_blank');

    printWindow.document.write('<html><head><title>Print Barcode</title>');
    printWindow.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>
    `);
    printWindow.document.write('</head><body>');

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

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

<script>
// initialize theme from localStorage on load
(function () {
    const saved = localStorage.getItem('adminTheme');
    const theme = (saved === 'light' || saved === 'dark') ? saved : 'dark';
    document.body.setAttribute('data-theme', theme);
})();

function toggleAdminTheme() {
    const current = document.body.getAttribute('data-theme') || 'dark';
    const next = current === 'dark' ? 'light' : 'dark';
    document.body.setAttribute('data-theme', next);
    localStorage.setItem('adminTheme', next);
}

function toggleAdminSidebar() {
    const sidebar = document.getElementById('sidebar');
    const main    = document.getElementById('main');
    if (!sidebar || !main) return;

    sidebar.classList.toggle('collapsed');
    main.classList.toggle('collapsed');
}
</script>

</body>
</html>
