<?php
session_start();
require 'config.php';

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

// Check admin authentication - commented out since admin uses localStorage
// if (!isset($_SESSION['admin_id'])) {
//     sendResponse(false, 'Unauthorized access', null);
// }

$method = $_SERVER['REQUEST_METHOD'];
$action = isset($_GET['action']) ? $_GET['action'] : '';

switch ($action) {
    case 'list':
        listTables();
        break;
    case 'create':
        createTable();
        break;
    case 'update':
        updateTable();
        break;
    case 'delete':
        deleteTable();
        break;
    case 'get':
        getTable();
        break;
    case 'get_availability':
        getTableAvailability();
        break;
    case 'merge':
        mergeTables();
        break;
    case 'unmerge':
        unmergeTables();
        break;
    case 'get_sections':
        getSections();
        break;
    case 'get_by_capacity':
        getTablesByCapacity();
        break;
    case 'update_capacity':
        updateTableCapacity();
        break;
    default:
        sendResponse(false, 'Invalid action', null);
}

// List all tables with filters
function listTables() {
    global $conn;
    
    $floor = isset($_GET['floor']) ? $_GET['floor'] : '';
    $section = isset($_GET['section']) ? $_GET['section'] : '';
    $status = isset($_GET['status']) ? $_GET['status'] : '';
    $date = isset($_GET['date']) ? $_GET['date'] : ''; // New date parameter for availability filtering
    
    // Exclude merged tables by default (they are dummy records)
    $sql = "SELECT * FROM restaurant_tables WHERE status != 'merged'";
    
    if ($floor) {
        $sql .= " AND floor_level = " . intval($floor);
    }
    if ($section) {
        $sql .= " AND section = '" . $conn->real_escape_string($section) . "'";
    }
    
    // If NO date is provided, filter by status from database
    if (!$date && $status) {
        $sql .= " AND status = '" . $conn->real_escape_string($status) . "'";
    }
    
    $sql .= " ORDER BY floor_level, section, table_number";
    
    error_log("Table listing SQL for date '$date': " . $sql);
    
    $result = $conn->query($sql);
    
    if ($result) {
        $tables = [];
        while ($row = $result->fetch_assoc()) {
            // If date is provided, recalculate status based on bookings for that date
            if ($date) {
                $date_escaped = $conn->real_escape_string($date);
                
                // Check if table is booked on this date
                $booking_check = $conn->query("
                    SELECT COUNT(*) as booking_count FROM table_bookings tb
                    INNER JOIN bookings b ON tb.booking_id = b.id
                    WHERE tb.table_id = " . intval($row['id']) . "
                    AND b.booking_date = '" . $date_escaped . "'
                    AND b.status IN ('pending', 'confirmed', 'checked_in')
                ");
                
                if ($booking_check) {
                    $booking_result = $booking_check->fetch_assoc();
                    if ($booking_result['booking_count'] > 0) {
                        $row['status'] = 'booked';
                    } else {
                        // Table has no booking on this date
                        if ($row['status'] !== 'maintenance') {
                            $row['status'] = 'available';
                        }
                    }
                }
            }
            
            // Apply status filter if date is selected
            if ($date && $status) {
                if ($row['status'] !== $status) {
                    continue; // Skip this table if it doesn't match the status filter
                }
            }
            
            $tables[] = $row;
        }
        
        // Debug logging
        if ($date) {
            error_log("Date: $date | Total tables: " . count($tables) . " | Query: " . json_encode($tables));
        }
        
        sendResponse(true, 'Tables fetched successfully', $tables);
    } else {
        sendResponse(false, 'Error fetching tables: ' . $conn->error, null);
    }
}

// Create new table
function createTable() {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(false, 'POST method required', null);
    }
    
    $data = json_decode(file_get_contents("php://input"), true);
    
    $table_number = isset($data['table_number']) ? $data['table_number'] : '';
    $capacity = isset($data['capacity']) ? intval($data['capacity']) : 4;
    $floor = isset($data['floor_level']) ? intval($data['floor_level']) : 1;
    $section = isset($data['section']) ? $data['section'] : '';
    $notes = isset($data['notes']) ? $data['notes'] : '';
    
    if (!$table_number) {
        sendResponse(false, 'Table number is required', null);
    }
    
    // Check if table already exists
    $check = $conn->query("SELECT id FROM restaurant_tables WHERE table_number = '" . $conn->real_escape_string($table_number) . "'");
    if ($check->num_rows > 0) {
        sendResponse(false, 'Table number already exists', null);
    }
    
    $sql = "INSERT INTO restaurant_tables (table_number, base_capacity, current_capacity, floor_level, section, notes, status) 
            VALUES ('" . $conn->real_escape_string($table_number) . "', " . $capacity . ", " . $capacity . ", " . $floor . ", 
                    '" . $conn->real_escape_string($section) . "', '" . $conn->real_escape_string($notes) . "', 'available')";
    
    if ($conn->query($sql) === TRUE) {
        sendResponse(true, 'Table created successfully', ['id' => $conn->insert_id]);
    } else {
        sendResponse(false, 'Error creating table: ' . $conn->error, null);
    }
}

