<?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)
// Accept manager_id from session or from GET parameter (for client-side authentication)
$manager_id = null;

if (isset($_SESSION['admin_id']) || isset($_SESSION['manager_id'])) {
    // Session-based authentication (admin or manager)
    if (isset($_SESSION['manager_id'])) {
        $manager_id = $_SESSION['manager_id'];
    }
} elseif (isset($_GET['manager_id'])) {
    $manager_id = intval($_GET['manager_id']);
    // Validate the manager exists
    $validateRes = $conn->query("SELECT id FROM managers WHERE id = " . $manager_id . " LIMIT 1");
    if (!$validateRes || $validateRes->num_rows === 0) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        exit;
    }
} else {
    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
]);
?>
