<?php
// Live account management — split out of the old combined add-account.php
// per the Trading Center architectural-separation refactor. This page is
// ONLY deposit / withdraw / close tools for existing live accounts. It
// never renders an account-creation form (that's add-live-account.php) and
// it never renders any prop-firm control.
$userId = $auth->requireAuth();

$highlightAccountId = $_GET['account_id'] ?? null;

// 2026-08-17 account-level workflow isolation: this query bypassed
// src/AccountPicker.php's apFetchAccounts() entirely (its own direct,
// unscoped SELECT) — real leak, closed the same way as everywhere else,
// via trading_accounts.workflow_context (migration_add_account_workflow_context.sql).
$manageWorkflowState = ValidationService::getWorkflowState($userId, $db);
$liveAccounts = $db->raw(
    "SELECT id, label, current_balance, lifecycle_display_id, prop_firm_name, currency, initial_deposit
     FROM trading_accounts
     WHERE user_id = :uid
       AND account_type = 'personal'
       AND lifecycle_state = 'active'
       AND workflow_context = :wfctx
       AND deleted_at IS NULL
     ORDER BY created_at DESC",
    [':uid' => $userId, ':wfctx' => $manageWorkflowState]
);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Live Accounts - 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)}

.success-banner{display:none;background:color-mix(in srgb,var(--positive) 10%,transparent);border:1px solid color-mix(in srgb,var(--positive) 30%,transparent);color:var(--positive);border-radius:var(--radius-md);padding:.6rem .8rem;font-size:.82rem;margin-bottom:1rem;max-width:640px}
.success-banner.show{display:block}
.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;max-width:640px}
.error-banner.show{display:block}

