<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}
require_once 'db_connect.php';

$items = $conn->query("SELECT id, name, retail_price FROM items ORDER BY name")->fetchAll(PDO::FETCH_ASSOC);

$store_name = 'اسم المحل';
try {
    $stmt = $conn->prepare("SELECT store_name FROM settings LIMIT 1");
    $stmt->execute();
    $setting = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($setting && !empty($setting['store_name'])) $store_name = $setting['store_name'];
} catch (Exception $e) {}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>طباعة باركود - Xprinter XP-370B</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background: #f4f6f9; font-family: Arial; padding: 20px 0; }
        .container { max-width: 900px; background: #fff; border-radius: 15px; padding: 30px; box-shadow: 0 8px 25px rgba(0,0,0,0.1); }
        h2 { text-align: center; color: #2c3e50; margin-bottom: 30px; }
        #barcodePreview { margin-top: 30px; text-align: center; padding: 25px; border: 3px dashed #3498db; border-radius: 15px; display: none; background: #f8fdff; }
        .btn { border-radius: 12px; padding: 12px 30px; font-weight: bold; margin: 8px; }
        .btn-print, .btn-print-all, .btn-save { display: none; }
        #barcodeImage { border: 1px solid #ddd; border-radius: 8px; max-width: 100%; height: auto; }
    </style>
</head>
<body>
<div class="container">
    <h2>طباعة باركود - ليبل 40×25 مم</h2>

    <div class="row g-3">
        <div class="col-md-8">
            <label class="form-label fw-bold">اسم الصنف</label>
            <select class="form-select form-select-lg" id="itemSelect" onchange="updatePrice()" required>
                <option value="">اختر الصنف...</option>
                <?php foreach ($items as $item): ?>
                    <option value="<?= $item['id'] ?>" data-price="<?= $item['retail_price'] ?>">
                        <?= htmlspecialchars($item['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
        <div class="col-md-4">
            <label class="form-label fw-bold">السعر</label>
            <input type="text" class="form-control form-control-lg" id="retailPrice" readonly>
        </div>
    </div>

    <div class="text-center mt-4">
        <button type="button" class="btn btn-primary btn-lg px-5" onclick="generateBarcode()">إنشاء الباركود</button>
        <button type="button" class="btn btn-secondary btn-lg" onclick="location.href='dashboard.php'">رجوع</button>
    </div>

    <div id="barcodePreview">
        <h4 class="text-success">معاينة الليبل (40×25 مم)</h4>
        <img id="barcodeImage" alt="Barcode">
        <div class="mt-4">
            <button class="btn btn-success btn-lg btn-print" onclick="printBarcode()">طباعة ليبل واحد</button>
            <button class="btn btn-info btn-lg btn-print-all" onclick="printAllBarcodes()">طباعة كل الأصناف</button>
            <button class="btn btn-warning btn-lg btn-save" onclick="saveBarcode()">حفظ كصورة</button>
        </div>
    </div>
</div>

<canvas id="tempCanvas" style="display:none;"></canvas>

<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>
<script>
const storeName = <?= json_encode($store_name) ?>;

function updatePrice() {
    const price = document.getElementById('itemSelect').selectedOptions[0]?.getAttribute('data-price') || '';
    document.getElementById('retailPrice').value = price ? price + ' ج.م' : '';
}

function generateBarcode() {
    const id = document.getElementById('itemSelect').value;
    const name = document.getElementById('itemSelect').selectedOptions[0].text.trim();
    const price = document.getElementById('retailPrice').value;

    if (!id) return alert('اختر الصنف أولاً');

    JsBarcode("#tempCanvas", id, {
        format: "CODE128",
        width: 1.15,
        height: 40,
        displayValue: true,
        text: name.substring(0,18) + (name.length > 18 ? '...' : '') + ' | ' + price,
        fontSize: 13,
        textMargin: 4,
        margin: 5,
        flat: true,
        background: "#ffffff",
        lineColor: "#000000"
    });

    document.getElementById('barcodeImage').src = document.getElementById('tempCanvas').toDataURL("image/png");
    document.getElementById('barcodePreview').style.display = 'block';
    document.querySelectorAll('.btn-print, .btn-print-all, .btn-save').forEach(b => b.style.display = 'inline-block');
}

// طباعة ليبل واحد فقط - مخصص لـ Xprinter XP-370B بدون Cutter
function printBarcode() {
    const imgSrc = document.getElementById('barcodeImage').src;

    const printWin = window.open('', '_blank', 'width=400,height=300');

    printWin.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <style>
                @page { size: 40mm 25mm; margin:0; }
                body { 
                    margin:0; padding:0; width:40mm; height:25mm;
                    display:flex; flex-direction:column; justify-content:center; align-items:center;
                    font-family: Arial, sans-serif;
                }
                .store { font-size:8px; font-weight:bold; margin-bottom:1mm; }
                img { width:38mm; height:15mm; object-fit:contain; image-rendering:pixelated; }
            </style>
        </head>
        <body onload="window.print(); setTimeout(() => window.close(), 1000)">
            <div class="store">${storeName}</div>
            <img src="${imgSrc}">
        </body>
        </html>
    `);

    printWin.document.close();
}

function printAllBarcodes() {
    alert("سيتم طباعة جميع الأصناف على ورق A4 للمعاينة فقط");
}

function saveBarcode() {
    const a = document.createElement('a');
    a.href = document.getElementById('barcodeImage').src;
    const name = document.getElementById('itemSelect').selectedOptions[0].text.substring(0,20).replace(/[^ا-يءئأإآ0-9\s]/g, '_');
    a.download = 'ليبل_' + name + '.png';
    a.click();
}
</script>
</body>
</html>