<?php
// Bootstrap de sesión y conexión DB para acceso directo
// Evitar warning: "Session cannot be started after headers have already been sent"
// Solo iniciar sesión si no está activa y aún no se enviaron headers
if (session_status() !== PHP_SESSION_ACTIVE && !headers_sent()) {
    session_start();
}

// Inicializar $db para evitar warnings si no se define en el layout
$db = $db ?? null;
if (!isset($db) || !is_object($db)) {
    // Resolver ruta de conexión de forma robusta desde ubicación del módulo
    $basePath = dirname(__DIR__, 2); // .../simple_crm
    $connPath = $basePath . DIRECTORY_SEPARATOR . 'database' . DIRECTORY_SEPARATOR . 'connection.php';
    if (file_exists($connPath)) {
        require_once $connPath;
        if (function_exists('getDB')) {
            $db = getDB();
        }
    }
}

// Obtener información de la cuenta del cliente
$client_id = $_SESSION['client_id'] ?? ($_SESSION['user']['id'] ?? null);
$client_info = $_SESSION['client_info'] ?? null;

// Cargar datos reales si hay conexión DB
if ($db) {
    $account_info = $db->selectOne(
        "SELECT * FROM trading_accounts WHERE client_id = ? AND status = 'active' ORDER BY created_at DESC LIMIT 1",
        [$client_id]
    );

    if (!$account_info) {
        // No crear cuentas demo automáticamente; usar client_accounts como fuente real si existe
        $client_account = $db->selectOne(
            "SELECT * FROM client_accounts WHERE client_id = ? AND status = 'active' ORDER BY created_at DESC LIMIT 1",
            [$client_id]
        );

        if ($client_account) {
            // Mapear campos a la estructura esperada por el frontend
            $account_info = [
                'id' => $client_account['id'],
                'account_number' => $client_account['account_number'] ?? null,
                'account_type' => $client_account['account_type'] ?? 'standard',
                'currency' => $client_account['currency'] ?? 'USD',
                'leverage' => isset($client_account['leverage']) ? (int)$client_account['leverage'] : 100,
                'balance' => isset($client_account['balance']) ? (float)$client_account['balance'] : 0.00,
                // En ausencia de trading_accounts, usar balance como equity inicial y margen 0
                'equity' => isset($client_account['balance']) ? (float)$client_account['balance'] : 0.00,
                'margin' => 0.00,
                'free_margin' => isset($client_account['balance']) ? (float)$client_account['balance'] : 0.00,
            ];
        }
    }

    // Verificar que account_info no sea false; usar estructura vacía con ceros
    if (!$account_info) {
        $account_info = [
            'id' => 0,
            'account_number' => 'N/A',
            'account_type' => 'standard',
            'balance' => 0.00,
            'equity' => 0.00,
            'margin' => 0.00,
            'free_margin' => 0.00,
            'leverage' => 100,
            'currency' => 'USD'
        ];
    }

    // Obtener posiciones abiertas/cerradas y órdenes (solo si existe cuenta en trading_accounts)
    $open_positions = [];
    $closed_positions = [];
    $pending_orders = [];
    if (!empty($account_info['id'])) {
        $open_positions = $db->select(
            "SELECT * FROM trading_positions WHERE account_id = ? AND status = 'open'",
            [$account_info['id']]
        ) ?: [];

        $closed_positions = $db->select(
            "SELECT * FROM trading_positions WHERE account_id = ? AND status = 'closed' ORDER BY closed_at DESC",
            [$account_info['id']]
        ) ?: [];

        $pending_orders = $db->select(
            "SELECT * FROM trading_orders WHERE account_id = ? AND status = 'pending'",
            [$account_info['id']]
        ) ?: [];
    }
} else {
    // Sin DB: usar estructuras vacías sin datos simulados
    $account_info = [
        'id' => 0,
        'account_number' => 'N/A',
        'account_type' => 'standard',
        'balance' => 0.00,
        'equity' => 0.00,
        'margin' => 0.00,
        'free_margin' => 0.00,
        'leverage' => 100,
        'currency' => 'USD'
    ];
    $open_positions = [];
    $pending_orders = [];
}
?>

