<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/config.php';

header('Content-Type: application/json; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    jsonResponse(false, 'Invalid request method', [], 405);
}

$auth = new Auth();
if (!$auth->check()) {
    jsonResponse(false, 'Unauthorized', [], 401);
}

$restaurantId = $auth->restaurantId();
if (!$restaurantId) {
    jsonResponse(false, 'No restaurant associated', [], 403);
}

$db = Database::getInstance();
$pdo = $db->getConnection();

$stmt = $pdo->prepare(
    "SELECT t.id, t.table_number, t.table_name, t.capacity, t.area, t.status,
            o.id AS current_order_id, o.order_number, o.order_status, o.grand_total
     FROM tables t
     LEFT JOIN orders o ON t.id = o.table_id
        AND o.order_status IN ('new', 'confirmed', 'preparing', 'ready')
        AND o.is_demo = 0
     WHERE t.restaurant_id = ? AND t.is_active = 1
     ORDER BY CAST(t.table_number AS UNSIGNED), t.table_number"
);
$stmt->execute([$restaurantId]);
$tables = $stmt->fetchAll();

jsonResponse(true, 'Tables loaded', ['tables' => $tables]);
