<!DOCTYPE html>
<?php
/* Owner-setup page. Vars: $baseUrl, $assetsUrl, $token, $verified, $pending, $ownerUser */
if (!isset($baseUrl)) $baseUrl = '';
if (!isset($assetsUrl)) $assetsUrl = rtrim($baseUrl, '/') . '/assets';
?>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="robots" content="noindex,nofollow">
    <title><?= htmlspecialchars(\PpPhp\Core\Brand::name()) ?> · Establish Owner</title>
    <?php include constant('BASE_PATH') . '/core/views/favicon.php'; ?>
    <link href="<?= $assetsUrl ?>/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="<?= $assetsUrl ?>/icons/bootstrap-icons.css" rel="stylesheet">
    <?php include constant('BASE_PATH') . '/core/views/theme-head.php'; ?>
    <link href="<?= $assetsUrl ?>/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <script src="<?= $assetsUrl ?>/sweetalert2/sweetalert2.min.js"></script>
    <style>
        body { background: var(--pp-app-bg, #f5f6fa); color: var(--pp-text, #172033); }
        .os-topbar { background: var(--pp-surface, #fff); border-bottom: 1px solid var(--pp-border, #e6e9f0); }
        .os-wrap { max-width: 560px; margin: 2.4rem auto; padding: 0 1rem; }
        .os-card { background: var(--pp-surface, #fff); border: 1px solid var(--pp-border, #e6e9f0); border-radius: 16px; box-shadow: 0 8px 30px rgba(15,23,42,.06); overflow: hidden; }
        .os-head { padding: 1.4rem 1.6rem; background: linear-gradient(135deg, #b45309, #d97706); color: #fff; }
        .os-badge { display: inline-flex; align-items: center; gap: .35rem; font-size: .72rem; font-weight: 700; letter-spacing: .04em; text-transform: uppercase; background: rgba(255,255,255,.18); padding: .2rem .6rem; border-radius: 999px; }
        .os-body { padding: 1.6rem; }
        label { font-size: 12.5px; font-weight: 600; margin: 14px 0 6px; display:block; }
        input { width:100%; padding:11px 12px; border:1px solid var(--pp-border,#e2e8f0); border-radius:10px; font-size:14px; background:var(--pp-surface,#fff); color:var(--pp-text,#172033); }
        .os-code { letter-spacing: 8px; font-size: 20px; text-align:center; font-weight:700; }
        .os-note { display:flex; gap:.6rem; align-items:flex-start; background:var(--pp-surface-soft,#f1f5f9); border:1px solid var(--pp-border,#e2e8f0); border-radius:12px; padding:.8rem 1rem; font-size:.86rem; color:var(--pp-muted,#475569); margin-top:1rem; }
    </style>
</head>
<body>
    <div class="os-topbar py-2">
        <div class="d-flex align-items-center px-3" style="max-width:1100px;margin:0 auto;">
            <a href="<?= $baseUrl ?>/projects" class="text-decoration-none d-flex align-items-center" style="color:inherit;">
                <?= \PpPhp\Core\Brand::lockup(32) ?>
            </a>
            <div class="ms-auto d-flex align-items-center gap-2"><a href="<?= $baseUrl ?>/projects" class="btn btn-sm btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i>Back to Projects</a><?php include constant('BASE_PATH') . '/core/views/theme-toggle.php'; ?></div>
        </div>
    </div>

    <div class="os-wrap">
        <div class="os-card">
            <div class="os-head">
                <div class="os-badge"><i class="bi bi-shield-lock-fill"></i> Platform owner</div>
                <h3 class="mt-2 mb-1"><i class="bi bi-patch-check me-2"></i>Establish the Owner</h3>
                <p class="mb-0" style="opacity:.92;">The owner account (<code style="color:#fff"><?= htmlspecialchars($ownerUser) ?></code>) is created only after verifying the platform owner's email.</p>
            </div>
            <div class="os-body">
            <?php if ($verified): ?>
                <div class="text-center py-3">
                    <div style="font-size:40px;color:#16a34a"><i class="bi bi-check-circle-fill"></i></div>
                    <h5 class="mt-2">Owner already established</h5>
                    <p class="text-muted mb-0">This install already has a verified platform owner. Nothing to do here.</p>
                </div>
            <?php else: ?>
                <p class="text-muted">Establishing the owner is a two-step, email-verified action. A 6-digit code is sent to the platform owner's mailbox — only someone who receives it can complete this.</p>

                <!-- Step 1 -->
                <div id="step1">
                    <button id="btnSend" class="btn btn-warning w-100"><i class="bi bi-envelope-paper me-1"></i>Send verification code</button>
                    <?php if ($pending): ?><p class="text-muted mt-2 mb-0" style="font-size:.84rem">A code was already sent and may still be valid — enter it below, or send a new one.</p><?php endif; ?>
                </div>

                <!-- Step 2 -->
                <div id="step2" class="<?= $pending ? '' : 'd-none' ?>">
                    <label>Verification code</label>
                    <input type="text" id="code" class="os-code" inputmode="numeric" maxlength="6" placeholder="000000" autocomplete="one-time-code">
                    <label>Set the owner password</label>
                    <input type="password" id="password" minlength="10" placeholder="At least 10 characters" autocomplete="new-password">
                    <button id="btnVerify" class="btn btn-primary w-100 mt-3"><i class="bi bi-patch-check me-1"></i>Verify &amp; establish owner</button>
                    <button id="btnResend" class="btn btn-link btn-sm w-100 mt-1 text-decoration-none">Send a new code</button>
                </div>

                <div class="os-note">
                    <i class="bi bi-hdd-network mt-1"></i>
                    <div><strong>No email needed.</strong> Whether or not mail is set up, your 6-digit code is also written to a file on <em>this server</em> at
                        <code><?= htmlspecialchars(\PpPhp\Core\Auth\OwnerVerification::codeFileRelPath()) ?></code> —
                        open it with cPanel File Manager, FTP or SSH and enter the code below. Being able to read that file is what proves you own this server, so it's a safe way to finish setup before email is configured. The owner email is fixed and never taken from this page.</div>
                </div>
            <?php endif; ?>
            </div>
        </div>
    </div>

    <?php if (!$verified): ?>
    <script>
    (function () {
        const token = <?= json_encode($token) ?>;
        const b = <?= json_encode(rtrim($baseUrl, '/')) ?>;
        const step1 = document.getElementById('step1');
        const step2 = document.getElementById('step2');
        const btnSend = document.getElementById('btnSend');
        const btnResend = document.getElementById('btnResend');
        const btnVerify = document.getElementById('btnVerify');

        async function send(btn) {
            const old = btn.innerHTML; btn.disabled = true; btn.innerHTML = 'Sending…';
            try {
                const fd = new URLSearchParams(); fd.set('_token', token);
                const r = await fetch(b + '/platform/owner-setup/send', { method:'POST', credentials:'same-origin', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body: fd.toString() });
                const j = await r.json();
                if (j.success) { step2.classList.remove('d-none'); Swal.fire({icon:'success',title:'Code sent',text:j.message}); }
                else Swal.fire({icon:'error',title:'Could not send',text:j.message||'Error'});
            } catch (e) { Swal.fire({icon:'error',title:'Error',text:String(e)}); }
            finally { btn.disabled = false; btn.innerHTML = old; }
        }
        btnSend.addEventListener('click', () => send(btnSend));
        btnResend.addEventListener('click', () => send(btnResend));

        btnVerify.addEventListener('click', async function () {
            const code = document.getElementById('code').value.trim();
            const password = document.getElementById('password').value;
            if (code.length !== 6) return Swal.fire({icon:'warning',title:'Enter the 6-digit code'});
            if (password.length < 10) return Swal.fire({icon:'warning',title:'Password too short',text:'At least 10 characters.'});
            const old = btnVerify.innerHTML; btnVerify.disabled = true; btnVerify.innerHTML = 'Verifying…';
            try {
                const r = await fetch(b + '/platform/owner-setup/verify', { method:'POST', credentials:'same-origin', headers:{'Content-Type':'application/json'}, body: JSON.stringify({ _token: token, code, password }) });
                const j = await r.json();
                if (j.success) { await Swal.fire({icon:'success',title:'Owner established',text:j.message}); location.href = b + '/projects'; }
                else { Swal.fire({icon:'error',title:'Not verified',text:j.message||'Error'}); btnVerify.disabled = false; btnVerify.innerHTML = old; }
            } catch (e) { Swal.fire({icon:'error',title:'Error',text:String(e)}); btnVerify.disabled = false; btnVerify.innerHTML = old; }
        });
    })();
    </script>
    <?php endif; ?>
</body>
</html>
