<?php
// Live/personal account creation — split out of the old combined
// add-account.php per the Trading Center architectural-separation refactor.
// This page is LIVE ACCOUNT ONLY: no prop firm fields, no challenge type,
// no attempt/continue concept, and no deposit/withdraw/close tools (those
// live in manage-live-accounts.php).
$userId = $auth->requireAuth();

$tcBackUrl = '/traderalign/trading-center?hub=accounts&kind=live';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Add Live Account - TraderAlign</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="/traderalign/assets/tokens.css">
<link rel="icon" type="image/png" sizes="32x32" href="/traderalign/assets/favicon/favicon-32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/traderalign/assets/favicon/favicon-16.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/traderalign/assets/favicon/apple-touch-icon.png">
    <link rel="shortcut icon" href="/traderalign/assets/favicon/favicon.ico">
<link rel="stylesheet" href="/traderalign/assets/css/brand.css">
<style>
.dash-layout{display:flex;min-height:100vh}
.sidebar{width:4rem;background:var(--sidebar);border-right:1px solid var(--sidebar-border);display:flex;flex-direction:column;align-items:center;padding-top:1rem;gap:.25rem;position:fixed;top:0;left:0;bottom:0;z-index:40}
.sidebar a{display:flex;align-items:center;justify-content:center;width:2.75rem;height:2.75rem;border-radius:var(--radius-md);color:var(--foreground-dim);transition:background var(--t-fast),color var(--t-fast);position:relative}
.sidebar a:hover{background:var(--background-surface);color:var(--foreground)}
.sidebar a.active{background:var(--background-surface);color:var(--sidebar-primary)}
.sidebar a .tt{position:absolute;left:3.5rem;background:var(--popover);color:var(--foreground);font-size:.75rem;padding:.25rem .625rem;border-radius:var(--radius-sm);white-space:nowrap;pointer-events:none;opacity:0;transition:opacity var(--t-fast)}
.sidebar a:hover .tt{opacity:1}
.main{margin-left:4rem;flex:1;padding:2rem}
body{background:var(--background);margin:0}
.page-title{font-size:1.5rem;font-weight:700;color:var(--foreground);margin-bottom:.15rem}
.page-sub{color:var(--foreground-muted);font-size:.88rem;margin-bottom:1.5rem;line-height:1.5}
.back-link{font-size:.82rem;color:var(--foreground-dim);margin-bottom:1.25rem;display:inline-flex;align-items:center;gap:.3rem;text-decoration:none}
.back-link:hover{color:var(--primary)}

.form-card{background:var(--background-elevated);border:1px solid var(--border);border-radius:var(--radius-xl);padding:1.5rem;max-width:640px}
.field-group{margin-bottom:1.1rem}
.field-group label{display:block;font-size:.72rem;font-weight:600;text-transform:uppercase;letter-spacing:.05em;color:var(--foreground-dim);margin-bottom:.4rem}
.field-row{display:flex;gap:.75rem}
.field-row .field-group{flex:1}
input[type="text"], input[type="number"], select{
  width:100%;height:2.5rem;padding:0 .75rem;background:var(--background-surface);
  border:1px solid var(--border);border-radius:var(--radius-md);color:var(--foreground);
  font-family:var(--font-sans);font-size:.9rem;outline:none;transition:border-color var(--t-fast);
}
input:focus, select:focus{border-color:var(--primary)}

.form-actions{display:flex;gap:.6rem;justify-content:flex-end;margin-top:1.5rem;padding-top:1.25rem;border-top:1px solid var(--border)}
.error-banner{display:none;background:color-mix(in srgb,var(--negative) 10%,transparent);border:1px solid color-mix(in srgb,var(--negative) 30%,transparent);color:var(--negative);border-radius:var(--radius-md);padding:.6rem .8rem;font-size:.82rem;margin-bottom:1rem}
.error-banner.show{display:block}
.preview-label{font-size:.78rem;color:var(--foreground-dim);margin-top:.5rem}
.preview-label b{color:var(--foreground);font-family:var(--font-mono);font-weight:600}
</style>
</head>
<body class="dash-layout">
<?php include __DIR__ . '/sidebar.php'; ?>

