<?php
// FILE: modules/pos/thungan.php
// UPDATE: Đã sửa tên cột khớp với Database (prd_quycach, prd_tenquycach)
ini_set('display_errors', 1);
error_reporting(E_ALL);
header('Content-Type: text/html; charset=utf-8');

require_once __DIR__ . '/../../config/database.php';
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!$conn->set_charset("utf8mb4")) { $conn->set_charset("utf8"); }

$current_user_name = $_SESSION['display_name'] ?? 'Nhân viên';
$user_store_id = $_SESSION['store_id'] ?? 1;
$current_date = date('d/m/Y H:i');

// 1. Lấy danh mục
$categories = $conn->query("SELECT ID, prd_group_name FROM cms_products_group WHERE parentid = 0 ORDER BY id ASC")->fetch_all(MYSQLI_ASSOC);

// 2. Lấy sản phẩm (ĐÃ SỬA SQL ĐÚNG CẤU TRÚC BẢNG)
// Sử dụng cột 'prd_quycach' và 'prd_tenquycach' có sẵn trong DB của bạn
$sql_products = "SELECT ID, prd_code, prd_name, prd_sell_price, prd_image_url, prd_group_id, prd_type, prd_sls, prd_origin_price,
                 IFNULL(prd_quycach, 1) as prd_quycach, 
                 IFNULL(prd_tenquycach, '') as prd_tenquycach 
                 FROM cms_products 
                 WHERE deleted = 0 AND prd_status = 1 
                 ORDER BY prd_type DESC, prd_group_id ASC, prd_name ASC";

$products = $conn->query($sql_products)->fetch_all(MYSQLI_ASSOC);
$json_products = json_encode($products, JSON_UNESCAPED_UNICODE);

