<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../../config/database.php';
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$initial_order_items_json = '[]';
$initial_order_info_json = 'null';
$order_id_to_edit = 0;
$is_editing = false;
$page_title = 'Tạo Đơn Hàng Khởi Tạo';
$order_status = 0;

$current_user_name = $_SESSION['display_name'] ?? 'Nhân viên';
$current_user_id = $_SESSION['user_id'] ?? 0;
$user_store_id = $_SESSION['store_id'] ?? 0;

$stores = [];
$result_stores = $conn->query("SELECT id, store_name FROM cms_stores ORDER BY store_name ASC");
if ($result_stores) {
    $stores = $result_stores->fetch_all(MYSQLI_ASSOC);
}

if ($user_store_id == 0 && $current_user_id > 0) {
    $stmt_user = $conn->prepare("SELECT store_id FROM cms_users WHERE id = ?");
    $stmt_user->bind_param("i", $current_user_id);
    $stmt_user->execute();
    $user_result = $stmt_user->get_result()->fetch_assoc();
    if ($user_result && $user_result['store_id']) {
        $user_store_id = $user_result['store_id'];
        $_SESSION['store_id'] = $user_store_id;
    }
    $stmt_user->close();
}

date_default_timezone_set('Asia/Ho_Chi_Minh');
$current_datetime = date('Y-m-d\TH:i');

