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

// Remove BOM and ensure proper encoding
ob_clean();
header('Cache-Control: no-cache, must-revalidate');

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

try {
    // Get database connection
    $pdo = getDBConnection();
    
    // Get normal days (check both value and setting_value columns)
    $normalDaysQuery = $pdo->prepare("SELECT COALESCE(value, setting_value) FROM settings WHERE setting_key = 'normal_days'");
    $normalDaysQuery->execute();
    $normalDays = json_decode($normalDaysQuery->fetchColumn() ?: '[]', true);
    
    // Get tatkal days (check both value and setting_value columns)
    $tatkalDaysQuery = $pdo->prepare("SELECT COALESCE(value, setting_value) FROM settings WHERE setting_key = 'tatkal_days'");
    $tatkalDaysQuery->execute();
    $tatkalDays = json_decode($tatkalDaysQuery->fetchColumn() ?: '[]', true);
    
    // Default days if not set
    if (empty($normalDays)) {
        $normalDays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
    }
    
    if (empty($tatkalDays)) {
        $tatkalDays = ['monday', 'tuesday', 'wednesday', 'friday'];
    }
    
    // Day mapping
    $dayMapping = [
        'monday' => 'Monday',
        'tuesday' => 'Tuesday',
        'wednesday' => 'Wednesday',
        'thursday' => 'Thursday',
        'friday' => 'Friday',
        'saturday' => 'Saturday',
        'sunday' => 'Sunday'
    ];
    
    // Format response
    $response = [
        'success' => true,
        'normal_days' => $normalDays,
        'tatkal_days' => $tatkalDays,
        'day_mapping' => $dayMapping,
        'normal_days_count' => count($normalDays),
        'tatkal_days_count' => count($tatkalDays),
        'timestamp' => date('Y-m-d H:i:s')
    ];
    
    echo json_encode($response, JSON_UNESCAPED_UNICODE);
    
} catch (Exception $e) {
    error_log("Day settings error: " . $e->getMessage());
    
    echo json_encode([
        'success' => false,
        'message' => 'Error fetching day settings: ' . $e->getMessage(),
        'normal_days' => ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'],
        'tatkal_days' => ['monday', 'tuesday', 'wednesday', 'friday'],
        'timestamp' => date('Y-m-d H:i:s')
    ], JSON_UNESCAPED_UNICODE);
}
?>
