<?php
// Clean output buffer and set headers
ob_clean();
header('Content-Type: application/json; charset=utf-8');
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
        $stmt = $pdo->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'tatkal_%'");
        $stmt->execute();
        $settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
        
        // Get individual tatkal day settings
        $tatkalDays = [];
        $daySettings = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
        
        foreach ($daySettings as $day) {
            $dayKey = 'tatkal_' . $day . '_enabled';
            if (isset($settings[$dayKey]) && $settings[$dayKey] === '1') {
                $tatkalDays[] = $day;
            }
        }
        
        // Default tatkal days if none are set
        if (empty($tatkalDays)) {
            $tatkalDays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'];
        }
        
        // Get normal days (fallback)
        $normalDaysQuery = $pdo->prepare("SELECT COALESCE(value, setting_value) FROM settings WHERE setting_key = 'normal_days'");
        $normalDaysQuery->execute();
        $normalDays = json_decode($normalDaysQuery->fetchColumn() ?: '[]', true);
        
        if (empty($normalDays)) {
            $normalDays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
        }
        
        // Build response
        $response = [
            'success' => true,
            'tatkal_enabled' => $settings['tatkal_enabled'] ?? '0',
            'tatkal_price' => $settings['tatkal_price'] ?? '1500',
            'tatkal_slots' => $settings['tatkal_slots'] ?? '10',
            'tatkal_advance_days' => $settings['tatkal_advance_days'] ?? '7',
            'settings' => $settings,
            'tatkal_monday' => $settings['tatkal_monday_enabled'] ?? (in_array('monday', $tatkalDays) ? '1' : '0'),
            'tatkal_tuesday' => $settings['tatkal_tuesday_enabled'] ?? (in_array('tuesday', $tatkalDays) ? '1' : '0'),
            'tatkal_wednesday' => $settings['tatkal_wednesday_enabled'] ?? (in_array('wednesday', $tatkalDays) ? '1' : '0'),
            'tatkal_thursday' => $settings['tatkal_thursday_enabled'] ?? (in_array('thursday', $tatkalDays) ? '1' : '0'),
            'tatkal_friday' => $settings['tatkal_friday_enabled'] ?? (in_array('friday', $tatkalDays) ? '1' : '0'),
            'tatkal_saturday' => $settings['tatkal_saturday_enabled'] ?? (in_array('saturday', $tatkalDays) ? '1' : '0'),
            'tatkal_sunday' => $settings['tatkal_sunday_enabled'] ?? (in_array('sunday', $tatkalDays) ? '1' : '0'),
            'normal_days' => $normalDays,
            'tatkal_days' => $tatkalDays
        ];
        
        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']);
}
?>
