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

if (ob_get_level()) {
    ob_clean();
}

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    http_response_code(200);
    exit();
}

require_once '../config/database.php';

try {
    $pdo = getDBConnection();

    // Fetch tatkal settings
    $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'tatkal_%'");
    $stmt->execute();
    $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

    $tatkalEnabled = ($settings['tatkal_enabled'] ?? '0') === '1';
    $advanceDays = (int)($settings['tatkal_advance_days'] ?? 7);

    if (!$tatkalEnabled) {
        echo json_encode(['success' => true, 'available_dates' => [], 'message' => 'Tatkal booking is disabled']);
        exit();
    }

    $dayNames = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
    $enabledDays = [];
    foreach ($dayNames as $day) {
        $dayKey = 'tatkal_' . $day . '_enabled';
        if (isset($settings[$dayKey]) && $settings[$dayKey] === '1') {
            $enabledDays[] = $day;
        }
    }

    // If no days are specifically enabled, return empty dates
    if (empty($enabledDays)) {
        echo json_encode([
            'success' => true,
            'available_dates' => [],
            'message' => 'No tatkal days are enabled'
        ]);
        exit();
    }

    $availableDates = [];
    $today = new DateTime();
    $today->setTime(0, 0, 0); // Normalize to start of day

    for ($i = 0; $i <= $advanceDays; $i++) {
        $date = clone $today;
        $date->add(new DateInterval('P' . $i . 'D'));
        
        $dayName = strtolower($date->format('l'));
        
        if (in_array($dayName, $enabledDays)) {
            $availableDates[] = [
                'date' => $date->format('Y-m-d'),
                'day_name' => ucfirst($dayName),
                'formatted_date' => $date->format('d M Y'),
                'is_today' => $i === 0
            ];
        }
    }

    echo json_encode(['success' => true, 'available_dates' => $availableDates]);

} catch (Exception $e) {
    error_log("Error in get_tatkal_dates.php: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => 'Error fetching tatkal dates: ' . $e->getMessage()]);
}
?>
