<?php
/**
 * API Endpoint: Chart Data (LIVE)
 * Obtiene datos históricos desde Finage API (sin simulación)
 */

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');

require_once __DIR__ . '/../finage_api.php';

try {
    // Parámetros
    $symbol = strtoupper(trim($_GET['symbol'] ?? 'EURUSD'));
    $timeframe = strtoupper(trim($_GET['timeframe'] ?? 'M15'));
    $limit = min(max(intval($_GET['limit'] ?? 100), 1), 1000);

    // Validaciones
    if (!preg_match('/^[A-Z0-9]{3,10}$/', $symbol)) {
        throw new Exception('Símbolo inválido');
    }
    $validTimeframes = ['M1','M5','M15','M30','H1','H4','D1'];
    if (!in_array($timeframe, $validTimeframes)) {
        throw new Exception('Timeframe inválido');
    }

    // Mapear timeframe a intervalos Finage
    $map = [
        'M1' => '1min',
        'M5' => '5min',
        'M15' => '15min',
        'M30' => '30min',
        'H1' => '1hour',
        'H4' => '4hour',
        'D1' => '1day'
    ];
    $interval = $map[$timeframe];

    // Determinar tipo de símbolo (forex/stock/crypto) desde config
    $configPath = dirname(__DIR__, 2) . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'finage_config.php';
    $cfg = file_exists($configPath) ? include $configPath : [];
    $type = 'forex';
    if (!empty($cfg['stock_symbols']) && in_array($symbol, $cfg['stock_symbols'])) {
        $type = 'stock';
    } elseif (!empty($cfg['crypto_symbols']) && in_array($symbol, $cfg['crypto_symbols'])) {
        $type = 'crypto';
    }

    // Llamar a Finage API
    $finage = getFinageAPI();
    if ($interval === '1day') {
        $raw = $finage->getHistoricalData($symbol, $interval, $limit, $type);
    } else {
        $raw = $finage->getIntradayData($symbol, $interval, $limit, $type);
    }

    // Transformar al formato esperado
    $data = [];
    foreach ($raw as $c) {
        $ts = isset($c['time']) ? intval($c['time']) : (isset($c['t']) ? intval($c['t']) : 0);
        if ($ts <= 0) { continue; }
        $data[] = [
            'timestamp' => $ts,
            'datetime' => date('Y-m-d H:i:s', $ts),
            'open' => floatval($c['open'] ?? $c['o'] ?? 0),
            'high' => floatval($c['high'] ?? $c['h'] ?? 0),
            'low' => floatval($c['low'] ?? $c['l'] ?? 0),
            'close' => floatval($c['close'] ?? $c['c'] ?? 0),
            'volume' => intval($c['volume'] ?? $c['v'] ?? 0)
        ];
    }

    echo json_encode([
        'success' => true,
        'symbol' => $symbol,
        'timeframe' => $timeframe,
        'data' => $data,
        'count' => count($data),
        'generated_at' => date('Y-m-d H:i:s')
    ]);
} catch (Exception $e) {
    error_log("Error en chart-data.php: " . $e->getMessage());
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
