<?php
require_once __DIR__ . '/../../templates/header.php';
?>

<style>
    body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; background-color: #f8f9fc; }
    .card { border-radius: 0.75rem; }
    .card-header { background-color: #fff; border-bottom: 1px solid #e3e6f0; padding: 1rem 1.5rem; display: flex; justify-content: space-between; align-items: center; }
    .card-title { font-size: 1.5rem; font-weight: 700; color: #4e73df; margin: 0; }
    .search-container { position: relative; }
    #search-results { position: absolute; width: 100%; max-height: 300px; overflow-y: auto; background-color: #fff; border: 1px solid #ddd; border-top: none; z-index: 1000; display: none; border-radius: 0 0 0.5rem 0.5rem; box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.15); }
    .search-item { padding: 10px 15px; cursor: pointer; border-bottom: 1px solid #f0f0f0; }
    .search-item:last-child { border-bottom: none; }
    .search-item:hover { background-color: #f0f2f5; }
    .search-item strong { color: #3a3b45; }
    .search-item small { color: #858796; }
    #print-list thead th { background-color: #f8f9fc; }
    #print-list .quantity-input, #print-list .price-input { text-align: center; }
</style>

<div class="container-fluid">
    <div class="card shadow-sm">
        <div class="card-header">
            <h2 class="card-title"><i class="fas fa-barcode me-2"></i>In mã vạch sản phẩm</h2>
            <div>
                <button id="download-pdf-btn" class="btn btn-primary shadow-sm"><i class="fas fa-print me-2"></i> In Tem / Tạo PDF</button>
                <a href="/quanlybanhang/modules/products/list.php" class="btn btn-secondary shadow-sm"><i class="fas fa-arrow-left me-2"></i> Quay lại</a>
            </div>
        </div>
        <div class="card-body">
            <div class="form-group search-container mb-4">
                <input type="text" id="product-search" class="form-control" placeholder="Nhập mã hoặc tên sản phẩm để thêm..." autocomplete="off">
                <div id="search-results"></div>
            </div>
            <div class="table-responsive">
                <table class="table table-hover" id="print-list">
                    <thead><tr><th style="width: 5%;">STT</th><th style="width: 15%;">Mã hàng</th><th style="width: 40%; text-align: left;">Tên sản phẩm</th><th style="width: 15%;">Số lượng in</th><th style="width: 15%;">Giá bán</th><th style="width: 10%;"></th></tr></thead>
                    <tbody>
                        <tr class="placeholder-row">
                            <td colspan="6" class="text-center text-muted py-5">Chưa có sản phẩm trong danh sách in.</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../templates/footer.php'; ?>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js"></script>

<script>
$(document).ready(function() {
    const searchInput = $('#product-search');
    const searchResults = $('#search-results');
    const printListBody = $('#print-list tbody');
    let addedProducts = new Set();
    let searchTimeout;

    function removeVietnameseTones(str) {
        if (!str) return "";
        str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g, "a");
        str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, "e");
        str = str.replace(/ì|í|ị|ỉ|ĩ/g, "i");
        str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, "o");
        str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u");
        str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y");
        str = str.replace(/đ/g, "d");
        str = str.replace(/À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ/g, "A");
        str = str.replace(/È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ/g, "E");
        str = str.replace(/Ì|Í|Ị|Ỉ|Ĩ/g, "I");
        str = str.replace(/Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ/g, "O");
        str = str.replace(/Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ/g, "U");
        str = str.replace(/Ỳ|Ý|Ỵ|Ỷ|Ỹ/g, "Y");
        str = str.replace(/Đ/g, "D");
        return str;
    }

    searchInput.on('keyup', function() {
        clearTimeout(searchTimeout);
        const term = $(this).val();
        if (term.length < 1) { searchResults.hide().empty(); return; }
        searchTimeout = setTimeout(() => {
            $.ajax({
                url: '/quanlybanhang/ajax/products_ajax.php',
                type: 'GET',
                data: { action: 'search_products_for_barcode', term: term },
                dataType: 'json',
                success: function(products) {
                    searchResults.empty();
                    if (products && products.length > 0) {
                        products.forEach(p => {
                            const itemHtml = `<div><strong>${p.name}</strong></div><small>${p.code}</small>`;
                            searchResults.append(`<div class="search-item" data-product='${JSON.stringify(p)}'>${itemHtml}</div>`);
                        });
                        searchResults.show();
                    } else { searchResults.hide(); }
                }
            });
        }, 300);
    });

    searchResults.on('click', '.search-item', function() {
        const product = JSON.parse($(this).attr('data-product'));
        if (product && !addedProducts.has(product.id)) {
            if (printListBody.find('.placeholder-row').length) {
                printListBody.empty();
            }
            addProductToTable(product);
            addedProducts.add(product.id);
        }
        searchInput.val('').focus();
        searchResults.hide().empty();
    });

    $(document).on('click', (e) => { if (!$(e.target).closest('.search-container').length) searchResults.hide(); });

    function addProductToTable(product) {
        const rowCount = printListBody.find('tr').length + 1;
        const formattedPrice = (product.price || 0).toLocaleString('vi-VN');
        const newRow = `
            <tr data-product-id="${product.id}" data-product-code="${product.code || ''}" data-product-name="${product.name}">
                <td class="align-middle text-center">${rowCount}</td>
                <td class="align-middle text-center">${product.code || 'N/A'}</td>
                <td class="align-middle">${product.name}</td>
                <td><input type="number" class="form-control form-control-sm quantity-input" value="1" min="1"></td>
                <td><input type="text" class="form-control form-control-sm price-input" value="${formattedPrice}"></td>
                <td class="align-middle text-center"><button class="btn btn-danger btn-sm delete-row-btn"><i class="fas fa-trash-alt"></i></button></td>
            </tr>`;
        printListBody.append(newRow);
    }

    printListBody.on('input', '.price-input', function() {
        let value = $(this).val().replace(/[^0-9]/g, '');
        if (value) $(this).val(parseInt(value).toLocaleString('vi-VN'));
    });

    printListBody.on('click', '.delete-row-btn', function() {
        const row = $(this).closest('tr');
        addedProducts.delete(row.data('product-id'));
        row.remove();
        printListBody.find('tr').each((index, el) => $(el).find('td:first-child').text(index + 1));
        if (printListBody.find('tr').length === 0) {
            printListBody.html('<tr class="placeholder-row"><td colspan="6" class="text-center text-muted py-5">Chưa có sản phẩm trong danh sách in.</td></tr>');
        }
    });

    $('#download-pdf-btn').on('click', async function() {
        if (printListBody.find('.placeholder-row').length) {
            alert('Vui lòng thêm sản phẩm vào danh sách để in tem.');
            return;
        }

        const printButton = $(this);
        printButton.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-2"></i>Đang tải font...');

        try {
            const fontUrl = '/quanlybanhang/assets/fonts/Arimo-Bold.ttf';
            const fontResponse = await fetch(fontUrl);
            
            if (!fontResponse.ok) {
                throw new Error(`Không thể tải font. Mã lỗi: ${fontResponse.status}`);
            }

            const fontBuffer = await fontResponse.arrayBuffer();
            
            const uint8Array = new Uint8Array(fontBuffer);
            let binaryString = '';
            uint8Array.forEach(byte => {
                binaryString += String.fromCharCode(byte);
            });
            const fontBase64 = btoa(binaryString);
            
            printButton.html('<i class="fas fa-cog fa-spin me-2"></i>Đang tạo PDF...');

            const { jsPDF } = window.jspdf;
            const pageWidthMm = 110;
            const pageHeightMm = 22;
            const doc = new jsPDF({
                orientation: 'landscape',
                unit: 'mm',
                format: [pageWidthMm, pageHeightMm]
            });

            doc.addFileToVFS('Arimo-Bold.ttf', fontBase64);
            doc.addFont('Arimo-Bold.ttf', 'ArimoBold', 'bold');
            
            const labelWidth = 35;
            const labelHeight = 22;
            const gapX = 2.5;
            let labelCounter = 0;

            printListBody.find('tr').each(function() {
                const row = $(this);
                const quantity = parseInt(row.find('.quantity-input').val()) || 0;
                const price = row.find('.price-input').val();
                const productName = row.data('product-name');
                const originalProductCode = row.data('product-code');
                const sanitizedProductCode = removeVietnameseTones(String(originalProductCode));

                for (let i = 0; i < quantity; i++) {
                    if (labelCounter > 0 && labelCounter % 3 === 0) {
                        doc.addPage([pageWidthMm, pageHeightMm], 'landscape');
                    }

                    const colIndex = labelCounter % 3;
                    const currentX = (labelWidth + gapX) * colIndex;
                    const currentY = 0;
                    
                    doc.setFont('ArimoBold', 'bold');
                    doc.setFontSize(7);
                    doc.text(productName, currentX + (labelWidth / 2), currentY + 4, { align: 'center', maxWidth: labelWidth - 2 });

                    const canvas = document.createElement('canvas');
                    if (sanitizedProductCode && sanitizedProductCode.trim() !== '') {
                        try {
                            JsBarcode(canvas, sanitizedProductCode, {
                                format: "CODE128",
                                width: 1.2,
                                height: 25,
                                displayValue: true,
                                text: sanitizedProductCode,
                                fontSize: 8,
                                margin: 0,
                                textMargin: 0
                            });
                            const imgData = canvas.toDataURL('image/jpeg', 1.0);
                            doc.addImage(imgData, 'JPEG', currentX + 2, currentY + 6, labelWidth - 4, 10);
                        } catch (e) {
                            console.error("Lỗi tạo barcode:", sanitizedProductCode, e);
                            doc.text("Mã không hợp lệ", currentX + (labelWidth / 2), currentY + 12, { align: 'center' });
                        }
                    } else {
                         doc.text("Không có mã", currentX + (labelWidth / 2), currentY + 12, { align: 'center' });
                    }
                    
                    doc.setFontSize(8);
                    doc.text(price, currentX + (labelWidth / 2), currentY + 20, { align: 'center' });

                    labelCounter++;
                }
            });
            
            doc.save(`MaVach-${new Date().toISOString().slice(0,10)}.pdf`);

        } catch (error) {
            console.error('Lỗi khi tạo PDF:', error);
            alert('Đã xảy ra lỗi khi tạo file PDF. Vui lòng thử lại.\nChi tiết: ' + error.message);
        } finally {
            printButton.prop('disabled', false).html('<i class="fas fa-print me-2"></i> In Tem / Tạo PDF');
        }
    });
});
</script>