.manage-section{max-width:640px}
.manage-section .section-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:1rem}
.manage-section .section-title{font-size:.9rem;font-weight:700;color:var(--foreground)}
.manage-section .section-count{font-size:.72rem;color:var(--foreground-dim);font-family:var(--font-mono)}
.live-account-card{background:var(--background-elevated);border:1px solid var(--border);border-radius:var(--radius-lg);padding:1rem 1.1rem;margin-bottom:.65rem;transition:border-color var(--t-fast),opacity .3s ease,box-shadow var(--t-fast)}
.live-account-card:hover{border-color:color-mix(in srgb,var(--primary) 30%,transparent)}
.live-account-card.highlight{border-color:var(--primary);box-shadow:0 0 0 3px color-mix(in srgb,var(--primary) 18%,transparent)}
.live-account-card .lac-top{display:flex;align-items:center;justify-content:space-between;gap:1rem}
.live-account-card .lac-left{flex:1;min-width:0}
.live-account-card .lac-name{font-size:.85rem;font-weight:600;color:var(--foreground);margin-bottom:.2rem}
.live-account-card .lac-meta{display:flex;align-items:center;gap:.75rem;flex-wrap:wrap}
.live-account-card .lac-balance{font-size:.78rem;font-family:var(--font-mono);color:var(--foreground-muted);font-weight:500}
.live-account-card .lac-id{font-size:.68rem;font-family:var(--font-mono);color:var(--foreground-dim);background:var(--background-surface);padding:.1rem .5rem;border-radius:var(--radius-full)}
.live-account-card .lac-currency{font-size:.65rem;color:var(--foreground-dim);text-transform:uppercase}
.lac-actions{display:flex;align-items:center;gap:.35rem;flex-shrink:0}
.action-btn{font-size:.65rem;font-weight:600;padding:.3rem .6rem;border-radius:var(--radius-md);cursor:pointer;transition:all var(--t-fast);white-space:nowrap;border:1px solid var(--border);background:var(--background-surface);color:var(--foreground-dim)}
.action-btn:hover{background:var(--background-elevated);color:var(--foreground);border-color:color-mix(in srgb,var(--primary) 30%,transparent)}
.deposit-btn{color:var(--positive);border-color:color-mix(in srgb,var(--positive) 25%,transparent);background:color-mix(in srgb,var(--positive) 5%,transparent)}
.deposit-btn:hover{background:color-mix(in srgb,var(--positive) 12%,transparent);border-color:color-mix(in srgb,var(--positive) 40%,transparent);color:var(--positive)}
.withdraw-btn{color:var(--warning);border-color:color-mix(in srgb,var(--warning) 25%,transparent);background:color-mix(in srgb,var(--warning) 5%,transparent)}
.withdraw-btn:hover{background:color-mix(in srgb,var(--warning) 12%,transparent);border-color:color-mix(in srgb,var(--warning) 40%,transparent);color:var(--warning)}
.close-btn{font-size:.65rem;font-weight:600;color:var(--negative);background:color-mix(in srgb,var(--negative) 8%,transparent);border:1px solid color-mix(in srgb,var(--negative) 25%,transparent);padding:.3rem .6rem;border-radius:var(--radius-md);cursor:pointer;transition:all var(--t-fast);white-space:nowrap}
.close-btn:hover{background:color-mix(in srgb,var(--negative) 16%,transparent);border-color:color-mix(in srgb,var(--negative) 45%,transparent)}
.transaction-form{display:none;margin-top:.65rem;padding-top:.65rem;border-top:1px solid var(--border);align-items:center;gap:.5rem;flex-wrap:wrap}
.transaction-form.visible{display:flex}
.transaction-form .tx-label{font-size:.68rem;font-weight:600;color:var(--foreground-dim);text-transform:uppercase;letter-spacing:.04em;white-space:nowrap}
.transaction-form input[type="number"]{width:120px;height:2.1rem;font-size:.82rem;padding:0 .6rem;background:var(--background-surface);border:1px solid var(--border);border-radius:var(--radius-md);color:var(--foreground);font-family:var(--font-sans)}
.transaction-form .tx-confirm-btn{font-size:.68rem;font-weight:600;padding:.3rem .75rem;border-radius:var(--radius-md);cursor:pointer;transition:all var(--t-fast);white-space:nowrap;border:none;color:#fff}
.tx-confirm-btn.deposit{background:var(--positive)}
.tx-confirm-btn.deposit:hover{opacity:.9}
.tx-confirm-btn.withdrawal{background:var(--warning)}
.tx-confirm-btn.withdrawal:hover{opacity:.9}
.tx-confirm-btn:disabled{opacity:.45;cursor:not-allowed}
.tx-cancel-btn{font-size:.68rem;font-weight:500;color:var(--foreground-dim);background:none;border:none;cursor:pointer;padding:.3rem .5rem}
.tx-cancel-btn:hover{color:var(--foreground)}
.close-dropdown{display:none;margin-top:.65rem;padding-top:.65rem;border-top:1px solid var(--border);flex-direction:column;gap:.5rem}
.close-dropdown.visible{display:flex}
.close-dropdown select{height:2.2rem;font-size:.8rem;background:var(--background-surface);border:1px solid var(--border);border-radius:var(--radius-md);color:var(--foreground);padding:0 .6rem}
.close-confirm-btn{font-size:.72rem;font-weight:600;color:#fff;background:var(--negative);border:none;padding:.35rem .85rem;border-radius:var(--radius-md);cursor:pointer;transition:opacity var(--t-fast);align-self:flex-end}
.close-confirm-btn:hover{opacity:.9}
.close-confirm-btn:disabled{opacity:.45;cursor:not-allowed}
.no-accounts-msg{font-size:.8rem;color:var(--foreground-dim);padding:1.5rem;text-align:center;background:var(--background-elevated);border:1px dashed var(--border);border-radius:var(--radius-lg)}
</style>
</head>
<body class="dash-layout">
<?php include __DIR__ . '/sidebar.php'; ?>

<main class="main">
    <a href="/traderalign/trading-center?hub=accounts&kind=live" class="back-link">← Back to Live Accounts</a>
    <h1 class="page-title">Manage Live Accounts</h1>
    <p class="page-sub">Deposit, withdraw, or close an existing live trading account.</p>

    <div class="success-banner" id="manageSuccessBanner"></div>
    <div class="error-banner" id="manageErrorBanner"></div>

    <div class="manage-section">
        <div class="section-header">
            <span class="section-title">Your Live Accounts</span>
            <span class="section-count" id="liveAccountCount"><?= count($liveAccounts) ?> active</span>
        </div>
        <div id="liveAccountList">
            <?php if (empty($liveAccounts)): ?>
            <div class="no-accounts-msg" id="noAccountsMsg">No active live accounts yet. Add one from the Live Accounts menu.</div>
            <?php else: ?>
            <?php foreach ($liveAccounts as $la):
                $labelParts = explode(' - ', $la['label'], 2);
                $displayBroker = $labelParts[0] ?? $la['label'];
                $displayLabel = $labelParts[1] ?? '';
                $isHighlighted = $highlightAccountId !== null && $highlightAccountId === $la['id'];
            ?>
            <div class="live-account-card<?= $isHighlighted ? ' highlight' : '' ?>" id="lac-<?= htmlspecialchars($la['id']) ?>">
                <div class="lac-top">
                    <div class="lac-left">
                        <div class="lac-name"><?= htmlspecialchars($displayBroker) ?> - <?= htmlspecialchars($displayLabel) ?></div>
                        <div class="lac-meta">
                            <span class="lac-balance" id="balance-<?= htmlspecialchars($la['id']) ?>">$<?= number_format((float)($la['current_balance'] ?? 0), 2) ?></span>
                            <span class="lac-currency"><?= htmlspecialchars($la['currency'] ?? 'USD') ?></span>
                            <span class="lac-id"><?= htmlspecialchars($la['lifecycle_display_id'] ?? '') ?></span>
                        </div>
                    </div>
                    <div class="lac-actions">
                        <button class="action-btn deposit-btn" onclick="toggleTransactionForm('<?= htmlspecialchars($la['id']) ?>', 'deposit')" title="Deposit">+ Deposit</button>
                        <button class="action-btn withdraw-btn" onclick="toggleTransactionForm('<?= htmlspecialchars($la['id']) ?>', 'withdrawal')" title="Withdraw">- Withdraw</button>
                        <button class="close-btn" onclick="toggleCloseDropdown('<?= htmlspecialchars($la['id']) ?>')" title="Close Account">Close</button>
                    </div>
                </div>
                <!-- Transaction Form -->
                <div class="transaction-form" id="tx-form-<?= htmlspecialchars($la['id']) ?>">
                    <span class="tx-label" id="tx-label-<?= htmlspecialchars($la['id']) ?>">Deposit</span>
                    <span class="tx-label">$</span>
                    <input type="number" id="tx-amount-<?= htmlspecialchars($la['id']) ?>" placeholder="Amount" min="0.01" step="any">
                    <button class="tx-confirm-btn" id="tx-confirm-<?= htmlspecialchars($la['id']) ?>" onclick="confirmTransaction('<?= htmlspecialchars($la['id']) ?>')">Confirm</button>
                    <button class="tx-cancel-btn" onclick="toggleTransactionForm('<?= htmlspecialchars($la['id']) ?>', null)">Cancel</button>
                </div>
                <!-- Close Dropdown -->
                <div class="close-dropdown" id="close-dd-<?= htmlspecialchars($la['id']) ?>">
                    <select id="outcome-<?= htmlspecialchars($la['id']) ?>">
                        <option value="">Select closure reason...</option>
                        <option value="CAPITAL_DEPLETED">Capital Depleted</option>
                        <option value="FULL_WITHDRAWAL">Full Withdrawal</option>
                        <option value="ACCOUNT_RETIRED">Account Retired</option>
                        <option value="ACCOUNT_MIGRATED">Account Migrated</option>
                        <option value="MANUAL_CLOSURE">Manual Closure</option>
                        <option value="OTHER">Other</option>
                    </select>
                    <button class="close-confirm-btn" onclick="confirmCloseAccount('<?= htmlspecialchars($la['id']) ?>')">Confirm Close</button>
                </div>
            </div>
            <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</main>

<script>
let activeTxType = {};

function showManageSuccess(msg) {
    const el = document.getElementById('manageSuccessBanner');
    el.textContent = msg;
    el.classList.add('show');
    setTimeout(() => el.classList.remove('show'), 4000);
}
function showManageError(msg) {
    const el = document.getElementById('manageErrorBanner');
    el.textContent = msg;
    el.classList.add('show');
    setTimeout(() => el.classList.remove('show'), 5000);
}

function toggleTransactionForm(accountId, type) {
    const form = document.getElementById('tx-form-' + accountId);
    const closeDD = document.getElementById('close-dd-' + accountId);
    const label = document.getElementById('tx-label-' + accountId);
    const confirmBtn = document.getElementById('tx-confirm-' + accountId);
    const amountInput = document.getElementById('tx-amount-' + accountId);

    if (closeDD) closeDD.classList.remove('visible');

    if (!type) {
        form.classList.remove('visible');
        delete activeTxType[accountId];
        return;
    }

    document.querySelectorAll('.transaction-form').forEach(el => {
        if (el.id !== 'tx-form-' + accountId) el.classList.remove('visible');
    });
    document.querySelectorAll('.close-dropdown').forEach(el => el.classList.remove('visible'));

    if (activeTxType[accountId] === type && form.classList.contains('visible')) {
        form.classList.remove('visible');
        delete activeTxType[accountId];
        return;
    }

    activeTxType[accountId] = type;

    if (type === 'deposit') {
        label.textContent = 'Deposit';
        confirmBtn.textContent = 'Deposit';
        confirmBtn.className = 'tx-confirm-btn deposit';
    } else {
        label.textContent = 'Withdraw';
        confirmBtn.textContent = 'Withdraw';
        confirmBtn.className = 'tx-confirm-btn withdrawal';
    }

    amountInput.value = '';
    form.classList.add('visible');
    amountInput.focus();
}

async function confirmTransaction(accountId) {
    const type = activeTxType[accountId];
    if (!type) return;

    const amountInput = document.getElementById('tx-amount-' + accountId);
    const amount = parseFloat(amountInput.value);

    if (!amount || amount <= 0) {
        alert('Please enter a valid amount.');
        amountInput.focus();
        return;
    }

    const confirmBtn = document.getElementById('tx-confirm-' + accountId);
    const originalText = confirmBtn.textContent;
    confirmBtn.disabled = true;
    confirmBtn.textContent = 'Processing...';

    try {
        const response = await fetch('/traderalign/api/accounts/transaction', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ account_id: accountId, type: type, amount: amount }),
        });

        const data = await response.json();

        if (data.error) {
            alert(data.error);
            confirmBtn.disabled = false;
            confirmBtn.textContent = originalText;
            return;
        }

        const balanceEl = document.getElementById('balance-' + accountId);
        if (balanceEl && data.new_balance !== undefined) {
            balanceEl.textContent = '$' + parseFloat(data.new_balance).toLocaleString('en-US', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
        }

        const form = document.getElementById('tx-form-' + accountId);
        form.classList.remove('visible');
        delete activeTxType[accountId];

        const label = type === 'deposit' ? 'Deposit' : 'Withdrawal';
        showManageSuccess(`${label} of $${amount.toFixed(2)} completed successfully.`);

    } catch (err) {
        alert('Failed to process transaction. Please try again.');
        confirmBtn.disabled = false;
        confirmBtn.textContent = originalText;
    }
}