// 3. Lấy danh sách bàn
$tables = $conn->query("SELECT t.id, t.table_name, a.area_name, t.table_status 
                        FROM cms_tables t 
                        LEFT JOIN cms_areas a ON t.area_id = a.id 
                        WHERE t.deleted=0 AND t.store_id=$user_store_id 
                        ORDER BY a.id ASC, t.table_name ASC")->fetch_all(MYSQLI_ASSOC);
$json_tables = json_encode($tables, JSON_UNESCAPED_UNICODE);

// 4. Lấy khách hàng
$check_col = $conn->query("SHOW COLUMNS FROM cms_customers LIKE 'deleted'");
$where_cust = ($check_col->num_rows > 0) ? "WHERE deleted=0" : "";
$customers = $conn->query("SELECT ID, customer_name, customer_phone FROM cms_customers $where_cust LIMIT 100")->fetch_all(MYSQLI_ASSOC);
$json_customers = json_encode($customers, JSON_UNESCAPED_UNICODE);
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>POS Thu Ngân F&B</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />

    <style>
        :root { --primary-color: #0d6efd; --bg-gray: #f0f2f5; }
        body { background-color: var(--bg-gray); height: 100vh; overflow: hidden; font-family: 'Segoe UI', sans-serif; font-size: 0.95rem; }
        
        /* HEADER & LAYOUT */
        .pos-header { height: 50px; background: #fff; border-bottom: 1px solid #ddd; padding: 0 15px; display: flex; align-items: center; justify-content: space-between; }
        .pos-container { display: flex; height: calc(100vh - 50px); }
        .left-panel { width: 65%; display: flex; flex-direction: column; padding: 10px; }
        .right-panel { width: 35%; background: #fff; border-left: 1px solid #ddd; display: flex; flex-direction: column; }

        .btn-table-selector { font-weight: 700; font-size: 1.1rem; color: #d63384; border: 2px dashed #d63384; padding: 5px 20px; border-radius: 20px; cursor: pointer; transition: 0.2s; }
        .btn-table-selector:hover, .btn-table-selector.active { background: #d63384; color: #fff; border-style: solid; box-shadow: 0 0 10px rgba(214, 51, 132, 0.5); }

        /* --- DANH MỤC --- */
        .category-bar { display: flex; gap: 10px; overflow-x: auto; padding-bottom: 8px; margin-bottom: 10px; scrollbar-width: thin; }
        
        .cat-item { 
            white-space: nowrap; padding: 10px 20px; 
            border-radius: 25px; cursor: pointer; 
            font-weight: 800; font-size: 1rem;
            color: #fff; 
            border: none;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            transition: transform 0.2s;
            text-shadow: 0 1px 2px rgba(0,0,0,0.2);
        }
        .cat-item:hover { transform: translateY(-2px); opacity: 0.9; }
        .cat-item.active { transform: scale(1.05); box-shadow: 0 0 0 3px rgba(0,0,0,0.2) inset; text-decoration: underline; }

        .cat-item:nth-child(8n+1) { background-color: #0d6efd; }
        .cat-item:nth-child(8n+2) { background-color: #198754; }
        .cat-item:nth-child(8n+3) { background-color: #dc3545; }
        .cat-item:nth-child(8n+4) { background-color: #fd7e14; }
        .cat-item:nth-child(8n+5) { background-color: #6f42c1; }
        .cat-item:nth-child(8n+6) { background-color: #0dcaf0; color: #000; text-shadow:none; }
        .cat-item:nth-child(8n+7) { background-color: #d63384; }
        .cat-item:nth-child(8n+8) { background-color: #20c997; }
        .cat-item:first-child { background-color: #343a40 !important; }

        /* --- SẢN PHẨM --- */
        .product-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(135px, 1fr)); gap: 12px; overflow-y: auto; padding-right: 5px; padding-bottom: 50px; }
        
        .product-card { 
            background: #fff; border-radius: 10px; overflow: hidden; 
            box-shadow: 0 2px 4px rgba(0,0,0,0.08); cursor: pointer; 
            transition: transform 0.1s; border: 1px solid transparent; 
            position: relative; 
        }
        .product-card:hover { transform: translateY(-3px); border-color: var(--primary-color); box-shadow: 0 4px 8px rgba(0,0,0,0.15); }
        
        .prod-img { height: 100px; width: 100%; object-fit: cover; background: #f8f9fa; }
        .prod-info { padding: 8px; }
        .prod-name { font-weight: 700; font-size: 0.95rem; color: #333; margin-bottom: 2px; line-height: 1.2; height: 36px; overflow: hidden; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; }
        .prod-price { font-weight: 800; color: #d63384; font-size: 1rem; }
        
        /* --- HIỂN THỊ TỒN KHO TRÊN ẢNH --- */
        .stock-badge {
            position: absolute;
            top: 5px; right: 5px;
            font-size: 0.75rem; font-weight: 700;
            padding: 4px 8px; border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.3); z-index: 2;
            text-align: right; line-height: 1.1; max-width: 90%;
        }
        .stock-val { font-size: 0.9rem; font-weight: 900; display: block; }
        .stock-detail { font-size: 0.65rem; font-weight: normal; opacity: 0.95; white-space: nowrap; display: block; margin-top: 1px; }

        .stock-ok { background-color: rgba(13, 110, 253, 0.95); color: #fff; border: 1px solid #fff; }
        .stock-warn { background-color: rgba(253, 126, 20, 0.95); color: #fff; border: 1px solid #fff; }
        .stock-out { background-color: rgba(220, 53, 69, 0.95); color: #fff; border: 1px solid #fff; }

        /* GIỎ HÀNG */
        .cart-header { padding: 10px 15px; border-bottom: 1px solid #eee; background: #f8f9fa; }
        .cart-items { flex: 1; overflow-y: auto; }
        .cart-table th { position: sticky; top: 0; background: #eee; z-index: 1; font-size: 0.85rem; padding: 8px; text-transform: uppercase; color: #555; }
        .cart-table td { padding: 8px; vertical-align: middle; border-bottom: 1px solid #f1f1f1; }
        .cart-item-name { font-size: 1rem; font-weight: 700; color: #212529; line-height: 1.2; }
        .cart-item-price { font-size: 0.85rem; color: #6c757d; }
        .cart-note { font-size: 0.85rem; color: #dc3545; font-style: italic; margin-top: 2px; }

        .qty-btn { width: 28px; height: 28px; border: 1px solid #ddd; background: #fff; border-radius: 4px; font-weight: bold; cursor: pointer; }
        .qty-btn:hover { background: #e9ecef; }
        .qty-input { width: 40px; text-align: center; border: 1px solid #ced4da; font-weight: bold; height: 28px; border-radius: 4px; margin: 0 2px; }
        .qty-input:focus { border-color: #0d6efd; outline: none; background: #f0f8ff; }

        .btn-note { color: #fd7e14; cursor: pointer; margin-right: 5px; }

        /* THANH TOÁN */
        .pay-area { padding: 15px; background: #fdfdfe; border-top: 1px solid #ddd; box-shadow: 0 -2px 10px rgba(0,0,0,0.05); }
        .pay-row { display: flex; justify-content: space-between; margin-bottom: 8px; align-items: center; font-size: 0.95rem; }
        .pay-area .pay-row .pay-label { font-weight: 800 !important; font-size: 1.1rem !important; color: #212529 !important; }
        #discount-val { font-size: 2.2rem !important; font-weight: 900 !important; color: #d63384 !important; height: 55px !important; text-align: center !important; border: 2px solid #d63384 !important; background-color: #fff5f8; }
        #discount-type { font-size: 1.8rem !important; font-weight: 800 !important; height: 55px !important; }
        #total-qty { font-size: 1.3rem !important; font-weight: 800 !important; }
        .pay-total-value#grand-total { font-size: 2rem !important; font-weight: 900 !important; color: #dc3545 !important; }
        #customer-pay { font-size: 1.5rem !important; font-weight: 800 !important; height: 45px !important; color: #198754 !important; }
        #change-amount { font-size: 1.5rem !important; font-weight: 800 !important; }

        .btn-pay-big { height: 50px; font-size: 1.2rem; font-weight: 700; text-transform: uppercase; }
        .pay-buttons { display: grid; grid-template-columns: 1fr 1fr 2fr; gap: 8px; margin-top: 10px; }

        /* MODAL BÀN */
        .modal-body-scroll { max-height: 75vh; overflow-y: auto; background-color: #f8f9fc; padding: 20px; }
        .area-title { font-size: 1.1rem; font-weight: 800; color: #4e73df; text-transform: uppercase; border-left: 5px solid #4e73df; padding-left: 10px; margin-bottom: 15px; margin-top: 15px; }
        .table-grid-modal { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 15px; }
        .table-item { background: #fff; border: 2px solid #e3e6f0; border-radius: 12px; padding: 15px 5px; text-align: center; cursor: pointer; transition: 0.2s; }
        .table-item:hover { transform: translateY(-3px); box-shadow: 0 5px 15px rgba(0,0,0,0.1); border-color: #4e73df; }
        .table-item.free { border-color: #1cc88a; background-color: #f0fdf4; }
        .table-item.busy { border-color: #e74a3b; background-color: #fef2f2; }
        .table-item.busy .table-icon { color: #e74a3b; animation: pulse 2s infinite; }
        .table-item.free .table-icon { color: #1cc88a; }
        .table-icon { font-size: 2.5rem; margin-bottom: 8px; }
        .table-name { font-weight: 800; font-size: 1rem; color: #333; }
        @keyframes pulse { 0% { transform: scale(1); } 50% { transform: scale(1.1); } 100% { transform: scale(1); } }
        .select2-container--bootstrap-5 .select2-selection { border-radius: 0.375rem; }
    </style>
</head>
<body>

<input type="hidden" id="json-products" value='<?= $json_products ?>'>
<input type="hidden" id="json-tables" value='<?= $json_tables ?>'>
<input type="hidden" id="json-customers" value='<?= $json_customers ?>'>
<input type="hidden" id="current-order-id" value="0">

<header class="pos-header">
    <div class="d-flex align-items-center gap-3">
        <a href="/quanlybanhang/modules/dashboard/" class="btn btn-outline-secondary btn-sm" title="Về trang chủ"><i class="fas fa-home"></i></a>
        <div class="btn-table-selector" onclick="showTableModal()">
            <i class="fas fa-chair me-2"></i><span id="selected-table-name">CHỌN BÀN</span>
            <input type="hidden" id="selected-table-id" value="0">
        </div>
        <div class="input-group input-group-sm" style="width: 250px;">
            <span class="input-group-text bg-white"><i class="fas fa-search text-muted"></i></span>
            <input type="text" id="search-product" class="form-control" placeholder="Tìm món (F2)...">
        </div>
    </div>
    <div class="d-flex align-items-center gap-3 text-secondary" style="font-size: 0.9rem;">
        <span class="fw-bold text-dark"><i class="far fa-clock me-1"></i> <?= $current_date ?></span>
        <span class="fw-bold text-primary"><i class="fas fa-user-circle me-1"></i> <?= htmlspecialchars($current_user_name) ?></span>
    </div>
</header>

<div class="pos-container">
    <div class="left-panel">
        <div class="category-bar">
            <div class="cat-item active" onclick="filterCat('all')">TẤT CẢ</div>
            <?php foreach($categories as $c): ?>
                <div class="cat-item" onclick="filterCat(<?= $c['ID'] ?>)"><?= $c['prd_group_name'] ?></div>
            <?php endforeach; ?>
        </div>
        <div class="product-grid" id="product-list"></div>
    </div>

    <div class="right-panel">
        <div class="cart-header">
            <div class="input-group input-group-sm mb-1">
                <span class="input-group-text bg-white"><i class="fas fa-user"></i></span>
                <select class="form-select" id="customer-select" style="width: 70%;">
                    <option value="1">Khách lẻ</option>
                </select>
                <button class="btn btn-outline-primary" onclick="showAddCustomerModal()"><i class="fas fa-plus"></i></button>
            </div>
            <div class="cart-info-line text-end">
                <span class="text-danger fw-bold cursor-pointer" onclick="clearCart()"><i class="fas fa-trash-alt me-1"></i> Xóa đơn</span>
            </div>
        </div>
        
        <div class="cart-items">
            <table class="table cart-table mb-0 w-100">
                <thead class="table-light"><tr><th>Tên món</th><th class="text-center" width="100">SL</th><th class="text-end">Tiền</th><th></th></tr></thead>
                <tbody id="cart-body"></tbody>
            </table>
        </div>

        <div class="pay-area">
            <div class="pay-row">
                <span class="pay-label">Tổng số lượng:</span>
                <span class="pay-value" id="total-qty">0</span>
            </div>
            <div class="pay-row">
                <span class="pay-label">Giảm giá:</span>
                <div class="input-group" style="width: 160px;">
                    <input type="text" id="discount-val" class="form-control" value="0" onblur="calcTotal()">
                    <select class="form-select" id="discount-type" onchange="calcTotal()" style="width: 65px; flex:none;"><option value="%">%</option><option value="vnd">đ</option></select>
                </div>
            </div>
            <div class="pay-row pay-total-row">
                <span class="pay-total-label">TỔNG CỘNG:</span>
                <span class="pay-total-value" id="grand-total">0 ₫</span>
            </div>
            <div class="pay-row align-items-center">
                <span class="pay-label">Khách đưa:</span>
                <input type="text" id="customer-pay" class="form-control" style="width: 180px;" value="0" onkeyup="formatMoneyInput(this); calcChange()">
            </div>
            <div class="pay-row text-secondary">
                <span class="pay-label" id="change-label">Tiền thừa:</span>
                <span class="pay-value" id="change-amount">0 ₫</span>
            </div>
            <div class="pay-buttons">
                <button class="btn btn-outline-dark fw-bold py-2" onclick="saveAndPrintKitchen()"><i class="fas fa-print d-block mb-1 fs-5"></i> In Bếp</button>
                <button class="btn btn-primary fw-bold py-2" onclick="saveOrder('save')"><i class="fas fa-save d-block mb-1 fs-5"></i> Lưu Đơn</button>
                <button class="btn btn-success btn-pay-big" onclick="payOrder()"><i class="fas fa-money-bill-wave me-2"></i> THANH TOÁN</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="noteModal" tabindex="-1"><div class="modal-dialog modal-sm modal-dialog-centered"><div class="modal-content"><div class="modal-header py-2"><h6 class="modal-title fw-bold">Ghi chú món ăn</h6><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><input type="text" id="item-note-input" class="form-control" placeholder="Vd: Ít cay..."><div class="mt-2 d-flex flex-wrap gap-2"><button class="btn btn-outline-secondary btn-sm" onclick="addQuickNote('Không hành')">Không hành</button><button class="btn btn-outline-secondary btn-sm" onclick="addQuickNote('Ít cay')">Ít cay</button><button class="btn btn-outline-secondary btn-sm" onclick="addQuickNote('Mang về')">Mang về</button></div></div><div class="modal-footer py-1"><button type="button" class="btn btn-primary w-100" onclick="saveNote()">Xong</button></div></div></div></div>

<div class="modal fade" id="tableModal" tabindex="-1" aria-hidden="true"><div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable"><div class="modal-content"><div class="modal-header bg-primary text-white py-3"><h5 class="modal-title fw-bold text-uppercase"><i class="fas fa-map-marked-alt me-2"></i>Sơ đồ bàn</h5><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div><div class="modal-body modal-body-scroll"><div id="table-list-modal"></div></div></div></div></div>

<div class="modal fade" id="addCustomerModal" tabindex="-1"><div class="modal-dialog modal-sm modal-dialog-centered"><div class="modal-content"><div class="modal-header py-2"><h6 class="modal-title fw-bold">Thêm khách</h6><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><div class="mb-2"><input type="text" id="new-cust-name" class="form-control" placeholder="Tên khách (*)"></div><div class="mb-3"><input type="text" id="new-cust-phone" class="form-control" placeholder="Số điện thoại"></div><button class="btn btn-primary w-100 btn-sm" onclick="addNewCustomer()">Lưu</button></div></div></div></div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
    const allProducts = JSON.parse($('#json-products').val() || '[]');
    const allTables = JSON.parse($('#json-tables').val() || '[]');
    const initCustomers = JSON.parse($('#json-customers').val() || '[]');
    let cart = [];
    let currentTableId = 0;
    let editingNoteIndex = -1;

    $(document).ready(function() {
        renderProducts(allProducts);
        renderTablesModal();
        $('#customer-select').select2({ theme: "bootstrap-5", placeholder: "Tìm khách...", allowClear: false });
        initCustomers.forEach(c => { if(c.ID != 1) $('#customer-select').append(new Option(c.customer_name + ' - ' + c.customer_phone, c.ID, false, false)); });
        $('#customer-select').val(1).trigger('change'); 
        $('#search-product').on('keyup', function() {
            let term = $(this).val().toLowerCase();
            renderProducts(allProducts.filter(p => p.prd_name.toLowerCase().includes(term) || p.prd_code.toLowerCase().includes(term)));
        });
        if(currentTableId === 0) showTableModal();
    });

    // --- RENDER SẢN PHẨM & TỒN KHO THÔNG MINH ---
    function renderProducts(list) {
        let html = '';
        list.forEach(p => {
            let img = p.prd_image_url ? `/quanlybanhang/${p.prd_image_url}` : 'https://via.placeholder.com/150';
            
            // Logic Hiển thị Tồn kho (Đã map đúng cột DB của bạn)
            let stockBadge = '';
            if(p.prd_type == 0) { // Hàng hóa
                let sls = parseInt(p.prd_sls);
                // Dùng prd_quycach thay cho prd_convert_rate
                let rate = parseInt(p.prd_quycach) || 1; 
                // Dùng prd_tenquycach thay cho prd_unit_big
                let unitBig = p.prd_tenquycach || 'Lốc/Bao'; 
                let stockClass = 'stock-ok';
                
                if (sls <= 0) {
                    stockBadge = `<div class="stock-badge stock-out">HẾT HÀNG</div>`;
                } else {
                    if (sls < 10) stockClass = 'stock-warn';
                    
                    let displayHtml = `<span class="stock-val">${sls}</span>`;
                    
                    if(rate > 1) {
                        let packs = Math.floor(sls / rate); // Số bao nguyên
                        let loose = sls % rate; // Số lẻ
                        let detailText = `(${packs} ${unitBig} ${loose > 0 ? ':' + loose : ''})`;
                        displayHtml += `<span class="stock-detail">${detailText}</span>`;
                    }
                    
                    stockBadge = `<div class="stock-badge ${stockClass}">${displayHtml}</div>`;
                }
            }

            html += `
            <div class="product-card" onclick="addToCart(${p.ID})">
                ${stockBadge}
                <img src="${img}" class="prod-img">
                <div class="prod-info">
                    <div class="prod-name" title="${p.prd_name}">${p.prd_name}</div>
                    <div class="prod-price">${Number(p.prd_sell_price).toLocaleString()}</div>
                </div>
            </div>`;
        });
        $('#product-list').html(html);
    }

    function renderTablesModal() {
        let groupedTables = {};
        if (allTables.length === 0) { $('#table-list-modal').html('<div class="text-center p-5 text-muted">Chưa có dữ liệu bàn</div>'); return; }
        allTables.forEach(t => {
            let areaName = t.area_name || 'Khu vực khác';
            if (!groupedTables[areaName]) groupedTables[areaName] = [];
            groupedTables[areaName].push(t);
        });
        let html = '';
        for (const [area, tables] of Object.entries(groupedTables)) {
            html += `<div class="area-title"><i class="fas fa-layer-group"></i> ${area} <span class="badge bg-secondary ms-2 text-white" style="font-size: 0.7rem; border-radius: 50%;">${tables.length}</span></div><div class="table-grid-modal">`;
            tables.forEach(t => {
                let isBusy = (t.table_status == 1);
                html += `<div class="table-item ${isBusy?'busy':'free'}" onclick="selectTable(${t.id}, '${t.table_name}')"><div class="table-icon"><i class="fas ${isBusy?'fa-user-friends':'fa-chair'}"></i></div><div class="table-name">${t.table_name}</div><div class="small mt-1">${isBusy?'<span class="text-danger fw-bold">Có khách</span>':'<span class="text-success">Trống</span>'}</div></div>`;
            });
            html += `</div>`;
        }
        $('#table-list-modal').html(html);
    }

    function addToCart(id) {
        let p = allProducts.find(x => x.ID == id);
        if (!p) return;
        if (p.prd_type == 0 && p.prd_sls <= 0) { alert('Hàng hóa này đã hết tồn kho!'); return; }
        let item = cart.find(x => x.id == id && (!x.note));
        if (item) item.qty++; 
        else cart.push({ id: p.ID, name: p.prd_name, price: p.prd_sell_price, qty: 1, type: p.prd_type, origin: p.prd_origin_price||0, note: '' });
        renderCart();
    }

    function renderCart() {
        let html = '', totalQty = 0, subTotal = 0;
        cart.forEach((item, index) => {
            let total = item.price * item.qty;
            let noteHtml = item.note ? `<div class="cart-note"><i class="fas fa-pen-alt me-1"></i>${item.note}</div>` : '';
            
            html += `<tr>
                <td>
                    <div class="cart-item-name">${item.name} 
                        <i class="fas fa-edit btn-note ms-2" title="Ghi chú" onclick="openNoteModal(${index})"></i>
                    </div>
                    ${noteHtml}
                    <div class="cart-item-price">${Number(item.price).toLocaleString()}</div>
                </td>
                <td class="text-center">
                    <div class="d-flex align-items-center justify-content-center">
                        <button class="qty-btn" onclick="changeQty(${index}, -1)">-</button>
                        <input type="number" class="qty-input" value="${item.qty}" onchange="updateQtyManual(${index}, this)" onclick="this.select()">
                        <button class="qty-btn" onclick="changeQty(${index}, 1)">+</button>
                    </div>
                </td>
                <td class="text-end fw-bold text-dark">${total.toLocaleString()}</td>
                <td class="text-center text-danger cursor-pointer" onclick="removeCart(${index})"><i class="fas fa-times"></i></td>
            </tr>`;
            totalQty += Number(item.qty); subTotal += total;
        });
        $('#cart-body').html(html);
        $('#total-qty').text(totalQty);
        calcTotal(subTotal);
    }

    function updateQtyManual(index, input) {
        let newQty = parseFloat(input.value);
        if(!newQty || newQty <= 0) { alert('Số lượng không hợp lệ'); renderCart(); return; }
        let item = cart[index];
        if(item.type == 0) {
             let product = allProducts.find(p => p.ID == item.id);
             if(product && newQty > parseFloat(product.prd_sls)) { alert('Vượt quá tồn kho! Tồn: ' + product.prd_sls); renderCart(); return; }
        }
        cart[index].qty = newQty; renderCart();
    }

    function openNoteModal(index) {
        editingNoteIndex = index; $('#item-note-input').val(cart[index].note || ''); $('#noteModal').modal('show'); setTimeout(() => $('#item-note-input').focus(), 500);
    }
    function addQuickNote(text) {
        let current = $('#item-note-input').val(); $('#item-note-input').val(current ? current + ', ' + text : text);
    }
    function saveNote() {
        if(editingNoteIndex > -1) { cart[editingNoteIndex].note = $('#item-note-input').val(); renderCart(); }
        $('#noteModal').modal('hide');
    }

    function changeQty(index, delta) { cart[index].qty = Number(cart[index].qty) + delta; if (cart[index].qty <= 0) cart.splice(index, 1); renderCart(); }
    function removeCart(index) { cart.splice(index, 1); renderCart(); }
    function clearCart() { if(confirm('Xóa đơn?')) { cart = []; renderCart(); } }

    function calcTotal(subTotalArg = null) {
        let subTotal = subTotalArg;
        if (subTotal === null) subTotal = cart.reduce((sum, item) => sum + (item.price * item.qty), 0);
        let discVal = parseFloat($('#discount-val').val().replace(/,/g, '')) || 0;
        let discType = $('#discount-type').val();
        let discount = discType === '%' ? subTotal * (discVal / 100) : discVal;
        let grandTotal = Math.max(0, subTotal - discount);
        
        $('#grand-total').text(grandTotal.toLocaleString() + ' ₫').data('val', grandTotal);
        if(document.activeElement.id !== 'customer-pay') { $('#customer-pay').val(grandTotal.toLocaleString()); }
        calcChange();
    }

    function calcChange() {
        let total = $('#grand-total').data('val') || 0;
        let pay = parseFloat($('#customer-pay').val().replace(/,/g, '')) || 0;
        let change = pay - total;
        if(change >= 0) {
            $('#change-label').text('Tiền thừa:').removeClass('text-danger').addClass('text-secondary');
            $('#change-amount').text(change.toLocaleString() + ' ₫').removeClass('text-danger').addClass('text-success');
        } else {
            $('#change-label').text('Còn Nợ:').removeClass('text-secondary').addClass('text-danger fw-bold');
            $('#change-amount').text(Math.abs(change).toLocaleString() + ' ₫').removeClass('text-success').addClass('text-danger fw-bold');
        }
    }
    function formatMoneyInput(input) { input.value = Number(input.value.replace(/[^0-9]/g, '')).toLocaleString(); }
    function showTableModal() { $('#tableModal').modal('show'); }
    function selectTable(id, name) {
        currentTableId = id; $('#selected-table-id').val(id); $('#selected-table-name').text(name);
        $('.btn-table-selector').addClass('active'); $('#tableModal').modal('hide');
        $.get('/quanlybanhang/ajax/pos_table_ajax.php', { action: 'get_table_order', table_id: id }, function(res) {
            let rs = JSON.parse(res); if(rs.status == 'success' && rs.data) { cart = rs.data; renderCart(); } else { cart = []; renderCart(); }
        });
    }

    function saveOrder(type) {
        if (!cart.length) return alert('Chưa chọn món!');
        if (!currentTableId) return alert('Chưa chọn bàn!');
        let data = {
            action: 'save_order', table_id: currentTableId, customer_id: $('#customer-select').val(),
            items: JSON.stringify(cart), discount: $('#discount-val').val().replace(/,/g, ''), discount_type: $('#discount-type').val(), type: type
        };
        $.post('/quanlybanhang/ajax/pos_table_ajax.php', data, function(res) {
            let rs = JSON.parse(res);
            if(rs.status == 'success') {
                if (type != 'kitchen') { alert('Đã lưu đơn!'); location.reload(); }
            } else alert(rs.message);
        });
    }

    function saveAndPrintKitchen() {
        if (!cart.length) return alert('Chưa chọn món!');
        if (!currentTableId) return alert('Chưa chọn bàn!');
        saveOrder('kitchen'); 
        let tableName = $('#selected-table-name').text();
        let printWindow = window.open('', '', 'width=400,height=600');
        let html = `<html><head><style>body { font-family: Arial, sans-serif; padding: 10px; } h1 { text-align: center; } h2 { font-size: 35px; margin: 10px 0; border: 3px solid #000; padding: 5px; text-align: center; } .item { border-bottom: 1px dashed #000; padding: 10px 0; } .qty-name { font-size: 22px; font-weight: bold; } .note { font-size: 18px; font-style: italic; font-weight: bold; }</style></head><body><h1>PHIẾU BẾP</h1><p style="text-align: center;">${new Date().toLocaleString('vi-VN')}</p><h2>${tableName}</h2><hr>`;
        cart.forEach(item => { html += `<div class="item"><div class="qty-name">[ ${item.qty} ] ${item.name}</div>${item.note ? `<div class="note">Ghi chú: ${item.note}</div>` : ''}</div>`; });
        html += `</body></html>`;
        printWindow.document.write(html); printWindow.document.close(); printWindow.focus();
        setTimeout(() => { printWindow.print(); printWindow.close(); location.reload(); }, 500);
    }

    function payOrder() {
        if (!currentTableId || !cart.length) return;
        if (!confirm('Thanh toán và trả bàn?')) return;
        let data = {
            action: 'pay_order', table_id: currentTableId, customer_id: $('#customer-select').val(),
            items: JSON.stringify(cart), discount: $('#discount-val').val().replace(/,/g, ''), discount_type: $('#discount-type').val(),
            customer_pay: $('#customer-pay').val().replace(/,/g, '')
        };
        $.post('/quanlybanhang/ajax/pos_table_ajax.php', data, function(res) {
            let rs = JSON.parse(res);
            if(rs.status == 'success') {
                let printUrl = '/quanlybanhang/modules/pos/print_invoice.php?order_id=' + rs.order_id;
                let printWindow = window.open(printUrl, '_blank', 'width=400,height=600');
                setTimeout(() => location.reload(), 1000);
            } else alert(rs.message);
        });
    }
    
    function filterCat(id) { $('.cat-item').removeClass('active'); if(id === 'all') renderProducts(allProducts); else renderProducts(allProducts.filter(p => p.prd_group_id == id)); }
</script>
</body>
</html>