<?php
session_start();
require_once __DIR__ . '/core/init.php'; 
require_once __DIR__ . '/core/helpers.php'; 

// 1. Kiểm tra đăng nhập
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$store_id = $_SESSION['store_id'];
$current_user_name = $_SESSION['display_name'] ?? 'Nhân viên';
date_default_timezone_set('Asia/Ho_Chi_Minh');

// 2. Lấy thông tin (nếu là Sửa) hoặc set mặc định (nếu là Mới)
$order_id = intval($_GET['edit_order_id'] ?? 0);
$is_edit = $order_id > 0;

$initial_order_data_json = 'null';
$initial_items_json = '[]'; 

if ($is_edit) {
    // Tải dữ liệu đơn hàng cũ (Logic từ file pos.php gốc)
    $stmt_order = $conn->prepare("SELECT o.*, c.customer_name, c.customer_group 
                                 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);
    $stmt_order->execute();
    $order = $stmt_order->get_result()->fetch_assoc();
    $stmt_order->close();

    if ($order) {
        $initial_order_data_json = json_encode($order);
        
        $order_items_from_db = json_decode($order['detail_order'], true);
        $enriched_items = [];
        if (is_array($order_items_from_db) && !empty($order_items_from_db)) {
            $product_ids = array_column($order_items_from_db, '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 ($order_items_from_db as $item) {
                if (isset($products_info[$item['id']])) {
                    $p_info = $products_info[$item['id']];
                    $inventory_for_edit = floatval($p_info['prd_sls']);
                    if ($order['order_status'] == 1) { // Hoàn kho tạm thời
                         $inventory_for_edit += floatval($item['quantity'] ?? 0);
                    }
                    
                    $enriched_items[] = [
                        'id' => $p_info['ID'],
                        'code' => $p_info['prd_code'],
                        'name' => $p_info['prd_name'],
                        'inventory' => $inventory_for_edit,
                        'origin_price' => $p_info['prd_origin_price'],
                        'price_retail' => $p_info['prd_sell_price'],
                        'price_wholesale' => $p_info['prd_sell_price2'],
                        'unit' => $p_info['prd_unit_name'] ?? 'N/A',
                        'price' => $item['price'] ?? 0,
                        'quantity' => $item['quantity'] ?? 1,
                        'percent' => $item['percent'] ?? 0,
                        'note' => $item['note'] ?? ''
                    ];
                }
            }
        }
        $initial_items_json = json_encode($enriched_items);
    } 
}
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?php echo $is_edit ? 'Sửa Đơn Hàng' : 'Tạo Đơn Hàng'; ?></title>
    <link rel="stylesheet" href="/quanlybanhang/assets/css/mobile.css?v=<?php echo time(); ?>">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>

    <div class="pos-shell">
        
        <header class="pos-header">
            <a href="mobile.php?page=orders" class="back-button"><i class="fa-solid fa-arrow-left"></i></a>
            <h1><?php echo $is_edit ? 'Sửa Đơn Hàng' : 'Tạo Đơn Hàng'; ?></h1>
            <div class="header-actions">
                <span style="font-size: 14px;"><?php echo htmlspecialchars($current_user_name); ?></span>
            </div>
        </header>

        <form id="pos-form" onsubmit="return false;">
            
            <input type="hidden" id="order_id" value="<?php echo $order_id; ?>">
            <input type="hidden" id="customer_id" value="1">
            <input type="hidden" id="customer_group" value="1">
            <input type="hidden" id="payment_method" value="1">
            <input type="hidden" id="vat_percent" value="0">
            <input type="hidden" id="is_editing" value="<?php echo $is_edit ? 'true' : 'false'; ?>">
            <input type="hidden" id="original_order_status" value="<?php echo $order['order_status'] ?? '-1'; ?>">

            <main class="pos-content">
                
                <div class="card">
                    <div class="pos-section-actions">
                        <a href="mobile.php?page=customers&select=true" class="pos-action-button" id="btn-select-customer">
                            <i class="fa-solid fa-user-plus"></i>
                            <div class="action-text">
                                <span class="label">Khách hàng</span>
                                <span class="value" id="customer-name-display">Khách lẻ</span>
                            </div>
                        </a>
                        <a href="mobile.php?page=products&select=true" class="pos-action-button">
                            <i class="fa-solid fa-plus-circle"></i>
                            <span class="label">Thêm sản phẩm</span>
                        </a>
                        <button type="button" class="pos-action-button-icon" id="btn-scan-barcode">
                            <i class="fa-solid fa-barcode"></i>
                        </button>
                    </div>
                </div>

                <div class="pos-cart-container" id="pos-cart-container">
                    <div class="pos-cart-list" id="pos-cart-list">
                        </div>
                </div>
                
                <div class="pos-checkout-panel">
                    <div class="card" style="margin: 0;">
                        <div class="list-stat-item">
                            <span class="label">Ghi chú</span>
                            <input type="text" id="order_notes" class="form-control" placeholder="Ghi chú đơn hàng...">
                        </div>
                        
                        <hr class="form-divider">

                        <div class="list-stat-item">
                            <span class="label">Tổng SL</span>
                            <span class="value" id="summary-total-qty">0</span>
                        </div>
                        <div class="list-stat-item">
                            <span class="label">Tiền hàng</span>
                            <span class="value" id="summary-subtotal">0 đ</span>
                        </div>
                        <div class="list-stat-item">
                            <span class="label">Giảm giá (Đơn)</span>
                            <div class="input-group-discount">
                                <input type="text" id="order_discount_value" class="form-control" value="0">
                                <select id="order_discount_type" class="form-control">
                                    <option value="fixed">VND</option>
                                    <option value="percent">%</option>
                                </select>
                            </div>
                        </div>

                        <hr class="form-divider">

                        <div class="list-stat-item summary-total-row">
                            <span class="label">TỔNG CỘNG</span>
                            <span class="value" id="summary-final-total">0 đ</span>
                        </div>

                        <div class="list-stat-item">
                            <span class="label">Khách trả</span>
                            <input type="text" id="customer_pay" class="form-control" value="0">
                        </div>
                        <div class="list-stat-item">
                            <span class="label">Còn nợ</span>
                            <span class="value" id="summary-debt" style="color: var(--text-danger); font-weight: bold;">0 đ</span>
                        </div>
                    </div>
                </div>
            </main>

            <footer class="pos-footer-actions">
                <button type="button" id="btn-save-draft" class="btn-action-footer btn-draft">
                    <i class="fa-solid fa-file-alt"></i>
                    <span>Lưu Khởi Tạo</span>
                </button>
                <button type="button" id="btn-save-complete" class="btn-action-footer btn-save">
                    <i class="fa-solid fa-check"></i>
                    <span>Lưu & Hoàn Thành</span>
                </button>
            </footer>
        </form>
    </div> 

    <div id="add-customer-modal" class="pos-modal-overlay" style="display: none;">
    </div>