if (isset($_GET['edit_order_id']) && is_numeric($_GET['edit_order_id'])) {
    $order_id_to_edit = intval($_GET['edit_order_id']);
    $is_editing = true;
    $page_title = 'Sửa Đơn Hàng';

    $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) {
        $order_status = $order['order_status'];
        $order['customer_name'] = empty($order['customer_name']) ? 'Khách lẻ' : $order['customer_name'];
        $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) && !empty($order_items_from_db)) {
            $valid_items = array_filter($order_items_from_db, function($item) {
                return isset($item['id']) && is_numeric($item['id']);
            });

            if (!empty($valid_items)) {
                $product_ids = array_column($valid_items, 'id');
                $live_product_data = [];
                
                if (!empty($product_ids)) {
                    $ids_placeholder = implode(',', array_fill(0, count($product_ids), '?'));
                    $types = str_repeat('i', count($product_ids));
                    
                    $sql_products = "SELECT p.ID, p.prd_sls, p.prd_name, p.prd_code, p.prd_sell_price, p.prd_origin_price, 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()) {
                        $live_product_data[$row['ID']] = $row;
                    }
                    $stmt_products->close();
                }
            
                foreach ($valid_items as $item) {
                    $product_id = intval($item['id']);
                    if (isset($live_product_data[$product_id])) {
                        $live_data = $live_product_data[$product_id];
                        $inventory_on_load = floatval($live_data['prd_sls']);
                        if ($order_status > 0) { 
                           $inventory_on_load += floatval($item['quantity'] ?? 0);
                        }
                        $enriched_items[] = [
                            'id' => $product_id,
                            'code' => $live_data['prd_code'],
                            'name' => $live_data['prd_name'],
                            'inventory' => $inventory_on_load,
                            'origin_price' => $live_data['prd_origin_price'],
                            'unit' => $live_data['prd_unit_name'] ?? 'N/A',
                            'price' => $item['price'] ?? $live_data['prd_sell_price'],
                            'quantity' => $item['quantity'] ?? 1,
                            'percent' => $item['percent'] ?? 0,
                            'note' => $item['note'] ?? ''
                        ];
                    }
                }
            }
        }
        $initial_order_items_json = json_encode($enriched_items);
        
        if (!empty($order['sell_date'])) {
            $current_datetime = date('Y-m-d\TH:i', strtotime($order['sell_date']));
        }
    } else {
        die("Không tìm thấy đơn hàng để sửa.");
    }
}
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <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; }
    body { background-color: #f0f2f5; display: flex; flex-direction: column; }
    .pos-header { background-color: #1a73e8; color: white; padding: 0.5rem 1.5rem; display: flex; align-items: center; justify-content: space-between; flex-shrink: 0; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
    .pos-main-content { flex-grow: 1; padding: 1rem; overflow: hidden; }
    .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; }
    #order-table thead { position: sticky; top: 0; z-index: 10; background-color: #f8f9fa; }
    #order-table td, #order-table th { vertical-align: middle; padding: 0.6rem 0.5rem; }
    .order-item-note { font-size: 0.9em; color: #28a745; background-color: #e9f7ef; border: 1px dashed #28a745; padding: 0.2rem 0.4rem; margin-top: 0.3rem; border-radius: 0.25rem; }
    .quantity-input, .price-input { height: 38px; font-size: 1rem; }
    .price-input.is-invalid { border-color: #dc3545; }
    .pos-right-column .form-label { font-weight: 600; margin-bottom: 0.5rem; }
    .payment-info-container .info-line { padding: 0.6rem 0; font-size: 1.05rem; }
    .payment-info-container .summary-total { font-size: 1.75rem; font-weight: bold; color: #dc3545; }
    .btn-lg { padding: 0.75rem 1rem; font-size: 1.1rem; }
    .customer-result-item .debt-line { font-weight: 700 !important; color: #dc3545 !important; }
    .search-wrapper { position: relative; }
    .autocomplete-results {
        position: absolute;
        top: 100%;
        left: 0;
        right: 0;
        z-index: 999;
        background-color: #fff;
        border: 1px solid #ddd;
        border-top: none;
        border-radius: 0 0 .375rem .375rem;
        box-shadow: 0 0.5rem 1rem rgba(0,0,0,.15);
        max-height: 450px;
        overflow-y: auto;
        display: none;
    }
    .autocomplete-results .result-item {
        padding: 0.75rem 1rem;
        cursor: pointer;
        border-bottom: 1px solid #dcebff;
        background-color: #f0f7ff;
    }
    .autocomplete-results .result-item:last-child {
        border-bottom: none;
    }
    .autocomplete-results .result-item:hover {
        background-color: #d0e8ff;
    }
    .product-result-name { font-size: 1.1em; font-weight: 600; }
    .product-result-code { font-size: 0.95em; color: #6c757d; }
    .customer-result-item .name {
        font-size: 1.1em;
        font-weight: 600;
        color: #0d6efd;
    }
    .customer-result-item .info-line {
        font-size: 0.95em;
        color: #333;
        display: flex;
        align-items: center;
        line-height: 1.6;
    }
    .customer-result-item .info-line i {
        min-width: 20px;
        color: #555;
    }
</style>
</head>
<body>
    <header class="pos-header">
        <div class="header-left d-flex align-items-center gap-3">
            <a href="/quanlybanhang/modules/orders/list.php" class="text-white text-decoration-none fs-5" title="Quay lại danh sách đơn hàng"><i class="fas fa-arrow-left"></i></a>
            <div class="vr bg-white opacity-25"></div>
            <h5 class="mb-0"><?php echo htmlspecialchars($page_title); ?></h5>
        </div>
        <div class="header-right d-flex align-items-center gap-3">
            <div class="d-flex align-items-center gap-2">
                <span>Cửa hàng:</span>
                <select class="form-select form-select-sm" id="store-id" style="width: auto; background-color: #4f8de1; color: white; border: none;" <?php echo ($is_editing && $order_status > 0) ? 'disabled' : ''; ?>>
                    <?php foreach ($stores as $store): ?>
                        <option value="<?php echo $store['id']; ?>" <?php echo ($store['id'] == $user_store_id) ? 'selected' : ''; ?>><?php echo htmlspecialchars($store['store_name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="vr bg-white opacity-25"></div>
            <span>Xin chào, <strong><?php echo htmlspecialchars($current_user_name); ?></strong></span>
        </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" class="form-control" id="product-search" placeholder="Nhập mã hoặc tên sản phẩm (F2)..." autocomplete="off" <?php echo ($is_editing && $order_status > 0) ? 'disabled' : ''; ?>>
                            <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="order-table">
                            <thead class="table-light">
                                <tr>
                                    <th style="width: 40px;">#</th><th>Tên sản phẩm</th><th style="width: 100px;">ĐVT</th>
                                    <th style="width: 120px;" class="text-center">Số lượng</th><th style="width: 220px;" class="text-end">Giá bán</th>
                                    <th style="width: 150px;" class="text-end">Thành tiền</th><th style="width: 40px;"></th>
                                </tr>
                            </thead>
                            <tbody id="order-table-body"></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="customer-info-box d-flex flex-column gap-3">
                            <div>
                                <label for="customer-search" class="form-label">Khách hàng (F4)</label>
                                <div class="input-group">
                                    <div class="search-wrapper flex-grow-1">
                                        <input type="text" class="form-control" id="customer-search" value="Khách lẻ" data-customer-id="1" autocomplete="off" <?php echo ($is_editing && $order_status > 0) ? 'disabled' : ''; ?>>
                                        <div id="customer-search-results" class="autocomplete-results"></div>
                                    </div>
                                    <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" <?php echo ($is_editing && $order_status > 0) ? 'disabled' : ''; ?>><i class="fas fa-plus"></i></button>
                                </div>
                            </div>
                            <div>
                                <label for="sale-date" class="form-label">Ngày bán</label>
                                <input type="datetime-local" class="form-control" id="sale-date" value="<?php echo htmlspecialchars($current_datetime); ?>" <?php echo ($is_editing && $order_status > 0) ? 'disabled' : ''; ?>>
                            </div>
                            <div>
                                <label for="order-notes" class="form-label">Ghi chú chung</label>
                                <textarea class="form-control" id="order-notes" rows="2" <?php echo ($is_editing && $order_status > 0) ? 'disabled' : ''; ?>></textarea>
                            </div>
                        </div>
                        
                        <div class="payment-info-container mt-auto">
                            <div class="d-flex justify-content-between align-items-center info-line">
                                <span>Hình thức</span>
                                <div class="d-flex gap-3">
                                    <div class="form-check"><input class="form-check-input" type="radio" name="paymentMethod" id="payment-cash" value="1" checked><label class="form-check-label" for="payment-cash">Tiền mặt</label></div>
                                    <div class="form-check"><input class="form-check-input" type="radio" name="paymentMethod" id="payment-card" value="2"><label class="form-check-label" for="payment-card">Thẻ</label></div>
                                    <div class="form-check"><input class="form-check-input" type="radio" name="paymentMethod" id="payment-transfer" value="3"><label class="form-check-label" for="payment-transfer">CK</label></div>
                                </div>
                            </div>
                             <div class="d-flex justify-content-between align-items-center info-line">
                                <span>VAT</span>
                                <div style="width: 180px;"><select class="form-select" id="order-vat"><option value="0">0%</option><option value="5">5%</option><option value="8">8%</option><option value="10">10%</option></select></div>
                            </div>
                            <hr class="my-2">
                            <div class="d-flex justify-content-between info-line"><span>Tiền hàng</span><span class="fw-bold" id="sub-total">0</span></div>
                            <div class="d-flex justify-content-between info-line"><span>Tổng SL</span><span class="fw-bold" id="total-quantity">0</span></div>
                            <div class="d-flex justify-content-between align-items-center info-line">
                                <span>Giảm giá (F7)</span>
                                <div class="input-group" style="width: 180px;">
                                    <input type="text" class="form-control text-end" id="order-discount-value" value="0">
                                    <select class="form-select flex-grow-0" id="order-discount-type" style="width: 70px;"><option value="percent" selected>%</option><option value="fixed">VND</option></select>
                                </div>
                            </div>
                            <hr class="my-2">
                            <div class="d-flex justify-content-between info-line"><span class="fw-bold fs-5">Tổng cộng</span><span class="summary-total" id="grand-total">0</span></div>
                            <div class="d-flex justify-content-between align-items-center info-line"><span>Khách trả (F8)</span><div style="width: 180px;"><input type="text" class="form-control text-end fw-bold" id="amount-paid" value="0"></div></div>
                            <div class="d-flex justify-content-between info-line"><span class="fw-bold">Còn nợ</span><span class="fw-bold text-danger fs-5" id="amount-debt">0</span></div>
                        </div>
                    </div>
                    <div class="pos-card-body border-top p-2 mt-auto">
                        <div class="d-grid gap-2">
                            <?php if ($is_editing && $order_status == 0): ?>
                                <button class="btn btn-secondary btn-lg" id="btn-draft-save"><i class="fas fa-save me-2"></i>Lưu thay đổi (khởi tạo)</button>
                                <button class="btn btn-success btn-lg" id="btn-confirm-order"><i class="fas fa-check-circle me-2"></i>Xác nhận & Hoàn thành</button>
                            <?php elseif ($is_editing && $order_status > 0): ?>
                                <div class="alert alert-success text-center">Đơn hàng đã được hoàn thành.</div>
                            <?php else: ?>
                                <button class="btn btn-primary btn-lg" id="btn-create-draft"><i class="fas fa-file-alt me-2"></i>Lưu khởi tạo</button>
                            <?php endif; ?>
                            <button class="btn btn-light border" id="btn-cancel"><i class="fas fa-times me-2"></i>Hủy</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
    
    <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>
    <div id="discount-popover-content" class="d-none">
        <div class="input-group">
            <input type="number" class="form-control form-control-sm popover-discount-input" placeholder="Nhập %" min="0" max="100">
            <span class="input-group-text">%</span>
        </div>
        <div class="d-grid mt-2">
            <button class="btn btn-primary btn-sm popover-apply-discount">Áp dụng</button>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.1.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; ?>;
        const isEditing = <?php echo json_encode($is_editing); ?>;
        const orderStatus = <?php echo $order_status; ?>;
        
        $(document).ready(function() {
            const AJAX_URL = '/quanlybanhang/ajax/poskhoitao_ajax.php';
            
            function formatNumber(num) { return (parseFloat(num) || 0).toLocaleString('vi-VN'); }
            function parseNumber(str) { return parseFloat(String(str).replace(/\./g, '').replace(',', '.')) || 0; }
            
            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="product-result-code">Mã: ${item.code}</div></div><div><span>Tồn: ${item.inventory || 0}</span></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) { addProductToCart(productData); }
                $('#product-search').val('').focus();
                $('#product-search-results').empty().hide();
            });

            let customerSearchTimeout;
            $('#customer-search').on('keyup', function() {
                const searchTerm = $(this).val();
                const resultsContainer = $('#customer-search-results');
                if (searchTerm.length < 1) {
                    $(this).data('customerId', 1);
                }
                clearTimeout(customerSearchTimeout);
                if (searchTerm.length < 1) {
                    resultsContainer.empty().hide();
                    return;
                }
                customerSearchTimeout = setTimeout(() => {
                    $.ajax({
                        url: AJAX_URL,
                        dataType: 'json',
                        data: { action: 'search_customers', term: searchTerm },
                        success: function(data) {
                            resultsContainer.empty().show();
                            if (data && data.length > 0) {
                                $.each(data, function(i, item) {
                                    const debtClass = (parseFloat(item.total_debt) || 0) > 0 ? 'debt-line' : '';
                                    const resultHTML = `
                                        <div class="customer-result-item">
                                            <div class="name"><i class="fas fa-user"></i> ${item.name}</div>
                                            <div class="info-line"><i class="fas fa-phone"></i> ${item.phone || 'Chưa có SĐT'}</div>
                                            <div class="info-line"><i class="fas fa-shopping-cart"></i> Đã mua: ${item.order_count || 0} đơn</div>
                                            <div class="info-line"><i class="fas fa-dollar-sign"></i> Tổng mua: ${formatNumber(item.total_spent || 0)}</div>
                                            <div class="info-line ${debtClass}"><i class="fas fa-exclamation-circle"></i> Còn nợ: ${formatNumber(item.total_debt || 0)}</div>
                                        </div>`;
                                    const resultElement = $('<div class="result-item"></div>').html(resultHTML).data('customerData', item);
                                    resultsContainer.append(resultElement);
                                });
                            } else {
                                resultsContainer.append('<div class="p-2 text-muted">Không tìm thấy khách hàng.</div>');
                            }
                        }
                    });
                }, 300);
            });

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

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

            $('#btn-save-customer').on('click', function() {
                const form = $('#addCustomerForm');
                const customerName = form.find('[name="customer_name"]').val().trim();
                if (!customerName) {
                    showNotification('Vui lòng nhập tên khách hàng.');
                    return;
                }
                const customerData = {
                    action: 'add_customer',
                    customer_name: customerName,
                    customer_phone: form.find('[name="customer_phone"]').val().trim(),
                    customer_address: form.find('[name="customer_address"]').val().trim()
                };
                $.ajax({
                    url: AJAX_URL, type: 'POST', data: customerData, dataType: 'json',
                    success: function(response) {
                        if (response.status === 'success' && response.customer) {
                            const customer = response.customer;
                            $('#customer-search').val(customer.name).data('customerId', customer.id);
                            const modal = bootstrap.Modal.getInstance(document.getElementById('addCustomerModal'));
                            modal.hide();
                            form.trigger('reset');
                            showNotification('Thêm khách hàng thành công!');
                        } else {
                            showNotification('Lỗi: ' + (response.message || 'Không thể thêm khách hàng.'));
                        }
                    },
                    error: function() { showNotification('Đã có lỗi kết nối xảy ra.'); }
                });
            });
            
            function updateDebt() {
                const grandTotal = parseNumber($('#grand-total').text());
                const amountPaid = parseNumber($('#amount-paid').val());
                $('#amount-debt').text(formatNumber(Math.round(grandTotal - amountPaid)));
            }

            function updateCalculations() {
                let originalSubTotal = 0;
                let subTotalAfterItemDiscounts = 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 itemDiscountPercent = parseFloat(row.data('discount-percent')) || 0;
                    
                    const lineSubTotal = quantity * price;
                    const itemDiscountAmount = lineSubTotal * (itemDiscountPercent / 100);
                    const finalLineTotal = lineSubTotal - itemDiscountAmount;

                    row.find('.line-total').text(formatNumber(Math.round(finalLineTotal)));
                    
                    originalSubTotal += lineSubTotal;
                    subTotalAfterItemDiscounts += finalLineTotal;
                    totalQuantity += quantity;
                });

                $('#sub-total').text(formatNumber(Math.round(originalSubTotal)));
                $('#total-quantity').text(totalQuantity);
                
                const discountType = $('#order-discount-type').val();
                const rawDiscountValue = $('#order-discount-value').val();
                const orderDiscountValue = discountType === 'percent' ? parseFloat(String(rawDiscountValue).replace(',', '.')) || 0 : parseNumber(rawDiscountValue);
                
                let orderDiscountAmount = (discountType === 'percent') ? (subTotalAfterItemDiscounts * (orderDiscountValue / 100)) : orderDiscountValue;
                
                const totalAfterAllDiscounts = subTotalAfterItemDiscounts - orderDiscountAmount;
                const vatPercent = parseNumber($('#order-vat').val());
                const vatAmount = totalAfterAllDiscounts * (vatPercent / 100);
                const grandTotal = totalAfterAllDiscounts + vatAmount;

                $('#grand-total').text(formatNumber(Math.round(grandTotal)));
                if (!$(document.activeElement).is('#amount-paid')) {
                    $('#amount-paid').val(formatNumber(Math.round(grandTotal)));
                }
                updateDebt();
            }

            function addProductToCart(product, isInitialLoad = false) {
                const quantityToAdd = isInitialLoad ? (product.quantity || 1) : 1;
                const existingRow = $(`#order-table-body tr[data-product-id="${product.id}"]`);

                if (existingRow.length > 0 && !isInitialLoad) {
                    const qtyInput = existingRow.find('.quantity-input');
                    qtyInput.val(parseNumber(qtyInput.val()) + quantityToAdd).trigger('input');
                } else {
                    const stt = $('#order-table-body tr').length + 1;
                    const discountPercent = product.percent || 0;
                    const newRow = `<tr data-product-id="${product.id}" data-code="${product.code}" data-inventory="${product.inventory}" data-origin-price="${product.origin_price}" data-discount-percent="${discountPercent}">
                        <td>${stt}</td>
                        <td><div class="order-item-name">${product.name}</div><input type="text" class="form-control form-control-sm order-item-note" placeholder="Ghi chú..." value="${product.note || ''}"></td>
                        <td>${product.unit || 'N/A'}</td>
                        <td class="text-center"><input type="number" class="form-control quantity-input text-center" value="${quantityToAdd}" min="1"></td>
                        <td>
                            <div class="input-group">
                                <input type="text" class="form-control price-input text-end" value="${formatNumber(product.price)}">
                                <button class="btn btn-outline-primary btn-sm btn-item-discount" type="button" title="Giảm giá sản phẩm">${discountPercent}%</button>
                            </div>
                        </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 rounded-circle p-0" style="width:24px;height:24px;" type="button">&times;</button></td>
                    </tr>`;
                    $('#order-table-body').append(newRow);
                }
                updateCalculations();
            }
            
            function loadInitialOrder() {
                if (isEditing && initialOrderInfo) {
                    if (initialOrderItems && Array.isArray(initialOrderItems) && initialOrderItems.length > 0) {
                        $('#order-table-body').empty();
                        initialOrderItems.forEach(item => addProductToCart(item, true));
                    }
                    if (initialOrderInfo.customer_id) {
                        $('#customer-search').val(initialOrderInfo.customer_name).data('customerId', initialOrderInfo.customer_id);
                    }
                    $('#order-notes').val(initialOrderInfo.notes);
                    
                    const discountValue = initialOrderInfo.discount_percent > 0 ? initialOrderInfo.discount_percent : (initialOrderInfo.total_discount || 0);
                    const discountType = initialOrderInfo.discount_percent > 0 ? 'percent' : 'fixed';

                    $('#order-discount-value').val(String(discountValue).replace('.', '.'));
                    $('#order-discount-type').val(discountType);
                    
                    $('#order-vat').val(initialOrderInfo.vat);
                    $('input[name="paymentMethod"][value="' + initialOrderInfo.payment_method + '"]').prop('checked', true);
                    $('#amount-paid').val(formatNumber(initialOrderInfo.customer_pay));
                }
                 updateCalculations();
            }
            
            function saveOrder(status, button) {
                let items = [];
                $('#order-table-body tr').each(function() {
                    const row = $(this);
                    items.push({
                        id: row.data('product-id'),
                        quantity: parseNumber(row.find('.quantity-input').val()),
                        price: parseNumber(row.find('.price-input').val()),
                        percent: parseFloat(row.data('discount-percent')) || 0,
                        note: row.find('.order-item-note').val(),
                        name: row.find('.order-item-name').text()
                    });
                });

                if (items.length === 0) { showNotification('Vui lòng thêm sản phẩm.'); return; }
                
                const discountType = $('#order-discount-type').val();
                const rawDiscountValue = $('#order-discount-value').val();
                const discountValueToSend = discountType === 'percent' ? parseFloat(String(rawDiscountValue).replace(',', '.')) || 0 : parseNumber(rawDiscountValue);

                const orderData = {
                    action: 'save_or_update_order',
                    order_id: orderIdToEdit,
                    order_status: status,
                    store_id: $('#store-id').val(),
                    customer_id: $('#customer-search').data('customerId') || 1,
                    notes: $('#order-notes').val(),
                    customer_pay: parseNumber($('#amount-paid').val()),
                    items: JSON.stringify(items),
                    discount_value: discountValueToSend,
                    discount_type: discountType,
                    vat: $('#order-vat').val(),
                    payment_method: $('input[name="paymentMethod"]:checked').val(),
                    sale_date: $('#sale-date').val()
                };
                
                const originalButtonHtml = button.html();
                button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Đang xử lý...');
                
                $.ajax({
                    url: AJAX_URL, type: 'POST', data: orderData, dataType: 'json',
                    success: res => {
                        if (res.status === 'success') {
                            alert(res.message);
                            window.location.href = '/quanlybanhang/modules/orders/list.php';
                        } else { showNotification('Lỗi: ' + (res.message || 'Không thể xử lý.')); }
                    },
                    error: () => { showNotification('Đã có lỗi kết nối.'); },
                    complete: () => { button.prop('disabled', false).html(originalButtonHtml); }
                });
            }
            
            let activeDiscountTrigger = null;
            $('#order-table-body').on('click', '.btn-item-discount', function(e) {
                e.stopPropagation();
                if (activeDiscountTrigger) { $(activeDiscountTrigger).popover('dispose'); }
                activeDiscountTrigger = this;
                const currentDiscount = $(this).closest('tr').data('discount-percent');
                $(this).popover({
                    container: 'body', html: true, placement: 'left',
                    title: 'Giảm giá sản phẩm',
                    content: function() {
                        const content = $('#discount-popover-content').clone().removeClass('d-none');
                        content.find('.popover-discount-input').val(currentDiscount);
                        return content;
                    }
                }).popover('show');
            });

            $('body').on('click', '.popover-apply-discount', function() {
                if (!activeDiscountTrigger) return;
                const popoverEl = $(this).closest('.popover');
                const newDiscount = parseFloat(popoverEl.find('.popover-discount-input').val());
                if (!isNaN(newDiscount) && newDiscount >= 0 && newDiscount <= 100) {
                    const row = $(activeDiscountTrigger).closest('tr');
                    row.data('discount-percent', newDiscount);
                    $(activeDiscountTrigger).text(newDiscount + '%');
                    updateCalculations();
                    $(activeDiscountTrigger).popover('dispose');
                    activeDiscountTrigger = null;
                } else {
                   showNotification('Vui lòng nhập số hợp lệ từ 0 đến 100.');
                }
            });

            $('body').on('input', '.quantity-input, .price-input, #order-discount-value, #order-discount-type, #order-vat', updateCalculations);
            $('body').on('change', '#order-discount-type, #order-vat', updateCalculations);
            $('body').on('blur', '.price-input, #amount-paid, #order-discount-value', function() {
                if ($(this).is('#order-discount-value') && $('#order-discount-type').val() === 'percent') {
                     $(this).val(String($(this).val()).replace(',', '.'));
                     return;
                }
                $(this).val(formatNumber(parseNumber($(this).val())));
            });
            $('body').on('input', '#amount-paid', updateDebt);

            $('#order-table-body').on('click', '.btn-remove-item', function() {
                $(this).closest('tr').remove();
                $('#order-table-body tr').each((index, el) => $(el).find('td:first').text(index + 1));
                updateCalculations();
            });

            $('#btn-create-draft').on('click', function() { saveOrder(0, $(this)); });
            $('#btn-draft-save').on('click', function() { saveOrder(0, $(this)); });
            $('#btn-confirm-order').on('click', function() {
                if (confirm('Bạn có chắc muốn hoàn thành đơn hàng này? Thao tác sẽ trừ kho và ghi nhận công nợ.')) {
                    saveOrder(1, $(this));
                }
            });
            $('#btn-cancel').on('click', function() {
                window.location.href = '/quanlybanhang/modules/orders/list.php';
            });

            $(document).on('keydown', function(e) {
                if (!e.key) return;
                const key = e.key.toUpperCase();
                if (key === 'F2') { e.preventDefault(); $('#product-search').focus(); }
                if (key === 'F4') { e.preventDefault(); $('#customer-search').focus(); }
            });

            loadInitialOrder();
        });
    </script>
</body>
</html>