<?php
// FILE: modules/tables/index.php
// FIX LỖI: Xử lý API ngay đầu file để tránh lẫn lộn HTML Header
session_start();
ini_set('display_errors', 0);
error_reporting(E_ALL);

// Nếu là gọi API (POST request có action), xử lý và trả về JSON ngay lập tức
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    ob_start(); // Bắt đầu bộ đệm để xóa mọi khoảng trắng thừa
    require_once __DIR__ . '/../../config/database.php';
    header('Content-Type: application/json; charset=utf-8');
    
    $store_id = $_SESSION['store_id'] ?? 1;
    $action = $_POST['action'] ?? '';

    try {
        switch ($action) {
            case 'get_areas': 
                $res = $conn->query("SELECT * FROM cms_areas WHERE store_id=$store_id AND deleted=0 ORDER BY id ASC")->fetch_all(MYSQLI_ASSOC);
                ob_clean(); // Xóa sạch buffer trước khi in JSON
                echo json_encode(['status'=>'success', 'data'=>$res]); 
                break;

            case 'save_area':
                $id = intval($_POST['area_id']); $name = trim($_POST['area_name']);
                if(empty($name)) { ob_clean(); die(json_encode(['status'=>'error', 'message'=>'Nhập tên khu vực'])); }
                
                $stmt = $conn->prepare("SELECT id FROM cms_areas WHERE area_name=? AND store_id=? AND deleted=0 AND id!=?");
                $stmt->bind_param("sii", $name, $store_id, $id); $stmt->execute();
                if($stmt->get_result()->num_rows > 0) { ob_clean(); die(json_encode(['status'=>'error', 'message'=>'Khu vực đã tồn tại'])); }
                
                if($id>0) { $s=$conn->prepare("UPDATE cms_areas SET area_name=? WHERE id=?"); $s->bind_param("si", $name, $id); }
                else { $s=$conn->prepare("INSERT INTO cms_areas (area_name, store_id) VALUES (?, ?)"); $s->bind_param("si", $name, $store_id); }
                $s->execute(); 
                ob_clean(); echo json_encode(['status'=>'success']);
                break;

            case 'delete_area':
                $id = intval($_POST['id']);
                $check = $conn->query("SELECT count(*) FROM cms_tables WHERE area_id=$id AND deleted=0")->fetch_row()[0];
                if($check > 0) { ob_clean(); die(json_encode(['status'=>'error', 'message'=>'Khu vực đang có bàn'])); }
                $conn->query("UPDATE cms_areas SET deleted=1 WHERE id=$id");
                ob_clean(); echo json_encode(['status'=>'success']);
                break;

            case 'get_tables':
                $area_id = intval($_POST['area_id']);
                $where = "t.store_id=$store_id AND t.deleted=0" . ($area_id>0 ? " AND t.area_id=$area_id" : "");
                $res = $conn->query("SELECT t.*, a.area_name FROM cms_tables t LEFT JOIN cms_areas a ON t.area_id=a.id WHERE $where ORDER BY t.area_id ASC, t.table_name ASC")->fetch_all(MYSQLI_ASSOC);
                ob_clean(); echo json_encode(['status'=>'success', 'data'=>$res]);
                break;

            case 'save_table':
                $id = intval($_POST['table_id']); $name = trim($_POST['table_name']); $area_id = intval($_POST['area_id']);
                if(empty($name) || !$area_id) { ob_clean(); die(json_encode(['status'=>'error', 'message'=>'Nhập tên & chọn khu vực'])); }
                
                // CHECK TRÙNG TÊN TRONG CÙNG KHU VỰC
                $stmt = $conn->prepare("SELECT id FROM cms_tables WHERE table_name=? AND area_id=? AND store_id=? AND deleted=0 AND id!=?");
                $stmt->bind_param("siii", $name, $area_id, $store_id, $id); $stmt->execute();
                if($stmt->get_result()->num_rows > 0) { ob_clean(); die(json_encode(['status'=>'error', 'message'=>'Tên bàn này đã tồn tại trong khu vực này!'])); }
                
                if($id>0) { $s=$conn->prepare("UPDATE cms_tables SET table_name=?, area_id=? WHERE id=?"); $s->bind_param("sii", $name, $area_id, $id); }
                else { $s=$conn->prepare("INSERT INTO cms_tables (table_name, area_id, store_id, table_status) VALUES (?, ?, ?, 0)"); $s->bind_param("sii", $name, $area_id, $store_id); }
                $s->execute(); 
                ob_clean(); echo json_encode(['status'=>'success']);
                break;

            case 'delete_table':
                $conn->query("UPDATE cms_tables SET deleted=1 WHERE id=".intval($_POST['id']));
                ob_clean(); echo json_encode(['status'=>'success']);
                break;
        }
    } catch (Exception $e) { 
        ob_clean(); echo json_encode(['status'=>'error', 'message'=>$e->getMessage()]); 
    }
    exit(); // QUAN TRỌNG: Dừng ngay tại đây để không in ra HTML Header bên dưới
}

