<?php
/**
 * Get Calendar Availability API
 * Returns table availability data for the next 30 days for calendar display
 */

session_start();
header('Content-Type: application/json');
require_once 'config.php';

// Check if user is logged in
if (!isset($_SESSION['user_id']) && !isset($_COOKIE['user_id'])) {
    $user_id = $_COOKIE['user_id'] ?? $_SESSION['user_id'] ?? null;
    if (!$user_id) {
        http_response_code(401);
        echo json_encode(['success' => false, 'message' => 'Unauthorized']);
        exit;
    }
}

try {
    $guests = isset($_GET['guests']) ? intval($_GET['guests']) : 2;
    
    // Get availability for next 30 days
    $availabilityData = [];
    $today = new DateTime();
    
    for ($i = 0; $i < 30; $i++) {
        $date = clone $today;
        $date->modify("+$i days");
        $dateStr = $date->format('Y-m-d');
        $dayOfWeek = $date->format('w'); // 0 = Sunday, 6 = Saturday
        
        // Skip Sundays if restaurant is closed
        if ($dayOfWeek == 0) {
            $availabilityData[$dateStr] = [
                'date' => $dateStr,
                'total_tables' => 0,
                'available_tables' => 0,
                'status' => 'closed',
                'percentage' => 0
            ];
            continue;
        }
        
        // Check available tables for this date (across all time slots: Lunch and Dinner)
        // We'll check if there are any available tables for standard booking times
        $sql = "SELECT 
                    COUNT(DISTINCT rt.id) as total_available
                FROM restaurant_tables rt
                WHERE rt.status != 'merged'
                AND rt.current_capacity >= " . $guests . "
                AND rt.id NOT IN (
                    SELECT tb.table_id 
                    FROM table_bookings tb
                    INNER JOIN bookings b ON tb.booking_id = b.id
                    WHERE DATE(b.booking_date) = '" . $conn->real_escape_string($dateStr) . "'
                    AND b.status NOT IN ('cancelled')
                )";
        
        $result = $conn->query($sql);
        $available = $result ? $result->fetch_assoc()['total_available'] : 0;
        
        // Get total tables count for percentage calculation
        $totalSql = "SELECT COUNT(*) as total FROM restaurant_tables WHERE status != 'merged' AND current_capacity >= " . $guests;
        $totalResult = $conn->query($totalSql);
        $total = $totalResult ? $totalResult->fetch_assoc()['total'] : 10;
        
        $percentage = $total > 0 ? ($available / $total) * 100 : 0;
        
        // Determine status based on availability
        if ($percentage >= 75) {
            $status = 'available';
        } elseif ($percentage >= 25) {
            $status = 'limited';
        } else {
            $status = 'booked';
        }
        
        $availabilityData[$dateStr] = [
            'date' => $dateStr,
            'total_tables' => $total,
            'available_tables' => intval($available),
            'status' => $status,
            'percentage' => round($percentage, 1)
        ];
    }
    
    echo json_encode([
        'success' => true,
        'data' => $availabilityData,
        'guests' => $guests
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>