// Update table details
function updateTable() {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(false, 'POST method required', null);
    }
    
    $data = json_decode(file_get_contents("php://input"), true);
    
    $id = isset($data['id']) ? intval($data['id']) : 0;
    $table_number = isset($data['table_number']) ? $data['table_number'] : null;
    $capacity = isset($data['capacity']) ? intval($data['capacity']) : null;
    $section = isset($data['section']) ? $data['section'] : null;
    $notes = isset($data['notes']) ? $data['notes'] : null;
    $status = isset($data['status']) ? $data['status'] : null;
    
    if (!$id) {
        sendResponse(false, 'Table ID is required', null);
    }
    
    $updates = [];
    if ($table_number !== null) {
        $updates[] = "table_number = '" . $conn->real_escape_string($table_number) . "'";
    }
    if ($capacity !== null) {
        $updates[] = "current_capacity = " . $capacity;
    }
    $floor = isset($data['floor_level']) ? $data['floor_level'] : null;
    if ($floor !== null) {
        $updates[] = "floor_level = " . intval($floor);
    }
    if ($section !== null) {
        $updates[] = "section = '" . $conn->real_escape_string($section) . "'";
    }
    if ($notes !== null) {
        $updates[] = "notes = '" . $conn->real_escape_string($notes) . "'";
    }
    if ($status !== null) {
        $updates[] = "status = '" . $conn->real_escape_string($status) . "'";
    }
    
    if (empty($updates)) {
        sendResponse(false, 'No fields to update', null);
    }
    
    $sql = "UPDATE restaurant_tables SET " . implode(", ", $updates) . " WHERE id = " . $id;
    
    if ($conn->query($sql) === TRUE) {
        sendResponse(true, 'Table updated successfully', null);
    } else {
        sendResponse(false, 'Error updating table: ' . $conn->error, null);
    }
}

// Delete table
function deleteTable() {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(false, 'POST method required', null);
    }
    
    $data = json_decode(file_get_contents("php://input"), true);
    $id = isset($data['id']) ? intval($data['id']) : 0;
    
    if (!$id) {
        sendResponse(false, 'Table ID is required', null);
    }
    
    $sql = "DELETE FROM restaurant_tables WHERE id = " . $id;
    
    if ($conn->query($sql) === TRUE) {
        sendResponse(true, 'Table deleted successfully', null);
    } else {
        sendResponse(false, 'Error deleting table: ' . $conn->error, null);
    }
}

// Get single table details
function getTable() {
    global $conn;
    
    $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if (!$id) {
        sendResponse(false, 'Table ID is required', null);
    }
    
    $sql = "SELECT * FROM restaurant_tables WHERE id = " . $id;
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $table = $result->fetch_assoc();
        sendResponse(true, 'Table fetched successfully', $table);
    } else {
        sendResponse(false, 'Table not found', null);
    }
}

// Get table availability for a specific date and time
function getTableAvailability() {
    global $conn;
    
    $date = isset($_GET['date']) ? $_GET['date'] : '';
    $time = isset($_GET['time']) ? $_GET['time'] : '';
    $guests = isset($_GET['guests']) ? intval($_GET['guests']) : 0;
    
    if (!$date || !$time || !$guests) {
        sendResponse(false, 'Date, time, and guest count required', null);
    }
    
    $sql = "SELECT rt.* FROM restaurant_tables rt
            LEFT JOIN table_bookings tb ON rt.id = tb.table_id
            LEFT JOIN bookings b ON tb.booking_id = b.id
            WHERE rt.status != 'merged' 
            AND rt.current_capacity >= " . $guests . "
            AND (b.id IS NULL OR 
                 (b.booking_date != '" . $conn->real_escape_string($date) . "' OR
                  TIME_FORMAT(b.slot_time, '%H:%i') != '" . $conn->real_escape_string($time) . "'))
            GROUP BY rt.id
            ORDER BY rt.floor_level, rt.section, rt.table_number";
    
    $result = $conn->query($sql);
    
    if ($result) {
        $tables = [];
        while ($row = $result->fetch_assoc()) {
            $tables[] = $row;
        }
        sendResponse(true, 'Available tables fetched', $tables);
    } else {
        sendResponse(false, 'Error fetching availability: ' . $conn->error, null);
    }
}