<script>
    // Dữ liệu ban đầu từ PHP
    const IS_EDITING = <?php echo json_encode($is_edit); ?>;
    const INITIAL_ORDER_DATA = <?php echo $initial_order_data_json; ?>;
    const INITIAL_ITEMS = <?php echo $initial_items_json; ?>;
    const ORIGINAL_ORDER_STATUS = <?php echo $order['order_status'] ?? '-1'; ?>;
    
    // URLs AJAX
    const AJAX_URL_FINAL = '/quanlybanhang/ajax/pos_ajax.php';
    const AJAX_URL_DRAFT = '/quanlybanhang/ajax/pos_ajax_draft.php';

    // --- (MỚI) Quản lý State (Giỏ hàng & Khách hàng) bằng localStorage ---
    function getCart() { return JSON.parse(localStorage.getItem('pos_cart') || '[]'); }
    function saveCart(cart) { localStorage.setItem('pos_cart', JSON.stringify(cart)); }
    function getCustomer() { return JSON.parse(localStorage.getItem('pos_customer') || '{"id":1, "name":"Khách lẻ", "group":1}'); }
    function saveCustomer(customer) { localStorage.setItem('pos_customer', JSON.stringify(customer)); }

    document.addEventListener('DOMContentLoaded', function() {
        
        // --- 1. HÀM CHUNG ---
        function parseCurrency(value) { return parseFloat(String(value).replace(/[^0-9]/g, '')) || 0; }
        function formatCurrency(value) { return value.toLocaleString('vi-VN'); }

        const cartListContainer = document.getElementById('pos-cart-list');
        const customerDisplay = document.getElementById('customer-name-display');
        const customerIdInput = document.getElementById('customer_id');
        const customerGroupInput = document.getElementById('customer_group');
        const customerPayInput = document.getElementById('customer_pay');
        const finalTotalEl = document.getElementById('summary-final-total');
        const debtEl = document.getElementById('summary-debt');
        
        let customerPayManuallyChanged = false;

        // --- 2. HÀM TÍNH TOÁN VÀ RENDER ---
        function updateDebtOnly() {
            const finalTotal = parseCurrency(finalTotalEl.textContent);
            const customerPay = parseCurrency(customerPayInput.value);
            const debt = finalTotal - customerPay;
            debtEl.textContent = formatCurrency(Math.round(debt)) + ' đ';
        }

        function recalculateAndUpdateAll() {
            let totalQty = 0;
            let subtotal = 0;
            const cart = getCart();
            
            cart.forEach(item => {
                const qty = item.quantity;
                const price = item.price;
                const discountPercent = item.percent || 0;
                const lineTotal = (qty * price) * (1 - discountPercent / 100);
                totalQty += qty;
                subtotal += lineTotal;
            });

            const discountValue = parseCurrency(document.getElementById('order_discount_value').value);
            const discountType = document.getElementById('order_discount_type').value;
            let orderDiscountAmount = (discountType === 'percent') ? (subtotal * (discountValue / 100)) : discountValue;
            const finalTotal = Math.round(subtotal - orderDiscountAmount);
            
            finalTotalEl.textContent = formatCurrency(finalTotal) + ' đ';
            
            if (!customerPayManuallyChanged) {
                customerPayInput.value = formatCurrency(finalTotal);
            }
            
            updateDebtOnly(); 
            
            document.getElementById('summary-total-qty').textContent = formatCurrency(totalQty);
            document.getElementById('summary-subtotal').textContent = formatCurrency(Math.round(subtotal)) + ' đ';
        }

        // --- 3. (MỚI) HÀM RENDER GIỎ HÀNG (Layout ngang) ---
        function renderCart() {
            const cart = getCart();
            cartListContainer.innerHTML = '';
            
            if (cart.length === 0) {
                cartListContainer.innerHTML = '<p class="no-items">Chưa có sản phẩm nào. <br>Nhấn "Thêm sản phẩm" để bắt đầu.</p>';
                recalculateAndUpdateAll();
                return;
            }

            cart.forEach((item, index) => {
                const lineTotal = (item.quantity * item.price) * (1 - (item.percent || 0) / 100);
                const newCardHTML = `
                    <div class="pos-item-card-horizontal" data-index="${index}" data-id="${item.id}">
                        <div class="item-info">
                            <span class="item-name">${item.name}</span>
                            <span class="sub-text">Mã: ${item.code} | Giá: ${formatCurrency(item.price)}</span>
                        </div>
                        <div class="item-controls-horizontal">
                            <button type="button" class="btn-qty-horizontal minus">-</button>
                            <input type="number" class="qty-input-horizontal" value="${item.quantity}" min="1">
                            <button type="button" class="btn-qty-horizontal plus">+</button>
                        </div>
                        <span class="item-total-horizontal">${formatCurrency(Math.round(lineTotal))} đ</span>
                        <button type="button" class="btn-delete-item-horizontal"><i class="fa-solid fa-trash"></i></button>
                    </div>
                `;
                cartListContainer.insertAdjacentHTML('beforeend', newCardHTML);
            });
            
            addListenersToCartItems();
            recalculateAndUpdateAll();
        }
        
        function addListenersToCartItems() {
            document.querySelectorAll('.pos-item-card-horizontal').forEach(card => {
                const index = card.dataset.index;
                
                card.querySelector('.btn-delete-item-horizontal').addEventListener('click', () => {
                    let cart = getCart();
                    cart.splice(index, 1);
                    saveCart(cart);
                    renderCart();
                });
                
                card.querySelector('.btn-qty-horizontal.plus').addEventListener('click', () => {
                    let cart = getCart();
                    cart[index].quantity++;
                    saveCart(cart);
                    renderCart();
                });
                
                card.querySelector('.btn-qty-horizontal.minus').addEventListener('click', () => {
                    let cart = getCart();
                    cart[index].quantity--;
                    if (cart[index].quantity <= 0) {
                        cart.splice(index, 1);
                    }
                    saveCart(cart);
                    renderCart();
                });

                card.querySelector('.qty-input-horizontal').addEventListener('change', (e) => {
                    let cart = getCart();
                    let newQty = parseInt(e.target.value) || 1;
                    if (newQty <= 0) newQty = 1;
                    cart[index].quantity = newQty;
                    saveCart(cart);
                    renderCart();
                });
            });
        }
        
        // --- 4. HÀM RENDER KHÁCH HÀNG ---
        function renderCustomer() {
            const customer = getCustomer();
            customerDisplay.textContent = customer.name;
            customerIdInput.value = customer.id;
            customerGroupInput.value = customer.group;
        }

        // --- 5. GÁN SỰ KIỆN THANH TOÁN ---
        document.querySelectorAll('#order_discount_value, #order_discount_type').forEach(input => {
            input.addEventListener('input', recalculateAndUpdateAll);
            if (input.id === 'order_discount_value') {
                input.addEventListener('blur', function() {
                    this.value = formatCurrency(parseCurrency(this.value));
                    recalculateAndUpdateAll();
                });
            }
        });
        customerPayInput.addEventListener('input', updateDebtOnly);
        customerPayInput.addEventListener('blur', function() {
            this.value = formatCurrency(parseCurrency(this.value));
            updateDebtOnly();
        });
        customerPayInput.addEventListener('keydown', () => { customerPayManuallyChanged = true; });

        // --- 6. HÀM LƯU ĐƠN HÀNG (AJAX) ---
        function saveOrder(status) {
            const btn = (status === 0) ? document.getElementById('btn-save-draft') : document.getElementById('btn-save-complete');
            const btnOriginalText = btn.innerHTML;
            btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Đang lưu...';
            btn.disabled = true;

            const cart = getCart();
            if (cart.length === 0) {
                alert('Vui lòng thêm sản phẩm vào đơn hàng.');
                btn.innerHTML = btnOriginalText;
                btn.disabled = false;
                return;
            }

            const formData = getOrderData(cart, status);
            if (!formData) {
                btn.innerHTML = btnOriginalText;
                btn.disabled = false;
                return;
            }

            let targetUrl = AJAX_URL_FINAL;
            if (IS_EDITING) {
                if (ORIGINAL_ORDER_STATUS == 0) {
                    targetUrl = AJAX_URL_DRAFT;
                    formData.append('action', 'save_or_update_order');
                    formData.append('order_status', status);
                } else {
                    targetUrl = AJAX_URL_FINAL;
                    formData.append('action', 'edit_order');
                }
            } else {
                if (status === 0) {
                    targetUrl = AJAX_URL_DRAFT;
                    formData.append('action', 'save_or_update_order');
                    formData.append('order_status', 0);
                } else {
                    targetUrl = AJAX_URL_FINAL;
                    formData.append('action', 'save_order');
                }
            }
            
            submitOrder(btn, targetUrl, formData);
        }
        
        function getOrderData(cart, orderStatus) {
            let hasError = false;
            cart.forEach(item => {
                if (hasError) return;
                
                if (item.price < item.origin_price) {
                    alert(`Giá bán của sản phẩm "${item.name}" không được thấp hơn giá vốn!`);
                    hasError = true;
                }
                
                if (orderStatus == 1) {
                    const isFinalizingDraft = IS_EDITING && ORIGINAL_ORDER_STATUS == 0;
                    if ((!IS_EDITING || isFinalizingDraft) && item.quantity > item.inventory) {
                         alert(`Số lượng bán (${item.quantity}) của sản phẩm "${item.name}" vượt quá tồn kho (${item.inventory}).`);
                         hasError = true;
                    }
                }
            });
            if (hasError) return null;

            const formData = new FormData();
            formData.append('order_id', document.getElementById('order_id').value);
            formData.append('store_id', <?php echo $store_id; ?>);
            formData.append('customer_id', customerIdInput.value);
            formData.append('notes', document.getElementById('order_notes').value);
            formData.append('customer_pay', parseCurrency(customerPayInput.value));
            formData.append('items', JSON.stringify(cart));
            
            let discount_val_submit = parseCurrency(document.getElementById('order_discount_value').value);
            let discount_type_submit = document.getElementById('order_discount_type').value;
            formData.append('discount_value', discount_val_submit);
            formData.append('discount_type', discount_type_submit);

            formData.append('vat', document.getElementById('vat_percent').value);
            formData.append('payment_method', document.getElementById('payment_method').value);
            formData.append('sale_date', new Date().toISOString().slice(0, 19).replace('T', ' '));
            
            return formData;
        }

        function submitOrder(buttonEl, targetUrl, formData) {
            fetch(targetUrl, {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                if (data.status === 'success') {
                    localStorage.removeItem('pos_cart');
                    localStorage.removeItem('pos_customer');
                    window.location.href = 'mobile.php?page=orders';
                } else {
                    buttonEl.innerHTML = (formData.get('order_status') == 0) ? '<i class="fa-solid fa-file-alt"></i><span>Lưu Khởi Tạo</span>' : '<i class="fa-solid fa-check"></i><span>Lưu & Hoàn Thành</span>';
                    buttonEl.disabled = false;
                }
            })
            .catch(error => {
                alert('Lỗi kết nối. Không thể lưu đơn hàng.');
                buttonEl.innerHTML = (formData.get('order_status') == 0) ? '<i class="fa-solid fa-file-alt"></i><span>Lưu Khởi Tạo</span>' : '<i class="fa-solid fa-check"></i><span>Lưu & Hoàn Thành</span>';
                buttonEl.disabled = false;
            });
        }

        document.getElementById('btn-save-draft').addEventListener('click', () => saveOrder(0));
        document.getElementById('btn-save-complete').addEventListener('click', () => saveOrder(1));

        // --- 7. TẢI DỮ LIỆU BAN ĐẦU ---
        if (IS_EDITING) {
            // Đẩy dữ liệu đơn hàng cũ vào localStorage
            const customer = { id: INITIAL_ORDER_DATA.customer_id, name: INITIAL_ORDER_DATA.customer_name, group: INITIAL_ORDER_DATA.customer_group };
            saveCustomer(customer);
            saveCart(INITIAL_ITEMS);

            // Tải thông tin thanh toán cũ
            document.getElementById('order_notes').value = INITIAL_ORDER_DATA.notes;
            if (INITIAL_ORDER_DATA.discount_percent > 0) {
                document.getElementById('order_discount_type').value = 'percent';
                document.getElementById('order_discount_value').value = INITIAL_ORDER_DATA.discount_percent;
            } else {
                document.getElementById('order_discount_type').value = 'fixed';
                document.getElementById('order_discount_value').value = formatCurrency(INITIAL_ORDER_DATA.total_discount);
            }
            customerPayInput.value = formatCurrency(INITIAL_ORDER_DATA.customer_pay);
            customerPayManuallyChanged = true;
        } else {
            // (MỚI) Nếu là đơn hàng mới, kiểm tra xem có action 'new' không
            // Nếu có, xóa giỏ hàng cũ
            const urlParams = new URLSearchParams(window.location.search);
            if (urlParams.get('action') === 'new') {
                localStorage.removeItem('pos_cart');
                localStorage.removeItem('pos_customer');
                // Tải lại trang mà không có action=new để tránh lặp
                window.location.replace('pos_mobile.php');
            }
        }

        renderCustomer();
        renderCart();
        recalculateAndUpdateAll(); // Tính toán lần đầu

        // --- 8. TẢI MODAL THÊM KHÁCH HÀNG ---
        const modal = document.getElementById('add-customer-modal');
        document.getElementById('btn-show-add-customer').addEventListener('click', (e) => {
             e.preventDefault(); 
             modal.style.display = 'flex';
             fetch('mobile_views/customer_add_modal.php') 
                .then(response => response.text())
                .then(html => {
                    modal.innerHTML = html;
                    addModalListeners();
                });
        });
        
        function addModalListeners() {
            document.getElementById('btn-close-modal').addEventListener('click', () => { modal.style.display = 'none'; });
            document.getElementById('btn-cancel-add-customer').addEventListener('click', () => { modal.style.display = 'none'; });
            
            document.getElementById('btn-save-customer').addEventListener('click', function() {
                const btn = this;
                const addCustomerForm = document.getElementById('add-customer-form');
                const customerName = addCustomerForm.querySelector('[name="customer_name"]').value;
                if (!customerName) {
                    alert('Vui lòng nhập tên khách hàng.');
                    return;
                }
                btn.disabled = true;
                btn.textContent = 'Đang lưu...';

                const formData = new FormData(addCustomerForm);
                formData.append('action', 'add_customer');
                
                fetch(AJAX_URL_FINAL, { method: 'POST', body: formData })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success' && data.customer) {
                        alert('Thêm khách hàng thành công!');
                        const newCustomer = { id: data.customer.id, name: data.customer.name, group: data.customer.customer_group || 1 };
                        saveCustomer(newCustomer);
                        renderCustomer();
                        modal.style.display = 'none';
                    } else {
                        alert('Lỗi: ' + data.message);
                    }
                    btn.disabled = false;
                    btn.textContent = 'Lưu';
                })
                .catch(() => {
                    alert('Lỗi kết nối.');
                    btn.disabled = false;
                    btn.textContent = 'Lưu';
                });
            });
        }
    });
</script>
</body>
</html>