<?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');
        // 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 ot.id) as total_available
                FROM online_tables ot
                WHERE ot.status != 'reserved'
                AND ot.current_capacity >= " . $guests . "
                AND ot.id NOT IN (
                    SELECT otb.online_table_id 
                    FROM online_table_bookings otb
                    INNER JOIN bookings b ON otb.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 online_tables WHERE status != 'reserved' 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()
    ]);
}
?>
