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

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

// Database configuration
$host = 'localhost';
$dbname = 'astro_db';
$username = 'root';
$password = '';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    try {
        // Get tatkal settings from tatkal_settings table
        $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM tatkal_settings");
        $stmt->execute();
        $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        
        // Default values
        $response = [
            'success' => true,
            'tatkal_enabled' => $settings['enabled'] ?? '1',
            'tatkal_price' => $settings['price'] ?? '1500',
            'tatkal_slots' => $settings['max_slots'] ?? '10',
            'tatkal_advance_days' => $settings['advance_days'] ?? '7',
            'tatkal_monday' => $settings['monday'] ?? '1',
            'tatkal_tuesday' => $settings['tuesday'] ?? '1',
            'tatkal_wednesday' => $settings['wednesday'] ?? '1',
            'tatkal_thursday' => $settings['thursday'] ?? '1',
            'tatkal_friday' => $settings['friday'] ?? '1',
            'tatkal_saturday' => $settings['saturday'] ?? '1',
            'tatkal_sunday' => $settings['sunday'] ?? '0',
            'start_time' => $settings['start_time'] ?? '09:00',
            'end_time' => $settings['end_time'] ?? '18:00',
            'min_advance_hours' => $settings['min_advance_hours'] ?? '2',
            'max_advance_hours' => $settings['max_advance_hours'] ?? '168'
        ];
        
        echo json_encode($response);
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => 'Error fetching settings: ' . $e->getMessage()]);
    }
} else {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
}
?>