// Merge tables
function mergeTables() {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(false, 'POST method required', null);
    }
    
    $data = json_decode(file_get_contents("php://input"), true);
    
    $table_ids = isset($data['table_ids']) ? $data['table_ids'] : [];
    
    if (count($table_ids) < 2) {
        sendResponse(false, 'At least 2 tables required to merge', null);
    }
    
    $conn->begin_transaction();
    
    try {
        // Convert to integers
        $table_ids = array_map('intval', $table_ids);
        $ids_str = implode(',', $table_ids);
        
        // Get all table info including status
        $result = $conn->query("SELECT id, table_number, base_capacity, current_capacity, status FROM restaurant_tables WHERE id IN (" . $ids_str . ") ORDER BY id ASC");
        
        $tables = [];
        $total_capacity = 0;
        $table_names = [];
        $table_info = []; // Store both ID and name for unmerging
        $main_table_status = ''; // Store the original status of the main table
        
        while ($row = $result->fetch_assoc()) {
            $tables[] = $row;
            $total_capacity += $row['current_capacity'];
            $table_names[] = $row['table_number'];
            $table_info[] = [
                'id' => $row['id'],
                'name' => $row['table_number'],
                'base_capacity' => $row['base_capacity'],
                'current_capacity' => $row['current_capacity'], // Store current (edited) capacity
                'status' => $row['status'] // Store original status for each table
            ];
            // Store the main table's original status
            if ($row['id'] == $table_ids[0]) {
                $main_table_status = $row['status'];
            }
        }
        
        $main_table_id = $table_ids[0];
        $merged_table_name = implode(' + ', $table_names) . ' (Merged)';
        
        // Store table info for unmerging as JSON with IDs and details
        $merge_info = json_encode($table_info);
        
        // Update main table with combined name and total capacity but keep the original status
        $merged_name_escaped = $conn->real_escape_string($merged_table_name);
        
        // Store notes with properly escaped merge info
        $notes_value = $conn->real_escape_string("Merge Info: " . $merge_info);
        
        // Keep the original status instead of setting it to 'merged'
        $conn->query("UPDATE restaurant_tables SET current_capacity = " . $total_capacity . ", table_number = '" . $merged_name_escaped . "', notes = '" . $notes_value . "' WHERE id = " . $main_table_id);
        
        // Mark other tables as merged and hide them
        for ($i = 1; $i < count($table_ids); $i++) {
            $table_id = $table_ids[$i];
            $conn->query("UPDATE restaurant_tables SET status = 'merged' WHERE id = " . $table_id);
        }
        
        $conn->commit();
        
        // Fetch and return the updated main table
        $main_result = $conn->query("SELECT * FROM restaurant_tables WHERE id = " . $main_table_id);
        $updated_table = $main_result->fetch_assoc();
        
        sendResponse(true, 'Tables merged successfully', [
            'main_table_id' => $main_table_id, 
            'merged_table' => $updated_table,
            'total_capacity' => $total_capacity,
            'merged_ids' => $table_ids
        ]);
    } catch (Exception $e) {
        $conn->rollback();
        sendResponse(false, 'Error merging tables: ' . $e->getMessage(), null);
    }
}

