<?php
session_start();
// Incluir helpers para rutas dinámicas antes de validar sesión
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(__DIR__))); }
require_once BASE_PATH . '/modules/shared/helpers.php';

// Verificar si el cliente está logueado
if (!isset($_SESSION['client_id'])) {
    header('Location: ' . module_url('client_portal/login.php'));
    exit();
}

// Variables para el layout
$page_title = 'Dashboard';
$module = 'dashboard';
$action = 'index';

// Preparar datos del cliente y métricas
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

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

// Cuentas del cliente
$stmtAcc = $pdo->prepare("SELECT id, account_type, account_number, currency, balance, status, provider FROM client_accounts WHERE client_id = ? ORDER BY created_at ASC");
$stmtAcc->execute([$clientId]);
$accounts = $stmtAcc->fetchAll();

// Totales
$totalBalance = 0.0; $activeAccounts = 0;
foreach ($accounts as $a) { if (($a['status'] ?? 'active') === 'active') { $totalBalance += (float)$a['balance']; $activeAccounts++; } }

// Sumas de transacciones
$stmtDeps = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM client_transactions WHERE client_id = ? AND type = 'deposit'");
$stmtDeps->execute([$clientId]);
$sumDeposits = (float)$stmtDeps->fetchColumn();

$stmtWds = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM client_transactions WHERE client_id = ? AND type = 'withdrawal'");
$stmtWds->execute([$clientId]);
$sumWithdrawals = (float)$stmtWds->fetchColumn();

// Capturar contenido del dashboard
ob_start();
?>
    <div class="section-header">
        <h2 class="section-title">
            <i class="fas fa-gauge-high"></i>
            Resumen de tu cuenta
        </h2>
        <div class="section-actions">
            <a class="client-action-btn webtrader" href="<?php echo module_url('webtrader/client_access.php'); ?>" target="_blank">
                <i class="fas fa-chart-line"></i>
                WebTrader
            </a>
            <a class="client-action-btn deposit" href="<?php echo module_url('client_portal/deposit.php'); ?>">
                <i class="fas fa-arrow-down"></i>
                Depositar
            </a>
            <a class="client-action-btn withdraw" href="<?php echo module_url('client_portal/withdraw.php'); ?>">
                <i class="fas fa-arrow-up"></i>
                Retirar
            </a>
        </div>
    </div>

    <section class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-wallet"></i></div>
            <div class="stat-content">
                <h3 class="stat-label">Balance total</h3>
                <p class="stat-value"><?php echo number_format($totalBalance, 2); ?> USD</p>
                <p class="stat-change neutral">Suma de cuentas activas</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-arrow-down"></i></div>
            <div class="stat-content">
                <h3 class="stat-label">Depósitos</h3>
                <p class="stat-value"><?php echo number_format($sumDeposits, 2); ?> USD</p>
                <p class="stat-change positive">Últimos movimientos</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-arrow-up"></i></div>
            <div class="stat-content">
                <h3 class="stat-label">Retiros</h3>
                <p class="stat-value"><?php echo number_format($sumWithdrawals, 2); ?> USD</p>
                <p class="stat-change negative">Últimos movimientos</p>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-id-card"></i></div>
            <div class="stat-content">
                <h3 class="stat-label">Cuentas activas</h3>
                <p class="stat-value"><?php echo (int)$activeAccounts; ?></p>
                <p class="stat-change neutral">Demo y Live</p>
            </div>
        </div>
    </section>

    <div class="section-header">
        <h2 class="section-title">
            <i class="fas fa-credit-card"></i>
            Tus cuentas
        </h2>
        <div class="section-actions">
            <a class="client-action-btn" href="<?php echo module_url('client_portal/create_account.php'); ?>">
                <i class="fas fa-plus-circle"></i>
                Crear cuenta
            </a>
        </div>
    </div>

    <section class="accounts-grid">
        <?php if (!empty($accounts)): foreach ($accounts as $acc): 
            $type = strtolower(trim($acc['account_type'] ?? ''));
            $variantClass = ($type === 'live') ? 'account-live' : (($type === 'demo') ? 'account-demo' : '');
            $balancePct = 0; 
            $balanceVal = (float)$acc['balance'];
        ?>
            <div class="account-card premium <?php echo $variantClass; ?>">
                <div class="account-card-header premium">
                    <div class="type-icon">
                        <?php if ($type === 'live'): ?>
                            <i class="fas fa-bolt"></i>
                        <?php elseif ($type === 'demo'): ?>
                            <i class="fas fa-flask"></i>
                        <?php else: ?>
                            <i class="fas fa-user"></i>
                        <?php endif; ?>
                    </div>
                    <div class="account-id">
                        <div class="type-name"><?php echo ucfirst($type ?: 'Cuenta'); ?></div>
                        <span class="account-number">#<?php echo htmlspecialchars($acc['account_number']); ?></span>
                    </div>
                </div>
                <div class="account-card-body">
                    <div class="balance">
                        <div class="label">Balance</div>
                        <div class="value"><?php echo number_format($balanceVal, 2) . ' ' . htmlspecialchars($acc['currency']); ?></div>
                        <div class="balance-bar">
                            <div class="balance-fill" style="width: <?php echo max(0, min(100, $balanceVal / max(1, $totalBalance) * 100)); ?>%"></div>
                        </div>
                    </div>
                    <div class="account-kpis">
                        <span class="kpi-chip"><i class="fas fa-tag"></i> <?php echo ucfirst($type ?: 'Cuenta'); ?></span>
                        <span class="kpi-chip"><i class="fas fa-dollar-sign"></i> <?php echo strtoupper($acc['currency']); ?></span>
                        <?php if (!empty($acc['provider'])): ?>
                            <span class="kpi-chip"><i class="fas fa-server"></i> <?php echo htmlspecialchars($acc['provider']); ?></span>
                        <?php endif; ?>
                        <span class="kpi-chip status <?php echo ($acc['status'] === 'active') ? 'ok' : 'bad'; ?>">
                            <i class="fas fa-circle"></i> <?php echo ucfirst($acc['status']); ?>
                        </span>
                    </div>
                    <div class="account-card-actions">
                        <a class="client-action-btn deposit btn-size-sm" href="<?php echo module_url('client_portal/deposit.php'); ?>?account_id=<?php echo (int)$acc['id']; ?>">
                            <i class="fas fa-arrow-down"></i> Depositar
                        </a>
                        <a class="client-action-btn withdraw btn-size-sm" href="<?php echo module_url('client_portal/withdraw.php'); ?>?account_id=<?php echo (int)$acc['id']; ?>">
                            <i class="fas fa-arrow-up"></i> Retirar
                        </a>
                    </div>
                </div>
            </div>
        <?php endforeach; else: ?>
            <div class="empty-state" style="padding: 1rem; color: var(--text-muted);">
                No tienes cuentas aún.
                <div style="margin-top:8px;">
                    <a class="btn btn-primary btn-size-md" href="<?php echo module_url('client_portal/create_account.php'); ?>">
                        <i class="fas fa-plus-circle"></i> Crear cuenta
                    </a>
                </div>
            </div>
        <?php endif; ?>
    </section>
<?php
$content = ob_get_clean();

// Incluir el nuevo layout del portal de cliente
include __DIR__ . '/layout.php';