<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
    exit(0);
}

require_once "../config/database.php";

try {
    $pdo = getDBConnection();
    
    // Get available dates for tatkal booking
    $today = new DateTime();
    $today->setTime(0, 0, 0);
    
    // Get tatkal advance days setting
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'tatkal_advance_days'");
    $stmt->execute();
    $advanceDays = (int)$stmt->fetchColumn() ?: 7;
    
    $maxDate = clone $today;
    $maxDate->add(new DateInterval("P{$advanceDays}D"));
    
    $availableDates = [];
    $currentDate = clone $today;
    
    while ($currentDate <= $maxDate) {
        $dayName = strtolower($currentDate->format("l"));
        $daySettingKey = "tatkal_" . $dayName . "_enabled";
        
        // Check if this day is enabled for tatkal
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$daySettingKey]);
        $dayEnabled = $stmt->fetchColumn();
        
        if ($dayEnabled === "1") {
            // Check available slots for this day
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM appointments WHERE appointment_date = ? AND time_slot = 'tatkal'");
            $stmt->execute([$currentDate->format("Y-m-d")]);
            $bookedSlots = $stmt->fetchColumn();
            
            $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'tatkal_slots'");
            $stmt->execute();
            $maxSlots = (int)$stmt->fetchColumn() ?: 5;
            
            if ($bookedSlots < $maxSlots) {
                $availableDates[] = [
                    "date" => $currentDate->format("Y-m-d"),
                    "day_name" => $currentDate->format("l"),
                    "available_slots" => $maxSlots - $bookedSlots,
                    "total_slots" => $maxSlots
                ];
            }
        }
        
        $currentDate->add(new DateInterval("P1D"));
    }
    
    echo json_encode([
        "success" => true,
        "available_dates" => $availableDates,
        "advance_days" => $advanceDays
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => "Error: " . $e->getMessage()
    ]);
}
?>