<?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>
    /* CẤU TRÚC LAYOUT FULL MÀN HÌNH ĐỂ CÓ THANH CUỘN */
    html, body { 
        height: 100%; 
        overflow: hidden; 
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; 
        font-size: 14px;
    }
    .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 400px; /* Điều chỉnh cột phải nhỏ hơn chút */
        gap: 1rem; 
        height: 100%; 
    }
    .pos-left-column, .pos-right-column { 
        display: flex; 
        flex-direction: column; 
        gap: 1rem; 
        height: 100%; 
        overflow: hidden; /* Quan trọng để con cái cuộn */
    }
    .pos-card { 
        background-color: #fff; 
        border-radius: 0.5rem; 
        border: 1px solid #e0e0e0; 
        display: flex; 
        flex-direction: column; 
    }
    .pos-card-body { padding: 1rem; }

    /* --- THANH CUỘN CHO BẢNG SẢN PHẨM --- */
    .table-responsive-scroll {
        flex-grow: 1;
        overflow-y: auto; /* Kích hoạt cuộn dọc */
        border: 1px solid #dee2e6;
        border-radius: 0.25rem;
        height: 100%; /* Chiếm hết chiều cao cha */
    }
    
    #product-table {
        margin-bottom: 0;
        width: 100%;
        border-collapse: separate; 
        border-spacing: 0;
    }
    
    #product-table thead th { 
        position: sticky; /* Cố định tiêu đề */
        top: 0; 
        z-index: 10; 
        background-color: #f8f9fa; 
        border-bottom: 2px solid #dee2e6;
        padding: 10px;
        text-align: center;
        white-space: nowrap;
    }
    
    #product-table td { 
        vertical-align: middle; 
        padding: 8px 5px; 
        text-align: center;
        border-bottom: 1px solid #eee;
    }
    #product-table .product-info { text-align: left; }

    .quantity-input, .price-input, .discount-input { height: 34px; font-size: 1rem; text-align: center; width: 100%; }
    .price-input { text-align: right; }
    
    /* NÚT SỬA GIÁ NHANH */
    .btn-quick-price-edit {
        font-size: 0.8rem;
        color: #0d6efd;
        cursor: pointer;
        display: inline-flex;
        align-items: center;
        background: #e7f1ff;
        padding: 2px 6px;
        border-radius: 4px;
        margin-top: 4px;
        transition: all 0.2s;
    }
    .btn-quick-price-edit:hover { background: #0d6efd; color: #fff; }

    .summary-section .info-line { padding: 0.5rem 0; font-size: 1rem; display: flex; align-items: center; justify-content: space-between; }
    .summary-section .summary-total { font-size: 1.5rem; font-weight: bold; color: #dc3545; }
    #lack { font-size: 1.2rem !important; }
    
    /* --- TÌM KIẾM --- */
    .search-wrapper { position: relative; }
    .autocomplete-results {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        z-index: 1050; /* Đảm bảo đè lên mọi thứ */
        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: 10px 15px;
        cursor: pointer;
        border-bottom: 1px solid #f0f0f0;
    }
    .autocomplete-results .result-item:hover {
        background-color: #e7f4ff;
    }
    .product-result-name { font-weight: bold; font-size: 1.05rem; }
    .badge-variant { font-size: 0.75rem; margin-right: 4px; }
</style>

<div class="main-content">
    <form id="import-form" novalidate style="height: 100%; display: flex; flex-direction: column;">
        <input type="hidden" id="slip_id" value="<?php echo $slip_id; ?>">
        <header class="pos-header">
            <h1 class="h5 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 btn-sm">Hủy</a>
                <button type="submit" class="btn btn-primary btn-sm"><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" style="flex: 0 0 auto;">
                        <div class="pos-card-body p-2">
                            <div class="search-wrapper">
                                <input type="text" id="product-search" class="form-control form-control-lg" 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: 1 1 auto; overflow: hidden;">
                        <div class="table-responsive-scroll">
                            <table class="table table-hover" id="product-table">
                                <thead class="table-light">
                                    <tr>
                                        <th style="width: 5%;">STT</th>
                                        <th style="width: 35%;" 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: 8%;">%CK</th>
                                        <th style="width: 14%;">Thành tiền</th>
                                        <th style="width: 5%;"></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr class="placeholder-row"><td colspan="8" 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="height: 100%;">
                        <div class="pos-card-body d-flex flex-column h-100">
                            <div class="d-flex flex-column gap-2" style="overflow-y: auto; flex-grow: 1;">
                                <div>
                                    <label class="form-label small fw-bold">Nhà cung cấp</label>
                                     <div class="search-wrapper">
                                        <input type="text" id="supplier-search" class="form-control form-control-sm" placeholder="Tìm NCC..." data-supplier-id="0" autocomplete="off">
                                        <div id="supplier-search-results" class="autocomplete-results"></div>
                                    </div>
                                </div>
                                <div>
                                    <label class="form-label small fw-bold">Ngày nhập</label>
                                    <input type="datetime-local" id="input_date" class="form-control form-control-sm">
                                </div>
                                <div>
                                    <label class="form-label small fw-bold">Ghi chú</label>
                                    <textarea id="notes" class="form-control form-control-sm" rows="3"></textarea>
                                </div>
                            </div>
                            
                            <div class="summary-section mt-auto pt-3 border-top">
                                <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 class="mb-0 small">Chiết khấu (%)</label>
                                    <div style="width: 120px;">
                                        <input type="number" id="order-discount" class="form-control form-control-sm 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 class="mb-0 small">Thanh toán</label>
                                    <div style="width: 120px;">
                                        <input type="text" id="payed" class="form-control form-control-sm 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">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-sm modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white py-2">
                <h6 class="modal-title"><i class="fas fa-tags me-1"></i>Sửa giá bán</h6>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="qp_product_id">
                <div class="mb-2 text-primary fw-bold small text-truncate" id="qp_product_name"></div>
                <div class="mb-2">
                    <label class="form-label small fw-bold text-danger mb-0">Giá bán lẻ</label>
                    <input type="text" class="form-control form-control-sm fw-bold text-danger" id="qp_sell_price" data-type="currency">
                </div>
                <div class="mb-2">
                    <label class="form-label small fw-bold text-primary mb-0">Giá bán sỉ</label>
                    <input type="text" class="form-control form-control-sm fw-bold text-primary" id="qp_sell_price2" data-type="currency">
                </div>
                <div class="text-end mt-3">
                    <button type="button" class="btn btn-primary btn-sm w-100" id="btn-save-price">Lưu thay đổi</button>
                </div>
            </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'; 

    function formatNumber(num) { return (parseFloat(num) || 0).toLocaleString('vi-VN'); }
    function parseNumber(str) { return parseFloat(String(str).replace(/\./g, '').replace(/,/g, '.')) || 0; }
    
    $('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="8" 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;
            
            // Variants string
            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>`;

            // 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="product-info">
                        <div class="fw-bold text-primary">${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 class="text-center">${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 class="text-center">
                        <button type="button" class="btn btn-link text-danger btn-remove-item" title="Xóa"><i class="fas fa-times"></i></button>
                    </td>
                </tr>`;
            tbody.append(itemHTML);
        });
        
        // Scroll xuống cuối bảng
        const tableContainer = document.querySelector('.table-responsive-scroll');
        if(tableContainer) tableContainer.scrollTop = tableContainer.scrollHeight;
        
        updateTotals();
    }

    // --- XỬ LÝ SỰ KIỆN CLICK CHỌN SẢN PHẨM (DÙNG DELEGATION) ---
    $('body').on('click', '#product-search-results .result-item', function() {
        const productData = $(this).data('productData');
        if (productData) addProductToTable(productData);
        $('#product-search').val('').focus();
        $('#product-search-results').empty().hide();
    });

    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, // Không cần ảnh nữa
                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) {
                            // Render không có ảnh
                            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">
                                    <div style="flex-grow:1;">
                                        <div class="product-result-name">${item.name}</div>
                                        <div>${variants}</div>
                                        <div class="small text-muted">Mã: ${item.code} | ĐVT: ${item.unit}</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);
    });

    // --- TÌM KIẾM NCC ---
    let supplierSearchTimeout;
    $('body').on('click', '#supplier-search-results .result-item', function() {
        const data = $(this).data('supplierData');
        if (data) { $('#supplier-search').val(data.name).data('supplierId', data.id); }
        $('#supplier-search-results').empty().hide();
    });

    $('#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>`;
                            resultsContainer.append($('<div class="result-item"></div>').html(resultHTML).data('supplierData', item));
                        });
                    } else { resultsContainer.append('<div class="p-2 text-muted">Không tìm thấy.</div>'); }
                }
            });
        }, 300);
    });

    // --- SỬA GIÁ NHANH ---
    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...');
        $.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('Lỗi: ' + res.message); }
            }
        });
        $('#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).text('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') { $('#quickPriceModal').modal('hide'); } else { alert('Lỗi: ' + res.message); }
            },
            complete: function() { $('#btn-save-price').prop('disabled', false).text('Lưu thay đổi'); }
        });
    });

    // --- 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 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).text('Đ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').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>