<?php
// thungan.php - Giao diện POS mới cho Shop Thời trang
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]";

// --- KHỞI TẠO BIẾN CƠ BẢN ---
$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;
$user_store_id = $_SESSION['store_id'] ?? 0;

// --- LẤY DANH SÁCH KHO ---
$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);
}

// Check store cho user nếu chưa có session
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');

// --- LẤY DANH MỤC SẢN PHẨM (MỚI CHO THUNGAN.PHP) ---
$categories = [];
// Giả định bảng danh mục là cms_product_groups hoặc cms_categories. 
// Nếu tên bảng khác, bạn hãy sửa lại query này.
// Tôi kiểm tra bảng thường gặp, nếu lỗi hãy check lại tên bảng danh mục của bạn.
$sql_cate = "SELECT id, prd_group_name FROM cms_product_groups WHERE deleted = 0 ORDER BY id ASC"; 
$result_cate = $conn->query($sql_cate);
if ($result_cate) {
    $categories = $result_cate->fetch_all(MYSQLI_ASSOC);
}

// --- LẤY DANH SÁCH SẢN PHẨM ĐỂ HIỂN THỊ LƯỚI (MỚI) ---
// Lấy tối đa 500 sản phẩm hiển thị ban đầu để đảm bảo tốc độ.
// Bạn có thể chỉnh LIMIT hoặc bỏ LIMIT nếu ít hàng.
$products_grid = [];
$sql_grid = "SELECT ID, prd_code, prd_name, prd_sell_price, prd_sell_price2, prd_sls, prd_image_url, prd_group_id 
             FROM cms_products 
             WHERE deleted = 0 AND prd_status = 1 
             ORDER BY ID DESC LIMIT 500";
$result_grid = $conn->query($sql_grid);
if ($result_grid) {
    $products_grid = $result_grid->fetch_all(MYSQLI_ASSOC);
}