<main class="main">
    <a href="<?= htmlspecialchars($tcBackUrl) ?>" class="back-link">← Back to Live Accounts</a>
    <h1 class="page-title">Add Live Account</h1>
    <p class="page-sub">Create a new personal live trading account.</p>

    <div class="form-card" id="liveAccountForm">
        <div class="error-banner" id="liveErrorBanner"></div>

        <div class="field-row">
            <div class="field-group">
                <label for="brokerName">Broker Name</label>
                <input type="text" id="brokerName" placeholder="e.g., HFM, IC Markets, Exness">
            </div>
            <div class="field-group">
                <label for="accountLabel">Account Label</label>
                <input type="text" id="accountLabel" placeholder="e.g., Main Trading Account">
            </div>
        </div>

        <div class="field-row">
            <div class="field-group">
                <label for="currency">Currency</label>
                <select id="currency" onchange="updateCurrencySymbolLabels()">
                    <?php foreach (CurrencyService::SUPPORTED_CURRENCIES as $code => $cur): ?>
                    <option value="<?= htmlspecialchars($code) ?>" <?= $code === 'USD' ? 'selected' : '' ?>><?= htmlspecialchars($code) ?> - <?= htmlspecialchars($cur['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="field-group">
                <label for="initialDeposit" id="initialDepositLabel">Initial Deposit ($)</label>
                <input type="number" id="initialDeposit" placeholder="1000" min="1" step="any">
            </div>
        </div>

        <div class="field-row">
            <div class="field-group">
                <label for="liveLeverage">Leverage</label>
                <select id="liveLeverage" onchange="handleLiveLeverageSelect()">
                    <option value="1:10">1:10</option>
                    <option value="1:30" selected>1:30</option>
                    <option value="1:50">1:50</option>
                    <option value="1:100">1:100</option>
                    <option value="1:200">1:200</option>
                    <option value="1:500">1:500</option>
                    <option value="__custom__">Custom…</option>
                </select>
                <input type="text" id="liveLeverageCustom" placeholder="e.g. 1:25" style="display:none;margin-top:.5rem">
            </div>
        </div>

        <div class="preview-label" id="livePreviewLabel"></div>

        <div class="form-actions">
            <button class="btn-ghost" onclick="window.location.href='<?= htmlspecialchars($tcBackUrl) ?>'">Cancel</button>
            <button class="btn btn-primary btn-md" onclick="saveLiveAccount()">Save Live Account</button>
        </div>
    </div>
</main>

<script>
// Symbol map sourced from the same server-side CurrencyService::SUPPORTED_CURRENCIES
// list rendered into the <select> above — never a second, independently
// hand-typed currency list.
const CURRENCY_SYMBOLS = <?= json_encode(array_map(fn($c) => $c['symbol'], CurrencyService::SUPPORTED_CURRENCIES)) ?>;
function updateCurrencySymbolLabels() {
    const code = document.getElementById('currency').value;
    const sym = CURRENCY_SYMBOLS[code] || code;
    const label = document.getElementById('initialDepositLabel');
    if (label) label.textContent = 'Initial Deposit (' + sym + ')';
}
updateCurrencySymbolLabels();

function handleLiveLeverageSelect() {
    const sel = document.getElementById('liveLeverage');
    const custom = document.getElementById('liveLeverageCustom');
    if (sel.value === '__custom__') {
        custom.style.display = '';
        custom.value = '';
        custom.focus();
    } else {
        custom.style.display = 'none';
    }
}

function getLiveLeverageValue() {
    const sel = document.getElementById('liveLeverage');
    if (sel.value === '__custom__') {
        return document.getElementById('liveLeverageCustom').value.trim();
    }
    return sel.value;
}

function updateLivePreview() {
    const broker = document.getElementById('brokerName').value.trim();
    const label = document.getElementById('accountLabel').value.trim();

    let previewText = '';
    if (broker && label) {
        previewText = 'Will display as <b>' + broker + ' - ' + label + '</b>';
    } else if (broker) {
        previewText = 'Will display as <b>' + broker + ' - Live Account</b>';
    }
    document.getElementById('livePreviewLabel').innerHTML = previewText;
}
document.getElementById('brokerName').addEventListener('input', updateLivePreview);
document.getElementById('accountLabel').addEventListener('input', updateLivePreview);
document.getElementById('initialDeposit').addEventListener('input', updateLivePreview);

function showLiveError(msg) {
    const el = document.getElementById('liveErrorBanner');
    el.textContent = msg;
    el.classList.add('show');
}
function clearLiveError() {
    document.getElementById('liveErrorBanner').classList.remove('show');
}

async function saveLiveAccount() {
    clearLiveError();

    const brokerName = document.getElementById('brokerName').value.trim();
    const accountLabel = document.getElementById('accountLabel').value.trim();
    const initialDeposit = parseFloat(document.getElementById('initialDeposit').value);
    const currency = document.getElementById('currency').value;
    const leverage = getLiveLeverageValue();

    if (!brokerName) return showLiveError('Broker name is required.');
    if (!accountLabel) return showLiveError('Account label is required.');
    if (!initialDeposit || initialDeposit <= 0) return showLiveError('Enter a valid initial deposit amount.');
    if (!leverage) return showLiveError('Select or enter a leverage value.');

    try {
        const response = await fetch('/traderalign/api/accounts/create', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                account_type: 'personal',
                broker_name: brokerName,
                account_label: accountLabel,
                initial_deposit: initialDeposit,
                currency: currency,
                leverage: leverage,
            }),
        });

        const data = await response.json();

        if (data.error) {
            showLiveError(data.error);
            return;
        }

        // Land on the new account's own Trading Center Account Home, not the
        // old checklist.php page. A brand-new live account always has a NULL
        // execution_model (it's set later from Additional Details), so it
        // always belongs in the "Not Categorized" bucket right after creation.
        window.location.href = '/traderalign/trading-center?hub=accounts&kind=live&view=center&exec=none&account_id=' + encodeURIComponent(data.account_id);
    } catch (err) {
        showLiveError('Failed to save live account. Please try again.');
    }
}
</script>
</body>
</html>
