<?php
/**
 * API Endpoint: Market Status
 * Obtiene el estado actual del mercado y horarios de trading
 */

session_start();

// Verificar autenticación del cliente
if (!isset($_SESSION['client_id']) || $_SESSION['client_status'] !== 'active') {
    http_response_code(401);
    echo json_encode(['error' => 'No autorizado']);
    exit;
}

// Solo permitir GET
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['error' => 'Método no permitido']);
    exit;
}

header('Content-Type: application/json');

try {
    $currentTime = new DateTime('now', new DateTimeZone('UTC'));
    $marketStatus = getMarketStatus($currentTime);
    
    echo json_encode([
        'success' => true,
        'current_time' => $currentTime->format('Y-m-d H:i:s T'),
        'server_time' => time(),
        'market_status' => $marketStatus,
        'trading_sessions' => getTradingSessions($currentTime),
        'next_session' => getNextTradingSession($currentTime),
        'market_holidays' => getUpcomingHolidays()
    ]);
    
} catch (Exception $e) {
    error_log("Error en market-status.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Error interno del servidor'
    ]);
}

/**
 * Obtener estado actual del mercado
 */
function getMarketStatus($currentTime) {
    $dayOfWeek = (int)$currentTime->format('N'); // 1 = Lunes, 7 = Domingo
    $hour = (int)$currentTime->format('H');
    $minute = (int)$currentTime->format('i');
    $timeInMinutes = $hour * 60 + $minute;
    
    // Mercado cerrado los fines de semana
    if ($dayOfWeek == 6 || $dayOfWeek == 7) { // Sábado o Domingo
        return [
            'status' => 'closed',
            'reason' => 'weekend',
            'message' => 'Mercado cerrado - Fin de semana',
            'next_open' => getNextMarketOpen($currentTime)
        ];
    }
    
    // Horarios de trading principales (UTC)
    $sessions = [
        'sydney' => ['start' => 22 * 60, 'end' => 7 * 60], // 22:00 - 07:00 UTC
        'tokyo' => ['start' => 0 * 60, 'end' => 9 * 60],   // 00:00 - 09:00 UTC
        'london' => ['start' => 8 * 60, 'end' => 17 * 60], // 08:00 - 17:00 UTC
        'new_york' => ['start' => 13 * 60, 'end' => 22 * 60] // 13:00 - 22:00 UTC
    ];
    
    $activeSessions = [];
    $isMarketOpen = false;
    
    foreach ($sessions as $sessionName => $session) {
        $start = $session['start'];
        $end = $session['end'];
        
        // Manejar sesiones que cruzan medianoche
        if ($start > $end) {
            if ($timeInMinutes >= $start || $timeInMinutes <= $end) {
                $activeSessions[] = $sessionName;
                $isMarketOpen = true;
            }
        } else {
            if ($timeInMinutes >= $start && $timeInMinutes <= $end) {
                $activeSessions[] = $sessionName;
                $isMarketOpen = true;
            }
        }
    }
    
    if ($isMarketOpen) {
        return [
            'status' => 'open',
            'message' => 'Mercado abierto',
            'active_sessions' => $activeSessions,
            'volatility' => calculateVolatility($activeSessions),
            'next_close' => getNextMarketClose($currentTime)
        ];
    } else {
        return [
            'status' => 'closed',
            'reason' => 'outside_hours',
            'message' => 'Mercado cerrado - Fuera del horario de trading',
            'next_open' => getNextMarketOpen($currentTime)
        ];
    }
}

/**
 * Obtener sesiones de trading
 */
function getTradingSessions($currentTime) {
    return [
        'sydney' => [
            'name' => 'Sydney',
            'timezone' => 'Australia/Sydney',
            'open_utc' => '22:00',
            'close_utc' => '07:00',
            'status' => isSessionActive('sydney', $currentTime)
        ],
        'tokyo' => [
            'name' => 'Tokyo',
            'timezone' => 'Asia/Tokyo',
            'open_utc' => '00:00',
            'close_utc' => '09:00',
            'status' => isSessionActive('tokyo', $currentTime)
        ],
        'london' => [
            'name' => 'London',
            'timezone' => 'Europe/London',
            'open_utc' => '08:00',
            'close_utc' => '17:00',
            'status' => isSessionActive('london', $currentTime)
        ],
        'new_york' => [
            'name' => 'New York',
            'timezone' => 'America/New_York',
            'open_utc' => '13:00',
            'close_utc' => '22:00',
            'status' => isSessionActive('new_york', $currentTime)
        ]
    ];
}

