<?php
// Portal Cliente - Asistente guiado para crear cuenta
if (session_status() === PHP_SESSION_NONE) { session_start(); }
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/shared/helpers.php';
if (!isset($_SESSION['client_id'])) { header('Location: ' . module_url('client_portal/login.php')); exit(); }

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

// Currencies disponibles (pueden ampliarse desde configuración en el futuro)
function getAllowedCurrencies($pdo) {
    try {
        $stmt = $pdo->prepare("SELECT config_value FROM system_config WHERE config_key = 'allowed_currencies' LIMIT 1");
        $stmt->execute();
        $val = $stmt->fetchColumn();
        if ($val) {
            $arr = json_decode($val, true);
            if (is_array($arr) && count($arr)) {
                return array_values(array_unique(array_map(function($c){ return strtoupper(trim($c)); }, $arr)));
            }
        }
    } catch (Throwable $e) { error_log('getAllowedCurrencies error: ' . $e->getMessage()); }
    return ['USD','EUR','GBP','JPY'];
}

function currencyLabel($code) {
    $map = [
        'USD' => 'USD ($)',
        'EUR' => 'EUR (€)',
        'GBP' => 'GBP (£)',
        'JPY' => 'JPY (¥)',
        'MXN' => 'MXN ($)',
        'AUD' => 'AUD ($)',
        'CAD' => 'CAD ($)',
        'CHF' => 'CHF (Fr)'
    ];
    $code = strtoupper($code);
    return $map[$code] ?? $code;
}

$allowedCurrencyCodes = getAllowedCurrencies($pdo);
$allowedCurrencies = array_map(function($c){ return ['code' => $c, 'label' => currencyLabel($c)]; }, $allowedCurrencyCodes);

function tableExists(PDO $pdo, $tableName) {
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = ?");
        $stmt->execute([$tableName]);
        return (bool)$stmt->fetchColumn();
    } catch (Throwable $e) {
        error_log('tableExists error: ' . $e->getMessage());
        return false;
    }
}

function fetchAccountTypes($pdo) {
    try {
        $stmt = $pdo->prepare("SELECT name, display_name, description, min_deposit, max_leverage, is_active FROM account_types WHERE is_active = 1 ORDER BY min_deposit ASC");
        $stmt->execute();
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        if ($rows && count($rows) > 0) { return $rows; }
    } catch (Throwable $e) {
        error_log('fetchAccountTypes error: ' . $e->getMessage());
    }
    // Fallback si no existe la tabla o está vacía
    return [
        ['name' => 'demo', 'display_name' => 'Cuenta Demo', 'description' => 'Cuenta de práctica con saldo virtual', 'min_deposit' => 0, 'max_leverage' => 500],
        ['name' => 'standard', 'display_name' => 'Cuenta Estándar', 'description' => 'Cuenta real para iniciar', 'min_deposit' => 100, 'max_leverage' => 100],
        ['name' => 'premium', 'display_name' => 'Cuenta Premium', 'description' => 'Mejores condiciones de trading', 'min_deposit' => 1000, 'max_leverage' => 200],
        ['name' => 'vip', 'display_name' => 'Cuenta VIP', 'description' => 'Para traders profesionales', 'min_deposit' => 10000, 'max_leverage' => 500],
    ];
}

function accountNumberExists($pdo, $number) {
    try {
        if (tableExists($pdo, 'trading_accounts')) {
            $exists1 = $pdo->prepare("SELECT 1 FROM trading_accounts WHERE account_number = ? LIMIT 1");
            $exists1->execute([$number]);
            if ($exists1->fetchColumn()) return true;
        }
    } catch (Throwable $e) {
        error_log('accountNumberExists trading_accounts check error: ' . $e->getMessage());
    }
    try {
        if (tableExists($pdo, 'client_accounts')) {
            $exists2 = $pdo->prepare("SELECT 1 FROM client_accounts WHERE account_number = ? LIMIT 1");
            $exists2->execute([$number]);
            return (bool)$exists2->fetchColumn();
        }
    } catch (Throwable $e) {
        error_log('accountNumberExists client_accounts check error: ' . $e->getMessage());
    }
    return false;
}