<div class="webtrader-container">
    <!-- Trading Controls eliminados por solicitud -->

    <!-- Contenido principal con layout en grid tipo Match-Trade -->
    <div class="webtrader-grid">
        <!-- Sidebar izquierda: Market Watch -->
        <aside class="left-sidebar" aria-label="Market Watch">
            <div class="market-watch-container">
                <!-- Header del Market Watch eliminado; se agrega encabezado de columnas -->
                <div class="market-watch luxury" id="market-watch">
                    <div class="mw-list-header" role="row">
                        <div class="mw-header-empty" aria-hidden="true"></div>
                        <div class="mw-header-col">Símbolo</div>
                        <div class="mw-header-col">Precio</div>
                        <div class="mw-header-col">Diario</div>
                    </div>
                    <div id="mwList" class="mw-list" role="list" aria-label="Lista de instrumentos">
                        <div id="mwLoader" class="skeleton" aria-hidden="true" style="display:none;height:48px;border-radius:8px;margin:6px 0"></div>
                        <div id="mwAdvOverlay" class="mw-adv-overlay" aria-hidden="true" style="display:none"></div>
                        <!-- Los símbolos se cargarán dinámicamente -->
                    </div>
                </div>
            </div>
        </aside>

        <!-- Panel central: Gráfica y acciones -->
        <section class="center-pane">
            <div class="chart-container">
                <div class="chart-toolbar" role="toolbar" aria-label="Barra de herramientas de la gráfica">
                        <div class="toolbar-group symbol-info">
                            <span id="symbol-flags" class="symbol-flags"></span>
                            <span class="symbol-name" id="current-symbol">EURUSD</span>
                            <span class="symbol-price" id="current-price">1.0850</span>
                            <span class="symbol-change" id="current-change">+0.0012 (+0.11%)</span>
                            <span class="symbol-pnl" id="current-pnl" title="P&L del símbolo">$0.00</span>
                            <span class="symbol-open-count" id="current-open-count" title="Posiciones abiertas del símbolo">(0)</span>
                        </div>
                    
                    <div class="toolbar-group timeframe-selector" aria-label="Selector de timeframe">
                        <span id="tfCurrentLabel" class="sr-only">1M</span>
                        <div class="tf-segmented" aria-label="Acceso rápido a timeframes">
                            <button class="tf-seg-btn" data-tf="1">1M</button>
                            <button class="tf-seg-btn" data-tf="5">5M</button>
                            <button class="tf-seg-btn" data-tf="15">15M</button>
                            <button class="tf-seg-btn" data-tf="30">30M</button>
                            <button class="tf-seg-btn" data-tf="60">1H</button>
                            <button class="tf-seg-btn" data-tf="240">4H</button>
                            <button class="tf-seg-btn" data-tf="1440">1D</button>
                        </div>
                    </div>
                    <div class="toolbar-group chart-tools" aria-label="Herramientas de gráfico">
                        <button class="tool-btn" id="btnZoomIn" title="Acercar">
                            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path fill="currentColor" d="M15.5 14h-.79l-.28-.27A6.471 6.471 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14zm1-7h-2v2H6v2h2v2h2v-2h2V9h-2z"/></svg>
                        </button>
                        <button class="tool-btn" id="btnZoomOut" title="Alejar">
                            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path fill="currentColor" d="M15.5 14h-.79l-.28-.27A6.471 6.471 0 0 0 16 9.5 6.5 6.5 0 1 0 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14zm-3 0h6v-2H6v2z"/></svg>
                        </button>
                        <button class="tool-btn" id="btnPanLeft" title="Pan izquierda">
                            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path fill="currentColor" d="M14 7l-5 5 5 5V7z"/></svg>
                        </button>
                        <button class="tool-btn" id="btnPanRight" title="Pan derecha">
                            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path fill="currentColor" d="M10 17l5-5-5-5v10z"/></svg>
                        </button>
                        <button class="tool-btn" id="btnResetZoom" title="Restablecer vista">
                            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path fill="currentColor" d="M12 5V2L8 6l4 4V7c2.76 0 5 2.24 5 5 0 1.01-.31 1.95-.84 2.74l1.46 1.46A6.96 6.96 0 0 0 19 12c0-3.86-3.14-7-7-7zm-5.16.26A6.96 6.96 0 0 0 5 12c0 3.86 3.14 7 7 7v3l4-4-4-4v3c-2.76 0-5-2.24-5-5 0-1.01.31-1.95.84-2.74L6.38 5.26z"/></svg>
                        </button>
                        <button class="tool-btn" id="btnToggleAutoscale" title="Auto-scale">
                            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path fill="currentColor" d="M4 4h6v2H6v4H4V4zm14 0v6h-2V6h-4V4h6zM4 20v-6h2v4h4v2H4zm16-6v6h-6v-2h4v-4h2z"/></svg>
                        </button>
                        <button class="tool-btn" id="btnToggleCrosshair" title="Crosshair">
                            <svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true"><path fill="currentColor" d="M11 2h2v5h-2V2zm0 15h2v5h-2v-5zM2 11h5v2H2v-2zm15 0h5v2h-5v-2zM12 7a5 5 0 100 10 5 5 0 000-10z"/></svg>
                        </button>
                        <span class="countdown" id="candleCountdown" title="Tiempo restante para cerrar la vela">00:00</span>
                        <div class="candle-progress" id="candleProgress"><div class="fill" style="width:0%"></div></div>
                    </div>
                </div>
                <div class="chart-area">
                    <div class="chart-skeleton skeleton" aria-hidden="true"></div>
                    <canvas id="candlestick-chart" width="800" height="400"></canvas>
                </div>
            </div>

            <!-- Paneles horizontales debajo de la gráfica -->
            <div class="bottom-panels bottom-row">
                <!-- Tabs horizontales para los paneles -->
                <div class="panel-tabs">
                    <div class="sr-only" aria-hidden="true"></div>
                    <div class="panel-tabs-inner" role="tablist" aria-label="Paneles inferiores">
                        <button class="tab-btn active" id="tab-positions" role="tab" aria-selected="true" aria-controls="positions-tab" data-tab="positions" tabindex="0">Abiertas</button>
                        <button class="tab-btn" id="tab-closed" role="tab" aria-selected="false" aria-controls="closed-tab" data-tab="closed" tabindex="0">Cerradas</button>
                        <button class="tab-btn" id="tab-orders" role="tab" aria-selected="false" aria-controls="orders-tab" data-tab="orders" tabindex="0">Órdenes</button>
                        <button class="tab-btn" id="tab-history" role="tab" aria-selected="false" aria-controls="history-tab" data-tab="history" tabindex="0">Historial</button>
                        <button class="tab-btn" id="tab-alerts" role="tab" aria-selected="false" aria-controls="alerts-tab" data-tab="alerts" tabindex="0">Alertas</button>
                    </div>
                </div>

                <!-- Contenido de los paneles -->
                <div class="panels-content">
                    <!-- Contenido de Abiertas -->
                    <div class="tab-content active" id="positions-tab" role="tabpanel" aria-labelledby="tab-positions">
                        <div class="positions-header">
                            <h5>Posiciones Abiertas (<?= count($open_positions) ?>)</h5>
                        </div>
                        <div class="positions-table">
                            <div id="positionsLoader" class="skeleton" aria-hidden="true" style="display:none;height:36px;border-radius:8px;margin:8px 0"></div>
                            <table class="table table-sm" id="positionsTable">
                                <thead>
                                    <tr>
                                        <th class="left">Símbolo</th>
                                        <th class="center">Tipo</th>
                                        <th class="numeric">Volumen</th>
                                        <th class="numeric">Precio apertura</th>
                                        <th class="numeric">Precio actual</th>
                                        <th class="numeric">S/L</th>
                                        <th class="numeric">T/P</th>
                                        <th class="numeric">P&L</th>
                                        <th class="center">Acciones</th>
                                    </tr>
                                </thead>
                                <tbody id="positions-tbody">
                                    <?php foreach ($open_positions as $position): ?>
                                    <tr data-position-id="<?= $position['id'] ?>">
                                        <td class="symbol"><div class="sym-wrap"><span class="sym"><?= $position['symbol'] ?></span><span class="opened-at"><?= $position['opened_at'] ?? '-' ?></span></div></td>
                                        <td><span class="badge badge-<?= $position['type'] == 'buy' ? 'success' : 'danger' ?>"><?= strtoupper($position['type']) ?></span></td>
                                        <td class="numeric"><?= $position['volume'] ?></td>
                                        <td class="numeric"><?= $position['open_price'] ?></td>
                                        <td class="numeric">-</td>
                                        <td class="numeric"><?= $position['stop_loss'] ?: '-' ?></td>
                                        <td class="numeric"><?= $position['take_profit'] ?: '-' ?></td>
                                        <td class="pnl numeric <?= $position['profit'] >= 0 ? 'profit' : 'loss' ?>">
                                            $<?= number_format($position['profit'], 2) ?>
                                        </td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-primary modify-position" data-id="<?= $position['id'] ?>">Modificar</button>
                                            <button class="btn btn-sm btn-outline-danger close-position" data-id="<?= $position['id'] ?>">Cerrar</button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Contenido de Cerradas -->
                    <div class="tab-content" id="closed-tab" role="tabpanel" aria-labelledby="tab-closed">
                        <div class="positions-header">
                            <h5>Operaciones Cerradas (<?= count($closed_positions) ?>)</h5>
                        </div>
                        <div class="positions-table">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Fecha cierre</th>
                                        <th>Símbolo</th>
                                        <th>Tipo</th>
                                        <th>Volumen</th>
                                        <th>Precio apertura</th>
                                        <th>Precio cierre</th>
                                        <th>P&L</th>
                                        <th>Comisión</th>
                                    </tr>
                                </thead>
                                <tbody id="closed-tbody">
                                    <?php foreach ($closed_positions as $position): ?>
                                    <tr data-position-id="<?= $position['id'] ?>">
                                        <td><?= htmlspecialchars($position['closed_at'] ?? '') ?></td>
                                        <td><?= htmlspecialchars($position['symbol']) ?></td>
                                        <td><span class="badge badge-<?= $position['type'] == 'buy' ? 'success' : 'danger' ?>"><?= strtoupper($position['type']) ?></span></td>
                                        <td class="numeric"><?= number_format((float)$position['volume'], 2) ?></td>
                                        <td class="numeric"><?= htmlspecialchars($position['open_price']) ?></td>
                                        <td class="numeric"><?= htmlspecialchars($position['close_price'] ?? '-') ?></td>
                                        <td class="pnl numeric <?= ($position['profit'] ?? 0) >= 0 ? 'profit' : 'loss' ?>">$
                                            <?= number_format((float)($position['profit'] ?? 0), 2) ?>
                                        </td>
                                        <td class="numeric"><?= number_format((float)($position['commission'] ?? 0), 2) ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Contenido de Órdenes -->
                    <div class="tab-content" id="orders-tab" role="tabpanel" aria-labelledby="tab-orders">
                        <div class="orders-header">
                            <h5>Órdenes Pendientes (<?= count($pending_orders) ?>)</h5>
                        </div>
                        <div class="orders-table">
                            <div id="ordersLoader" class="skeleton" aria-hidden="true" style="display:none;height:36px;border-radius:8px;margin:8px 0"></div>
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Símbolo</th>
                                        <th>Tipo</th>
                                        <th>Volumen</th>
                                        <th>Precio</th>
                                        <th>S/L</th>
                                        <th>T/P</th>
                                        <th>Estado</th>
                                        <th>Acciones</th>
                                    </tr>
                                </thead>
                                <tbody id="orders-tbody">
                                    <?php foreach ($pending_orders as $order): ?>
                                    <tr data-order-id="<?= $order['id'] ?>">
                                        <td><?= $order['symbol'] ?></td>
                                        <td><span class="badge badge-info"><?= strtoupper($order['type']) ?></span></td>
                                        <td class="numeric"><?= $order['volume'] ?></td>
                                        <td class="numeric"><?= $order['price'] ?></td>
                                        <td class="numeric"><?= $order['stop_loss'] ?: '-' ?></td>
                                        <td class="numeric"><?= $order['take_profit'] ?: '-' ?></td>
                                        <td><span class="badge badge-warning"><?= strtoupper($order['status']) ?></span></td>
                                        <td>
                                            <button class="btn btn-sm btn-outline-primary modify-order" data-id="<?= $order['id'] ?>">Modificar</button>
                                            <button class="btn btn-sm btn-outline-danger cancel-order" data-id="<?= $order['id'] ?>">Cancelar</button>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Contenido de Historial -->
                    <div class="tab-content" id="history-tab" role="tabpanel" aria-labelledby="tab-history">
                        <div class="history-header">
                            <h5>Historial de Transacciones</h5>
                            <div class="date-filter">
                                <input type="date" class="form-control form-control-sm" id="history-from">
                                <input type="date" class="form-control form-control-sm" id="history-to">
                                <button class="btn btn-sm btn-primary" id="filter-history">Filtrar</button>
                            </div>
                        </div>
                        <div class="history-table">
                            <table class="table table-sm">
                                <thead>
                                    <tr>
                                        <th>Fecha</th>
                                        <th>Símbolo</th>
                                        <th>Tipo</th>
                                        <th>Volumen</th>
                                        <th>Precio</th>
                                        <th>P&L</th>
                                        <th>Comisión</th>
                                    </tr>
                                </thead>
                                <tbody id="history-tbody">
                                    <!-- Se carga dinámicamente -->
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Contenido de Alertas -->
                    <div class="tab-content" id="alerts-tab" role="tabpanel" aria-labelledby="tab-alerts">
                        <div class="alerts-header">
                            <h5>Alertas de Precio</h5>
                            <button class="btn btn-sm btn-primary" id="new-alert-btn">Nueva Alerta</button>
                        </div>
                        <div class="alerts-list" id="alerts-list">
                            <!-- Se carga dinámicamente -->
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </div>
</div>

