<?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();
}

$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";

$initial_order_items_json = 'null';
$initial_order_info_json = 'null';
$order_id_to_edit = 0;
$is_editing = false;
$current_user_name = $_SESSION['display_name'] ?? 'Nhân viên';
$current_user_id = $_SESSION['user_id'] ?? 0;

$stores = [];
$user_store_id = 0;
$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 (isset($_SESSION['store_id'])) {
    $user_store_id = $_SESSION['store_id'];
} elseif ($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;

    $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_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ẻ';
            $order['customer_group'] = 1;
        }
        $initial_order_info_json = json_encode($order);
        $order_items_from_db = json_decode($order['detail_order'], true);
        
        $user_store_id = $order['store_id'] ?? $user_store_id;

        $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']])) {
                        $p_info = $products_info[$item['id']];
                        $enriched_items[] = [
                            'id' => $p_info['ID'],
                            'code' => $p_info['prd_code'],
                            'name' => $p_info['prd_name'],
                            'inventory' => floatval($p_info['prd_sls']) + ($order['order_status'] == 1 ? floatval($item['quantity'] ?? 0) : 0),
                            '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_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 $is_editing ? 'Sửa Đơn Hàng' : 'POS Bán Hàng'; ?></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-header .header-left, .pos-header .header-right { display: flex; align-items: center; gap: 1rem; }
    .pos-header .btn-back { color: white; text-decoration: none; font-size: 1.2rem; }
    .pos-header .header-divider { border-left: 1px solid rgba(255,255,255,0.3); height: 25px; }
    .pos-header .form-select { background-color: #4f8de1; color: white; border: none; font-weight: 500; }
    .pos-main-content { flex-grow: 1; padding: 1rem; overflow: hidden; }
    .pos-grid-container { display: grid; grid-template-columns: 1fr 450px; grid-template-rows: minmax(0, 1fr); 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-name { font-weight: 500; }
    .order-item-note { font-size: 0.95em; color: #28a745; background-color: #e9f7ef; border: 1px dashed #28a745; padding: 0.2rem 0.4rem; margin-top: 0.3rem; border-radius: 0.25rem; max-width: 250px; }
    .order-item-note::placeholder { color: #6c757d; }
    .quantity-input, .price-input { height: 38px; font-size: 1rem; }
    .product-result-name { font-size: 1.1em; font-weight: 600; }
    .product-result-code { font-size: 0.95em; color: #6c757d; }
    .customer-result-item .debt-line { font-weight: 700 !important; color: #dc3545 !important; }
    #order-table-body tr:hover { background-color: #f8f9fc; }
    .btn-remove-item { border-radius: 50%; width: 28px; height: 28px; line-height: 1; font-size: 1.2rem; display: flex; align-items: center; justify-content: center; }
    .pos-right-column .form-label { font-weight: 600; margin-bottom: 0.5rem; }
    .pos-right-column .form-control, .pos-right-column .form-select, .pos-right-column .input-group { font-size: 1rem; }
    .payment-info-container { margin-top: 1.5rem; }
    .payment-info-container .info-line { padding: 0.6rem 0; font-size: 1.05rem; display: flex; align-items: center; justify-content: space-between; }
    .payment-info-container .summary-total { font-size: 1.75rem; font-weight: bold; color: #dc3545; }
    #amount-debt { font-size: 1.5rem !important; }
    #amount-paid { font-size: 1.2rem !important; height: 40px; }
    .btn-lg { padding: 0.75rem 1rem; font-size: 1.1rem; }
    .search-wrapper { position: relative; }
    .autocomplete-results { position: absolute; top: 100%; left: 0; right: 0; z-index: 999; background-color: #fff; border: 1px solid #ddd; border-top: none; border-radius: 0 0 .375rem .375rem; box-shadow: 0 0.5rem 1rem rgba(0,0,0,.15); max-height: 450px; overflow-y: auto; display: none; }
    .autocomplete-results .result-item { padding: 0.75rem 1rem; cursor: pointer; 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; }
    .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">
        <a href="/quanlybanhang/modules/orders/list.php" class="btn-back" title="Quay lại danh sách đơn hàng"><i class="fas fa-arrow-left"></i></a>
        <div class="header-divider"></div>
        <h5 class="mb-0"><?php echo $is_editing ? 'Sửa Đơn Hàng' : 'POS Bán Hàng'; ?></h5>
    </div>
    <div class="header-right">
        <div class="d-flex align-items-center gap-2">
            <span>Cửa hàng (Kho):</span>
            <select class="form-select form-select-sm" id="store-id" style="width: auto;" <?php echo $is_editing ? 'disabled' : ''; ?>>
                <?php if (empty($stores)): ?>
                    <option>Chưa có kho</option>
                <?php else: ?>
                    <?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; ?>
                <?php endif; ?>
            </select>
        </div>
        <div class="header-divider"></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">
                        <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" data-customer-group="1" autocomplete="off">
                                    <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"><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); ?>">
                        </div>
                        <div>
                            <label for="order-notes" class="form-label">Ghi chú chung</label>
                            <textarea class="form-control" id="order-notes" rows="2"></textarea>
                        </div>
                    </div>
                    
                    <div class="payment-info-container mt-auto">
                        <div class="d-flex justify-content-between 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 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="info-line"><span>Tiền hàng</span><span class="fw-bold" id="sub-total">0</span></div>
                        <div class="info-line"><span>Tổng SL</span><span class="fw-bold" id="total-quantity">0</span></div>
                        <div class="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="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="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="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">
                         <div class="btn-group w-100">
                             <button class="btn btn-secondary btn-lg" id="btn-save-draft" style="width: 40%"><i class="fas fa-file-alt me-2"></i>Lưu Khởi Tạo</button>
                             <button class="btn btn-primary btn-lg" id="btn-save" style="width: 30%"><i class="fas fa-save me-2"></i>Lưu</button>
                             <button class="btn btn-success btn-lg" id="btn-save-print" style="width: 30%"><i class="fas fa-print me-2"></i>Lưu & In</button>
                         </div>
                        <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 p-2"><div class="input-group"><input type="text" class="form-control form-control-sm popover-discount-input" placeholder="0"><span class="input-group-text">%</span></div><div class="d-flex justify-content-end 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 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; ?>;
    const isEditing = <?php echo json_encode($is_editing); ?>;
    const baseUrl = '<?php echo $base_url; ?>';
    let activeDiscountTrigger = null;

    $(document).ready(function() {
        $('body').append(`<input type="hidden" id="editing_order_id" value="${orderIdToEdit}">`);
        const AJAX_URL_FINAL = '/quanlybanhang/ajax/pos_ajax.php';
        const AJAX_URL_DRAFT = '/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; }
        
        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() {
            let subTotalAfterItemDiscounts = 0;
            let totalQuantity = 0;
            let originalSubTotal = 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 discountPercent = parseFloat(String(row.data('discount-percent')).replace(',', '.')) || 0;

                const isFinalizingDraft = isEditing && initialOrderInfo && initialOrderInfo.order_status == 0;
                if ((!isEditing || isFinalizingDraft) && 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);
                }
                
                if (price < originPrice) { row.find('.price-input').addClass('is-invalid'); } 
                else { row.find('.price-input').removeClass('is-invalid'); }
                
                const lineSubTotal = quantity * price;
                const lineDiscountAmount = lineSubTotal * (discountPercent / 100);
                const lineTotal = lineSubTotal - lineDiscountAmount;

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

            $('#sub-total').text(formatNumber(Math.round(originalSubTotal)));
            $('#total-quantity').text(totalQuantity);
            
            const discountType = $('#order-discount-type').val();
            let discountValue;
            if (discountType === 'percent') {
                discountValue = parseFloat(String($('#order-discount-value').val()).replace(',', '.')) || 0;
            } else {
                discountValue = parseNumber($('#order-discount-value').val());
            }

            let totalOrderDiscountAmount = (discountType === 'percent') ? (subTotalAfterItemDiscounts * (discountValue / 100)) : discountValue;
            
            const subTotalAfterBothDiscounts = subTotalAfterItemDiscounts - totalOrderDiscountAmount;
            const vatPercent = parseNumber($('#order-vat').val());
            const vatAmount = subTotalAfterBothDiscounts * (vatPercent / 100);
            const grandTotal = subTotalAfterBothDiscounts + vatAmount;

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

        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_FINAL,
                    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 formattedPrice = formatNumber(item.price_retail);
                                const resultHTML = `
                                <div class="d-flex align-items-center w-100">
                                    <div style="flex: 1; min-width: 0;">
                                        <div class="product-result-name" style="white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${item.name}</div>
                                        <div class="product-result-code">Mã: ${item.code}</div>
                                    </div>
                                    <div style="width: 130px; text-align: right; font-weight: 600; color: #dc3545; padding-left: 1rem;">
                                        ${formattedPrice} đ
                                    </div>
                                    <div style="width: 80px; text-align: right;">
                                        <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.toLowerCase() === 'khách lẻ' || searchTerm.trim() === '') {
                 $(this).data('customerId', 1).data('customer-group', 1);
                 updateAllProductPricesInCart();
            }
            clearTimeout(customerSearchTimeout);
            if (searchTerm.length < 1) {
                resultsContainer.empty().hide();
                return;
            }
            customerSearchTimeout = setTimeout(() => {
                $.ajax({
                    url: AJAX_URL_FINAL,
                    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)}</div><div class="info-line ${debtClass}"><i class="fas fa-exclamation-circle"></i> Còn nợ: ${formatNumber(item.total_debt)}</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);
        });

        function updateAllProductPricesInCart() {
            const customerGroup = $('#customer-search').data('customer-group');
            $('#order-table-body tr').each(function() {
                const row = $(this);
                const priceRetail = row.data('price-retail');
                const priceWholesale = row.data('price-wholesale');
                const priceInput = row.find('.price-input');
                
                let newPrice = priceRetail;
                if (customerGroup == 0 && parseFloat(priceWholesale) > 0) {
                    newPrice = priceWholesale;
                }
                priceInput.val(formatNumber(newPrice));
            });
            updateCalculations();
        }

        $('#customer-search-results').on('click', '.result-item', function() {
            const customerData = $(this).data('customerData');
            if (customerData) {
                $('#customer-search')
                    .val(customerData.name)
                    .data('customerId', customerData.id)
                    .data('customer-group', customerData.customer_group);
                updateAllProductPricesInCart();
            }
            $('#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) {
                alert('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_FINAL,
                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).data('customer-group', customer.customer_group || 1);
                        const modal = bootstrap.Modal.getInstance(document.getElementById('addCustomerModal'));
                        modal.hide();
                        form.trigger('reset');
                        alert('Thêm khách hàng thành công!');
                        updateAllProductPricesInCart();
                    } else {
                        alert('Lỗi: ' + (response.message || 'Không thể thêm khách hàng.'));
                    }
                },
                error: function() {
                    alert('Đã có lỗi kết nối xảy ra.');
                }
            });
        });

        function addProductToCart(product, isInitialLoad = false) {
            const quantityToAdd = isInitialLoad ? (product.quantity || 1) : 1;
            if (!product || !product.name) return;
            
            if (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 && !isInitialLoad) {
                const quantityInput = existingRow.find('.quantity-input');
                quantityInput.val(parseNumber(quantityInput.val()) + quantityToAdd).trigger('input');
            } else {
                const stt = $('#order-table-body tr').length + 1;
                const discountPercent = product.percent || 0;
                const note = product.note || '';

                const customerGroup = $('#customer-search').data('customer-group');
                let priceToUse = product.price_retail;
                if (isInitialLoad && product.price) {
                    priceToUse = product.price;
                } else if (customerGroup == 0 && parseFloat(product.price_wholesale) > 0) {
                    priceToUse = product.price_wholesale;
                }
                
                const newRow = `
                    <tr data-product-id="${product.id}" 
                        data-code="${product.code || ''}" 
                        data-inventory="${product.inventory}" 
                        data-origin-price="${product.origin_price || 0}" 
                        data-discount-percent="${discountPercent}"
                        data-price-retail="${product.price_retail || 0}"
                        data-price-wholesale="${product.price_wholesale || 0}">
                        <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="${note}">
                        </td>
                        <td>${product.unit || ''}</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(priceToUse)}">
                                <button class="btn btn-outline-primary btn-item-discount" type="button" title="Giảm giá sản phẩm"><i class="fas fa-tag me-1"></i>${String(discountPercent).replace('.',',')}%</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">&times;</button></td>
                    </tr>`;
                $('#order-table-body').append(newRow);
            }
            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())));
        });
        
        $('#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() { isEditing ? window.location.href = '/quanlybanhang/modules/orders/list.php' : resetOrderForm(true); });

        $('#order-table-body').on('click', '.btn-item-discount', function(e) {
            e.stopPropagation();
            if (activeDiscountTrigger) { $(activeDiscountTrigger).popover('dispose'); }
            activeDiscountTrigger = this;

            const row = $(this).closest('tr');
            const currentDiscount = row.data('discount-percent');
            row.data('original-discount', currentDiscount);

            const popoverContent = $('#discount-popover-content').clone().removeClass('d-none').html();
            $(this).popover({
                container: 'body', html: true, placement: 'left',
                title: 'Giảm giá sản phẩm', content: popoverContent, sanitize: false
            }).popover('show');
            
            $('.popover-discount-input').val(String(currentDiscount).replace('.',',')).focus();
        });

        $('body').on('input', '.popover-discount-input', function() {
            if (!activeDiscountTrigger) return;
            const row = $(activeDiscountTrigger).closest('tr');
            const newDiscountRaw = $(this).val();
            const newDiscountValue = parseFloat(String(newDiscountRaw).replace(',', '.')) || 0;

            if (newDiscountValue >= 0 && newDiscountValue <= 100) {
                row.data('discount-percent', newDiscountValue);
                updateCalculations();
            }
        });

        $('body').on('click', '.popover-apply-discount', function() {
            if (!activeDiscountTrigger) return;
            const row = $(activeDiscountTrigger).closest('tr');
            const finalDiscount = row.data('discount-percent');

            row.removeData('original-discount');
            $(activeDiscountTrigger).html(`<i class="fas fa-tag me-1"></i>${String(finalDiscount).replace('.',',')}%`);
            
            $(activeDiscountTrigger).popover('dispose');
            activeDiscountTrigger = null;
        });

        $(document).on('click', function (e) {
            if (activeDiscountTrigger && !$(activeDiscountTrigger).is(e.target) && $(e.target).closest('.popover').length === 0) {
                const row = $(activeDiscountTrigger).closest('tr');
                const originalDiscount = row.data('original-discount');
                if (typeof originalDiscount !== 'undefined') {
                    row.data('discount-percent', originalDiscount);
                    $(activeDiscountTrigger).html(`<i class="fas fa-tag me-1"></i>${String(originalDiscount).replace('.',',')}%`);
                    row.removeData('original-discount');
                }
                $(activeDiscountTrigger).popover('dispose');
                activeDiscountTrigger = null;
                updateCalculations();
            }
        });
        
        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 (isEditing && initialOrderInfo) {
                if (initialOrderInfo.customer_id) {
                    $('#customer-search')
                        .val(initialOrderInfo.customer_name)
                        .data('customerId', initialOrderInfo.customer_id)
                        .data('customer-group', initialOrderInfo.customer_group);
                }
                initialOrderItems.forEach(item => addProductToCart(item, true));
                if (initialOrderInfo) {
                    $('#order-notes').val(initialOrderInfo.notes);
                    if (initialOrderInfo.discount_percent > 0) {
                        $('#order-discount-type').val('percent');
                        $('#order-discount-value').val(String(initialOrderInfo.discount_percent).replace('.', ','));
                    } else {
                        $('#order-discount-type').val('fixed');
                        $('#order-discount-value').val(formatNumber(initialOrderInfo.total_discount));
                    }
                    $('#order-vat').val(initialOrderInfo.vat);
                    $('input[name="paymentMethod"][value="' + initialOrderInfo.payment_method + '"]').prop('checked', true);
                    $('#amount-paid').val(formatNumber(initialOrderInfo.customer_pay)).trigger('blur');
                    updateCalculations();
                }
            }
        }
        
        function getOrderData() {
            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 null;
            }
            
            $('#order-table-body tr').each(function() {
                const row = $(this);
                const productName = row.find('.order-item-name').text().trim();
                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,
                    percent: parseFloat(String(row.data('discount-percent')).replace(',', '.')) || 0,
                    note: row.find('.order-item-note').val()
                });
            });
            
            if (hasError) return null;
            
            const discountType = $('#order-discount-type').val();
            const rawDiscountValue = $('#order-discount-value').val();
            const discountValueToSend = discountType === 'percent' ? (parseFloat(String(rawDiscountValue).replace(',', '.')) || 0) : parseNumber(rawDiscountValue);

            return {
                order_id: orderIdToEdit,
                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: parseNumber($('#order-vat').val()),
                payment_method: $('input[name="paymentMethod"]:checked').val(),
                sale_date: $('#sale-date').val()
            };
        }

        $('#btn-save-draft').on('click', function(e) {
            e.preventDefault();
            const orderData = getOrderData();
            if (!orderData) return;

            orderData.action = 'save_or_update_order';
            orderData.order_status = 0;
            
            $('.btn-lg').prop('disabled', true);

            $.ajax({
                url: AJAX_URL_DRAFT,
                type: 'POST',
                data: orderData,
                dataType: 'json',
                success: function(response) {
                    if (response.status === 'success') {
                        alert(response.message);
                        window.location.href = '/quanlybanhang/modules/orders/list.php';
                    } 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-lg').prop('disabled', false);
                }
            });
        });

        $('#btn-save, #btn-save-print').on('click', function(e) {
            e.preventDefault();
            const button = $(this);
            const isPrinting = button.is('#btn-save-print');
            const orderData = getOrderData();
            if (!orderData) return;

            let targetUrl = AJAX_URL_FINAL;
            
            if (isEditing) {
                if (initialOrderInfo && initialOrderInfo.order_status == 0) {
                    targetUrl = AJAX_URL_DRAFT; 
                    orderData.action = 'save_or_update_order';
                    orderData.order_status = 1; 
                } else {
                    targetUrl = AJAX_URL_FINAL;
                    orderData.action = 'edit_order';
                }
            } else {
                targetUrl = AJAX_URL_FINAL;
                orderData.action = 'save_order';
            }

            $('.btn-lg').prop('disabled', true);
            
            $.ajax({
                url: targetUrl,
                type: 'POST',
                data: orderData,
                dataType: 'json',
                success: function(response) {
                    if (response.status === 'success') {
                        alert(response.message);
                        if (isPrinting && response.order_id) {
                            window.open(`${baseUrl}/quanlybanhang/modules/pos/print_invoice.php?order_id=${response.order_id}`, '_blank');
                        }
                        window.location.href = '/quanlybanhang/modules/orders/list.php';
                    } 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-lg').prop('disabled', false);
                }
            });
        });


        $(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();
        updateCalculations();
    });
</script>
</body>
</html>