<?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 all tatkal day settings
    $tatkalDaySettings = [];
    $days = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
    
    foreach ($days as $day) {
        $settingKey = "tatkal_{$day}_enabled";
        $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
        $stmt->execute([$settingKey]);
        $value = $stmt->fetchColumn();
        
        $tatkalDaySettings[$day] = [
            'setting_key' => $settingKey,
            'value' => $value,
            'enabled' => $value === '1'
        ];
    }
    
    // Get tatkal advance days
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'tatkal_advance_days'");
    $stmt->execute();
    $advanceDays = $stmt->fetchColumn();
    
    // Get tatkal slots
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'tatkal_slots'");
    $stmt->execute();
    $maxSlots = $stmt->fetchColumn();
    
    // Get tatkal enabled
    $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = 'tatkal_enabled'");
    $stmt->execute();
    $tatkalEnabled = $stmt->fetchColumn();
    
    echo json_encode([
        "success" => true,
        "tatkal_enabled" => $tatkalEnabled,
        "advance_days" => $advanceDays,
        "max_slots" => $maxSlots,
        "day_settings" => $tatkalDaySettings,
        "enabled_days" => array_filter($tatkalDaySettings, function($day) {
            return $day['enabled'];
        })
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "message" => "Error: " . $e->getMessage()
    ]);
}
?>
