<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Method not allowed', [], 405);
}

$auth = new Auth();
$auth->requireRole(['restaurant_admin', 'restaurant_manager']);
$restaurantId = $auth->restaurantId();

$action = trim($_POST['action'] ?? '');
$db = Database::getInstance();

$csrf = new CSRF();
$token = $_POST[CSRF_TOKEN_NAME] ?? '';
if (!$csrf->verify($token)) {
    jsonResponse(false, 'Invalid security token');
}

switch ($action) {
    case 'save':
        $tableId = (int) ($_POST['id'] ?? 0);
        $tableNumber = trim($_POST['table_number'] ?? '');
        $tableName = trim($_POST['table_name'] ?? '');
        $capacity = (int) ($_POST['capacity'] ?? 4);
        $area = trim($_POST['area'] ?? '');
        $status = trim($_POST['status'] ?? 'available');
        $isActive = isset($_POST['is_active']) ? 1 : 0;

        if (empty($tableNumber)) {
            jsonResponse(false, 'Table number is required');
        }
        if ($capacity <= 0) {
            jsonResponse(false, 'Capacity must be greater than 0');
        }

        $validStatuses = ['available', 'occupied', 'reserved', 'maintenance'];
        if (!in_array($status, $validStatuses)) {
            $status = 'available';
        }

        $existing = $db->query(
            "SELECT id FROM tables WHERE restaurant_id = ? AND table_number = ? AND id != ?",
            [$restaurantId, $tableNumber, $tableId]
        )->fetch();

        if ($existing) {
            jsonResponse(false, 'Table number already exists');
        }

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

        if ($tableId > 0) {
            $db->update('tables', $data, 'id = ? AND restaurant_id = ?', [$tableId, $restaurantId]);
            jsonResponse(true, 'Table updated successfully');
        } else {
            $db->insert('tables', $data);
            jsonResponse(true, 'Table added successfully');
        }
        break;

    case 'get':
        $tableId = (int) ($_POST['id'] ?? 0);
        if ($tableId <= 0) {
            jsonResponse(false, 'Invalid table ID');
        }
        $table = $db->query(
            "SELECT * FROM tables WHERE id = ? AND restaurant_id = ?",
            [$tableId, $restaurantId]
        )->fetch();
        if (!$table) {
            jsonResponse(false, 'Table not found');
        }
        jsonResponse(true, 'Table loaded', ['table' => $table]);
        break;

    case 'delete':
        $tableId = (int) ($_POST['id'] ?? 0);
        if ($tableId <= 0) {
            jsonResponse(false, 'Invalid table ID');
        }
        $db->delete('tables', 'id = ? AND restaurant_id = ?', [$tableId, $restaurantId]);
        jsonResponse(true, 'Table deleted successfully');
        break;

    case 'toggle_active':
        $tableId = (int) ($_POST['id'] ?? 0);
        $isActive = (int) ($_POST['is_active'] ?? 0);
        if ($tableId <= 0) {
            jsonResponse(false, 'Invalid table ID');
        }
        $db->update('tables', ['is_active' => $isActive], 'id = ? AND restaurant_id = ?', [$tableId, $restaurantId]);
        jsonResponse(true, 'Table status updated');
        break;

    default:
        jsonResponse(false, 'Invalid action');
        break;
}