// Unmerge tables
function unmergeTables() {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(false, 'POST method required', null);
    }
    
    $data = json_decode(file_get_contents("php://input"), true);
    
    $main_table_id = isset($data['main_table_id']) ? intval($data['main_table_id']) : 0;
    
    if (!$main_table_id) {
        sendResponse(false, 'Main table ID required', null);
    }
    
    $conn->begin_transaction();
    
    try {
        // Get the main table with merge info in notes
        $main_result = $conn->query("SELECT id, base_capacity, table_number, notes FROM restaurant_tables WHERE id = " . $main_table_id);
        
        if ($main_result->num_rows === 0) {
            sendResponse(false, 'Main table not found', null);
            return;
        }
        
        $main_row = $main_result->fetch_assoc();
        
        // Extract merge info from notes
        $notes = $main_row['notes'];
        $table_info = [];
        
        // Try new format first: Merge Info with full table details including status
        if (preg_match('/Merge Info:\s*(\[[\s\S]*?\])/m', $notes, $matches)) {
            $json_str = $matches[1];
            // Remove escaped quotes if present
            $json_str = str_replace('\"', '"', $json_str);
            $table_info = json_decode($json_str, true);
        } 
        // Fall back to old format: Original tables with just names
        else if (preg_match('/Original tables:\s*(\[[\s\S]*?\])/m', $notes, $matches)) {
            $json_str = $matches[1];
            $json_str = str_replace('\"', '"', $json_str);
            $original_tables = json_decode($json_str, true);
            
            // For old format, we need to reconstruct table info by looking up original table names
            // But we'll need to get the original base capacities from somewhere
            // Since we don't have full info, we'll just restore the names
            if (!empty($original_tables)) {
                foreach ($original_tables as $idx => $table_name) {
                    $table_info[] = [
                        'id' => ($idx === 0) ? $main_table_id : null,
                        'name' => $table_name,
                        'base_capacity' => $main_row['base_capacity'], // Use main table's capacity for first table
                        'status' => 'available' // Default to available for old format
                    ];
                }
            }
        }
        
        // If we don't have stored info, we can't unmerge properly
        if (empty($table_info)) {
            sendResponse(false, 'Merge information not found. Cannot unmerge.', null);
            return;
        }
        
        // Restore each table to its original state
        foreach ($table_info as $info) {
            $table_id = intval($info['id']);
            $original_name = $info['name'];
            // Restore to current_capacity (which includes edits), not base_capacity
            $restore_capacity = isset($info['current_capacity']) ? intval($info['current_capacity']) : intval($info['base_capacity']);
            $original_status = isset($info['status']) ? $info['status'] : 'available'; // Restore original status
            
            $original_name_escaped = $conn->real_escape_string($original_name);
            
            $conn->query("UPDATE restaurant_tables SET table_number = '" . $original_name_escaped . "', current_capacity = " . $restore_capacity . ", status = '" . $conn->real_escape_string($original_status) . "', notes = '' WHERE id = " . $table_id);
            
            if ($conn->error) {
                throw new Exception("Error updating table " . $table_id . ": " . $conn->error);
            }
        }
        
        $conn->commit();
        sendResponse(true, 'Tables unmerged successfully', ['main_table_id' => $main_table_id]);
    } catch (Exception $e) {
        $conn->rollback();
        sendResponse(false, 'Error unmerging tables: ' . $e->getMessage(), null);
    }
}

// Get available sections
function getSections() {
    global $conn;
    
    $result = $conn->query("SELECT DISTINCT section FROM restaurant_tables WHERE section IS NOT NULL AND section != '' ORDER BY section");
    
    $sections = [];
    while ($row = $result->fetch_assoc()) {
        $sections[] = $row['section'];
    }
    
    sendResponse(true, 'Sections fetched', $sections);
}

// Get tables by capacity
function getTablesByCapacity() {
    global $conn;
    
    $capacity = isset($_GET['capacity']) ? intval($_GET['capacity']) : 0;
    
    if (!$capacity) {
        sendResponse(false, 'Capacity is required', null);
    }
    
    $sql = "SELECT * FROM restaurant_tables WHERE current_capacity >= " . $capacity . " AND status = 'available' ORDER BY current_capacity ASC";
    
    $result = $conn->query($sql);
    
    if ($result) {
        $tables = [];
        while ($row = $result->fetch_assoc()) {
            $tables[] = $row;
        }
        sendResponse(true, 'Tables fetched', $tables);
    } else {
        sendResponse(false, 'Error fetching tables: ' . $conn->error, null);
    }
}

// Update table capacity
function updateTableCapacity() {
    global $conn;
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        sendResponse(false, 'POST method required', null);
    }
    
    $data = json_decode(file_get_contents("php://input"), true);
    
    $id = isset($data['id']) ? intval($data['id']) : 0;
    $capacity = isset($data['capacity']) ? intval($data['capacity']) : 0;
    
    if (!$id || !$capacity) {
        sendResponse(false, 'Table ID and capacity required', null);
    }
    
    $sql = "UPDATE restaurant_tables SET current_capacity = " . $capacity . ", base_capacity = " . $capacity . " WHERE id = " . $id;
    
    if ($conn->query($sql) === TRUE) {
        sendResponse(true, 'Capacity updated', null);
    } else {
        sendResponse(false, 'Error updating capacity: ' . $conn->error, null);
    }
}
?>