// --- XỬ LÝ KHI SỬA ĐƠN HÀNG (GIỮ NGUYÊN LOGIC CŨ) ---
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'] ?? 'Cái',
                            '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 - Thu Ngân' : 'Thu Ngân - 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>
    /* --- GLOBAL LAYOUT --- */
    html, body { height: 100%; overflow: hidden; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; font-size: 14px; background-color: #f4f6f8; }
    
    .pos-container { display: flex; flex-direction: column; height: 100vh; }
    
    /* HEADER */
    .pos-header { background-color: #ffffff; padding: 0.5rem 1rem; border-bottom: 1px solid #e0e0e0; display: flex; justify-content: space-between; align-items: center; height: 50px; flex-shrink: 0; }
    .header-brand { font-weight: bold; font-size: 1.2rem; color: #1a73e8; text-decoration: none; }
    
    /* MAIN CONTENT SPLIT */
    .pos-content { display: flex; flex: 1; overflow: hidden; }
    
    /* --- LEFT COLUMN: PRODUCTS (70%) --- */
    .col-products { width: 68%; display: flex; flex-direction: column; border-right: 1px solid #e0e0e0; background: #f4f6f8; padding: 10px; }
    
    /* Search Bar */
    .product-search-bar { margin-bottom: 10px; position: relative; }
    .product-search-bar input { border-radius: 20px; padding-left: 35px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); border: 1px solid #ddd; height: 40px; }
    .product-search-bar i { position: absolute; left: 12px; top: 12px; color: #aaa; }
    
    /* Category Horizontal Menu */
    .category-bar { display: flex; overflow-x: auto; white-space: nowrap; gap: 10px; padding-bottom: 5px; margin-bottom: 10px; -webkit-overflow-scrolling: touch; scrollbar-width: none; }
    .category-bar::-webkit-scrollbar { display: none; }
    .cat-pill { 
        background: white; border: 1px solid #ddd; border-radius: 20px; padding: 6px 15px; cursor: pointer; color: #555; font-weight: 500; transition: all 0.2s; user-select: none;
    }
    .cat-pill:hover { background: #eef; color: #1a73e8; border-color: #1a73e8; }
    .cat-pill.active { background: #1a73e8; color: white; border-color: #1a73e8; }

    /* Product Grid */
    .product-grid-wrapper { flex: 1; overflow-y: auto; padding-right: 5px; }
    .product-grid { 
        display: grid; 
        grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); 
        gap: 10px; 
    }
    .product-card { 
        background: white; border-radius: 8px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.1); cursor: pointer; transition: transform 0.1s; border: 1px solid transparent; display: flex; flex-direction: column;
    }
    .product-card:active { transform: scale(0.98); }
    .product-card:hover { border-color: #1a73e8; box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
    .product-img { width: 100%; height: 110px; object-fit: cover; background: #eee; }
    .product-info { padding: 8px; flex: 1; display: flex; flex-direction: column; justify-content: space-between; }
    .p-name { font-weight: 600; font-size: 0.95rem; margin-bottom: 4px; line-height: 1.2; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; min-height: 2.4em; }
    .p-price { color: #dc3545; font-weight: bold; font-size: 1rem; }
    .p-stock { font-size: 0.8rem; color: #888; margin-top: 2px; }
    .p-stock.out { color: red; background: #ffebeb; padding: 2px 5px; border-radius: 4px; display: inline-block; }

    /* --- RIGHT COLUMN: CART & PAYMENT (30%) --- */
    .col-cart { width: 32%; display: flex; flex-direction: column; background: white; box-shadow: -2px 0 5px rgba(0,0,0,0.05); z-index: 10; }
    
    /* Cart Header & Customer */
    .cart-header { padding: 10px; border-bottom: 1px solid #eee; background: #f8f9fa; }
    .customer-select { display: flex; gap: 5px; margin-bottom: 5px; }
    
    /* Cart Items Table */
    .cart-items-wrapper { flex: 1; overflow-y: auto; padding: 0; }
    .table-cart { margin-bottom: 0; width: 100%; }
    .table-cart th { position: sticky; top: 0; background: #f1f3f4; z-index: 5; font-size: 0.85rem; padding: 8px 5px; }
    .table-cart td { padding: 8px 5px; vertical-align: middle; border-bottom: 1px solid #f0f0f0; }
    .table-cart tr:hover { background: #f8f9fc; }
    
    .qty-control { display: flex; align-items: center; justify-content: center; width: 80px; }
    .qty-btn { width: 24px; height: 24px; border: 1px solid #ddd; background: white; border-radius: 4px; display: flex; align-items: center; justify-content: center; cursor: pointer; font-size: 12px; }
    .qty-input { width: 30px; text-align: center; border: none; font-weight: bold; margin: 0 2px; }
    .cart-item-name { font-weight: 500; font-size: 0.9rem; }
    .cart-item-price { font-size: 0.9rem; color: #555; }
    
    /* Payment Section */
    .payment-section { padding: 15px; border-top: 1px solid #e0e0e0; background: #fff; box-shadow: 0 -2px 5px rgba(0,0,0,0.03); }
    .pay-row { display: flex; justify-content: space-between; margin-bottom: 6px; font-size: 0.95rem; align-items: center; }
    .pay-row.total { font-size: 1.4rem; font-weight: bold; color: #dc3545; margin-top: 10px; margin-bottom: 15px; border-top: 1px dashed #ddd; padding-top: 10px; }
    .form-control-sm-custom { padding: 2px 5px; height: 28px; font-size: 0.9rem; }
    
    /* Action Buttons */
    .action-buttons { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 10px; }
    .btn-pay { height: 50px; font-size: 1.1rem; font-weight: bold; display: flex; flex-direction: column; justify-content: center; align-items: center; line-height: 1.1; grid-column: span 2; }
    .btn-secondary-custom { height: 40px; }

    /* Autocomplete for Customer */
    .search-wrapper { position: relative; width: 100%; }
    .autocomplete-results { position: absolute; top: 100%; left: 0; right: 0; z-index: 1000; background: white; border: 1px solid #ddd; box-shadow: 0 4px 6px rgba(0,0,0,0.1); max-height: 300px; overflow-y: auto; display: none; border-radius: 0 0 5px 5px; }
    .result-item { padding: 8px 10px; cursor: pointer; border-bottom: 1px solid #eee; }
    .result-item:hover { background: #f0f7ff; }

    @media (max-width: 992px) {
        .pos-content { flex-direction: column; }
        .col-products { width: 100%; height: 50%; }
        .col-cart { width: 100%; height: 50%; border-left: none; border-top: 2px solid #ccc; }
    }
</style>
</head>
<body>

<div class="pos-container">
    <header class="pos-header">
        <div class="d-flex align-items-center gap-3">
            <a href="/quanlybanhang/modules/orders/list.php" class="btn btn-sm btn-outline-secondary"><i class="fas fa-arrow-left"></i> Thoát</a>
            <span class="header-brand"><?php echo $is_editing ? 'Sửa Đơn' : 'Thu Ngân'; ?></span>
            <div class="vr"></div>
            <select class="form-select form-select-sm" id="store-id" style="width: auto; border:none; background:#f0f2f5" <?php echo $is_editing ? '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>
            <span class="text-muted small">Xin chào, <b><?php echo htmlspecialchars($current_user_name); ?></b></span>
        </div>
    </header>

    <div class="pos-content">
        <div class="col-products">
            <div class="product-search-bar">
                <i class="fas fa-search"></i>
                <input type="text" class="form-control" id="product-search-grid" placeholder="Tìm tên, mã, quét mã vạch (F2)..." autocomplete="off">
            </div>

            <div class="category-bar">
                <div class="cat-pill active" data-cat-id="all">Tất cả</div>
                <?php foreach ($categories as $cat): ?>
                    <div class="cat-pill" data-cat-id="<?php echo $cat['id']; ?>"><?php echo htmlspecialchars($cat['prd_group_name']); ?></div>
                <?php endforeach; ?>
            </div>

            <div class="product-grid-wrapper">
                <div class="product-grid" id="grid-container">
                    </div>
            </div>
        </div>

        <div class="col-cart">
            <div class="cart-header">
                <div class="customer-select">
                    <div class="search-wrapper">
                        <input type="text" class="form-control form-control-sm" id="customer-search" value="Khách lẻ" data-customer-id="1" data-customer-group="1" placeholder="Tìm khách hàng (F4)..." autocomplete="off">
                        <div id="customer-search-results" class="autocomplete-results"></div>
                    </div>
                    <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#addCustomerModal"><i class="fas fa-plus"></i></button>
                </div>
                <div class="d-flex gap-2">
                    <input type="datetime-local" class="form-control form-control-sm" id="sale-date" value="<?php echo htmlspecialchars($current_datetime); ?>">
                </div>
            </div>

            <div class="cart-items-wrapper">
                <table class="table table-cart">
                    <thead>
                        <tr>
                            <th style="width: 45%;">Sản phẩm</th>
                            <th style="width: 25%; text-align: center">SL</th>
                            <th style="width: 30%; text-align: right">Thành tiền</th>
                        </tr>
                    </thead>
                    <tbody id="order-table-body">
                        </tbody>
                </table>
            </div>

            <div class="payment-section">
                <div class="pay-row">
                    <span>Tổng SL:</span> <strong id="total-quantity">0</strong>
                </div>
                <div class="pay-row">
                    <span>Tiền hàng:</span> <span id="sub-total">0</span>
                </div>
                <div class="pay-row">
                    <span>Chiết khấu (F7):</span>
                    <div class="d-flex" style="width: 140px;">
                        <input type="text" class="form-control form-control-sm-custom text-end" id="order-discount-value" value="0">
                        <select class="form-select form-select-sm-custom" id="order-discount-type" style="width: 60px; border-left:0"><option value="percent">%</option><option value="fixed">đ</option></select>
                    </div>
                </div>
                 <div class="pay-row">
                    <span>Thuế VAT:</span>
                    <select class="form-select form-select-sm-custom" id="order-vat" style="width: 80px;"><option value="0">0%</option><option value="8">8%</option><option value="10">10%</option></select>
                </div>
                
                <div class="pay-row total">
                    <span>KHÁCH PHẢI TRẢ</span>
                    <span id="grand-total">0</span>
                </div>

                <div class="pay-row">
                    <span>Khách đưa (F8):</span>
                    <input type="text" class="form-control form-control-sm text-end fw-bold text-success" id="amount-paid" value="0" style="width: 140px; font-size: 1.1rem">
                </div>
                <div class="pay-row" style="color: #666">
                    <span>Tiền thừa/Nợ:</span>
                    <span id="amount-debt">0</span>
                </div>

                <div class="mt-2 text-center">
                    <div class="form-check form-check-inline"><input type="radio" name="paymentMethod" id="pm1" value="1" checked class="form-check-input"><label for="pm1">Tiền mặt</label></div>
                    <div class="form-check form-check-inline"><input type="radio" name="paymentMethod" id="pm2" value="2" class="form-check-input"><label for="pm2">Chuyển khoản</label></div>
                </div>

                <div class="action-buttons">
                    <button class="btn btn-outline-secondary btn-secondary-custom" id="btn-save-draft"><i class="fas fa-save"></i> Lưu tạm</button>
                    <button class="btn btn-outline-primary btn-secondary-custom" id="btn-save"><i class="fas fa-check"></i> Lưu</button>
                    <button class="btn btn-success btn-pay" id="btn-save-print">
                        <i class="fas fa-print mb-1"></i> THANH TOÁN & IN
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="addCustomerModal" tabindex="-1"><div class="modal-dialog modal-sm"><div class="modal-content"><div class="modal-header"><h6 class="modal-title">Thêm khách mới</h6><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><form id="addCustomerForm"><div class="mb-2"><label class="form-label small">Tên khách (*)</label><input type="text" class="form-control form-control-sm" name="customer_name" required></div><div class="mb-2"><label class="form-label small">SĐT</label><input type="text" class="form-control form-control-sm" name="customer_phone"></div></form></div><div class="modal-footer"><button type="button" class="btn btn-sm btn-primary w-100" id="btn-save-customer">Lưu</button></div></div></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>
    // --- KHỞI TẠO DỮ LIỆU TỪ PHP ---
    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; ?>';
    
    // Dữ liệu sản phẩm load sẵn để hiển thị Grid (Cực nhanh)
    const allProducts = <?php echo json_encode($products_grid); ?>;
    
    // Đường dẫn ảnh mặc định (Thay thế nếu không có ảnh)
    const defaultImage = 'https://via.placeholder.com/150x110?text=No+Image';
    const folderImage = '<?php echo $base_url; ?>/img/products/'; // Sửa lại đường dẫn thực tế của bạn

    $(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';

        // --- HÀM TIỆN ÍCH ---
        function formatNumber(num) { return (parseFloat(num) || 0).toLocaleString('vi-VN'); }
        function parseNumber(str) { return parseFloat(String(str).replace(/\./g, '').replace(',', '.')) || 0; }

        // --- RENDER SẢN PHẨM RA GRID ---
        function renderGrid(products) {
            const container = $('#grid-container');
            container.empty();
            
            if(products.length === 0) {
                container.html('<div class="col-12 text-center text-muted mt-5">Không tìm thấy sản phẩm nào</div>');
                return;
            }

            products.forEach(p => {
                let imgUrl = p.prd_image_url ? (p.prd_image_url.startsWith('http') ? p.prd_image_url : folderImage + p.prd_image_url) : defaultImage;
                let stockClass = (p.prd_sls <= 0) ? 'out' : '';
                let stockText = (p.prd_sls <= 0) ? 'Hết hàng' : 'Tồn: ' + p.prd_sls;
                
                let html = `
                    <div class="product-card" data-id="${p.ID}" data-json='${JSON.stringify(p)}'>
                        <img src="${imgUrl}" class="product-img" loading="lazy" onerror="this.src='${defaultImage}'">
                        <div class="product-info">
                            <div class="p-name" title="${p.prd_name}">${p.prd_name}</div>
                            <div>
                                <div class="p-price">${formatNumber(p.prd_sell_price)}</div>
                                <div class="p-stock ${stockClass}">${stockText}</div>
                            </div>
                        </div>
                    </div>
                `;
                container.append(html);
            });
        }

        // Render ban đầu
        renderGrid(allProducts);

        // --- XỬ LÝ LỌC DANH MỤC ---
        $('.cat-pill').on('click', function() {
            $('.cat-pill').removeClass('active');
            $(this).addClass('active');
            const catId = $(this).data('cat-id');
            
            if(catId === 'all') {
                renderGrid(allProducts);
            } else {
                const filtered = allProducts.filter(p => p.prd_group_id == catId);
                renderGrid(filtered);
            }
        });

        // --- XỬ LÝ TÌM KIẾM SẢN PHẨM TRÊN GRID ---
        $('#product-search-grid').on('keyup', function() {
            const term = $(this).val().toLowerCase();
            if(term.length === 0) {
                $('.cat-pill.active').trigger('click'); // Reset về danh mục hiện tại
                return;
            }
            
            const filtered = allProducts.filter(p => 
                p.prd_name.toLowerCase().includes(term) || 
                p.prd_code.toLowerCase().includes(term)
            );
            renderGrid(filtered);
            
            // Nếu không tìm thấy trong list có sẵn, có thể gọi AJAX search (tuỳ chọn)
            // Ở đây tôi ưu tiên search local cho nhanh
        });

        // --- CLICK VÀO SẢN PHẨM TRÊN GRID -> THÊM VÀO GIỎ ---
        $('#grid-container').on('click', '.product-card', function() {
            const rawData = $(this).data('json');
            // Mapping dữ liệu từ bảng products sang cấu trúc cart item
            const productForCart = {
                id: rawData.ID,
                code: rawData.prd_code,
                name: rawData.prd_name,
                inventory: parseFloat(rawData.prd_sls),
                origin_price: rawData.prd_origin_price || 0,
                price_retail: rawData.prd_sell_price,
                price_wholesale: rawData.prd_sell_price2,
                unit: 'Cái', // Mặc định
                price: rawData.prd_sell_price, // Mặc định lấy giá lẻ
                quantity: 1,
                percent: 0
            };
            addProductToCart(productForCart);
        });

        // --- CÁC HÀM GIỎ HÀNG (GIỮ NGUYÊN LOGIC CŨ NHƯNG TỐI ƯU UI) ---
        function updateCalculations() {
            let subTotal = 0;
            let totalQty = 0;

            $('#order-table-body tr').each(function() {
                const row = $(this);
                const price = parseNumber(row.find('.price-input').val());
                const qty = parseNumber(row.find('.qty-input').val());
                const discountPercent = parseFloat(row.data('discount-percent')) || 0;
                
                let lineTotal = price * qty;
                lineTotal = lineTotal - (lineTotal * discountPercent / 100);
                
                row.find('.line-total').text(formatNumber(lineTotal));
                subTotal += lineTotal;
                totalQty += qty;
            });

            $('#sub-total').text(formatNumber(subTotal));
            $('#total-quantity').text(totalQty);

            // Discount Bill
            let discountBill = 0;
            const discType = $('#order-discount-type').val();
            const discVal = parseNumber($('#order-discount-value').val()); // Fixed logic parse
            
            if(discType === 'percent') {
                discountBill = subTotal * (discVal / 100);
            } else {
                discountBill = discVal;
            }

            const vatPercent = parseInt($('#order-vat').val());
            const afterDisc = subTotal - discountBill;
            const vatAmount = afterDisc * (vatPercent / 100);
            const grandTotal = afterDisc + vatAmount;

            $('#grand-total').text(formatNumber(Math.round(grandTotal)));
            
            // Tự động điền khách đưa (nếu đang không nhập)
            if(!$('#amount-paid').is(':focus')) {
                $('#amount-paid').val(formatNumber(Math.round(grandTotal)));
            }
            updateDebt();
        }

        function updateDebt() {
            const grand = parseNumber($('#grand-total').text());
            const paid = parseNumber($('#amount-paid').val());
            $('#amount-debt').text(formatNumber(grand - paid));
        }

        function addProductToCart(product, isInitial = false) {
            // Check inventory
            if(!isInitial && product.inventory <= 0) {
                 alert('Sản phẩm này đã hết hàng!');
                 return;
            }
            
            const existingRow = $(`#order-table-body tr[data-product-id="${product.id}"]`);
            if(existingRow.length > 0 && !isInitial) {
                const qtyInput = existingRow.find('.qty-input');
                let newQty = parseNumber(qtyInput.val()) + 1;
                // Check max stock
                if(newQty > product.inventory) {
                    alert('Đã đạt giới hạn tồn kho!');
                    newQty = product.inventory;
                }
                qtyInput.val(newQty);
                updateCalculations();
                // Scroll to row
                existingRow[0].scrollIntoView({behavior: "smooth", block: "nearest"});
            } else {
                const qty = isInitial ? product.quantity : 1;
                // Xác định giá (Lẻ/Buôn)
                const customerGroup = $('#customer-search').data('customer-group');
                let price = product.price_retail;
                if(isInitial) price = product.price; // Nếu load từ đơn cũ
                else if(customerGroup == 0 && product.price_wholesale > 0) price = product.price_wholesale;

                const html = `
                    <tr data-product-id="${product.id}" 
                        data-code="${product.code}" 
                        data-inventory="${product.inventory}"
                        data-origin-price="${product.origin_price}"
                        data-discount-percent="${product.percent || 0}"
                        data-price-retail="${product.price_retail}"
                        data-price-wholesale="${product.price_wholesale}">
                        <td>
                            <div class="cart-item-name">${product.name}</div>
                            <input type="text" class="form-control form-control-sm-custom price-input border-0 p-0 text-primary" value="${formatNumber(price)}" style="width:100px;">
                        </td>
                        <td>
                            <div class="qty-control">
                                <div class="qty-btn minus">-</div>
                                <input type="text" class="qty-input" value="${qty}">
                                <div class="qty-btn plus">+</div>
                            </div>
                        </td>
                        <td class="text-end">
                            <div class="line-total fw-bold">${formatNumber(price * qty)}</div>
                            <small class="text-danger remove-item" style="cursor:pointer">Xóa</small>
                        </td>
                    </tr>
                `;
                $('#order-table-body').prepend(html); // Thêm lên đầu cho dễ thấy
                updateCalculations();
            }
        }

        // --- SỰ KIỆN TRONG GIỎ HÀNG ---
        $('#order-table-body').on('click', '.plus', function() {
            const row = $(this).closest('tr');
            const input = row.find('.qty-input');
            const max = parseFloat(row.data('inventory'));
            let val = parseNumber(input.val()) + 1;
            if(val > max) { alert('Hết hàng trong kho!'); val = max; }
            input.val(val);
            updateCalculations();
        });

        $('#order-table-body').on('click', '.minus', function() {
            const row = $(this).closest('tr');
            const input = row.find('.qty-input');
            let val = parseNumber(input.val()) - 1;
            if(val < 1) val = 1;
            input.val(val);
            updateCalculations();
        });

        $('#order-table-body').on('click', '.remove-item', function() {
            $(this).closest('tr').remove();
            updateCalculations();
        });

        $('#order-table-body').on('change', '.qty-input, .price-input', function() {
            updateCalculations();
        });
        
        // Input mask format
        $('body').on('blur', '.price-input, #amount-paid, #order-discount-value', function() {
            if($(this).attr('id') === 'order-discount-value' && $('#order-discount-type').val() === 'percent') return;
            $(this).val(formatNumber(parseNumber($(this).val())));
            updateCalculations();
        });

        $('#order-discount-type, #order-vat').on('change', updateCalculations);

        // --- LOGIC SEARCH KHÁCH HÀNG (GIỮ NGUYÊN) ---
        let customerTimeout;
        $('#customer-search').on('keyup', function() {
            const term = $(this).val();
            const res = $('#customer-search-results');
            if(term.toLowerCase() === 'khách lẻ') {
                 $(this).data('customerId', 1).data('customer-group', 1);
            }
            clearTimeout(customerTimeout);
            if(term.length < 1) { res.hide(); return; }
            
            customerTimeout = setTimeout(() => {
                $.ajax({
                    url: AJAX_URL_FINAL, dataType: 'json',
                    data: { action: 'search_customers', term: term },
                    success: function(data) {
                        res.empty().show();
                        if(data && data.length) {
                            data.forEach(c => {
                                res.append(`<div class="result-item" data-json='${JSON.stringify(c)}'>
                                    <b>${c.name}</b> - ${c.phone}<br>
                                    <small>Nợ: ${formatNumber(c.total_debt)}</small>
                                </div>`);
                            });
                        } else { res.append('<div class="p-2">Không tìm thấy</div>'); }
                    }
                });
            }, 300);
        });

        $('#customer-search-results').on('click', '.result-item', function() {
            const c = $(this).data('json');
            $('#customer-search').val(c.name).data('customerId', c.id).data('customer-group', c.customer_group);
            $('#customer-search-results').hide();
            // Cập nhật lại giá nếu có giá sỉ
            // (Bạn có thể thêm hàm updatePriceByCustomerGroup ở đây nếu cần)
        });

        // --- LOAD ĐƠN CŨ NẾU CÓ ---
        if(isEditing && initialOrderInfo) {
             $('#customer-search').val(initialOrderInfo.customer_name).data('customerId', initialOrderInfo.customer_id);
             initialOrderItems.forEach(item => addProductToCart(item, true));
             // Set discount/vat/payment info... (Giản lược để code gọn, bạn có thể copy full từ file cũ nếu cần chi tiết load lại các trường này)
             $('#amount-paid').val(formatNumber(initialOrderInfo.customer_pay));
             updateCalculations();
        }

        // --- LƯU ĐƠN HÀNG ---
        function getOrderData() {
            let items = [];
            $('#order-table-body tr').each(function() {
                const row = $(this);
                items.push({
                    id: row.data('product-id'),
                    code: row.data('code'),
                    quantity: parseNumber(row.find('.qty-input').val()),
                    price: parseNumber(row.find('.price-input').val()),
                    name: row.find('.cart-item-name').text(),
                    origin_price: row.data('origin-price'),
                    percent: row.data('discount-percent') || 0
                });
            });

            if(items.length === 0) { alert('Chưa có sản phẩm!'); return null; }

            const discType = $('#order-discount-type').val();
            let discVal = $('#order-discount-value').val();
            if(discType !== 'percent') discVal = parseNumber(discVal);
            else discVal = parseFloat(discVal.replace(',','.'));

            return {
                store_id: $('#store-id').val(),
                customer_id: $('#customer-search').data('customerId') || 1,
                items: JSON.stringify(items),
                customer_pay: parseNumber($('#amount-paid').val()),
                discount_value: discVal,
                discount_type: discType,
                vat: $('#order-vat').val(),
                payment_method: $('input[name="paymentMethod"]:checked').val(),
                sale_date: $('#sale-date').val(),
                order_id: orderIdToEdit // Nếu sửa
            };
        }

        $('#btn-save, #btn-save-print, #btn-save-draft').on('click', function() {
            const btnId = $(this).attr('id');
            const data = getOrderData();
            if(!data) return;

            let url = AJAX_URL_FINAL;
            let action = 'save_order';

            if(btnId === 'btn-save-draft') {
                url = AJAX_URL_DRAFT;
                action = 'save_or_update_order'; // Logic khoitao
                data.order_status = 0;
            } else if (isEditing && initialOrderInfo.order_status == 1) {
                action = 'edit_order'; // Sửa đơn đã hoàn thành
            }

            data.action = action;

            // Disable btn
            $('.action-buttons button').prop('disabled', true);

            $.ajax({
                url: url, type: 'POST', dataType: 'json', data: data,
                success: function(res) {
                    if(res.status === 'success') {
                        if(btnId === 'btn-save-print') {
                            window.open(`${baseUrl}/quanlybanhang/modules/pos/print_invoice.php?order_id=${res.order_id}`, '_blank');
                        }
                        alert('Thành công!');
                        window.location.reload(); // Hoặc chuyển trang
                    } else {
                        alert(res.message);
                    }
                },
                error: function() { alert('Lỗi kết nối'); },
                complete: function() { $('.action-buttons button').prop('disabled', false); }
            });
        });

        // Phím tắt
        $(document).on('keydown', function(e) {
            if(e.key === 'F2') { e.preventDefault(); $('#product-search-grid').focus(); }
            if(e.key === 'F4') { e.preventDefault(); $('#customer-search').focus(); }
            if(e.key === 'F8') { e.preventDefault(); $('#amount-paid').focus().select(); }
        });
    });
</script>
</body>
</html>