<?php
$pageTitle = 'Tables & QR Codes';
require_once __DIR__ . '/includes/header.php';

$tables = $db->query("SELECT * FROM tables WHERE restaurant_id = ? ORDER BY table_number ASC", [$restaurantId])->fetchAll();

$qrCodes = $db->query("
    SELECT qr.*, t.table_number
    FROM qr_codes qr
    LEFT JOIN tables t ON qr.table_id = t.id
    WHERE qr.restaurant_id = ?
    ORDER BY qr.created_at DESC
", [$restaurantId])->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h6 class="mb-0">Tables & QR Codes</h6>
        <small class="text-muted">Manage tables and generate QR codes</small>
    </div>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#tableModal" onclick="resetTableForm()">
        <i class="fas fa-plus me-1"></i>Add Table
    </button>
</div>

<div class="row">
    <div class="col-lg-7">
        <div class="table-card">
            <div class="card-header"><i class="fas fa-chair me-2"></i>Tables</div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr><th>#</th><th>Name</th><th>Capacity</th><th>Area</th><th>Status</th><th>Active</th><th>Actions</th></tr>
                        </thead>
                        <tbody>
                            <?php if (empty($tables)): ?>
                                <tr><td colspan="7" class="text-center text-muted py-3">No tables</td></tr>
                            <?php else: ?>
                                <?php foreach ($tables as $tbl): ?>
                                <tr>
                                    <td><strong><?php echo sanitize($tbl['table_number']); ?></strong></td>
                                    <td><?php echo sanitize($tbl['table_name'] ?? '-'); ?></td>
                                    <td><?php echo $tbl['capacity']; ?></td>
                                    <td><?php echo sanitize($tbl['area'] ?? '-'); ?></td>
                                    <td><span class="badge bg-<?php echo $tbl['status'] === 'available' ? 'success' : ($tbl['status'] === 'occupied' ? 'danger' : 'warning'); ?>"><?php echo ucfirst($tbl['status']); ?></span></td>
                                    <td><?php echo $tbl['is_active'] ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-danger"></i>'; ?></td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary me-1" onclick="editTable(<?php echo $tbl['id']; ?>)"><i class="fas fa-edit"></i></button>
                                        <a href="<?php echo $baseUrl; ?>/restaurant-admin/tables.php?action=generate_qr&table_id=<?php echo $tbl['id']; ?>" class="btn btn-sm btn-outline-info me-1" title="Generate QR"><i class="fas fa-qrcode"></i></a>
                                        <button class="btn-ajax-delete btn btn-sm btn-outline-danger" data-url="<?php echo $baseUrl; ?>/restaurant-admin/tables.php" data-action="delete_table" data-name="<?php echo sanitize($tbl['table_number']); ?>" data-id="<?php echo $tbl['id']; ?>"><i class="fas fa-trash"></i></button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="col-lg-5">
        <div class="table-card">
            <div class="card-header"><i class="fas fa-qrcode me-2"></i>QR Codes</div>
            <div class="card-body">
                <?php if (empty($qrCodes)): ?>
                    <div class="text-center text-muted py-3">No QR codes generated</div>
                <?php else: ?>
                    <?php foreach ($qrCodes as $qr): ?>
                    <div class="d-flex justify-content-between align-items-center border-bottom py-2">
                        <div>
                            <strong class="small"><?php echo sanitize($qr['table_number'] ?? 'Restaurant'); ?></strong>
                            <div class="text-muted" style="font-size:11px;">Code: <code><?php echo sanitize($qr['code']); ?></code></div>
                        </div>
                        <div>
                            <span class="badge bg-<?php echo $qr['type'] === 'table' ? 'primary' : 'secondary'; ?>"><?php echo ucfirst($qr['type']); ?></span>
                            <?php if ($qr['is_active']): ?><span class="badge bg-success">Active</span><?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="tableModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="tableForm">
                <?php echo $csrf->field(); ?>
                <input type="hidden" name="action" id="tblAction" value="add_table">
                <input type="hidden" name="table_id" id="tblId" value="">
                <div class="modal-header">
                    <h5 class="modal-title" id="tblModalTitle">Add Table</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Table Number <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="table_number" id="tblNumber" required placeholder="e.g., T1, A5">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Table Name</label>
                            <input type="text" class="form-control" name="table_name" id="tblName" placeholder="e.g., Window Seat">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Capacity</label>
                            <input type="number" class="form-control" name="capacity" id="tblCapacity" value="4" min="1">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Area</label>
                            <input type="text" class="form-control" name="area" id="tblArea" placeholder="e.g., Indoor">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Status</label>
                            <select class="form-select" name="status" id="tblStatus">
                                <?php foreach (['available'=>'Available','occupied'=>'Occupied','reserved'=>'Reserved','cleaning'=>'Cleaning'] as $val => $lbl): ?>
                                <option value="<?php echo $val; ?>"><?php echo $lbl; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="is_active" id="tblActive" value="1" checked>
                            <label class="form-check-label">Active</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save me-1"></i>Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function resetTableForm() {
    document.getElementById('tblAction').value = 'add_table';
    document.getElementById('tblId').value = '';
    document.getElementById('tblNumber').value = '';
    document.getElementById('tblName').value = '';
    document.getElementById('tblCapacity').value = '4';
    document.getElementById('tblArea').value = '';
    document.getElementById('tblStatus').value = 'available';
    document.getElementById('tblActive').checked = true;
    document.getElementById('tblModalTitle').textContent = 'Add Table';
}