function generateAccountNumber($pdo, $currency) {
    $prefix = 'TR';
    do {
        $number = $prefix . '-' . strtoupper($currency) . '-' . date('ymd') . '-' . str_pad((string)random_int(0, 999999), 6, '0', STR_PAD_LEFT);
    } while (accountNumberExists($pdo, $number));
    return $number;
}

function getTypeRow($pdo, $typeName) {
    try {
        $stmt = $pdo->prepare("SELECT name, display_name, min_deposit, max_leverage FROM account_types WHERE name = ? LIMIT 1");
        $stmt->execute([$typeName]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) return $row;
    } catch (Throwable $e) { error_log('getTypeRow error: ' . $e->getMessage()); }
    // Fallback
    $defaults = [
        'demo' => ['name' => 'demo', 'display_name' => 'Cuenta Demo', 'min_deposit' => 0, 'max_leverage' => 100],
        'standard' => ['name' => 'standard', 'display_name' => 'Cuenta Estándar', 'min_deposit' => 100, 'max_leverage' => 100],
        'premium' => ['name' => 'premium', 'display_name' => 'Cuenta Premium', 'min_deposit' => 1000, 'max_leverage' => 200],
        'vip' => ['name' => 'vip', 'display_name' => 'Cuenta VIP', 'min_deposit' => 10000, 'max_leverage' => 500],
    ];
    return $defaults[strtolower($typeName)] ?? ['name' => $typeName, 'display_name' => ucfirst($typeName), 'min_deposit' => 0, 'max_leverage' => 100];
}

function createAccount($pdo, $clientId, $typeName, $currency) {
    $type = getTypeRow($pdo, $typeName);
    $leverage = (int)($type['max_leverage'] ?? 100);
    $accountNumber = generateAccountNumber($pdo, $currency);

    $initialBalance = strtolower($typeName) === 'demo' ? 10000.00 : 0.00;
    $equity = $initialBalance;

    try {
        $pdo->beginTransaction();
        // trading_accounts (si existe)
        if (tableExists($pdo, 'trading_accounts')) {
            try {
                $stmtTa = $pdo->prepare("INSERT INTO trading_accounts (client_id, account_type, account_number, balance, equity, margin, free_margin, margin_level, leverage, currency, status, created_at) VALUES (?, ?, ?, ?, ?, 0.00, ?, 0.00, ?, ?, 'active', NOW())");
                $stmtTa->execute([$clientId, $type['name'], $accountNumber, $initialBalance, $equity, $equity, $leverage, strtoupper($currency)]);
            } catch (Throwable $e) {
                // Registrar pero continuar con la creación en client_accounts
                error_log('createAccount trading_accounts insert skipped: ' . $e->getMessage());
            }
        }

        // client_accounts (para que aparezca en Dashboard)
        if (!tableExists($pdo, 'client_accounts')) {
            throw new RuntimeException('Tabla requerida client_accounts no existe.');
        }
        $stmtCa = $pdo->prepare("INSERT INTO client_accounts (client_id, account_type, account_number, currency, balance, provider, status, created_at) VALUES (?, ?, ?, ?, ?, 'internal', 'active', NOW())");
        $stmtCa->execute([$clientId, $type['display_name'], $accountNumber, strtoupper($currency), $initialBalance]);

        $pdo->commit();
        return ['success' => true, 'account_number' => $accountNumber, 'currency' => strtoupper($currency), 'type' => $type['display_name']];
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) { $pdo->rollBack(); }
        error_log('createAccount error: ' . $e->getMessage());
        return ['success' => false, 'error' => 'No se pudo crear la cuenta.'];
    }
}

