<?php
// File: modules/pos/pos.php

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

$initial_order_items_json = 'null';
$initial_order_info_json = 'null';
$order_id_to_edit = 0;

if (isset($_GET['edit_order_id']) && is_numeric($_GET['edit_order_id'])) {
    $order_id_to_edit = intval($_GET['edit_order_id']);
    
    $stmt_order = $conn->prepare("SELECT o.*, c.customer_name FROM cms_orders o LEFT JOIN cms_customers c ON o.customer_id = c.ID WHERE o.ID = ? AND o.deleted = 0");
    
    $stmt_order->bind_param("i", $order_id_to_edit);
    $stmt_order->execute();
    $order = $stmt_order->get_result()->fetch_assoc();
    $stmt_order->close();

    if ($order) {
        if (empty($order['customer_name'])) {
            $order['customer_name'] = 'Khách lẻ';
        }
        
        $initial_order_info_json = json_encode($order);
        $order_items_from_db = json_decode($order['detail_order'], true);
        
        $enriched_items = [];
        if (is_array($order_items_from_db)) {
            
            $valid_items = array_filter($order_items_from_db, function($item) {
                return is_array($item) && isset($item['id']) && is_numeric($item['id']);
            });

            if (!empty($valid_items)) {
                $product_ids = array_column($valid_items, 'id');
                $products_info = [];

                if (!empty($product_ids)) {
                    $ids_placeholder = implode(',', array_fill(0, count($product_ids), '?'));
                    $types = str_repeat('i', count($product_ids));
                    
                    $sql_products = "SELECT p.*, u.prd_unit_name 
                                     FROM cms_products p 
                                     LEFT JOIN cms_products_unit u ON p.prd_unit_id = u.id 
                                     WHERE p.ID IN ($ids_placeholder)";

                    $stmt_products = $conn->prepare($sql_products);
                    $stmt_products->bind_param($types, ...$product_ids);
                    $stmt_products->execute();
                    $products_result = $stmt_products->get_result();
                    
                    while($row = $products_result->fetch_assoc()) {
                        $products_info[$row['ID']] = $row;
                    }
                    $stmt_products->close();
                }

                foreach ($valid_items as $item) {
                    if (isset($products_info[$item['id']])) {
                        $product_row = $products_info[$item['id']];
                        
                        // Logic PHP: Tính tồn kho ảo (Tồn thực + Số đang giữ trong đơn) để hiển thị đúng
                        $quantity_in_current_order = floatval($item['quantity'] ?? 0);
                        $available_inventory_for_edit = floatval($product_row['prd_sls']) + $quantity_in_current_order;
                        
                        $cost_price = ($product_row['prd_average_cost'] > 0) ? $product_row['prd_average_cost'] : $product_row['prd_origin_price'];

                        $enriched_items[] = [
                            'id'           => $product_row['ID'],
                            'code'         => $product_row['prd_code'],
                            'name'         => $product_row['prd_name'],
                            'inventory'    => $available_inventory_for_edit, 
                            'origin_price' => $cost_price,
                            'unit'         => $product_row['prd_unit_name'] ?? 'N/A',
                            'quycach_sl'   => $product_row['prd_quycach'],
                            'quycach_ten'  => $product_row['prd_tenquycach'],
                            'price'        => $item['price'] ?? 0,
                            'quantity'     => $item['quantity'] ?? 1,
                            'discount'     => 0
                        ];
                    }
                }
            }
        }
        $initial_order_items_json = json_encode($enriched_items);
    }
}
?>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />

