<?php
// Enable error reporting (remove or comment out on live server)
error_reporting(E_ALL);
ini_set('display_errors', 1);

ob_start();

// ------------------------- SAFE INCLUDE HANDLING -------------------------
$include_error = false;

if (!file_exists("db/cn.php")) {
    die("ERROR: db/cn.php not found.");
}
include("db/cn.php");
if (!isset($connection)) {
    die("ERROR: \$connection not defined in db/cn.php");
}
$conn = $connection;

if (!file_exists("common/tx.php")) {
    $tx = "Barcode Labels"; // fallback title
} else {
    include("common/tx.php");
    if (!isset($tx)) $tx = "Barcode Labels";
}

// Optional sidebar, topbar, footer – if missing, the page will still work
$sidebar_ok = file_exists("common/sd.php");
$topbar_ok  = file_exists("common/log.php");
$footer_ok  = file_exists("common/main_ft.php");
// ------------------------- END SAFE INCLUDES -------------------------

// Fetch products from database
$products = [];
$sql = "SELECT product_id, product_name, category, retail_price FROM products";
$result = $conn->query($sql);
if ($result && $result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $products[] = $row;
    }
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title><?php echo htmlspecialchars($tx); ?></title>

    <!-- Custom fonts -->
    <link href="../vendor/fontawesome-free/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Quicksand:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- SB Admin 2 styles -->
    <link href="../css/sb-admin-2.min.css" rel="stylesheet">
    <link href="../css/sb-admin-2.css" rel="stylesheet">

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

    <style>
        body { font-family: 'Quicksand', sans-serif; background-color: #f8f9fc; }
        .page-title { font-size: 1.4rem; font-weight: 700; color: #212529; margin-bottom: 0; }
        .search-input { border-radius: 50px; border: 1px solid #ced4da; padding-left: 20px; transition: all 0.3s; }
        .search-input:focus { border-color: #0A4657; box-shadow: 0 0 0 0.2rem rgba(10,70,87,0.15); }
        .card { border: none; border-radius: 15px; box-shadow: 0 2px 20px rgba(0,0,0,0.05); }
        .card-header { background: #fff; border-bottom: 1px solid rgba(0,0,0,0.05); padding: 1.2rem 1.5rem; }
        .table thead th { background-color: #0A4657; color: #fff; font-weight: 600; font-size: 0.85rem; text-transform: uppercase; padding: 12px 8px; }
        .table tbody td { vertical-align: middle; font-size: 0.9rem; padding: 10px 8px; }
        .table tbody tr:hover { background-color: rgba(10,70,87,0.04); }
        .barcode { display: block; margin: 0 auto; max-width: 100%; height: auto; }
        .btn-action { border-radius: 8px; padding: 4px 10px; font-size: 0.8rem; }
        .btn-update { background: #0A4657; border: 1px solid #0A4657; color: #fff; }
        .btn-update:hover { background: #fff; color: #0A4657; border-color: #0A4657; }
        .table-responsive { border-radius: 0 0 15px 15px; }
        #table-container { max-height: 70vh; overflow-y: auto; }
        .search-wrapper { position: relative; }
        .search-wrapper .fa-search { position: absolute; right: 15px; top: 50%; transform: translateY(-50%); color: #aaa; }
        .no-data-message { background: #0A4657; color: #fff; border-radius: 10px; padding: 20px; font-weight: 600; text-align: center; }
    </style>
</head>

<body id="page-top">
    <div id="wrapper">
        <?php if ($sidebar_ok) include("common/sd.php"); else echo '<div class="alert alert-warning m-3">Sidebar file missing</div>'; ?>

        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">
                    <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
                        <i class="fa fa-bars"></i>
                    </button>
                    <?php if ($topbar_ok) include('common/log.php'); else echo '<span class="mr-auto">Topbar missing</span>'; ?>
                </nav>

                <div class="container-fluid">
                    <div class="card shadow mb-4">
                        <div class="card-header py-3 d-flex justify-content-between align-items-center">
                            <h6 class="page-title m-0 font-weight-bold" style="color: #0A4657;">Product Barcode Labels</h6>
                            <div class="search-wrapper">
                                <input type="text" id="searchInput" class="form-control search-input" placeholder="Search product..." style="width: 250px;">
                                <i class="fas fa-search"></i>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="table-responsive" id="table-container">
                                <table class="table table-bordered" id="productTable" width="100%" cellspacing="0">
                                    <thead>
                                        <tr><th>Product ID</th><th>Product Name</th><th>Category</th><th>Retail Price</th><th>Barcode</th><th>Action</th></tr>
                                    </thead>
                                    <tbody>
                                        <?php if (!empty($products)): ?>
                                            <?php foreach ($products as $product):
                                                $id       = htmlspecialchars($product['product_id']);
                                                $name     = htmlspecialchars($product['product_name']);
                                                $category = htmlspecialchars($product['category']);
                                                $price    = htmlspecialchars($product['retail_price']);
                                            ?>
                                                <tr>
                                                    <td><?php echo $id; ?></td>
                                                    <td><?php echo $name; ?></td>
                                                    <td><?php echo $category; ?></td>
                                                    <td>Rs. <?php echo $price; ?></td>
                                                    <td><svg class="barcode" data-value="<?php echo $id; ?>"></svg></td>
                                                    <td>
                                                        <button class="btn btn-update btn-action print-label-btn"
                                                            data-id="<?php echo $id; ?>"
                                                            data-name="<?php echo $name; ?>"
                                                            data-price="<?php echo $price; ?>">
                                                            <i class="fas fa-print"></i> Print
                                                        </button>
                                                    </td>
                                                </tr>
                                            <?php endforeach; ?>
                                        <?php else: ?>
                                            <tr><td colspan="6" class="no-data-message">No products found in database.</td></tr>
                                        <?php endif; ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <?php if ($footer_ok) include("common/main_ft.php"); else echo '<footer class="sticky-footer bg-white"><div class="container my-auto">Footer missing</div></footer>'; ?>
        </div>
    </div>

    <a class="scroll-to-top rounded" href="#page-top"><i class="fas fa-angle-up"></i></a>

    <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog">
        <div class="modal-dialog"><div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Ready to Leave?</h5><button class="close" data-dismiss="modal">×</button></div>
            <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div>
            <div class="modal-footer"><button class="btn btn-secondary" data-dismiss="modal">Cancel</button><a class="btn btn-primary" href="">Logout</a></div>
        </div></div>
    </div>

    <script src="../vendor/jquery/jquery.min.js"></script>
    <script src="../vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="../vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="../js/sb-admin-2.min.js"></script>

    <script>
        $(document).ready(function () {
            // Render barcodes in table
            JsBarcode(".barcode", {
                format: "CODE128", width: 2, height: 45,
                displayValue: true, fontSize: 12, margin: 5
            }).init();

            // Search filter
            $("#searchInput").on("keyup", function () {
                var val = $(this).val().toLowerCase();
                $("#productTable tbody tr").filter(function () {
                    $(this).toggle($(this).text().toLowerCase().indexOf(val) > -1);
                });
            });

            // Print SINGLE label (38x25mm) – SINGLE sticker, no blank label
            $(".print-label-btn").click(function () {
                var id = $(this).data('id'), name = $(this).data('name'), price = $(this).data('price');
                var safeName = String(name).replace(/'/g, "\\'"), safePrice = String(price).replace(/'/g, "\\'"), safeId = String(id).replace(/'/g, "\\'");

                var w = window.open('', '_blank', 'width=400,height=300');
                var d = w.document;
                d.write('<!DOCTYPE html><html><head><meta charset="utf-8"><title>Barcode Label</title><style>');
                d.write('@page { size: 38mm 25mm; margin: 0; }');
                d.write('*{margin:0;padding:0;box-sizing:border-box;}');
                d.write('html,body{width:38mm;height:25mm;margin:0;padding:0;background:#fff;overflow:hidden;}');
                d.write('@media screen{body{background:#f0f0f0;}.label{border:1px dashed #aaa;}}');
                // FIX: removed "* { break-inside: avoid }" which pushed the whole body to a 2nd label.
                // Now we just hard-clip to exactly one 38x25mm page.
                d.write('@media print{html,body{background:#fff!important;width:38mm!important;height:25mm!important;overflow:hidden!important;-webkit-print-color-adjust:exact;print-color-adjust:exact;}.label{border:none!important;page-break-after:avoid;}}');
                d.write('.label{width:38mm;height:24.5mm;background:#fff;display:flex;flex-direction:column;justify-content:center;align-items:center;padding:0.5mm 1mm;margin:0;overflow:hidden;}');
                d.write('.pname{font-size:8.5pt;font-weight:700;color:#000;text-align:center;line-height:1.1;max-width:35mm;max-height:6.5mm;margin-bottom:0.4mm;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;word-break:break-word;}');
                d.write('#printBarcode{width:33mm;max-width:33mm;height:auto;max-height:12.5mm;display:block;margin:0 auto;}');
                d.write('.pprice{font-size:10.5pt;font-weight:800;color:#0A4657;margin-top:0.6mm;text-align:center;}');
                d.write('</style></head><body>');
                d.write('<div class="label"><div class="pname">' + safeName + '</div><svg id="printBarcode"></svg><div class="pprice">Rs. ' + safePrice + '</div></div>');
                d.write('<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"><\/script>');
                d.write('<script>(function(){ var printed=false; function doPrint(){ if(printed)return; printed=true; window.focus(); window.print(); setTimeout(function(){ try{ window.close(); }catch(e){} },400); } window.onafterprint=function(){ try{ window.close(); }catch(e){} }; function render(){ try{ JsBarcode("#printBarcode","'+safeId+'",{ format:"CODE128", width:1.7, height:36, displayValue:true, fontSize:11, margin:0, textMargin:1, lineColor:"#000000", background:"#ffffff" }); }catch(e){} requestAnimationFrame(function(){ requestAnimationFrame(doPrint); }); } if(document.readyState!=="loading"){ render(); } else { document.addEventListener("DOMContentLoaded",render); } })();<\/script>');
                d.write('</body></html>');
                d.close();
            });
        });
    </script>
</body>

</html>