/**
 * Verificar si una sesión está activa
 */
function isSessionActive($sessionName, $currentTime) {
    $hour = (int)$currentTime->format('H');
    $minute = (int)$currentTime->format('i');
    $timeInMinutes = $hour * 60 + $minute;
    
    $sessions = [
        'sydney' => ['start' => 22 * 60, 'end' => 7 * 60],
        'tokyo' => ['start' => 0 * 60, 'end' => 9 * 60],
        'london' => ['start' => 8 * 60, 'end' => 17 * 60],
        'new_york' => ['start' => 13 * 60, 'end' => 22 * 60]
    ];
    
    if (!isset($sessions[$sessionName])) {
        return false;
    }
    
    $session = $sessions[$sessionName];
    $start = $session['start'];
    $end = $session['end'];
    
    if ($start > $end) {
        return $timeInMinutes >= $start || $timeInMinutes <= $end;
    } else {
        return $timeInMinutes >= $start && $timeInMinutes <= $end;
    }
}

/**
 * Calcular volatilidad basada en sesiones activas
 */
function calculateVolatility($activeSessions) {
    $volatilityLevels = [
        'low' => 1,
        'medium' => 2,
        'high' => 3,
        'very_high' => 4
    ];
    
    $sessionCount = count($activeSessions);
    
    // Overlaps importantes
    $hasLondonNY = in_array('london', $activeSessions) && in_array('new_york', $activeSessions);
    $hasTokyoLondon = in_array('tokyo', $activeSessions) && in_array('london', $activeSessions);
    
    if ($hasLondonNY) {
        return ['level' => 'very_high', 'description' => 'Volatilidad muy alta - Overlap Londres/Nueva York'];
    } elseif ($hasTokyoLondon) {
        return ['level' => 'high', 'description' => 'Volatilidad alta - Overlap Tokyo/Londres'];
    } elseif ($sessionCount >= 2) {
        return ['level' => 'medium', 'description' => 'Volatilidad media - Múltiples sesiones'];
    } elseif ($sessionCount == 1) {
        return ['level' => 'low', 'description' => 'Volatilidad baja - Una sesión activa'];
    } else {
        return ['level' => 'very_low', 'description' => 'Volatilidad muy baja - Mercado cerrado'];
    }
}

/**
 * Obtener próxima apertura del mercado
 */
function getNextMarketOpen($currentTime) {
    $dayOfWeek = (int)$currentTime->format('N');
    
    // Si es fin de semana, próxima apertura es lunes
    if ($dayOfWeek >= 6) {
        $nextMonday = clone $currentTime;
        $nextMonday->modify('next monday 22:00:00');
        return $nextMonday->format('Y-m-d H:i:s T');
    }
    
    // Si es día de semana, buscar próxima sesión
    $nextOpen = clone $currentTime;
    $nextOpen->modify('+1 hour');
    return $nextOpen->format('Y-m-d H:i:s T');
}

/**
 * Obtener próximo cierre del mercado
 */
function getNextMarketClose($currentTime) {
    $nextClose = clone $currentTime;
    $nextClose->modify('+4 hours');
    return $nextClose->format('Y-m-d H:i:s T');
}

/**
 * Obtener próxima sesión de trading
 */
function getNextTradingSession($currentTime) {
    return [
        'name' => 'London',
        'opens_at' => '08:00 UTC',
        'time_until' => '2 horas 15 minutos'
    ];
}

/**
 * Obtener próximos días festivos
 */
function getUpcomingHolidays() {
    return [
        [
            'date' => '2024-12-25',
            'name' => 'Navidad',
            'markets_affected' => ['US', 'EU', 'UK']
        ],
        [
            'date' => '2024-12-26',
            'name' => 'Boxing Day',
            'markets_affected' => ['UK', 'AU']
        ],
        [
            'date' => '2025-01-01',
            'name' => 'Año Nuevo',
            'markets_affected' => ['Global']
        ]
    ];
}
?>