<style>
    #page-content-wrapper { padding: 0; background-color: #e9ecef; }
    .pos-grid-container { display: grid; grid-template-columns: 2fr 1fr; gap: 1.5rem; height: calc(100vh - 10px); padding: 1rem; }
    .pos-left-column, .pos-right-column { display: flex; flex-direction: column; gap: 1.5rem; max-height: calc(100vh - 30px); }
    .pos-card { background-color: #fff; border-radius: 0.5rem; box-shadow: 0 2px 10px rgba(0,0,0,0.05); display: flex; flex-direction: column; }
    .pos-card.flex-grow { flex-grow: 1; overflow: hidden; }
    .pos-card-header { padding: 1rem 1.25rem; border-bottom: 1px solid #dee2e6; font-weight: 600; font-size: 1.1rem; }
    .pos-card-body { padding: 1.25rem; flex-grow: 1; overflow-y: auto; }
    .pos-card-footer { padding: 1rem; border-top: 1px solid #e9ecef; background-color: #f8f9fa; }
    .order-table-container { flex-grow: 1; overflow-y: auto; }
    #order-table thead { position: sticky; top: 0; z-index: 10; background-color: #f8f9fa;}
    .summary-row { display: flex; justify-content: space-between; align-items: center; padding: 0.75rem 0; border-bottom: 1px dashed #e9ecef; }
    .summary-row:last-child { border-bottom: none; }
    .summary-row-total { padding: 1rem 0; font-size: 1.5rem; font-weight: 700; color: #dc3545; }
    #amount-paid { font-size: 1.1rem; font-weight: bold; }
    .select2-results > .select2-results__options { max-height: 70vh !important; }
    .select2-results__option { font-size: 14px; padding: 6px 12px; }
</style>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />
<link rel="stylesheet" href="pos_theme.css">

<div class="d-flex" id="wrapper">
    <?php require_once __DIR__ . '/../../templates/sidebar.php'; ?>

    <div id="page-content-wrapper">
        <div class="pos-grid-container">
            <div class="pos-left-column">
                <div class="pos-card">
                    <div class="pos-card-body" style="flex-grow: 0; padding: 1rem;">
                        <select class="form-control" id="product-search"></select>
                    </div>
                </div>
                <div class="pos-card flex-grow">
                    <div class="order-table-container">
                        <table class="table table-sm table-hover" id="order-table">
                            <thead class="table-light">
                                <tr>
                                    <th style="width: 40px;">#</th>
                                    <th>Tên sản phẩm</th>
                                    <th style="width: 150px;">Quy cách</th> 
                                    <th style="width: 100px;">ĐVT</th>
                                    <th style="width: 100px;" class="text-center">Số lượng</th>
                                    <th style="width: 120px;" class="text-end">Giá bán</th>
                                    <th style="width: 120px;" class="text-end">Giá vốn</th>
                                    <th style="width: 120px;" class="text-end">Thành tiền</th>
                                    <th style="width: 40px;"></th>
                                </tr>
                            </thead>
                            <tbody id="order-table-body"></tbody>
                        </table>
                    </div>
                    <div class="p-3 border-top text-muted small">
                        <i class="fas fa-keyboard me-2"></i> Phím tắt: <b>F2</b> (Tìm SP), <b>F4</b> (Tìm KH), <b>F9</b> (Lưu), <b>F10</b> (Lưu & In).
                    </div>
                </div>
            </div>

            <div class="pos-right-column">
                <div class="pos-card">
                    <div class="pos-card-header">Thông tin đơn hàng</div>
                    <div class="pos-card-body">
                        <div class="mb-3">
                            <label for="customer-search" class="form-label fw-bold">Khách hàng (F4)</label>
                            <div class="input-group">
                                <select class="form-control" id="customer-search">
                                    <option value="1" selected>Khách lẻ</option>
                                </select>
                                <button class="btn btn-outline-primary" type="button" data-bs-toggle="modal" data-bs-target="#addCustomerModal" title="Thêm khách hàng mới"><i class="fas fa-plus"></i></button>
                            </div>
                        </div>
                        <div>
                            <label for="order-notes" class="form-label fw-bold">Ghi chú</label>
                            <textarea class="form-control" id="order-notes" rows="2"></textarea>
                        </div>
                    </div>
                </div>

                <div class="pos-card flex-grow">
                    <div class="pos-card-header">Thanh toán</div>
                    <div class="pos-card-body">
                        <div class="summary-row"><span>Tiền hàng</span><span id="sub-total" class="fw-bold">0</span></div>
                        <div class="summary-row"><span>Tổng số lượng</span><span id="total-quantity" class="fw-bold">0</span></div>
                        <div class="summary-row">
                            <span>Giảm giá (F7)</span>
                            <div class="d-flex" style="width: 150px;">
                                <input type="number" class="form-control form-control-sm" id="order-discount-value" value="0" min="0">
                                <select class="form-select form-select-sm ms-1" id="order-discount-type" style="width: 80px;">
                                    <option value="percent">%</option>
                                    <option value="fixed">VND</option>
                                </select>
                            </div>
                        </div>
                        <div class="summary-row">
                            <span>VAT</span>
                               <select class="form-select form-select-sm" id="order-vat" style="width: 150px;">
                                <option value="0">0%</option><option value="5">5%</option><option value="8">8%</option><option value="10">10%</option>
                            </select>
                        </div>
                        <div class="summary-row summary-row-total"><span>TỔNG CỘNG</span><span id="grand-total">0</span></div>
                        <div class="summary-row"><label for="amount-paid" class="fw-bold">Khách trả (F8)</label><input type="text" class="form-control form-control-sm text-end fw-bold" id="amount-paid" value="0" style="width: 150px;"></div>
                         <div class="summary-row"><span>Còn nợ</span><span id="amount-debt" class="fw-bold text-danger">0</span></div>
                    </div>
                    <div class="pos-card-footer">
                        <div class="mb-3">
                             <label class="form-label fw-bold mb-2">Hình thức thanh toán</label>
                             <div class="btn-group w-100" role="group">
                                <input type="radio" class="btn-check" name="paymentMethod" id="payment-cash" value="cash" autocomplete="off" checked>
                                <label class="btn btn-outline-primary" for="payment-cash"><i class="fas fa-money-bill-wave me-1"></i> Tiền mặt</label>
                                <input type="radio" class="btn-check" name="paymentMethod" id="payment-card" value="card" autocomplete="off">
                                <label class="btn btn-outline-primary" for="payment-card"><i class="far fa-credit-card me-1"></i> Thẻ</label>
                                <input type="radio" class="btn-check" name="paymentMethod" id="payment-transfer" value="transfer" autocomplete="off">
                                <label class="btn btn-outline-primary" for="payment-transfer"><i class="fas fa-university me-1"></i> CK</label>
                            </div>
                        </div>
                        <div class="d-grid gap-2">
                            <button class="btn btn-success btn-lg" id="btn-save-print"><i class="fas fa-print me-2"></i>Lưu & In (F10)</button>
                            <div class="d-flex gap-2">
                                <button class="btn btn-primary w-100" id="btn-save"><i class="fas fa-save me-2"></i>Lưu (F9)</button>
                                <button class="btn btn-secondary w-100" id="btn-cancel"><i class="fas fa-times me-2"></i>Hủy</button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="addCustomerModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Thêm khách hàng mới</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <form id="addCustomerForm">
                    <div class="mb-3"><label class="form-label">Tên khách hàng (*)</label><input type="text" class="form-control" name="customer_name" required></div>
                    <div class="mb-3"><label class="form-label">Số điện thoại</label><input type="text" class="form-control" name="customer_phone"></div>
                    <div class="mb-3"><label class="form-label">Địa chỉ</label><input type="text" class="form-control" name="customer_address"></div>
                </form>
            </div>
            <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Hủy</button><button type="button" class="btn btn-primary" id="btn-save-customer">Lưu khách hàng</button></div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../templates/footer.php'; ?>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
const initialOrderItems = <?php echo $initial_order_items_json; ?>;
const initialOrderInfo = <?php echo $initial_order_info_json; ?>;
const orderIdToEdit = <?php echo $order_id_to_edit; ?>;

$(document).ready(function() {
    $('body').append(`<input type="hidden" id="editing_order_id" value="${orderIdToEdit}">`);
    const AJAX_URL = '/quanlybanhang/ajax/pos_ajax.php';

    function formatNumber(num) { return (parseFloat(num) || 0).toLocaleString('vi-VN'); }
    function parseNumber(str) { return parseFloat(String(str).replace(/\./g, '').replace(',', '.')) || 0; }
    
    function updateDebt() {
        const grandTotal = parseNumber($('#grand-total').text());
        const amountPaid = parseNumber($('#amount-paid').val());
        const amountDebt = grandTotal - amountPaid;
        $('#amount-debt').text(formatNumber(Math.round(amountDebt)));
    }

    function updateCalculations() {
        // Kiểm tra xem có đang ở chế độ SỬA ĐƠN hay không
        const isEditing = parseNumber($('#editing_order_id').val()) > 0;

        let subTotal = 0;
        let totalQuantity = 0;
        $('#order-table-body tr').each(function() {
            const row = $(this);
            let quantity = parseNumber(row.find('.quantity-input').val());
            const price = parseNumber(row.find('.price-input').val());
            const maxInventory = parseNumber(row.data('inventory'));
            const originPrice = parseFloat(row.data('origin-price')) || 0;
            
            const specQuantity = parseNumber(row.data('spec-quantity'));
            if (specQuantity > 0) {
                const specName = row.data('spec-name') || ''; 
                const packs = Math.floor(quantity / specQuantity);
                const looseItems = quantity % specQuantity;
                row.find('.spec-display').text(`${packs} ${specName} lẻ ${looseItems}`.trim());
            }

            // --- [LOGIC MỚI - CHUẨN XÁC] ---
            // Nếu KHÔNG phải là sửa đơn (tức là Đơn Mới), thì BẮT BUỘC kiểm tra tồn kho
            if (!isEditing) {
                if (quantity > maxInventory) {
                    alert('Số lượng bán vượt quá tồn kho (' + maxInventory + ')! Đã tự động điều chỉnh.');
                    quantity = maxInventory;
                    row.find('.quantity-input').val(maxInventory);
                }
            }
            // Nếu LÀ sửa đơn (isEditing = true), thì BỎ QUA kiểm tra ở đây.
            // Server (pos_ajax.php) sẽ lo liệu việc kiểm tra logic hoàn kho/xuất kho sau.
            // -------------------------------

            if (price < originPrice) { row.find('.price-input').addClass('is-invalid'); } 
            else { row.find('.price-input').removeClass('is-invalid'); }

            const lineTotal = quantity * price;
            row.find('.line-total').text(formatNumber(Math.round(lineTotal)));
            subTotal += lineTotal;
            totalQuantity += quantity;
        });

        $('#sub-total').text(formatNumber(Math.round(subTotal)));
        $('#total-quantity').text(totalQuantity);
        
        const discountValue = parseNumber($('#order-discount-value').val());
        const discountType = $('#order-discount-type').val();
        let totalDiscountAmount = (discountType === 'percent') ? (subTotal * (discountValue / 100)) : discountValue;
        const subTotalAfterDiscount = subTotal - totalDiscountAmount;
        const vatPercent = parseNumber($('#order-vat').val());
        const vatAmount = subTotalAfterDiscount * (vatPercent / 100);
        const grandTotal = subTotalAfterDiscount + vatAmount;

        $('#grand-total').text(formatNumber(Math.round(grandTotal)));
        
        $('#amount-paid').val(formatNumber(Math.round(grandTotal)));
        
        updateDebt();
    }

    $('#product-search').select2({
        theme: 'bootstrap-5',
        placeholder: 'Nhập mã hoặc tên sản phẩm (F2)...',
        minimumInputLength: 1,
        ajax: {
            url: AJAX_URL,
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return { action: 'search_products', term: params.term };
            },
            processResults: function (data) {
                return {
                    results: $.map(data, function(item) {
                        return {
                            id: item.id,
                            text: `[${item.code || 'N/A'}] ${item.name} - Tồn: ${item.inventory}`,
                            productData: item
                        }
                    })
                };
            }
        }
    });

    $('#customer-search').select2({ 
        theme: 'bootstrap-5', 
        placeholder: 'Tìm khách hàng (F4)...', 
        minimumInputLength: 1,
        ajax: { 
            url: AJAX_URL, 
            dataType: 'json', 
            delay: 250, 
            data: function (params) { return { action: 'search_customers', term: params.term }; }, 
            processResults: function (data) { return { results: $.map(data, function(item) { return { id: item.id, text: item.label } })}; } 
        }, 
        allowClear: true,
        language: {
            inputTooShort: function (args) {
                var remainingChars = args.minimum - args.input.length;
                return 'Vui lòng nhập thêm ' + remainingChars + ' ký tự';
            },
            searching: function() { return 'Đang tìm kiếm...'; },
            noResults: function() { return 'Không tìm thấy khách hàng'; }
        }
    });
        
    function addProductToCart(product, isInitialLoad = false) {
        const quantityToAdd = isInitialLoad ? (product.quantity || 1) : 1;
        if (!product || !product.name) return;
        
        // Logic thêm sản phẩm:
        // Nếu không phải load từ DB (tức là thêm mới bằng tay) VÀ không phải đang sửa đơn -> Kiểm tra tồn kho
        const isEditing = parseNumber($('#editing_order_id').val()) > 0;
        if (!isInitialLoad && !isEditing && product.inventory < quantityToAdd) {
            alert('Sản phẩm "' + product.name + '" đã hết hàng!');
            return;
        }

        const existingRow = $(`#order-table-body tr[data-product-id="${product.id}"]`);
        if (existingRow.length > 0) {
            const quantityInput = existingRow.find('.quantity-input');
            quantityInput.val(parseNumber(quantityInput.val()) + quantityToAdd).trigger('input');
        } else {
            const stt = $('#order-table-body tr').length + 1;
            const newRow = `<tr data-product-id="${product.id}" 
                                data-code="${product.code || ''}" 
                                data-inventory="${product.inventory}" 
                                data-origin-price="${product.origin_price || 0}"
                                data-spec-quantity="${product.quycach_sl || 0}"
                                data-spec-name="${product.quycach_ten || ''}">
                <td>${stt}</td>
                <td>${product.name}</td>
                <td class="spec-display"></td>
                <td>${product.unit || ''}</td>
                <td class="text-center"><input type="number" class="form-control form-control-sm quantity-input text-center" value="${quantityToAdd}" min="1"></td>
                <td class="text-end"><input type="text" class="form-control form-control-sm price-input text-end" value="${formatNumber(product.price || 0)}"></td>
                <td class="text-end">${formatNumber(product.origin_price || 0)}</td>
                <td class="line-total text-end fw-bold">0</td>
                <td class="text-center"><button class="btn btn-danger btn-sm btn-remove-item py-0 px-2">&times;</button></td>
            </tr>`;
            $('#order-table-body').append(newRow);
        }
        updateCalculations();
    }
    
    $('#order-table-body').on('blur', '.price-input, #amount-paid', function() {
        var value = parseNumber($(this).val());
        $(this).val(formatNumber(value));
    });

    $('#product-search').on('select2:select', function (e) { if (e.params.data.productData) { addProductToCart(e.params.data.productData, false); } $(this).val(null).trigger('change'); $('#product-search').select2('open'); });
    
    $('#order-table-body').on('input', '.quantity-input, .price-input', updateCalculations);
    $('#order-discount-value, #order-discount-type, #order-vat').on('input change', updateCalculations);
    
    $('#amount-paid').on('input change', updateDebt);
    
    $('#order-table-body').on('click', '.btn-remove-item', function() { $(this).closest('tr').remove(); $('#order-table-body tr').each(function(index) { $(this).find('td:first').text(index + 1); }); updateCalculations(); });
    $('#btn-cancel').on('click', function() { resetOrderForm(true); });
    
    function resetOrderForm(showAlert = true) { 
        const doReset = () => { window.location.href = '/quanlybanhang/modules/pos/pos.php'; }; 
        if (showAlert && $('#order-table-body tr').length > 0) { 
            if(confirm('Bạn có chắc chắn muốn hủy và làm mới đơn hàng?')) { doReset(); } 
        } else { doReset(); } 
    }

    function loadInitialOrder() { 
        if (orderIdToEdit > 0 && initialOrderItems) { 
            initialOrderItems.forEach(item => addProductToCart(item, true)); 
            if (initialOrderInfo) { 
                if (initialOrderInfo.customer_id && initialOrderInfo.customer_id > 1) { 
                    var option = new Option(initialOrderInfo.customer_name, initialOrderInfo.customer_id, true, true); 
                    $('#customer-search').append(option).trigger('change'); 
                } 
                $('#order-notes').val(initialOrderInfo.notes); 
                if (parseFloat(initialOrderInfo.discount_percent) > 0) { 
                    $('#order-discount-type').val('percent'); 
                    $('#order-discount-value').val(parseFloat(initialOrderInfo.discount_percent)); 
                } else { 
                    $('#order-discount-type').val('fixed'); 
                    $('#order-discount-value').val(parseNumber(initialOrderInfo.discount_item)); 
                } 
                $('#order-vat').val(initialOrderInfo.vat); 
                $('#amount-paid').val(formatNumber(initialOrderInfo.customer_pay)).trigger('blur');
                updateDebt();
            } 
        }
    }
    
    $('#btn-save, #btn-save-print').on('click', function(e) {
        e.preventDefault();
        const button = $(this);
        const isPrinting = button.is('#btn-save-print');
        let items = []; let hasError = false;
        if ($('#order-table-body tr').length === 0) { alert('Vui lòng thêm sản phẩm vào đơn hàng.'); return; }
        $('#order-table-body tr').each(function() {
            const row = $(this);
            const productName = row.find('td:nth-child(2)').text();
            const price = parseNumber(row.find('.price-input').val());
            const originPrice = parseFloat(row.data('origin-price')) || 0;
            
            if (price < originPrice) {
                alert(`Giá bán của sản phẩm "${productName}" không được thấp hơn giá vốn!`);
                hasError = true;
                return false;
            }
            items.push({ id: row.data('product-id'), code: row.data('code'), quantity: parseNumber(row.find('.quantity-input').val()), price: price, name: productName, origin_price: originPrice });
        });
        if (hasError) return;
        const editingId = parseNumber($('#editing_order_id').val());
        const orderData = {
            action: editingId > 0 ? 'edit_order' : 'save_order', order_id: editingId, customer_id: $('#customer-search').val() || 1, notes: $('#order-notes').val(), customer_pay: parseNumber($('#amount-paid').val()), items: JSON.stringify(items), discount_value: parseNumber($('#order-discount-value').val()), discount_type: $('#order-discount-type').val(), vat: parseNumber($('#order-vat').val()), payment_method: $('input[name="paymentMethod"]:checked').val()
        };
        
        button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Đang xử lý...');
        
        $.ajax({
            url: AJAX_URL, type: 'POST', data: orderData, dataType: 'json',
            success: function(response) {
                if (response.status === 'success') {
                    alert(response.message);
                    if (isPrinting && response.order_id) { window.open(`print_invoice.php?order_id=${response.order_id}`, '_blank'); }
                    resetOrderForm(false);
                } else { alert('Lỗi: ' + (response.message || 'Không thể xử lý đơn hàng.')); }
            },
            error: function() { alert('Đã có lỗi kết nối xảy ra.'); },
            complete: function() {
                $('#btn-save').prop('disabled', false).html('<i class="fas fa-save me-2"></i>Lưu (F9)');
                $('#btn-save-print').prop('disabled', false).html('<i class="fas fa-print me-2"></i>Lưu & In (F10)');
            }
        });
    });
    
    $(document).on('keydown', function(e) { if (e.key.toUpperCase() === 'F2') { e.preventDefault(); $('#product-search').select2('open'); } if (e.key.toUpperCase() === 'F4') { e.preventDefault(); $('#customer-search').select2('open'); } if (e.key.toUpperCase() === 'F9') { e.preventDefault(); $('#btn-save').click(); } if (e.key.toUpperCase() === 'F10') { e.preventDefault(); $('#btn-save-print').click(); } });
    
    loadInitialOrder();
});
</script>