document.addEventListener('keydown', function(e) {
    if (e.key === 'Enter') {
        const visibleForm = document.querySelector('.transaction-form.visible');
        if (visibleForm) {
            const accountId = visibleForm.id.replace('tx-form-', '');
            if (activeTxType[accountId]) {
                confirmTransaction(accountId);
            }
        }
    }
});

function toggleCloseDropdown(accountId) {
    const dd = document.getElementById('close-dd-' + accountId);
    const txForm = document.getElementById('tx-form-' + accountId);

    if (txForm) txForm.classList.remove('visible');
    delete activeTxType[accountId];

    document.querySelectorAll('.close-dropdown').forEach(el => {
        if (el.id !== 'close-dd-' + accountId) el.classList.remove('visible');
    });
    document.querySelectorAll('.transaction-form').forEach(el => el.classList.remove('visible'));

    dd.classList.toggle('visible');
}

async function confirmCloseAccount(accountId) {
    const outcomeSelect = document.getElementById('outcome-' + accountId);
    const outcome = outcomeSelect.value;

    if (!outcome) {
        alert('Please select a closure reason.');
        return;
    }

    const confirmBtn = document.querySelector('#close-dd-' + accountId + ' .close-confirm-btn');
    const originalText = confirmBtn.textContent;
    confirmBtn.disabled = true;
    confirmBtn.textContent = 'Closing...';

    try {
        const response = await fetch('/traderalign/api/accounts/close', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ account_id: accountId, outcome: outcome }),
        });

        const data = await response.json();

        if (data.error) {
            alert(data.error);
            confirmBtn.disabled = false;
            confirmBtn.textContent = originalText;
            return;
        }

        const card = document.getElementById('lac-' + accountId);
        const dd = document.getElementById('close-dd-' + accountId);

        if (card) {
            card.style.opacity = '0';
            setTimeout(() => {
                card.remove();
                if (dd) dd.remove();
                updateLiveAccountCount();
                showManageSuccess('Account closed successfully.');
            }, 300);
        }

    } catch (err) {
        alert('Failed to close account. Please try again.');
        confirmBtn.disabled = false;
        confirmBtn.textContent = originalText;
    }
}

function updateLiveAccountCount() {
    const remainingCards = document.querySelectorAll('.live-account-card').length;
    const countEl = document.getElementById('liveAccountCount');
    if (countEl) {
        countEl.textContent = remainingCards + ' active';
    }

    if (remainingCards === 0) {
        const list = document.getElementById('liveAccountList');
        if (list) {
            list.innerHTML = '<div class="no-accounts-msg" id="noAccountsMsg">No active live accounts yet. Add one from the Live Accounts menu.</div>';
        }
    }
}

document.addEventListener('click', function(e) {
    if (!e.target.closest('.close-dropdown') && !e.target.closest('.close-btn') &&
        !e.target.closest('.transaction-form') && !e.target.closest('.action-btn')) {
        document.querySelectorAll('.close-dropdown').forEach(dd => dd.classList.remove('visible'));
        document.querySelectorAll('.transaction-form').forEach(el => el.classList.remove('visible'));
    }
});

<?php if ($highlightAccountId): ?>
(function () {
    var el = document.getElementById('lac-<?= addslashes(htmlspecialchars($highlightAccountId)) ?>');
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
})();
<?php endif; ?>
</script>
</body>
</html>
