<?php
/**
 * Fix Merged Tables Status
 * Updates merged primary tables from 'merged' status to 'available' 
 * so they can be booked while keeping secondary tables as 'merged'
 */

session_start();
require 'config.php';

header('Content-Type: application/json');

// Check if user is authenticated (admin or manager)
if (!isset($_SESSION['admin_id']) && !isset($_SESSION['manager_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Get all tables with '+' in their name and 'merged' status
// These are primary merged tables that should be 'available' for booking
$query = "SELECT id, table_number, status FROM restaurant_tables 
          WHERE table_number LIKE '%+%' AND status = 'merged'";

$result = $conn->query($query);

if (!$result) {
    echo json_encode(['success' => false, 'message' => 'Database query failed']);
    exit;
}

$affected_tables = [];

while ($table = $result->fetch_assoc()) {
    // Update primary merged tables to 'available' status
    $update_query = "UPDATE restaurant_tables SET status = 'available' WHERE id = " . $table['id'];
    if ($conn->query($update_query)) {
        $affected_tables[] = [
            'id' => $table['id'],
            'name' => $table['table_number'],
            'new_status' => 'available'
        ];
    }
}

echo json_encode([
    'success' => true,
    'message' => 'Fixed ' . count($affected_tables) . ' merged table(s)',
    'affected_tables' => $affected_tables
]);
?>
