<?php
/** @var string $baseUrl @var string $assetsUrl @var array $user @var string $active */
/** @var int $backupCount @var string $setupSecret @var string $otpauth @var string $csrf */
/** @var string $flash @var string $error @var array $backupCodes @var bool $emailPending */
$assetsUrl = $assetsUrl ?? rtrim($baseUrl, '/');
$b = rtrim($baseUrl, '/');
$h = static fn ($s) => htmlspecialchars((string) $s, ENT_QUOTES);
$on = $active !== '';
$methodLabel = $active === 'totp' ? 'Authenticator app' : ($active === 'email' ? 'Email codes' : '');
// Pretty-print the base32 secret in groups of 4 for manual entry.
$prettyKey = trim(chunk_split($setupSecret, 4, ' '));
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Two-factor authentication · <?= $h(\PpPhp\Core\Brand::name()) ?></title>
    <?php include constant('BASE_PATH') . '/core/views/favicon.php'; ?>
    <link href="<?= $h($assetsUrl) ?>/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="<?= $h($assetsUrl) ?>/icons/bootstrap-icons.css" rel="stylesheet">
    <?php include constant('BASE_PATH') . '/core/views/theme-head.php'; ?>
    <link href="<?= $h($assetsUrl) ?>/css/account.css?v=<?= (int) @filemtime(constant('BASE_PATH') . '/public/assets/css/account.css') ?>" rel="stylesheet">
    <style>
        /* master enable/disable switch */
        .sec-switch { display:flex; align-items:center; gap:.9rem; padding:1rem 1.15rem; border-radius:16px; margin-bottom:1rem;
                      border:1px solid var(--pp-border,#242a3a); background:color-mix(in srgb, var(--pp-surface,#141824) 60%, transparent); transition:border-color .25s; }
        .sec-switch.on { border-color:color-mix(in srgb,#10b981 45%, var(--pp-border,#242a3a)); }
        .sec-sw-ic { width:2.4rem; height:2.4rem; flex:0 0 auto; display:inline-flex; align-items:center; justify-content:center; border-radius:12px; font-size:1.15rem;
                     color:var(--pp-text-muted,#9aa3b2); background:color-mix(in srgb, var(--pp-text-muted,#9aa3b2) 16%, transparent); transition:.25s; }
        .sec-switch.on .sec-sw-ic { color:#10b981; background:color-mix(in srgb,#10b981 16%,transparent); }
        .sw-copy { flex:1; min-width:0; } .sw-copy b { font-size:.98rem; display:block; } .sw-copy small { color:var(--pp-text-muted,#9aa3b2); font-size:.8rem; }
        .sw-toggle { position:relative; width:52px; height:30px; flex:0 0 auto; display:inline-block; }
        .sw-toggle input { position:absolute; inset:0; width:100%; height:100%; margin:0; opacity:0; cursor:pointer; z-index:2; }
        .sw-track { position:absolute; inset:0; border-radius:999px; background:var(--pp-border,#3a4152); transition:background .22s; }
        .sw-knob  { position:absolute; top:3px; left:3px; width:24px; height:24px; border-radius:50%; background:#fff; box-shadow:0 1px 3px rgba(0,0,0,.45); transition:transform .22s; }
        .sw-toggle input:checked ~ .sw-track { background:linear-gradient(135deg, var(--pp-accent,#6366f1), #8b5cf6); }
        .sw-toggle input:checked ~ .sw-knob  { transform:translateX(22px); }
        .sw-toggle input:focus-visible ~ .sw-track { outline:2px solid var(--pp-accent,#818cf8); outline-offset:2px; }
        .sec-reveal[hidden] { display:none; }
        .sec-reveal { animation:secReveal .28s ease; }
        @keyframes secReveal { from { opacity:0; transform:translateY(-6px); } to { opacity:1; transform:none; } }
        #secTurnOff.pulse { animation:secPulse 1.4s ease; }
        @keyframes secPulse { 0%,100% { box-shadow:0 0 0 0 transparent; } 30% { box-shadow:0 0 0 3px color-mix(in srgb,#ef4444 45%,transparent); border-color:#ef4444; } }
        @media (prefers-reduced-motion: reduce) { .sec-reveal, #secTurnOff.pulse { animation:none; } }
        .sec-method { position:relative; border:1px solid var(--pp-border,#242a3a); border-radius:16px; padding:1.15rem 1.25rem; margin-bottom:1rem;
                      background:color-mix(in srgb, var(--pp-surface,#141824) 60%, transparent); transition:border-color .2s; }
        .sec-method:hover { border-color:color-mix(in srgb, var(--pp-accent,#6366f1) 35%, var(--pp-border,#242a3a)); }
        .sec-method > h3 { font-size:1rem; font-weight:800; margin:0 0 .2rem; display:flex; align-items:center; gap:.55rem; }
        .sec-method > h3 .sec-mi { width:2rem; height:2rem; flex:0 0 auto; display:inline-flex; align-items:center; justify-content:center;
                    border-radius:9px; font-size:1rem; color:var(--pp-accent,#818cf8); background:color-mix(in srgb,var(--pp-accent,#6366f1) 15%,transparent); }
        .sec-method p { color:var(--pp-text-muted,#9aa3b2); font-size:.85rem; margin:.15rem 0 1rem; line-height:1.5; }
        .sec-rec { font-size:.6rem; font-weight:800; letter-spacing:.06em; text-transform:uppercase; color:var(--pp-accent,#818cf8);
                   background:color-mix(in srgb,var(--pp-accent,#6366f1) 15%,transparent); padding:.14rem .45rem; border-radius:999px; }
        /* QR: frame hugs the (square) canvas; canvas forced to a fixed square so it can't stretch or overflow */
        .sec-qr { display:grid; grid-template-columns:auto 1fr; gap:1.4rem; align-items:center; }
        @media (max-width:540px){ .sec-qr { grid-template-columns:1fr; justify-items:center; text-align:center; } }
        .sec-qr-frame { background:#fff; padding:12px; border-radius:16px; line-height:0; display:inline-block;
                        box-shadow:0 6px 20px rgba(0,0,0,.28); flex:0 0 auto; }
        #secQr { display:block; width:188px; height:188px; }
        #secQr canvas, #secQr img { width:188px !important; height:188px !important; display:block; image-rendering:pixelated; border-radius:2px; }
        .sec-qr-body { min-width:0; width:100%; }
        .sec-key-label { font-size:.7rem; font-weight:700; letter-spacing:.05em; text-transform:uppercase; color:var(--pp-text-muted,#9aa3b2); margin-bottom:.35rem; display:block; }
        .sec-key { font-family:ui-monospace,Menlo,monospace; font-size:1rem; font-weight:600; letter-spacing:.12em; word-break:break-all; color:var(--pp-text,#e5e7eb);
                   background:var(--pp-app-bg,#0b1120); border:1px dashed var(--pp-border,#242a3a); border-radius:10px; padding:.6rem .75rem; text-align:center; }
        .sec-backup { background:var(--pp-app-bg,#0b1120); border:1px solid color-mix(in srgb,#10b981 40%,var(--pp-border,#242a3a)); border-radius:12px; padding:1rem; margin-bottom:1rem; }
        .sec-codes { display:grid; grid-template-columns:repeat(2,1fr); gap:.4rem .9rem; font-family:ui-monospace,monospace; font-size:.95rem; letter-spacing:.05em; margin:.6rem 0; }
        @media (min-width:560px){ .sec-codes{ grid-template-columns:repeat(5,1fr); } }
        .sec-codes span { padding:.25rem .3rem; text-align:center; background:var(--pp-surface,#141824); border-radius:7px; }
    </style>
</head>
<body class="acct-body">
    <header class="acct-top">
        <a class="acct-brand-min" href="<?= $b ?>/projects" aria-label="Home"><?= \PpPhp\Core\Brand::lockup(30) ?></a>
        <div class="acct-top-actions">
            <a href="#" class="acct-back" data-guide-open="secGuide" data-tip="How two-factor works &amp; how to set it up"><i class="bi bi-question-circle"></i> Guide</a>
            <a href="<?= $b ?>/profile" class="acct-back"><i class="bi bi-arrow-left"></i> Profile</a>
            <?php include constant('BASE_PATH') . '/core/views/theme-toggle.php'; ?>
        </div>
    </header>

    <main class="acct-main">
        <div class="acct-card">
            <div class="acct-head">
                <div class="acct-avatar"><i class="bi bi-shield-lock"></i></div>
                <div class="acct-head-copy">
                    <div class="acct-eyebrow">Account security</div>
                    <h1 class="acct-title">Two-factor authentication</h1>
                    <p class="acct-sub">Add a second step at sign-in so a stolen password isn't enough to get in.</p>
                </div>
            </div>

            <?php if (!empty($flash)): ?>
                <div class="acct-alert is-success"><i class="bi bi-check-circle-fill"></i><span><?= $h($flash) ?></span></div>
            <?php endif; ?>
            <?php if (!empty($error)): ?>
                <div class="acct-alert is-error"><i class="bi bi-exclamation-triangle-fill"></i><span><?= $h($error) ?></span></div>
            <?php endif; ?>

            <div class="sec-switch <?= $on ? 'on' : 'off' ?>">
                <span class="sec-sw-ic"><i class="bi bi-shield-<?= $on ? 'check' : 'lock' ?>"></i></span>
                <div class="sw-copy">
                    <b>Two-factor authentication</b>
                    <small id="secSwState"><?= $on
                        ? 'On · ' . $h($methodLabel) . ' · ' . (int) $backupCount . ' backup code' . ($backupCount === 1 ? '' : 's') . ' left'
                        : 'Off · turn on to add a second step at sign-in' ?></small>
                </div>
                <label class="sw-toggle" title="Enable or disable two-factor authentication">
                    <input type="checkbox" id="sec2faSwitch" <?= $on ? 'checked' : '' ?> aria-label="Toggle two-factor authentication">
                    <span class="sw-track"></span><span class="sw-knob"></span>
                </label>
            </div>

            <div id="secReveal" class="sec-reveal" <?= $on ? '' : 'hidden' ?>>
            <?php if (!empty($backupCodes)): ?>
            <div class="sec-backup">
                <b><i class="bi bi-life-preserver"></i> Your backup codes</b>
                <p class="acct-sub" style="margin:.3rem 0 0">Each code works once if you lose access to your device. Store them somewhere safe — <b>they won't be shown again.</b></p>
                <div class="sec-codes">
                    <?php foreach ($backupCodes as $c): ?><span><?= $h($c) ?></span><?php endforeach; ?>
                </div>
                <button type="button" class="acct-btn acct-btn-ghost" onclick="navigator.clipboard&&navigator.clipboard.writeText(<?= htmlspecialchars(json_encode(implode("\n", $backupCodes)), ENT_QUOTES) ?>);this.innerHTML='<i class=\'bi bi-check2\'></i> Copied'"><i class="bi bi-clipboard"></i> Copy codes</button>
            </div>
            <?php endif; ?>

            <?php if (!$on): ?>
                <!-- ── Setup: authenticator app ── -->
                <div class="sec-method">
                    <h3><span class="sec-mi"><i class="bi bi-phone"></i></span> Authenticator app <span class="sec-rec">recommended</span></h3>
                    <p>Scan the QR code with Google Authenticator, Authy, 1Password or any TOTP app, then enter the 6-digit code it shows.</p>
                    <div class="sec-qr">
                        <div class="sec-qr-frame"><div id="secQr" data-otpauth="<?= $h($otpauth) ?>"></div></div>
                        <div class="sec-qr-body">
                            <span class="sec-key-label"><i class="bi bi-keyboard"></i> Can't scan? Enter this key manually</span>
                            <div class="sec-key"><?= $h($prettyKey) ?></div>
                            <form method="post" action="<?= $b ?>/account/security" style="margin-top:1rem">
                                <input type="hidden" name="_token" value="<?= $h($csrf) ?>">
                                <input type="hidden" name="action" value="enable_totp">
                                <label class="acct-label" for="totpCode">6-digit code from your app</label>
                                <input id="totpCode" name="code" class="acct-input" inputmode="numeric" autocomplete="one-time-code" maxlength="6" placeholder="000000" style="letter-spacing:.4em;font-weight:600" required>
                                <div class="acct-actions" style="margin-top:.8rem">
                                    <button type="submit" class="acct-btn acct-btn-primary"><i class="bi bi-check-lg"></i> Turn on authenticator</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- ── Setup: email codes ── -->
                <div class="sec-method">
                    <h3><span class="sec-mi"><i class="bi bi-envelope-at"></i></span> Email codes</h3>
                    <p>We'll email a 6-digit code to <b><?= $h($user['email'] ?? 'your address') ?></b> each time you sign in.</p>
                    <?php if (!$emailPending): ?>
                    <form method="post" action="<?= $b ?>/account/security">
                        <input type="hidden" name="_token" value="<?= $h($csrf) ?>">
                        <input type="hidden" name="action" value="send_email">
                        <button type="submit" class="acct-btn acct-btn-ghost"><i class="bi bi-send"></i> Email me a test code</button>
                    </form>
                    <?php else: ?>
                    <form method="post" action="<?= $b ?>/account/security">
                        <input type="hidden" name="_token" value="<?= $h($csrf) ?>">
                        <input type="hidden" name="action" value="enable_email">
                        <label class="acct-label" for="emailCode">Enter the code we emailed you</label>
                        <input id="emailCode" name="code" class="acct-input" inputmode="numeric" autocomplete="one-time-code" maxlength="6" placeholder="000000" required>
                        <div class="acct-actions" style="margin-top:.7rem">
                            <button type="submit" class="acct-btn acct-btn-primary"><i class="bi bi-check-lg"></i> Turn on email codes</button>
                        </div>
                    </form>
                    <form method="post" action="<?= $b ?>/account/security" style="margin-top:.5rem">
                        <input type="hidden" name="_token" value="<?= $h($csrf) ?>">
                        <input type="hidden" name="action" value="send_email">
                        <button type="submit" class="acct-linkbtn" style="background:none;border:0;color:var(--pp-accent,#818cf8);cursor:pointer;font-size:.84rem;padding:0"><i class="bi bi-arrow-repeat"></i> Send a new code</button>
                    </form>
                    <?php endif; ?>
                </div>
            <?php else: ?>
                <!-- ── Manage: 2FA is on ── -->
                <div class="sec-method">
                    <h3><span class="sec-mi"><i class="bi bi-life-preserver"></i></span> Backup codes</h3>
                    <p>You have <b><?= (int) $backupCount ?></b> unused backup code<?= $backupCount === 1 ? '' : 's' ?>. Generate a fresh set if you're running low or think they've been exposed.</p>
                    <form method="post" action="<?= $b ?>/account/security">
                        <input type="hidden" name="_token" value="<?= $h($csrf) ?>">
                        <input type="hidden" name="action" value="regen_backup">
                        <button type="submit" class="acct-btn acct-btn-ghost"><i class="bi bi-arrow-repeat"></i> Regenerate backup codes</button>
                    </form>
                </div>

                <div class="sec-method" id="secTurnOff">
                    <h3><span class="sec-mi" style="color:#ef4444;background:color-mix(in srgb,#ef4444 15%,transparent)"><i class="bi bi-shield-slash"></i></span> Turn off two-factor</h3>
                    <p>Confirm your current password to remove the second step. Your account will be protected by password only.</p>
                    <form method="post" action="<?= $b ?>/account/security" onsubmit="return confirm('Turn off two-factor authentication for your account?');">
                        <input type="hidden" name="_token" value="<?= $h($csrf) ?>">
                        <input type="hidden" name="action" value="disable">
                        <label class="acct-label" for="disPw">Current password</label>
                        <input id="disPw" name="password" type="password" class="acct-input" autocomplete="current-password" placeholder="••••••••" required>
                        <div class="acct-actions" style="margin-top:.7rem">
                            <button type="submit" class="acct-btn acct-btn-ghost" style="color:#ef4444;border-color:color-mix(in srgb,#ef4444 45%,transparent)"><i class="bi bi-shield-slash"></i> Turn off two-factor</button>
                        </div>
                    </form>
                </div>
            <?php endif; ?>
            </div><!-- /#secReveal -->
        </div>
    </main>

    <footer class="acct-foot"><?= $h(\PpPhp\Core\Brand::name()) ?><?php $__tg = \PpPhp\Core\Brand::tagline(); if ($__tg !== ''): ?> · <?= $h($__tg) ?><?php endif; ?></footer>
    <script src="<?= $h($assetsUrl) ?>/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
    // Master switch: reveal the setup when turned on; when 2FA is already active,
    // flipping it off can't silently disable (that needs the password) — instead we
    // guide the user to the password-protected "Turn off" card.
    (function () {
        var sw = document.getElementById('sec2faSwitch');
        var reveal = document.getElementById('secReveal');
        var card = document.querySelector('.sec-switch');
        var state = document.getElementById('secSwState');
        var isActive = <?= $on ? 'true' : 'false' ?>;
        if (!sw) { return; }
        sw.addEventListener('change', function () {
            if (isActive) {
                // Keep it visually on; disabling is deliberate + password-gated.
                sw.checked = true;
                var off = document.getElementById('secTurnOff');
                if (off) {
                    off.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    off.classList.add('pulse'); setTimeout(function(){ off.classList.remove('pulse'); }, 1500);
                    var pw = off.querySelector('input[type=password]'); if (pw) { setTimeout(function(){ pw.focus(); }, 400); }
                }
                return;
            }
            reveal.hidden = !sw.checked;
            card.classList.toggle('on', sw.checked);
            if (state) { state.textContent = sw.checked ? 'Choose how you want to receive your second step below' : 'Off · turn on to add a second step at sign-in'; }
            if (sw.checked) { reveal.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); }
        });
    })();
    </script>
    <?php if (!$on): ?>
    <script src="<?= $h($assetsUrl) ?>/js/pp-qr.js?v=<?= (int) @filemtime(constant('BASE_PATH') . '/public/assets/js/pp-qr.js') ?>"></script>
    <script>
    (function () {
        var el = document.getElementById('secQr');
        if (el && window.PPQR && el.dataset.otpauth) {
            try { PPQR.render(el, el.dataset.otpauth, { scale: 5 }); }
            catch (e) { el.innerHTML = '<span style="color:#64748b;font-size:.78rem;padding:1rem;text-align:center">Use the key below to add the account manually.</span>'; }
        }
    })();
    </script>
    <?php endif; ?>
    <?php
    $ownerGuide = [
        'id' => 'secGuide',
        'eyebrow' => 'Account security',
        'title' => 'Two-factor authentication',
        'subtitle' => 'A second step at sign-in so a stolen password alone can\'t get into your account.',
        'icon' => 'shield-lock-fill',
        'topics' => [
            ['id' => 'what', 'label' => 'What it is', 'icon' => 'stars',
             'keywords' => 'overview 2fa two factor totp email why',
             'body' => '<p class="og-lead">Two-factor authentication (2FA) adds a one-time code on top of your password. Even if someone learns your password, they can\'t sign in without your second step.</p>'
                . '<p>Turn it on with the switch at the top of the page — the setup options appear when it\'s on, and stay hidden when it\'s off. Every role can enable it for their own account.</p>'],
            ['id' => 'app', 'label' => 'Authenticator app', 'icon' => 'phone',
             'keywords' => 'authenticator totp google authy 1password qr scan key',
             'body' => '<h3>Recommended — works offline</h3><ol class="og-list">'
                . '<li>Open Google Authenticator, Authy, 1Password or any TOTP app.</li>'
                . '<li>Scan the QR code (or type the key shown beside it if you can\'t scan).</li>'
                . '<li>Enter the 6-digit code the app shows and press <b>Turn on authenticator</b>.</li>'
                . '</ol><div class="og-tip">The code changes every 30 seconds — if it\'s rejected, wait for a fresh one and check your device\'s clock is set to automatic.</div>'],
            ['id' => 'email', 'label' => 'Email codes', 'icon' => 'envelope-at',
             'keywords' => 'email code otp',
             'body' => '<p>Prefer email? Choose <b>Email codes</b> — we send a 6-digit code to your account email each time you sign in. Send yourself a test code, enter it, and it\'s on. (This needs the platform\'s email to be configured under Settings.)</p>'],
            ['id' => 'backup', 'label' => 'Backup codes', 'icon' => 'life-preserver',
             'keywords' => 'backup recovery codes lost device',
             'body' => '<p>When you turn on 2FA you get <b>10 single-use backup codes</b>. Save them somewhere safe — if you ever lose your phone, a backup code gets you in. Each works once; regenerate a fresh set anytime from this page.</p>'
                . '<div class="og-warn">Backup codes are shown only once, at the moment you enable 2FA or regenerate them.</div>'],
            ['id' => 'signin', 'label' => 'Signing in', 'icon' => 'box-arrow-in-right',
             'keywords' => 'login challenge sign in verify',
             'body' => '<p>After 2FA is on, signing in asks for your password, then a verification screen. Enter the code from your app or email — or a backup code if you\'re locked out of your device — and you\'re in.</p>'],
            ['id' => 'off', 'label' => 'Turning it off', 'icon' => 'shield-slash',
             'keywords' => 'disable turn off remove',
             'body' => '<p>To turn 2FA off, confirm your current password in the <b>Turn off two-factor</b> card. Your account then relies on your password alone, so only do this if you plan to switch methods or a device is being retired.</p>'],
        ],
    ];
    include constant('BASE_PATH') . '/core/views/owner-ux.php';
    ?>
</body>
</html>
