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

$slip_id = intval($_GET['id'] ?? 0);
$slip_data_for_js = 'null';
$page_title = 'Tạo phiếu nhập';
$page_sub_title = '';

if ($slip_id > 0) {
    $stmt = $conn->prepare("SELECT i.*, s.supplier_name FROM cms_input i LEFT JOIN cms_suppliers s ON i.supplier_id = s.ID WHERE i.id = ? AND i.deleted = 0");
    if($stmt) {
        $stmt->bind_param("i", $slip_id);
        $stmt->execute();
        $slip = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        if($slip) {
            $page_title = 'Chỉnh sửa Phiếu nhập';
            $page_sub_title = $slip['input_code'];
            $slip_items_from_db = json_decode($slip['detail_input'], true);
            $slip['detail_input'] = is_array($slip_items_from_db) ? $slip_items_from_db : [];
            $slip_data_for_js = json_encode($slip);
        }
    }
}
?>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css">
<style>
    html, body { 
        height: 100%; 
        overflow: hidden; 
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; 
        font-size: 15px;
    }
    .main-content {
        height: calc(100vh - 80px); 
        display: flex;
        flex-direction: column;
    }
    .pos-header { 
        background-color: #fff; 
        color: #333; 
        padding: 0.75rem 1.5rem; 
        display: flex; 
        align-items: center; 
        justify-content: space-between; 
        flex-shrink: 0; 
        border-bottom: 1px solid #e3e6f0;
    }
    .pos-main-content { 
        flex-grow: 1; 
        padding: 1rem; 
        overflow: hidden; 
        background-color: #f0f2f5;
    }
    .pos-grid-container { 
        display: grid; 
        grid-template-columns: 1fr 450px; 
        gap: 1rem; 
        height: 100%; 
    }
    .pos-left-column, .pos-right-column { 
        display: flex; 
        flex-direction: column; 
        gap: 1rem; 
        max-height: 100%; 
    }
    .pos-card { 
        background-color: #fff; 
        border-radius: 0.5rem; 
        border: 1px solid #e0e0e0; 
        display: flex; 
        flex-direction: column; 
    }
    .pos-card-body { padding: 1rem; }
    .order-table-container { 
        flex-grow: 1; 
        overflow-y: auto; 
        border: 1px solid #dee2e6; 
        border-radius: 0.25rem; 
    }
    #product-table thead { 
        position: sticky; 
        top: 0; 
        z-index: 10; 
        background-color: #f8f9fa; 
    }
    #product-table td, #product-table th { 
        vertical-align: middle; 
        padding: 0.6rem 0.5rem; 
        text-align: center;
    }
    #product-table .product-info { text-align: left; }
    .quantity-input, .price-input, .discount-input { height: 38px; font-size: 1rem; text-align: center; }
    .price-input { text-align: right; }
    .product-result-name, .supplier-result-item .name { font-size: 1.1em; font-weight: 600; }
    .btn-remove-item { border-radius: 50%; width: 28px; height: 28px; font-size: 1.2rem; }
    .pos-right-column .form-label { font-weight: 600; }
    .summary-section .info-line { padding: 0.6rem 0; font-size: 1.05rem; display: flex; align-items: center; justify-content: space-between; }
    .summary-section .summary-total { font-size: 1.75rem; font-weight: bold; color: #dc3545; }
    #lack { font-size: 1.5rem !important; }
    #payed { font-size: 1.2rem !important; height: 40px; }
    .btn-lg { padding: 0.75rem 1rem; font-size: 1.1rem; }
    .search-wrapper { position: relative; }
    .autocomplete-results {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        z-index: 999;
        background-color: #fff;
        border: 1px solid #ddd;
        border-top: none;
        border-radius: 0 0 .375rem .375rem;
        box-shadow: 0 0.5rem 1rem rgba(0,0,0,.15);
        max-height: 450px;
        overflow-y: auto;
        display: none;
    }
    .autocomplete-results .result-item {
        padding: 0.75rem 1rem;
        cursor: pointer;
        border-bottom: 1px solid #f0f0f0;
    }
    .autocomplete-results .result-item:hover {
        background-color: #e7f4ff;
    }
    .product-thumb { width: 40px; height: 40px; object-fit: cover; border-radius: 4px; border: 1px solid #ddd; margin-right: 10px; }
    .badge-variant { font-size: 0.75rem; margin-right: 4px; }
    
    /* CSS MỚI CHO NÚT SỬA GIÁ */
    .btn-quick-price-edit {
        font-size: 0.85rem;
        color: #0d6efd;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        background: #e7f1ff;
        padding: 2px 8px;
        border-radius: 4px;
        margin-top: 5px;
        transition: all 0.2s;
        border: 1px solid transparent;
    }
    .btn-quick-price-edit:hover {
        background: #0d6efd;
        color: #fff;
    }
</style>

<div class="main-content">
    <form id="import-form" novalidate>
        <input type="hidden" id="slip_id" value="<?php echo $slip_id; ?>">
        <header class="pos-header">
            <h1 class="h4 mb-0 text-gray-800">
                <a href="danhsach_phieunhap.php" class="text-dark me-2" title="Quay lại"><i class="fas fa-arrow-left"></i></a>
                <?php echo $page_title; ?> 
                <?php if($page_sub_title): ?><span class="badge bg-primary align-middle fs-6 ms-2"><?php echo $page_sub_title; ?></span><?php endif; ?>
            </h1>
            <div>
                <a href="tao_phieunhap.php" class="btn btn-secondary">Hủy</a>
                <button type="submit" class="btn btn-primary"><i class="fas fa-save me-2"></i>Lưu phiếu</button>
            </div>
        </header>

        <main class="pos-main-content">
            <div class="pos-grid-container">
                <div class="pos-left-column">
                    <div class="pos-card">
                        <div class="pos-card-body p-2">
                            <div class="search-wrapper">
                                <input type="text" id="product-search" class="form-control" placeholder="Nhập mã hoặc tên sản phẩm để tìm kiếm (F2)..." autocomplete="off">
                                <div id="product-search-results" class="autocomplete-results"></div>
                            </div>
                        </div>
                    </div>
                    <div class="pos-card" style="flex-grow: 1; overflow: hidden;">
                        <div class="order-table-container">
                            <table class="table table-hover" id="product-table">
                                <thead class="table-light">
                                    <tr>
                                        <th style="width: 5%;">STT</th>
                                        <th style="width: 10%;">Ảnh</th> <th style="width: 30%;" class="text-start">Tên sản phẩm</th>
                                        <th style="width: 10%;">SL</th>
                                        <th style="width: 8%;">ĐVT</th>
                                        <th style="width: 15%;">Giá nhập</th>
                                        <th style="width: 7%;">%CK</th>
                                        <th style="width: 12%;">Thành tiền</th>
                                        <th style="width: 3%;"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr class="placeholder-row"><td colspan="9" class="text-center p-5 text-muted">Chưa có sản phẩm</td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <div class="pos-right-column">
                    <div class="pos-card" style="flex-grow: 1;">
                        <div class="pos-card-body d-flex flex-column">
                            <div class="d-flex flex-column gap-3">
                                <div>
                                    <label for="supplier-search" class="form-label">Nhà cung cấp</label>
                                     <div class="search-wrapper">
                                        <input type="text" id="supplier-search" class="form-control" placeholder="Tìm nhà cung cấp..." data-supplier-id="0" autocomplete="off">
                                        <div id="supplier-search-results" class="autocomplete-results"></div>
                                    </div>
                                </div>
                                <div>
                                    <label for="input_date" class="form-label">Ngày nhập</label>
                                    <input type="datetime-local" id="input_date" class="form-control">
                                </div>
                                <div>
                                    <label for="notes" class="form-label">Ghi chú</label>
                                    <textarea id="notes" class="form-control" rows="3"></textarea>
                                </div>
                            </div>
                            
                            <div class="summary-section mt-auto">
                                <hr>
                                <div class="info-line">
                                    <span>Tiền hàng</span><span id="sub-total" class="fw-bold">0</span>
                                </div>
                                <div class="info-line">
                                    <label for="order-discount" class="form-label mb-0">Chiết khấu (%)</label>
                                    <div style="width: 180px;">
                                        <input type="number" id="order-discount" class="form-control text-end" value="0" min="0">
                                    </div>
                                </div>
                                <hr class="my-2">
                                <div class="info-line">
                                    <span class="fw-bold fs-5">Tổng cộng</span>
                                    <span id="grand-total" class="summary-total">0</span>
                                </div>
                                <div class="info-line">
                                    <label for="payed" class="form-label mb-0">Thanh toán</label>
                                    <div style="width: 180px;">
                                        <input type="text" id="payed" class="form-control text-end fw-bold" value="0">
                                    </div>
                                </div>
                                <div class="info-line">
                                    <span class="fw-bold">Còn nợ</span>
                                    <span id="lack" class="fw-bold text-danger fs-5">0</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </form>
</div>

<div class="modal fade" id="quickPriceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title"><i class="fas fa-tags me-2"></i>Cập nhật giá bán</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="qp_product_id">
                <div class="mb-3">
                    <label class="form-label fw-bold">Tên sản phẩm:</label>
                    <div id="qp_product_name" class="form-control-plaintext text-primary fw-bold border-bottom"></div>
                </div>
                <div class="row">
                    <div class="col-6">
                        <label class="form-label fw-bold text-danger">Giá bán lẻ:</label>
                        <input type="text" class="form-control fw-bold text-danger" id="qp_sell_price" data-type="currency">
                    </div>
                    <div class="col-6">
                        <label class="form-label fw-bold text-primary">Giá bán sỉ:</label>
                        <input type="text" class="form-control fw-bold text-primary" id="qp_sell_price2" data-type="currency">
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Hủy bỏ</button>
                <button type="button" class="btn btn-primary" id="btn-save-price"><i class="fas fa-save me-2"></i>Lưu giá mới</button>
            </div>
        </div>
    </div>
</div>

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

<script>
$(document).ready(function() {
    let productList = [];
    const slipData = <?php echo $slip_data_for_js; ?>;
    const AJAX_URL = '/quanlybanhang/ajax/imports_ajax.php';
    const PRODUCT_AJAX_URL = '/quanlybanhang/ajax/products_ajax.php'; // Link ajax xử lý sản phẩm

    function formatNumber(num) { return (parseFloat(num) || 0).toLocaleString('vi-VN'); }
    function parseNumber(str) { return parseFloat(String(str).replace(/\./g, '').replace(/,/g, '.')) || 0; }
    
    // Format input tiền tệ
    $('body').on('input', '[data-type="currency"]', function() {
        let val = parseNumber($(this).val());
        $(this).val(formatNumber(val));
    });

    function updateTotals() {
        let subTotal = 0;
        productList.forEach(p => {
            const lineTotal = (p.quantity || 0) * (p.price || 0);
            const itemDiscount = lineTotal * (parseFloat(p.discount_percent) || 0) / 100;
            subTotal += (lineTotal - itemDiscount);
        });

        const orderDiscountPercent = parseNumber($('#order-discount').val());
        const orderDiscountAmount = subTotal * (orderDiscountPercent / 100);
        const finalTotal = subTotal - orderDiscountAmount;

        $('#sub-total').text(formatNumber(Math.round(subTotal)));
        $('#grand-total').text(formatNumber(Math.round(finalTotal)));
        
        if (!$(document.activeElement).is('#payed')) {
            $('#payed').val(formatNumber(Math.round(finalTotal)));
        }
        
        let payed = parseNumber($('#payed').val());
        $('#lack').text(formatNumber(Math.round(finalTotal - payed)));
    }

    function renderProductList() {
        const tbody = $('#product-table tbody');
        tbody.empty();
        if (productList.length === 0) {
            tbody.html('<tr class="placeholder-row"><td colspan="9" class="text-center p-5 text-muted">Chưa có sản phẩm</td></tr>');
            updateTotals();
            return;
        }
        productList.forEach((p, index) => {
            const lineTotal = (p.quantity || 0) * (p.price || 0);
            const discountAmount = lineTotal * (parseFloat(p.discount_percent) || 0) / 100;
            const finalLineTotal = lineTotal - discountAmount;
            
            const imgUrl = p.image ? '/quanlybanhang/' + p.image : '/quanlybanhang/assets/img/no-image.png';
            
            let variantHtml = '';
            if(p.color) variantHtml += `<span class="badge bg-info text-dark badge-variant">${p.color}</span>`;
            if(p.size) variantHtml += `<span class="badge bg-secondary badge-variant">Size: ${p.size}</span>`;

            // BỔ SUNG NÚT SỬA GIÁ
            const editPriceBtn = `
                <div class="btn-quick-price-edit" onclick="openQuickPriceModal(${p.id}, '${p.name.replace(/'/g, "\\'")}')">
                    <i class="fas fa-tags me-1"></i> Sửa giá
                </div>`;

            const itemHTML = `
                <tr data-index="${index}" data-id="${p.id}">
                    <td class="text-center">${index + 1}</td>
                    <td class="text-center"><img src="${imgUrl}" class="product-thumb"></td>
                    <td class="product-info">
                        <div class="fw-bold">${p.name || 'N/A'}</div>
                        <div class="mt-1">${variantHtml}</div>
                        <div class="small text-muted mt-1">Mã: ${p.code || ''}</div>
                        ${editPriceBtn} 
                    </td>
                    <td><input type="number" class="form-control quantity-input" value="${p.quantity}" min="1" step="any"></td>
                    <td>${p.unit || 'N/A'}</td>
                    <td><input type="text" class="form-control price-input" value="${formatNumber(p.price)}"></td>
                    <td><input type="number" class="form-control discount-input" value="${p.discount_percent || 0}" min="0" step="any"></td>
                    <td class="text-end fw-bold line-total">${formatNumber(Math.round(finalLineTotal))}</td>
                    <td>
                        <button type="button" class="btn btn-link text-danger btn-remove-item" title="Xóa sản phẩm"><i class="fas fa-times-circle"></i></button>
                    </td>
                </tr>`;
            tbody.append(itemHTML);
        });
        updateTotals();
    }

    // --- LOGIC XỬ LÝ SỬA GIÁ ---
    window.openQuickPriceModal = function(productId, productName) {
        $('#qp_product_id').val(productId);
        $('#qp_product_name').text(productName);
        $('#qp_sell_price').val('Loading...');
        $('#qp_sell_price2').val('Loading...');
        
        // Gọi AJAX lấy giá hiện tại
        $.ajax({
            url: PRODUCT_AJAX_URL,
            type: 'GET',
            dataType: 'json',
            data: { action: 'get_product_details', product_id: productId },
            success: function(res) {
                if(res.status === 'success') {
                    $('#qp_sell_price').val(formatNumber(res.data.prd_sell_price));
                    $('#qp_sell_price2').val(formatNumber(res.data.prd_sell_price2));
                } else {
                    alert('Không lấy được thông tin giá: ' + res.message);
                }
            },
            error: function() { alert('Lỗi kết nối server khi lấy giá.'); }
        });

        $('#quickPriceModal').modal('show');
    };

    $('#btn-save-price').click(function() {
        const id = $('#qp_product_id').val();
        const price1 = parseNumber($('#qp_sell_price').val());
        const price2 = parseNumber($('#qp_sell_price2').val());

        $(this).prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Đang lưu...');

        $.ajax({
            url: PRODUCT_AJAX_URL,
            type: 'POST',
            dataType: 'json',
            data: { 
                action: 'update_product_prices', 
                product_id: id, 
                sell_price: price1, 
                sell_price2: price2 
            },
            success: function(res) {
                if(res.status === 'success') {
                    // alert(res.message); // Có thể bỏ alert nếu muốn trải nghiệm mượt hơn
                    $('#quickPriceModal').modal('hide');
                    // Tùy chọn: Toast thông báo thành công
                    const toast = document.createElement('div');
                    toast.className = 'position-fixed bottom-0 end-0 p-3';
                    toast.style.zIndex = '1100';
                    toast.innerHTML = `<div class="toast show align-items-center text-white bg-success border-0"><div class="d-flex"><div class="toast-body"><i class="fas fa-check-circle me-2"></i>Đã cập nhật giá bán mới!</div><button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button></div></div>`;
                    document.body.appendChild(toast);
                    setTimeout(()=> toast.remove(), 3000);
                } else {
                    alert('Lỗi: ' + res.message);
                }
            },
            error: function() { alert('Lỗi kết nối server khi lưu giá.'); },
            complete: function() {
                $('#btn-save-price').prop('disabled', false).html('<i class="fas fa-save me-2"></i>Lưu giá mới');
            }
        });
    });

    // --- KẾT THÚC LOGIC SỬA GIÁ ---

    function addProductToTable(product) {
        const existingProduct = productList.find(p => p.id === product.id);
        if (existingProduct) {
            existingProduct.quantity = (parseFloat(existingProduct.quantity) || 0) + 1;
        } else {
            productList.push({ 
                id: product.id, 
                name: product.name, 
                code: product.code, 
                unit: product.unit, 
                quantity: 1, 
                price: product.price || 0, 
                discount_percent: 0,
                image: product.image, 
                size: product.size,    
                color: product.color   
            });
        }
        renderProductList();
    }
    
    // --- TÌM KIẾM SẢN PHẨM ---
    let productSearchTimeout;
    $('#product-search').on('keyup', function() {
        const searchTerm = $(this).val();
        const resultsContainer = $('#product-search-results');
        clearTimeout(productSearchTimeout);
        if (searchTerm.length < 1) {
            resultsContainer.empty().hide();
            return;
        }
        productSearchTimeout = setTimeout(() => {
            $.ajax({
                url: AJAX_URL,
                dataType: 'json',
                data: { action: 'search_products', term: searchTerm },
                success: function(data) {
                    resultsContainer.empty().show();
                    if (data && data.length > 0) {
                        $.each(data, function(i, item) {
                            const imgUrl = item.image ? '/quanlybanhang/' + item.image : '/quanlybanhang/assets/img/no-image.png';
                            let variants = '';
                            if(item.color) variants += `<span class="badge bg-info text-dark badge-variant">${item.color}</span>`;
                            if(item.size) variants += `<span class="badge bg-secondary badge-variant">Size: ${item.size}</span>`;

                            const resultHTML = `
                                <div class="d-flex align-items-center">
                                    <img src="${imgUrl}" style="width: 40px; height: 40px; object-fit: cover; border-radius: 4px; margin-right: 10px;">
                                    <div style="flex-grow:1;">
                                        <div class="product-result-name">${item.name}</div>
                                        <div>${variants}</div>
                                        <div class="small text-muted">Mã: ${item.code}</div>
                                    </div>
                                    <div class="fw-bold text-success ms-2">Tồn: ${item.inventory}</div>
                                </div>`;
                            const resultElement = $('<div class="result-item"></div>').html(resultHTML).data('productData', item);
                            resultsContainer.append(resultElement);
                        });
                    } else {
                        resultsContainer.append('<div class="p-2 text-muted">Không tìm thấy sản phẩm.</div>');
                    }
                }
            });
        }, 300);
    });

    $('#product-search-results').on('click', '.result-item', function() {
        const productData = $(this).data('productData');
        if (productData) addProductToTable(productData);
        $('#product-search').val('').focus();
        $('#product-search-results').empty().hide();
    });

    // --- TÌM KIẾM NHÀ CUNG CẤP ---
    let supplierSearchTimeout;
    $('#supplier-search').on('keyup', function() {
        const searchTerm = $(this).val();
        const resultsContainer = $('#supplier-search-results');
        if (searchTerm.length < 1) {
            $(this).data('supplierId', 0);
        }
        clearTimeout(supplierSearchTimeout);
        if (searchTerm.length < 1) {
            resultsContainer.empty().hide();
            return;
        }
        supplierSearchTimeout = setTimeout(() => {
            $.ajax({
                url: AJAX_URL,
                dataType: 'json',
                data: { action: 'search_suppliers', term: searchTerm },
                success: function(data) {
                    resultsContainer.empty().show();
                    if (data && data.length > 0) {
                        $.each(data, function(i, item) {
                            const resultHTML = `<div class="supplier-result-item"><div class="name"><i class="fas fa-truck me-2"></i>${item.name}</div><div class="small text-muted"><i class="fas fa-phone"></i> ${item.phone || 'N/A'}</div></div>`;
                            const resultElement = $('<div class="result-item"></div>').html(resultHTML).data('supplierData', item);
                            resultsContainer.append(resultElement);
                        });
                    } else {
                        resultsContainer.append('<div class="p-2 text-muted">Không tìm thấy nhà cung cấp.</div>');
                    }
                }
            });
        }, 300);
    });

    $('#supplier-search-results').on('click', '.result-item', function() {
        const supplierData = $(this).data('supplierData');
        if (supplierData) {
            $('#supplier-search').val(supplierData.name).data('supplierId', supplierData.id);
        }
        $('#supplier-search-results').empty().hide();
    });

    // --- CHUNG ---
    $(document).on('click', function(e) {
        if (!$(e.target).closest('.search-wrapper').length) {
            $('.autocomplete-results').empty().hide();
        }
    });

    $('#product-table tbody').on('input', '.quantity-input, .price-input, .discount-input', function() {
        const row = $(this).closest('tr');
        const index = row.data('index');
        if (index === undefined || !productList[index]) return;
        
        productList[index].quantity = parseFloat(row.find('.quantity-input').val()) || 1;
        productList[index].price = parseNumber(row.find('.price-input').val());
        productList[index].discount_percent = parseFloat(row.find('.discount-input').val()) || 0;
        
        const lineTotal = productList[index].quantity * productList[index].price;
        const discountAmount = lineTotal * (productList[index].discount_percent / 100);
        row.find('.line-total').text(formatNumber(Math.round(lineTotal - discountAmount)));
        updateTotals();
    });
    
    $('#order-discount').on('input', updateTotals);
    $('#product-table tbody').on('blur', '.price-input', function() { $(this).val(formatNumber(parseNumber($(this).val()))); });
    $('#payed').on('input', updateTotals).on('blur', function() { $(this).val(formatNumber(parseNumber($(this).val()))); });
    
    $('#product-table tbody').on('click', '.btn-remove-item', function(e) { 
        e.preventDefault();
        productList.splice($(this).closest('tr').data('index'), 1); 
        renderProductList(); 
    });

    $('#import-form').on('submit', function(e) {
        e.preventDefault();
        if (productList.length === 0) { alert('Vui lòng thêm ít nhất một sản phẩm.'); return; }

        const payload = {
            action: 'save_slip', slip_id: $('#slip_id').val(),
            supplier_id: $('#supplier-search').data('supplierId') || 0, 
            input_date: $('#input_date').val(),
            notes: $('#notes').val(), payed: parseNumber($('#payed').val()),
            order_discount_percent: parseNumber($('#order-discount').val()),
            products_list: JSON.stringify(productList)
        };

        $(this).find('button[type="submit"]').prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Đang lưu...');

        $.post(AJAX_URL, payload, res => {
            if (res.status === 'success') {
                alert(res.message);
                window.location.href = `danhsach_phieunhap.php`;
            } else { 
                alert('Lỗi: ' + (res.message || 'Không xác định')); 
            }
        }, 'json').fail(() => alert('Lỗi kết nối máy chủ.'))
        .always(() => $(this).find('button[type="submit"]').prop('disabled', false).html('<i class="fas fa-save me-2"></i>Lưu phiếu'));
    });

    $(document).on('keydown', e => { 
        if (e.key && e.key.toUpperCase() === 'F2') { 
            e.preventDefault(); 
            $('#product-search').focus(); 
        }
    });

    if(slipData) {
        if (slipData.supplier_id > 0 && slipData.supplier_name) {
            $('#supplier-search').val(slipData.supplier_name).data('supplierId', slipData.supplier_id);
        }
        if (slipData.input_date) {
            const date = new Date(slipData.input_date);
            date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
            $('#input_date').val(date.toISOString().slice(0,16));
        }
        $('#notes').val(slipData.notes);
        $('#order-discount').val(slipData.discount || 0);
        productList = slipData.detail_input || [];
        $('#payed').val(formatNumber(slipData.payed));
        renderProductList();
    } else {
        const now = new Date();
        now.setMinutes(now.getMinutes() - now.getTimezoneOffset());
        $('#input_date').val(now.toISOString().slice(0,16));
        renderProductList();
    }
});
</script>