<?php
// WebTrader - Acceso desde Portal de Cliente
session_start();

// Verificar que el cliente esté autenticado
if (!isset($_SESSION['client_id'])) {
    if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
    require_once BASE_PATH . '/modules/shared/helpers.php';
    header('Location: ' . module_url('client_portal/login.php') . '?message=webtrader_access');
    exit();
}

// Configuración de base de datos
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
require_once BASE_PATH . '/modules/webtrader/finage_api.php';
require_once BASE_PATH . '/config/finage_config.php';
require_once BASE_PATH . '/modules/shared/helpers.php';

$clientId = (int)$_SESSION['client_id'];
$db = Database::getInstance();
$pdo = $db->getConnection();

// Obtener información del cliente
$stmtClient = $pdo->prepare("SELECT id, first_name, last_name, email, status FROM clients WHERE id = ? AND status = 'active'");
$stmtClient->execute([$clientId]);
$client = $stmtClient->fetch();

if (!$client) {
    header('Location: ' . module_url('client_portal/login.php') . '?message=client_not_found');
    exit();
}

// Obtener cuentas activas del cliente
$stmtAccounts = $pdo->prepare("SELECT id, account_type, account_number, currency, balance, status, provider FROM client_accounts WHERE client_id = ? AND status = 'active' ORDER BY account_type DESC, created_at ASC");
$stmtAccounts->execute([$clientId]);
$accounts = $stmtAccounts->fetchAll();

// Configuración del WebTrader para este cliente
$webtraderConfig = [
    'client_id' => $clientId,
    'client_name' => $client['first_name'] . ' ' . $client['last_name'],
    'client_email' => $client['email'],
    'accounts' => $accounts,
    // Configuración de puertos: el cliente construirá la URL del WS dinámicamente
    'websocket_port' => 8082,
    'default_symbols' => array_unique(array_merge([
        'EURUSD','GBPUSD','USDJPY','USDCHF','AUDUSD','USDCAD','NZDUSD','EURJPY'
    ], (array)($finageCfg['stock_symbols'] ?? ['AAPL','MSFT','AMZN','GOOGL','META','TSLA','NVDA','JPM','V','NFLX']))),
    'theme' => 'dark',
    'language' => 'es',
    'demo_mode' => false,
    'mw_refresh_ms' => 500,
    'mw_smooth_steps' => 6
];

// Crear token de sesión para el WebTrader
$sessionToken = bin2hex(random_bytes(32));
$_SESSION['webtrader_token'] = $sessionToken;
$_SESSION['webtrader_config'] = $webtraderConfig;
$_SESSION['client_info'] = $client; // Add client_info to session
// Sincronizar variables de sesión para compatibilidad con endpoints
$_SESSION['client_first_name'] = $client['first_name'] ?? '';
$_SESSION['client_last_name'] = $client['last_name'] ?? '';
$_SESSION['client_status'] = 'active';

// Redirigir al WebTrader con el token (ruta dinámica)
header('Location: ' . module_url('webtrader/index.php') . '?token=' . $sessionToken);
exit();
?>
