<?php
// modules/pos/pos_mobile.php - FINAL: PAYMENT MODAL & PRINT
if (file_exists(__DIR__ . '/../../core/init.php')) {
    require_once __DIR__ . '/../../core/init.php';
}
if (session_status() === PHP_SESSION_NONE) { session_start(); }

$current_user_name = $_SESSION['display_name'] ?? 'Nhân viên';
$user_group = $_SESSION['group_id'] ?? 0;
$is_admin = ($user_group == 1);

$areas = $conn->query("SELECT * FROM cms_areas WHERE deleted=0")->fetch_all(MYSQLI_ASSOC);
$tables = $conn->query("SELECT * FROM cms_tables WHERE deleted=0 ORDER BY area_id, table_name")->fetch_all(MYSQLI_ASSOC);

$tables_by_area = [];
foreach ($tables as $t) { $tables_by_area[$t['area_id']][] = $t; }
?>
<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Mobile POS</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.0.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    <style>
        body { background-color: #f2f4f8; padding-bottom: 80px; font-family: 'Segoe UI', sans-serif; -webkit-user-select: none; }
        
        /* HEADER */
        .app-header { background: #fff; padding: 10px 15px; position: sticky; top: 0; z-index: 1000; box-shadow: 0 2px 5px rgba(0,0,0,0.05); display: flex; justify-content: space-between; align-items: center; }
        .user-name { font-weight: 800; color: #0d6efd; }
        
        /* VIEW MANAGEMENT */
        .view-section { display: none; animation: fadeIn 0.2s; }
        .view-section.active { display: block; }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }

        /* TABLE MAP */
        .area-section { margin-bottom: 15px; padding: 0 10px; }
        .area-title { font-size: 0.9rem; font-weight: 700; color: #6c757d; margin: 10px 0 5px; text-transform: uppercase; border-left: 3px solid #0d6efd; padding-left: 8px; }
        .table-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
        
        .table-card { background: #fff; border-radius: 10px; padding: 15px 5px; text-align: center; box-shadow: 0 1px 3px rgba(0,0,0,0.1); border: 2px solid transparent; position: relative; }
        .table-card:active { transform: scale(0.95); }
        .table-card.busy { background: #fff0f0; border-color: #ffcdd2; }
        .table-card.busy .t-icon { color: #dc3545; }
        .table-card.busy .t-name { color: #dc3545; }
        .t-icon { font-size: 1.8rem; color: #adb5bd; margin-bottom: 5px; }
        .t-name { font-weight: 800; font-size: 0.85rem; color: #333; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .t-status { font-size: 0.65rem; color: #888; }

        /* ORDER VIEW */
        #view-order { background-color: #fff; min-height: 100vh; position: absolute; top: 0; left: 0; width: 100%; z-index: 1050; padding-bottom: 160px; }
        .order-header-sticky { position: sticky; top: 0; z-index: 1100; background: #f2f4f8; padding: 10px; border-bottom: 1px solid #ddd; }
        .order-info-bar { background: #fff; padding: 12px; border-radius: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); display: flex; justify-content: space-between; align-items: center; }
        .order-table-title { font-size: 1.1rem; font-weight: 800; color: #0d6efd; margin-bottom: 2px; }
        .order-area-name { font-size: 0.75rem; color: #666; font-weight: 600; }
        .btn-add-item-compact { background: #e7f1ff; color: #0d6efd; border: 1px solid #0d6efd; padding: 8px 15px; border-radius: 20px; font-weight: 700; font-size: 0.9rem; display: flex; align-items: center; gap: 5px; transition: all 0.2s; }

        /* CART LIST */
        .cart-list { padding: 10px; }
        .cart-item { background: #fff; padding: 12px; border-radius: 8px; margin-bottom: 8px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); border: 1px solid #eee; }
        .c-name { font-weight: 700; font-size: 1rem; color: #333; margin-bottom: 4px; }
        .c-note { font-size: 0.8rem; color: #fd7e14; font-style: italic; margin-bottom: 5px; display: block; }
        .c-price { color: #198754; font-weight: 700; }
        .qty-control { float: right; display: flex; align-items: center; background: #f8f9fa; border-radius: 20px; border: 1px solid #ddd; }
        .btn-qty { width: 35px; height: 32px; border: none; background: transparent; font-weight: bold; font-size: 1.1rem; color: #555; }
        .inp-qty { width: 35px; text-align: center; border: none; background: transparent; font-weight: 800; font-size: 0.9rem; }

        /* MENU */
        #page-menu { background-color: #fff; z-index: 2000; }
        .prod-item { background: #fff; padding: 10px; border-bottom: 1px solid #eee; display: flex; align-items: center; }
        .prod-img { width: 60px; height: 60px; border-radius: 8px; object-fit: cover; margin-right: 10px; background: #eee; }
        .prod-name { font-weight: 700; font-size: 0.95rem; color: #333; margin-bottom: 2px; }
        .prod-price { color: #198754; font-weight: 700; }
        .btn-add-cart { width: 32px; height: 32px; background: #0d6efd; color: #fff; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin-left: auto; }
        
        /* ACTION BAR */
        .bottom-action-bar { position: fixed; bottom: 0; left: 0; width: 100%; background: #fff; padding: 15px; border-top: 1px solid #ddd; display: flex; flex-direction: column; gap: 10px; z-index: 1100; box-shadow: 0 -4px 10px rgba(0,0,0,0.1); }
        .total-row { display: flex; justify-content: space-between; align-items: center; width: 100%; margin-bottom: 5px; }
        .total-money { font-size: 1.4rem; font-weight: 800; color: #dc3545; }
        
        /* NAV */
        .nav-bottom { position: fixed; bottom: 0; width: 100%; height: 60px; background: #fff; border-top: 1px solid #eee; display: flex; justify-content: space-around; z-index: 900; }
        .nav-btn { width: 25%; display: flex; flex-direction: column; align-items: center; justify-content: center; color: #999; text-decoration: none; font-size: 10px; }
        .nav-btn i { font-size: 20px; margin-bottom: 3px; }
        .nav-btn.active { color: #0d6efd; font-weight: 800; }

        /* --- PAYMENT MODAL STYLE --- */
        .pay-info-row { display: flex; justify-content: space-between; margin-bottom: 10px; align-items: center; }
        .pay-label { font-weight: 600; color: #555; }
        .pay-val { font-weight: 700; font-size: 1.1rem; }
        .input-pay { text-align: right; font-size: 1.5rem; font-weight: 800; color: #198754; border: 2px solid #198754; height: 50px; }
        .change-amount { font-size: 1.4rem; font-weight: 800; color: #0d6efd; }
        .debt-amount { font-size: 1.4rem; font-weight: 800; color: #dc3545; }
    </style>
</head>
<body>

    <div class="app-header" id="main-header">
        <div>
            <div class="welcome-text">Xin chào,</div>
            <div class="user-name"><?= htmlspecialchars($current_user_name) ?></div>
        </div>
        <div class="fw-bold text-secondary" id="clock">00:00</div>
    </div>

    <main id="main-content">
        <div id="view-tables" class="view-section active pb-5">
            <?php foreach($areas as $area): ?>
                <div class="area-section">
                    <div class="area-title"><?= $area['area_name'] ?></div>
                    <div class="table-grid">
                        <?php 
                        if(isset($tables_by_area[$area['id']])):
                            foreach($tables_by_area[$area['id']] as $t):
                                $isBusy = $t['table_status'] == 1;
                        ?>
                        <div class="table-card <?= $isBusy ? 'busy' : '' ?>" onclick="openTable(<?= $t['id'] ?>, '<?= $t['table_name'] ?>', '<?= $area['area_name'] ?>', <?= $isBusy ? 1 : 0 ?>)">
                            <div class="t-icon"><i class="fas <?= $isBusy ? 'fa-user-friends' : 'fa-chair' ?>"></i></div>
                            <div class="t-name"><?= $t['table_name'] ?></div>
                            <div class="t-status"><?= $isBusy ? 'Có khách' : 'Trống' ?></div>
                        </div>
                        <?php endforeach; endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <div id="view-order" class="view-section">
            <div class="order-header-sticky">
                <div class="order-info-bar">
                    <div class="order-table-info">
                        <div class="order-table-title" id="lbl-table-name">Bàn 1</div>
                        <div class="order-area-name">
                            <span id="lbl-area-name">Khu vực</span> | 
                            <i class="fas fa-user small me-1"></i><span id="lbl-customer" class="text-primary fw-bold" onclick="openCustomerModal()">Khách lẻ</span>
                        </div>
                    </div>
                    <button class="btn-add-item-compact" onclick="openMenu()">
                        <i class="fas fa-plus"></i> Thêm món
                    </button>
                </div>
            </div>

            <div id="cart-container" class="cart-list"></div>

            <div class="bottom-action-bar">
                <div class="total-row">
                    <span class="fw-bold text-dark">TỔNG CỘNG:</span>
                    <div class="total-money" id="lbl-total">0 ₫</div>
                </div>
                <div class="d-flex gap-2 w-100">
                    <button class="btn btn-dark fw-bold w-25" onclick="saveOrder('kitchen')"><i class="fas fa-print"></i> BẾP</button>
                    <button class="btn btn-primary fw-bold w-25" onclick="saveOrder('save')"><i class="fas fa-save"></i> LƯU</button>
                    <button class="btn btn-success fw-bold w-50" onclick="openPaymentModal()">THANH TOÁN</button>
                </div>
            </div>
        </div>

        <div id="page-menu" class="view-section position-fixed w-100 h-100 top-0 start-0 bg-white" style="z-index: 2000; overflow-y: auto;">
            <div class="p-2 border-bottom bg-white sticky-top d-flex gap-2 align-items-center shadow-sm">
                <button class="btn btn-light border" onclick="closeMenu()"><i class="fas fa-arrow-left"></i></button>
                <input type="text" id="search-prod" class="form-control rounded-pill bg-light border-0" placeholder="Tìm tên món...">
            </div>
            <div id="menu-list" class="pb-5"></div>
        </div>
    </main>

    <div class="modal fade" id="paymentModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header bg-success text-white py-2">
                    <h5 class="modal-title fw-bold">THANH TOÁN</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body bg-light">
                    <div class="bg-white p-3 rounded shadow-sm mb-3">
                        <div class="pay-info-row border-bottom pb-2">
                            <span class="pay-label">Tổng tiền hàng:</span>
                            <span class="pay-val" id="pay-total-goods">0</span>
                        </div>
                        <div class="pay-info-row pt-2">
                            <span class="pay-label text-primary">Khách cần trả:</span>
                            <span class="pay-val text-primary fs-4" id="pay-final-total">0</span>
                        </div>
                    </div>
                    
                    <div class="bg-white p-3 rounded shadow-sm">
                        <label class="form-label fw-bold text-secondary">Tiền khách đưa:</label>
                        <input type="text" id="input-customer-pay" class="form-control input-pay" onkeyup="calcPaymentChange()" onclick="this.select()">
                        
                        <div class="mt-3 text-center">
                            <span id="lbl-change-text" class="text-muted small">Tiền thừa:</span>
                            <div id="lbl-change-amount" class="change-amount">0 ₫</div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-success w-100 py-3 fw-bold fs-5" onclick="confirmPayment()"><i class="fas fa-check-circle me-2"></i> HOÀN TẤT & IN</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="noteModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered modal-sm"><div class="modal-content"><div class="modal-header py-2"><h6 class="modal-title">Ghi chú</h6></div><div class="modal-body"><input type="text" id="item-note-input" class="form-control mb-2" placeholder="Vd: Ít đá..."><div class="d-flex flex-wrap gap-2"><span class="badge bg-light text-dark border p-2" onclick="$('#item-note-input').val('Ít đá')">Ít đá</span><span class="badge bg-light text-dark border p-2" onclick="$('#item-note-input').val('Không đường')">Không đường</span><span class="badge bg-light text-dark border p-2" onclick="$('#item-note-input').val('Mang về')">Mang về</span></div></div><div class="modal-footer py-1"><button class="btn btn-primary w-100 btn-sm" onclick="saveNote()">Xong</button></div></div></div></div>
    <div class="modal fade" id="custModal" tabindex="-1"><div class="modal-dialog modal-fullscreen"><div class="modal-content"><div class="modal-header py-2"><input type="text" id="search-cust" class="form-control me-2" placeholder="Tìm khách..."><button class="btn btn-primary" onclick="addQuickCust()"><i class="fas fa-plus"></i></button><button class="btn-close ms-2" data-bs-dismiss="modal"></button></div><div class="modal-body p-0"><div class="list-group list-group-flush" id="cust-list"></div></div></div></div></div>

    <nav class="nav-bottom" id="main-nav">
        <a href="#" class="nav-btn active" onclick="location.reload()"><i class="fas fa-th-large"></i><span>Sơ đồ</span></a>
        <a href="#" class="nav-btn"><i class="fas fa-file-invoice"></i><span>Hóa đơn</span></a>
        <?php if($is_admin): ?><a href="/quanlybanhang/modules/dashboard/index.php" class="nav-btn"><i class="fas fa-chart-line"></i><span>Quản lý</span></a><?php endif; ?>
        <a href="/quanlybanhang/logout.php" class="nav-btn"><i class="fas fa-sign-out-alt"></i><span>Thoát</span></a>
    </nav>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <script>
        const AJAX_URL = '/quanlybanhang/ajax/pos_mobile_ajax.php';
        let currentTable = { id: 0, name: '', area: '' };
        let currentCustomer = { id: 1, name: 'Khách lẻ' };
        let cart = [];
        let editNoteIndex = -1;
        let currentOrderId = 0;

        $(document).ready(function() {
            setInterval(() => { const d = new Date(); $('#clock').text(d.getHours().toString().padStart(2,'0')+':'+d.getMinutes().toString().padStart(2,'0')); }, 1000);
            loadProducts('');
        });

        // --- NAVIGATION & TABLE ---
        function showScreen(id) { $('.view-section').removeClass('active'); $(id).addClass('active'); if(id === '#view-order' || id === '#page-menu') { $('#main-nav, #main-header').hide(); } else { $('#main-nav, #main-header').show(); } }
        function closeOrderView() { showScreen('#view-tables'); location.reload(); }
        function openTable(id, name, area, isBusy) {
            currentTable = { id, name, area };
            $('#lbl-table-name').text(name); $('#lbl-area-name').text(area);
            cart = []; currentCustomer = { id: 1, name: 'Khách lẻ' }; currentOrderId = 0; updateCustomerUI();
            if (isBusy) {
                $.get(AJAX_URL, { action: 'get_table_order', table_id: id }, function(res) {
                    if(res.status == 'success') {
                        currentOrderId = res.data.ID;
                        if(res.data.customer_id > 1) { currentCustomer = { id: res.data.customer_id, name: res.data.customer_name }; updateCustomerUI(); }
                        let items = JSON.parse(res.data.detail_order || '[]');
                        items.forEach(i => { cart.push({ id: i.id, name: i.name, code: i.code, price: parseFloat(i.price||0), qty: parseFloat(i.quantity||i.qty||0), note: i.note||'', type: i.type }); });
                        renderCart(); showScreen('#view-order');
                    }
                }, 'json');
            } else { showScreen('#view-order'); renderCart(); }
        }
        function updateCustomerUI() { $('#lbl-customer').text(currentCustomer.name); }
        
        // --- MENU & CART ---
        function openMenu() { showScreen('#page-menu'); }
        function closeMenu() { showScreen('#view-order'); renderCart(); }
        function loadProducts(term) {
            $.get(AJAX_URL, { action: 'search_products', term: term }, function(res) {
                let html = '';
                res.results.forEach(p => {
                    let img = p.image ? `/quanlybanhang/${p.image}` : 'https://via.placeholder.com/60';
                    html += `<div class="prod-item"><img src="${img}" class="prod-img"><div class="flex-grow-1"><div class="prod-name">${p.name}</div><div class="prod-price text-success">${parseInt(p.price_retail).toLocaleString()}</div></div><button class="btn-add-cart" onclick="addToCart(${p.id}, '${p.name}', ${p.price_retail}, ${p.type})"><i class="fas fa-plus"></i></button></div>`;
                });
                $('#menu-list').html(html);
            }, 'json');
        }
        $('#search-prod').keyup(function(){ loadProducts($(this).val()) });

        function addToCart(id, name, price, type) {
            let item = cart.find(i => i.id == id && !i.note);
            if(item) item.qty++; else cart.push({ id, name, price: parseFloat(price), qty: 1, type, note: '' });
            const Toast = Swal.mixin({ toast: true, position: 'top', showConfirmButton: false, timer: 800 });
            Toast.fire({ icon: 'success', title: 'Đã thêm ' + name });
        }
        function renderCart() {
            let html = ''; let total = 0;
            if(cart.length == 0) html = '<div class="text-center py-5 text-muted">Chưa có món nào. Hãy bấm "Thêm món"</div>';
            cart.forEach((item, idx) => {
                let line = item.price * item.qty; total += line;
                let note = item.note ? `<span class="c-note">(${item.note})</span>` : '';
                html += `<div class="cart-item"><div class="d-flex justify-content-between"><div class="c-name">${item.name}</div><div class="c-price">${line.toLocaleString()}</div></div>${note}<div class="d-flex justify-content-between align-items-center mt-2"><div class="text-muted small" onclick="editNote(${idx})"><i class="fas fa-pen text-warning me-1"></i>Ghi chú</div><div class="qty-control"><button class="btn-qty" onclick="changeQty(${idx}, -1)">-</button><input class="inp-qty" value="${item.qty}" readonly><button class="btn-qty" onclick="changeQty(${idx}, 1)">+</button></div></div></div>`;
            });
            $('#cart-container').html(html);
            $('#lbl-total').text(total.toLocaleString() + ' ₫');
        }
        function changeQty(idx, d) { cart[idx].qty += d; if(cart[idx].qty <= 0) cart.splice(idx, 1); renderCart(); }
        function editNote(idx) { editNoteIndex = idx; $('#item-note-input').val(cart[idx].note); $('#noteModal').modal('show'); }
        function saveNote() { if(editNoteIndex > -1) cart[editNoteIndex].note = $('#item-note-input').val(); $('#noteModal').modal('hide'); renderCart(); }
        function openCustomerModal() { $('#custModal').modal('show'); searchCust(''); }
        function searchCust(t) { $.get(AJAX_URL, { action: 'search_customers', term: t }, function(res) { let h = '<button class="list-group-item list-group-item-action" onclick="selCust(1,\'Khách lẻ\')">Khách lẻ</button>'; if(res.results) res.results.forEach(c => { h += `<button class="list-group-item list-group-item-action" onclick="selCust(${c.id},'${c.name}')">${c.name}</button>`; }); $('#cust-list').html(h); }, 'json'); }
        $('#search-cust').keyup(function(){ searchCust($(this).val()) });
        function selCust(id, name) { currentCustomer = {id, name}; updateCustomerUI(); $('#custModal').modal('hide'); }
        function addQuickCust() { let n = prompt('Tên khách:'); if(!n) return; $.post(AJAX_URL, { action: 'save_quick_customer', customer_name: n, customer_phone: '' }, function(res){ if(res.status=='success') selCust(res.customer_id, res.customer_name); }, 'json'); }

        // --- LOGIC THANH TOÁN ---
        function openPaymentModal() {
            if (cart.length == 0) return;
            // Tính tổng tiền
            let total = cart.reduce((a,b)=>a+(b.qty*b.price),0);
            
            // Hiển thị thông tin lên modal
            $('#pay-total-goods').text(total.toLocaleString() + ' ₫');
            $('#pay-final-total').text(total.toLocaleString() + ' ₫');
            
            // Mặc định tiền khách đưa = tổng tiền
            $('#input-customer-pay').val(total.toLocaleString()).data('raw', total);
            calcPaymentChange(); // Tính lại tiền thừa (sẽ là 0)
            
            $('#paymentModal').modal('show');
            setTimeout(() => $('#input-customer-pay').select(), 500);
        }

        function calcPaymentChange() {
            let total = parseFloat($('#pay-final-total').text().replace(/[^0-9]/g, '')) || 0;
            let payVal = $('#input-customer-pay').val().replace(/[^0-9]/g, '');
            let pay = parseFloat(payVal) || 0;
            
            // Format lại input khi nhập
            $('#input-customer-pay').val(new Intl.NumberFormat('vi-VN').format(pay));

            let change = pay - total;

            if (change >= 0) {
                $('#lbl-change-text').text('Tiền thừa:');
                $('#lbl-change-amount').removeClass('debt-amount').addClass('change-amount').text(change.toLocaleString() + ' ₫');
            } else {
                $('#lbl-change-text').text('Còn nợ:');
                $('#lbl-change-amount').removeClass('change-amount').addClass('debt-amount').text(Math.abs(change).toLocaleString() + ' ₫');
            }
        }

        function confirmPayment() {
            let payVal = parseFloat($('#input-customer-pay').val().replace(/[^0-9]/g, '')) || 0;
            
            $.post(AJAX_URL, {
                action: 'pay_order',
                table_id: currentTable.id,
                customer_id: currentCustomer.id,
                items: JSON.stringify(cart),
                customer_pay: payVal
            }, function(res) {
                if(res.status == 'success') {
                    $('#paymentModal').modal('hide');
                    
                    // IN BILL (Mở tab mới)
                    let printUrl = '/quanlybanhang/modules/pos/print_invoice.php?order_id=' + res.order_id;
                    window.open(printUrl, '_blank');
                    
                    // Reset giao diện
                    Swal.fire({ icon: 'success', title: 'Thanh toán xong!', timer: 1500, showConfirmButton: false });
                    setTimeout(() => closeOrderView(), 1000);
                } else {
                    alert(res.message || 'Lỗi thanh toán');
                }
            }, 'json');
        }

        function saveOrder(type) {
            if(cart.length == 0) return;
            $.post(AJAX_URL, {
                action: 'create_temp_order', order_id: currentOrderId, table_id: currentTable.id, customer_id: currentCustomer.id, items: JSON.stringify(cart), order_discount_val: 0
            }, function(res) {
                if(res.status == 'success') {
                    if(type == 'kitchen') alert('Đã gửi bếp!'); else alert('Đã lưu đơn!');
                    closeOrderView();
                } else alert(res.message);
            }, 'json');
        }
    </script>
</body>
</html>