<?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); /* Adjust 80px based on your actual header height */
        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;
    }
    .autocomplete-results .result-item:hover {
        background-color: #e7f4ff;
    }
</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: 35%;" class="text-start">Tên sản phẩm</th>
                                        <th style="width: 10%;">SL</th>
                                        <th style="width: 10%;">ĐVT</th>
                                        <th style="width: 15%;">Giá nhập</th>
                                        <th style="width: 10%;">%CK</th>
                                        <th style="width: 15%;">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="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>

<?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';

    function formatNumber(num) { return (parseFloat(num) || 0).toLocaleString('vi-VN'); }
    function parseNumber(str) { return parseFloat(String(str).replace(/\./g, '').replace(/,/g, '.')) || 0; }
    
    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;
            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">${p.name || 'N/A'}</div>
                        <div class="small text-muted">Mã: ${p.code || ''}</div>
                    </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();
    }

    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 
            });
        }
        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 resultHTML = `<div class="d-flex justify-content-between"><div><div class="product-result-name">${item.name}</div><div class="small text-muted">Mã: ${item.code}</div></div><div class="fw-bold text-success">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>