<!-- Modal para Nueva Orden -->
<div class="modal fade" id="newOrderModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Nueva Orden</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <form id="new-order-form">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Símbolo</label>
                                <select class="form-control" id="order-symbol" required>
                                    <option value="">Seleccionar símbolo</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Tipo de Orden</label>
                                <select class="form-control" id="order-type" required>
                                    <option value="market">Market</option>
                                    <option value="limit">Limit</option>
                                    <option value="stop">Stop</option>
                                    <option value="stop_limit">Stop Limit</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Dirección</label>
                                <div class="btn-group btn-group-toggle w-100" data-toggle="buttons">
                                    <label class="btn btn-outline-success active">
                                        <input type="radio" name="direction" value="buy" checked> BUY
                                    </label>
                                    <label class="btn btn-outline-danger">
                                        <input type="radio" name="direction" value="sell"> SELL
                                    </label>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Volumen</label>
                                <input type="number" class="form-control" id="order-volume" step="0.01" min="0.01" value="0.1" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Precio <span class="text-muted">(para órdenes limit/stop)</span></label>
                                <input type="number" class="form-control" id="order-price" step="0.00001">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Precio Actual</label>
                                <div class="current-prices">
                                    <span class="bid-price">Bid: <span id="current-bid">-</span></span>
                                    <span class="ask-price">Ask: <span id="current-ask">-</span></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Stop Loss</label>
                                <input type="number" class="form-control" id="order-sl" step="0.00001">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Take Profit</label>
                                <input type="number" class="form-control" id="order-tp" step="0.00001">
                            </div>
                        </div>
                    </div>
                    
                    <div class="order-summary">
                        <div class="summary-item">
                            <span>Margin Requerido:</span>
                            <span id="required-margin">$0.00</span>
                        </div>
                        <div class="summary-item">
                            <span>Valor del Pip:</span>
                            <span id="pip-value">$0.00</span>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                <button type="submit" form="new-order-form" class="btn btn-primary">Ejecutar Orden</button>
            </div>
        </div>
    </div>
</div>

<!-- Incluir scripts específicos del webtrader -->


<script>
// Los scripts de WebTrader ya están incluidos en webtrader_layout.php
// No es necesario inicializar aquí ya que se hace automáticamente
console.log('WebTrader content loaded - Account ID:', <?= $account_info['id'] ?>);
</script>