function fetchAccountTypesForCurrency($pdo, $currency) {
    try {
        $stmt = $pdo->prepare("SELECT at.name, at.display_name, at.description, at.min_deposit, at.max_leverage, COALESCE(map.is_enabled, 1) AS is_enabled
                                 FROM account_types at
                            LEFT JOIN account_type_currency map
                                   ON map.account_type = at.name AND map.currency = ?
                                WHERE at.is_active = 1
                             ORDER BY at.min_deposit ASC");
        $stmt->execute([strtoupper($currency)]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        if ($rows) {
            $rows = array_values(array_filter($rows, function($r){ return (int)$r['is_enabled'] === 1; }));
            if (count($rows) > 0) { return $rows; }
        }
    } catch (Throwable $e) {
        error_log('fetchAccountTypesForCurrency error: ' . $e->getMessage());
    }
    return [
        ['name' => 'demo', 'display_name' => 'Cuenta Demo', 'description' => 'Cuenta de práctica con saldo virtual', 'min_deposit' => 0, 'max_leverage' => 500],
        ['name' => 'standard', 'display_name' => 'Cuenta Estándar', 'description' => 'Cuenta real para iniciar', 'min_deposit' => 100, 'max_leverage' => 100],
        ['name' => 'premium', 'display_name' => 'Cuenta Premium', 'description' => 'Mejores condiciones de trading', 'min_deposit' => 1000, 'max_leverage' => 200],
        ['name' => 'vip', 'display_name' => 'Cuenta VIP', 'description' => 'Para traders profesionales', 'min_deposit' => 10000, 'max_leverage' => 500],
    ];
}

$step = $_POST['step'] ?? 'select_currency';
$selectedCurrency = $_POST['currency'] ?? '';
$created = null;

if ($step === 'create_account') {
    $typeName = $_POST['account_type'] ?? '';
    $currency = $_POST['currency'] ?? '';
    if ($typeName && $currency) {
        $created = createAccount($pdo, $clientId, $typeName, $currency);
        $step = 'done';
    } else {
        $step = 'select_currency';
    }
}

$effectiveCurrency = $selectedCurrency ?: ($allowedCurrencyCodes[0] ?? 'USD');
$accountTypes = fetchAccountTypesForCurrency($pdo, $effectiveCurrency);
$stepIndex = 1;
if ($step === 'select_types') { $stepIndex = 2; }
elseif ($step === 'create_account' || $step === 'done') { $stepIndex = 3; }
$progressClass = ($stepIndex === 1) ? 'progress-33' : (($stepIndex === 2) ? 'progress-66' : 'progress-100');
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Crear Cuenta - Trader Room</title>
    <link rel="stylesheet" href="<?php echo asset('public/style.css'); ?>">
    <link rel="stylesheet" href="<?php echo asset('public/client_portal.css'); ?>">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
</head>
<body>
<div class="client-portal-layout">
    <?php include __DIR__ . '/sidebar.php'; ?>
    <div class="client-main-wrapper">
        <header class="client-header">
            <div class="client-header-content">
                <div class="client-header-left">
                    <h1 class="client-page-title">Crear nueva cuenta</h1>
                </div>
            </div>
        </header>
        <main class="client-content account-create">
            <div class="wizard" id="wizardContainer">
                <div class="wizard-bar"><div class="wizard-fill <?= $progressClass ?>"></div></div>
                <div class="wizard-steps">
                    <div class="wizard-step <?= ($stepIndex>=1)?'is-done':'' ?> <?= ($stepIndex===1)?'is-current':'' ?>">
                        <span class="step-index">1</span>
                        <span class="step-title">Divisa</span>
                    </div>
                    <div class="wizard-step <?= ($stepIndex>=2)?'is-done':'' ?> <?= ($stepIndex===2)?'is-current':'' ?>">
                        <span class="step-index">2</span>
                        <span class="step-title">Tipo</span>
                    </div>
                    <div class="wizard-step <?= ($stepIndex>=3)?'is-done':'' ?> <?= ($stepIndex===3)?'is-current':'' ?>">
                        <span class="step-index">3</span>
                        <span class="step-title">Confirmación</span>
                    </div>
                </div>
            </div>
            <section class="card" id="accountCreateContent">
                <div class="card-body">
                    <?php if ($step === 'select_currency'): ?>
                        <h3>1. Selecciona la divisa</h3>
                        <form method="post" class="smooth-form" data-target="#accountCreateContent,#wizardContainer" style="margin-top: 12px;">
                            <input type="hidden" name="step" value="select_types">
                            <div class="form-group">
                                <label class="form-label" for="currency">Divisa</label>
                                <select class="form-control" id="currency" name="currency" required>
                                    <?php foreach ($allowedCurrencies as $c): ?>
                                        <option value="<?= htmlspecialchars($c['code']) ?>" <?= $selectedCurrency === $c['code'] ? 'selected' : '' ?>><?= htmlspecialchars($c['label']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-primary btn-size-md">Continuar</button>
                        </form>
                    <?php elseif (($step === 'select_types') || ($step === 'select_currency' && $selectedCurrency)): ?>
                        <?php $selCur = $selectedCurrency ?: ($_POST['currency'] ?? 'USD'); ?>
                        <h3>2. Elige el tipo de cuenta para <?= htmlspecialchars(strtoupper($selCur)) ?></h3>
                        <form method="post" class="smooth-form" data-target="#accountCreateContent,#wizardContainer" style="margin-top: 12px;">
                            <input type="hidden" name="step" value="create_account">
                            <input type="hidden" name="currency" value="<?= htmlspecialchars($selCur) ?>">
                            <div class="account-types-grid">
                                <?php foreach ($accountTypes as $t): ?>
                                    <label class="card selectable-card">
                                        <div class="card-body">
                                            <div style="display:flex; align-items:center; gap:8px;">
                                                <input type="radio" name="account_type" value="<?= htmlspecialchars($t['name']) ?>" required>
                                                <strong><?= htmlspecialchars($t['display_name']) ?></strong>
                                            </div>
                                            <div class="text-muted" style="margin-top:6px; font-size: 14px;"><?= htmlspecialchars($t['description'] ?? '') ?></div>
                                            <div style="margin-top:8px; font-size: 13px;">
                                                Depósito mínimo: <strong><?= number_format((float)($t['min_deposit'] ?? 0), 2) ?></strong><br>
                                                Apalancamiento máximo: <strong><?= (int)($t['max_leverage'] ?? 100) ?>x</strong>
                                            </div>
                                        </div>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                            <button type="submit" class="btn btn-primary btn-size-md" style="margin-top:12px;">Crear cuenta</button>
                        </form>
                    <?php elseif ($step === 'done' && $created && $created['success']): ?>
                        <style>
                            .modal-overlay { position: fixed; inset: 0; background: rgba(0,0,0,.5); display: none; align-items: center; justify-content: center; z-index: 1000; }
                            .modal-overlay.show { display: flex; }
                            .modal-box { background: #fff; border-radius: 12px; width: min(520px, 95vw); box-shadow: 0 10px 30px rgba(0,0,0,.2); overflow: hidden; }
                            .modal-header { padding: 16px 20px; font-weight: 600; font-size: 18px; border-bottom: 1px solid #eee; }
                            .modal-body { padding: 16px 20px; }
                            .modal-actions { padding: 16px 20px; display: flex; gap: 8px; justify-content: flex-end; border-top: 1px solid #eee; }
                        </style>
                        <div id="accountSuccessModal" class="modal-overlay" role="dialog" aria-modal="true">
                            <div class="modal-box">
                                <div class="modal-header">Cuenta creada</div>
                                <div class="modal-body">
                                    <p>Tu cuenta <strong><?= htmlspecialchars($created['type']) ?></strong> en <strong><?= htmlspecialchars($created['currency']) ?></strong> fue creada exitosamente.</p>
                                    <p>Número de cuenta: <strong><?= htmlspecialchars($created['account_number']) ?></strong></p>
                                </div>
                                <div class="modal-actions">
                                    <a class="btn btn-primary" href="<?php echo module_url('client_portal/dashboard.php'); ?>">Ir al Dashboard</a>
                                    <a class="btn" href="<?php echo module_url('webtrader/index.php'); ?>">Ir a WebTrader</a>
                                    <button type="button" class="btn" id="closeModalBtn">Cerrar</button>
                                </div>
                            </div>
                        </div>
                        <script>
                            document.addEventListener('DOMContentLoaded', function () {
                                var overlay = document.getElementById('accountSuccessModal');
                                if (overlay) { overlay.classList.add('show'); }
                                var closeBtn = document.getElementById('closeModalBtn');
                                if (closeBtn && overlay) {
                                    closeBtn.addEventListener('click', function(){ overlay.classList.remove('show'); });
                                }
                            });
                        </script>
                        <div class="alert alert-info" style="margin-top: 12px;">
                            La cuenta fue creada correctamente. Usa las acciones del modal.
                        </div>
                    <?php else: ?>
                        <h3>Error</h3>
                        <p>No se pudo crear la cuenta. Inténtalo nuevamente.</p>
            <a class="btn btn-primary" href="<?php echo module_url('client_portal/create_account.php'); ?>">Volver</a>
                    <?php endif; ?>
                </div>
            </section>
            <script src="<?php echo asset('public/smooth_submit.js'); ?>"></script>
        </main>
    </div>
</div>
</body>
</html>