// --- PHẦN GIAO DIỆN HTML (CHỈ CHẠY KHI TẢI TRANG) ---
require_once __DIR__ . '/../../templates/header.php';
?>

<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/@ttskch/select2-bootstrap4-theme@x.x.x/dist/select2-bootstrap4.min.css">

<style>
    /* CSS CŨ */
    .area-list-group { max-height: 600px; overflow-y: auto; }
    .area-item { cursor: pointer; transition: all 0.2s; font-weight: 600; font-size: 1rem; padding: 15px 20px; border-left: 5px solid transparent; color: #5a5c69; }
    .area-item:hover { background-color: #eaecf4; color: #4e73df; }
    .area-item.active { background-color: #4e73df; border-left-color: #2e59d9; color: #ffffff !important; box-shadow: 0 4px 6px rgba(78, 115, 223, 0.2); }
    .area-item.active .btn-link { color: #ffffff !important; opacity: 0.8; }
    .table-card { transition: transform 0.2s, box-shadow 0.2s; border: 0; border-radius: 8px; box-shadow: 0 0.15rem 1rem 0 rgba(58, 59, 69, 0.1); cursor: pointer; position: relative; overflow: hidden; background: #fff; }
    .table-card:hover { transform: translateY(-3px); border: 1px solid #4e73df; box-shadow: 0 0.5rem 1.5rem 0 rgba(58, 59, 69, 0.15)!important; }
    .table-card .card-body { padding: 1rem; text-align: center; padding-top: 1.8rem; }
    .table-icon { font-size: 2rem; color: #d1d3e2; margin-bottom: 5px; transition: color 0.2s; }
    .table-card:hover .table-icon { color: #4e73df; }
    .table-name { font-weight: 700; font-size: 1rem; color: #2e59d9; display: block; margin-bottom: 2px; }
    .table-area-badge { font-size: 0.7rem; font-weight: 800; text-transform: uppercase; position: absolute; top: 0; right: 0; background: #eaecf4; color: #4e73df; padding: 4px 8px; border-bottom-left-radius: 8px; letter-spacing: 0.5px; }
    .table-status-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; margin-right: 4px; }
    .status-free { background-color: #1cc88a; box-shadow: 0 0 5px #1cc88a; }
    .status-busy { background-color: #e74a3b; box-shadow: 0 0 5px #e74a3b; }
    .status-text { font-weight: 600; font-size: 0.8rem; }
    .btn-action-group { position: absolute; top: 5px; left: 5px; opacity: 0; transition: opacity 0.2s; background: rgba(255,255,255,0.9); border-radius: 5px; padding: 2px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
    .table-card:hover .btn-action-group { opacity: 1; }
    .select2-container { width: 100% !important; }
    .select2-container--bootstrap4 .select2-selection { height: calc(1.5em + .75rem + 2px) !important; }
</style>

<div class="container-fluid">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Quản lý Bàn & Khu vực</h1>
    </div>

    <div class="row">
        <div class="col-lg-3 col-md-4 mb-4">
            <div class="card shadow h-100 border-0">
                <div class="card-header py-3 d-flex justify-content-between align-items-center bg-primary text-white">
                    <h6 class="m-0 font-weight-bold" style="font-size: 1.1rem;"><i class="fas fa-map-marked-alt mr-2"></i>KHU VỰC</h6>
                    <button class="btn btn-sm btn-light text-primary rounded-circle shadow-sm" onclick="openAreaModal()" title="Thêm khu vực"><i class="fas fa-plus"></i></button>
                </div>
                <div class="list-group list-group-flush area-list-group" id="areaList">
                    <div class="text-center p-3"><span class="spinner-border spinner-border-sm text-primary"></span> Đang tải...</div>
                </div>
            </div>
        </div>

        <div class="col-lg-9 col-md-8">
            <div class="card shadow mb-4 border-0">
                <div class="card-header py-3 d-flex justify-content-between align-items-center bg-white border-bottom-0">
                    <h5 class="m-0 font-weight-bold text-primary" id="currentAreaTitle"><i class="fas fa-layer-group mr-2"></i>Tất cả bàn</h5>
                    <button class="btn btn-success shadow-sm" onclick="openTableModal()">
                        <i class="fas fa-plus mr-1"></i> Thêm Bàn Mới
                    </button>
                </div>
                <div class="card-body bg-light" style="min-height: 400px;">
                    <div class="row" id="tableGrid"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="areaModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-sm">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title font-weight-bold">Khu vực</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="areaForm">
                    <input type="hidden" name="area_id" id="area_id">
                    <div class="form-group mb-3">
                        <label class="fw-bold">Tên khu vực <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="area_name" id="area_name" required placeholder="Vd: Sân vườn...">
                    </div>
                    <div class="text-end">
                        <button type="button" class="btn btn-secondary btn-sm" data-bs-dismiss="modal">Hủy</button>
                        <button type="submit" class="btn btn-primary btn-sm">Lưu</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="tableModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title font-weight-bold">Thông tin Bàn</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="tableForm">
                    <input type="hidden" name="table_id" id="table_id">
                    <div class="form-group mb-3">
                        <label class="fw-bold">Tên bàn <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="table_name" id="table_name" required placeholder="Vd: Bàn 01">
                    </div>
                    <div class="form-group mb-3">
                        <label class="fw-bold">Thuộc khu vực <span class="text-danger">*</span></label>
                        <select class="form-control" name="area_id" id="table_area_id" required style="width: 100%;"></select>
                    </div>
                    <div class="text-end">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Hủy</button>
                        <button type="submit" class="btn btn-success">Lưu Bàn</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../../templates/footer.php'; ?>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

<script>
    let currentAreaId = 0;
    let areasData = [];

    $(document).ready(function() {
        $('#table_area_id').select2({ theme: 'bootstrap4', dropdownParent: $('#tableModal') });
        loadAreas();
        loadTables(0);
    });

    // --- JS KHU VỰC ---
    function loadAreas() {
        $.post('/quanlybanhang/modules/tables/index.php', { action: 'get_areas' }, function(res) {
            if (res.status === 'success') {
                areasData = res.data;
                renderAreas(res.data);
                renderAreaOptions(res.data);
            } else {
                console.error("Lỗi data khu vực:", res);
            }
        }, 'json').fail(function(xhr) { console.log(xhr.responseText); });
    }

    function renderAreas(data) {
        let html = `<a href="javascript:void(0)" class="list-group-item list-group-item-action area-item ${currentAreaId === 0 ? 'active' : ''}" onclick="filterTables(0, 'Tất cả bàn')"><i class="fas fa-layer-group mr-2"></i> TẤT CẢ</a>`;
        if(data.length === 0) html += `<div class="p-3 text-muted text-center small">Chưa có khu vực nào.</div>`;
        data.forEach(area => {
            html += `<div class="list-group-item list-group-item-action area-item d-flex justify-content-between align-items-center ${currentAreaId == area.id ? 'active' : ''}" onclick="filterTables(${area.id}, '${area.area_name}')">
                    <span>${area.area_name}</span>
                    <div class="btn-group">
                        <button class="btn btn-sm btn-link text-info p-0 mr-2" onclick="editArea(event, ${area.id}, '${area.area_name}')"><i class="fas fa-pen" style="font-size: 14px;"></i></button>
                        <button class="btn btn-sm btn-link text-danger p-0" onclick="deleteArea(event, ${area.id})"><i class="fas fa-trash" style="font-size: 14px;"></i></button>
                    </div>
                </div>`;
        });
        $('#areaList').html(html);
    }
    
    function openAreaModal() { $('#area_id').val(0); $('#area_name').val(''); $('#areaModal').modal('show'); setTimeout(() => $('#area_name').focus(), 500); }
    function editArea(e, id, name) { e.stopPropagation(); $('#area_id').val(id); $('#area_name').val(name); $('#areaModal').modal('show'); }
    function deleteArea(e, id) { e.stopPropagation(); if(confirm('Xóa khu vực này?')) { $.post('/quanlybanhang/modules/tables/index.php', { action: 'delete_area', id: id }, function(res) { if (res.status === 'success') loadAreas(); else alert(res.message); }, 'json'); } }

    $('#areaForm').on('submit', function(e) {
        e.preventDefault();
        $.post('/quanlybanhang/modules/tables/index.php', $(this).serialize() + '&action=save_area', function(res) {
            if (res.status === 'success') { $('#areaModal').modal('hide'); loadAreas(); } else alert(res.message);
        }, 'json');
    });

    // --- JS BÀN ---
    function filterTables(areaId, areaName) { 
        currentAreaId = areaId; 
        $('#currentAreaTitle').html(areaId === 0 ? '<i class="fas fa-layer-group mr-2"></i> Tất cả bàn' : `<i class="fas fa-map-marker-alt mr-2"></i> ${areaName}`); 
        renderAreas(areasData); loadTables(areaId); 
    }

    function loadTables(areaId) {
        $('#tableGrid').html('<div class="col-12 text-center py-5"><div class="spinner-border text-primary"></div></div>');
        $.post('/quanlybanhang/modules/tables/index.php', { action: 'get_tables', area_id: areaId }, function(res) {
            if (res.status === 'success') renderTables(res.data);
            else $('#tableGrid').html('<div class="col-12 text-center text-danger">' + res.message + '</div>');
        }, 'json').fail(function(xhr) { 
             // Debug: Nếu lỗi, in ra HTML trả về để kiểm tra
             console.log("Error loading tables:", xhr.responseText);
             $('#tableGrid').html('<div class="col-12 text-center text-danger">Lỗi dữ liệu (Xem Console)</div>');
        });
    }

    function renderTables(data) {
        let html = '';
        if (data.length === 0) html = '<div class="col-12 text-center text-muted py-5"><i class="fas fa-chair fa-3x mb-3 text-gray-300"></i><br>Chưa có bàn nào</div>';
        else {
            data.forEach(table => {
                let statusClass = table.table_status == 1 ? 'status-busy' : 'status-free';
                let statusText = table.table_status == 1 ? 'Có khách' : 'Trống';
                let iconColor = table.table_status == 1 ? '#e74a3b' : '#d1d3e2';
                let tableIcon = table.table_status == 1 ? 'fa-utensils' : 'fa-chair';
                html += `
                    <div class="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-6 mb-3">
                        <div class="card table-card h-100" onclick="editTable(${table.id}, '${table.table_name}', ${table.area_id})">
                            <div class="card-body">
                                <div class="btn-action-group"><button class="btn btn-sm btn-danger p-1 shadow-sm" onclick="deleteTable(event, ${table.id})"><i class="fas fa-times"></i></button></div>
                                <span class="table-area-badge highlight">${table.area_name}</span>
                                <div class="table-icon" style="color:${iconColor}"><i class="fas ${tableIcon}"></i></div>
                                <div class="table-name text-truncate">${table.table_name}</div>
                                <div class="small text-muted mt-1"><span class="table-status-dot ${statusClass}"></span> <span class="status-text">${statusText}</span></div>
                            </div>
                        </div>
                    </div>`;
            });
        }
        $('#tableGrid').html(html);
    }

    function renderAreaOptions(data) { let html = ''; data.forEach(area => { html += `<option value="${area.id}">${area.area_name}</option>`; }); $('#table_area_id').html(html); }
    function openTableModal() { $('#table_id').val(0); $('#table_name').val(''); if (currentAreaId > 0) $('#table_area_id').val(currentAreaId).trigger('change'); $('#tableModal').modal('show'); setTimeout(() => $('#table_name').focus(), 500); }
    function editTable(id, name, areaId) { $('#table_id').val(id); $('#table_name').val(name); $('#table_area_id').val(areaId).trigger('change'); $('#tableModal').modal('show'); }
    function deleteTable(e, id) { e.stopPropagation(); if(confirm('Xóa bàn này?')) { $.post('/quanlybanhang/modules/tables/index.php', { action: 'delete_table', id: id }, function(res) { if (res.status === 'success') loadTables(currentAreaId); else alert(res.message); }, 'json'); } }
    
    $('#tableForm').on('submit', function(e) {
        e.preventDefault();
        $.post('/quanlybanhang/modules/tables/index.php', $(this).serialize() + '&action=save_table', function(res) {
            if (res.status === 'success') { $('#tableModal').modal('hide'); loadTables(currentAreaId); } else alert(res.message);
        }, 'json');
    });
</script>