function editTable(id) {
    fetch(BASE_URL + '/restaurant-admin/tables.php?action=get_table&id=' + id, {headers:{'X-Requested-With':'XMLHttpRequest'}})
    .then(function(r){return r.json();})
    .then(function(data){
        if(data.success){
            var t = data.table;
            document.getElementById('tblAction').value = 'edit_table';
            document.getElementById('tblId').value = t.id;
            document.getElementById('tblNumber').value = t.table_number;
            document.getElementById('tblName').value = t.table_name || '';
            document.getElementById('tblCapacity').value = t.capacity;
            document.getElementById('tblArea').value = t.area || '';
            document.getElementById('tblStatus').value = t.status;
            document.getElementById('tblActive').checked = t.is_active == 1;
            document.getElementById('tblModalTitle').textContent = 'Edit Table';
            new bootstrap.Modal(document.getElementById('tableModal')).show();
        }
    });
}

document.getElementById('tableForm').addEventListener('submit', function(e) {
    e.preventDefault();
    var formData = new FormData(this);
    formData.append('csrf_token', CSRF_TOKEN);
    fetch(BASE_URL + '/restaurant-admin/tables.php', {method:'POST',body:formData,headers:{'X-Requested-With':'XMLHttpRequest'}})
    .then(function(r){return r.json();})
    .then(function(data){
        if(data.success){showAlert('success',data.message);setTimeout(function(){location.reload();},1000);}
        else{showAlert('danger',data.message);}
    });
});

document.querySelectorAll('.btn-ajax-delete[data-action]').forEach(function(btn) {
    btn.addEventListener('click', function(e) {
        e.preventDefault();
        if (confirm('Delete "' + (this.dataset.name || '') + '"?')) {
            ajaxPost(BASE_URL + '/restaurant-admin/tables.php', 'action=delete_table&id=' + this.dataset.id + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
                if (data.success) { showAlert('success', data.message); setTimeout(function(){location.reload();},1000); }
                else showAlert('danger', data.message);
            });
        }
    });
});
</script>

<?php
if (isset($_GET['action']) && $_GET['action'] === 'generate_qr') {
    $tableId = (int)($_GET['table_id'] ?? 0);
    $existing = $db->query("SELECT id FROM qr_codes WHERE restaurant_id = ? AND table_id = ?", [$restaurantId, $tableId])->fetch();
    if (!$existing) {
        $code = strtoupper($restaurant['code'] . '-' . ($tableId ? 'T' . $tableId : 'R'));
        $url = $baseUrl . '/menu/' . $restaurant['slug'] . ($tableId ? '?table=' . $tableId : '');
        $db->insert('qr_codes', [
            'restaurant_id' => $restaurantId,
            'table_id' => $tableId ?: null,
            'code' => $code,
            'url' => $url,
            'type' => $tableId ? 'table' : 'restaurant',
        ]);
    }
    redirect($baseUrl . '/restaurant-admin/tables.php');
    exit;
}

if (isset($_GET['action']) && $_GET['action'] === 'get_table') {
    $id = (int)($_GET['id'] ?? 0);
    $tbl = $db->query("SELECT * FROM tables WHERE id = ? AND restaurant_id = ?", [$id, $restaurantId])->fetch();
    if ($tbl) jsonResponse(true, 'ok', ['table' => $tbl]);
    jsonResponse(false, 'Not found');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (empty($_POST['csrf_token']) || !$csrf->verify($_POST['csrf_token'])) {
        jsonResponse(false, 'Invalid CSRF token');
    }

    $action = $_POST['action'] ?? '';

    if ($action === 'add_table' || $action === 'edit_table') {
        $id = (int)($_POST['table_id'] ?? 0);
        $tableNumber = trim($_POST['table_number'] ?? '');
        $tableName = trim($_POST['table_name'] ?? '');
        $capacity = max(1, (int)($_POST['capacity'] ?? 4));
        $area = trim($_POST['area'] ?? '');
        $status = $_POST['status'] ?? 'available';
        $isActive = isset($_POST['is_active']) ? 1 : 0;

        if (empty($tableNumber)) jsonResponse(false, 'Table number is required');

        $checkDup = $db->query("SELECT id FROM tables WHERE table_number = ? AND restaurant_id = ? AND id != ?", [$tableNumber, $restaurantId, $id])->fetch();
        if ($checkDup) jsonResponse(false, 'Table number already exists');

        $data = [
            'table_number' => $tableNumber,
            'table_name' => $tableName,
            'capacity' => $capacity,
            'area' => $area,
            'status' => $status,
            'is_active' => $isActive,
        ];

        if ($action === 'add_table') {
            $newId = $db->insert('tables', array_merge($data, ['restaurant_id' => $restaurantId]));
            jsonResponse(true, 'Table added');
        } else {
            $db->update('tables', $data, 'id = ? AND restaurant_id = ?', [$id, $restaurantId]);
            jsonResponse(true, 'Table updated');
        }
    }

    if ($action === 'delete_table') {
        $id = (int)($_POST['id'] ?? 0);
        $db->delete('tables', 'id = ? AND restaurant_id = ?', [$id, $restaurantId]);
        jsonResponse(true, 'Table deleted');
    }
}

require_once __DIR__ . '/includes/footer.php';
