<!DOCTYPE html>
<?php
/* Variables: $baseUrl, $assetsUrl, $menu, $user, $email, $sms, $templates,
   $presets, $placeholders, $emailReady, $activeTab */
if (!isset($baseUrl)) $baseUrl = '';
if (!isset($assetsUrl)) $assetsUrl = rtrim($baseUrl, '/') . '/assets';
if (!isset($menu) || !is_array($menu)) $menu = [];
$v = static fn(array $a, string $k, string $d = ''): string => htmlspecialchars((string)($a[$k] ?? $d));
?>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title><?= htmlspecialchars(\PpPhp\Core\Brand::name()) ?> · Settings</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>
        :root {
            --sidebar-width: 250px;
            --topbar-height: 60px;
        }

        body {
            background: var(--pp-app-bg, #f5f6fa);
            color: var(--pp-text, #172033);
            overflow-x: hidden;
        }

        .navbar-top {
            height: var(--topbar-height);
            z-index: 1030;
        }

        .sidebar {
            position: fixed;
            top: var(--topbar-height);
            left: 0;
            bottom: 0;
            width: var(--sidebar-width);
            background: var(--pp-surface, #1e293b);
            color: var(--pp-text-muted, #cbd5e1);
            border-right: 1px solid var(--pp-border, #26303f);
            overflow-x: hidden;
            z-index: 1020;
        }

        .sidebar .nav-link {
            color: var(--pp-text-muted, #cbd5e1);
            padding: .6rem 1.5rem;
            white-space: nowrap;
            border-radius: 8px;
            margin: 2px 8px;
        }

        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            background: color-mix(in srgb, var(--pp-accent, #4f46e5) 12%, transparent);
            color: var(--pp-text, #172033);
        }

        .set-main {
            margin-left: var(--sidebar-width);
            margin-top: var(--topbar-height);
            padding: 24px;
        }

        @media (max-width: 991.98px) {
            .sidebar {
                display: none;
            }

            .set-main {
                margin-left: 0;
            }
        }

        .set-head {
            display: flex;
            align-items: center;
            gap: 14px;
            margin-bottom: 18px;
        }

        .set-head-ic {
            width: 42px;
            height: 42px;
            flex: 0 0 42px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            color: #fff;
            background: linear-gradient(135deg, var(--pp-accent, #4f46e5), color-mix(in srgb, var(--pp-accent, #6366f1) 60%, #7c3aed));
        }

        .set-head h1 {
            margin: 0;
            font-size: 20px;
            font-weight: 800;
            letter-spacing: -.01em;
            color: var(--pp-text);
        }

        .set-head p {
            margin: 2px 0 0;
            font-size: 12.5px;
            color: var(--pp-text-muted);
        }

        .set-tabs {
            display: inline-flex;
            gap: 4px;
            padding: 4px;
            border-radius: 12px;
            margin-bottom: 18px;
            background: var(--pp-surface, #fff);
            border: 1px solid var(--pp-border, #e2e8f0);
            flex-wrap: wrap;
        }

        .set-tab {
            display: inline-flex;
            align-items: center;
            gap: 7px;
            border: 0;
            background: transparent;
            color: var(--pp-text-muted);
            font-size: 13px;
            font-weight: 600;
            padding: 8px 16px;
            border-radius: 9px;
            cursor: pointer;
            text-decoration: none;
        }

        .set-tab:hover {
            background: var(--pp-surface-soft);
            color: var(--pp-text);
        }

        .set-tab.active {
            color: var(--pp-accent-contrast, #fff);
            background: var(--pp-accent, #4f46e5);
        }

        .set-card {
            background: var(--pp-surface, #fff);
            border: 1px solid var(--pp-border, #e2e8f0);
            border-radius: 14px;
            margin-bottom: 18px;
            overflow: hidden;
        }

        .set-card-head {
            padding: 14px 18px;
            border-bottom: 1px solid var(--pp-border);
            background: var(--pp-surface-soft);
        }

        .set-card-head h6 {
            margin: 0;
            font-size: 14px;
            font-weight: 700;
            color: var(--pp-text);
        }

        .set-card-head p {
            margin: 2px 0 0;
            font-size: 12px;
            color: var(--pp-text-muted);
        }

        .set-card-body {
            padding: 18px;
        }

        .set-label {
            display: block;
            font-size: 12.5px;
            font-weight: 600;
            margin-bottom: 5px;
            color: var(--pp-text);
        }

        .set-hint {
            font-size: 11.5px;
            color: var(--pp-text-muted);
            margin-top: 5px;
        }

        .form-control,
        .form-select,
        .form-control:focus,
        .form-select:focus {
            background: var(--pp-input-bg, #fff);
            color: var(--pp-text);
            border-color: var(--pp-border);
        }

        .form-control::placeholder {
            color: var(--pp-text-muted);
        }

        .set-status {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            font-size: 11.5px;
            font-weight: 600;
            padding: 3px 10px;
            border-radius: 999px;
        }

        .set-status.on {
            color: #047857;
            background: color-mix(in srgb, #10b981 16%, var(--pp-surface));
        }

        .set-status.off {
            color: #b45309;
            background: color-mix(in srgb, #f59e0b 16%, var(--pp-surface));
        }

        .ph-chip {
            display: inline-block;
            font-family: ui-monospace, Menlo, monospace;
            font-size: 11px;
            cursor: pointer;
            padding: 2px 7px;
            border-radius: 5px;
            margin: 2px 3px 2px 0;
            border: 1px solid var(--pp-border);
            background: color-mix(in srgb, var(--pp-accent, #4f46e5) 10%, var(--pp-surface));
            color: var(--pp-accent);
        }

        .ph-chip:hover {
            background: var(--pp-accent);
            color: var(--pp-accent-contrast, #fff);
        }

        .tmpl-body {
            font-family: ui-monospace, Menlo, monospace;
            font-size: 12px;
            line-height: 1.6;
        }

        .set-note {
            display: flex;
            gap: 10px;
            padding: 12px 14px;
            border-radius: 10px;
            font-size: 12.5px;
            line-height: 1.55;
            color: var(--pp-text);
            background: color-mix(in srgb, #3b82f6 12%, var(--pp-surface));
            border: 1px solid color-mix(in srgb, #3b82f6 26%, transparent);
        }

        .set-note i {
            color: #3b82f6;
            font-size: 15px;
        }

        /* ── Combined header row (title left, note right) ─────────── */
        .set-topbar {
            display: flex;
            align-items: stretch;
            justify-content: space-between;
            gap: 16px;
            margin-bottom: 18px;
            flex-wrap: wrap;
        }

        .set-topbar .set-head {
            margin-bottom: 0;
            flex: 1 1 260px;
        }

        .set-note-inline {
            flex: 1 1 420px;
            max-width: 620px;
            align-items: flex-start;
            padding: 12px 15px;
        }

        @media (max-width: 767.98px) {
            .set-note-inline { flex-basis: 100%; }
        }

        /* ── Template cards ───────────────────────────────────────── */
        .tmpl-head {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            padding: 12px 16px;
        }

        .tmpl-head-main {
            display: flex;
            align-items: center;
            gap: 11px;
            flex: 1 1 auto;
            min-width: 0;
            cursor: pointer;
        }

        .tmpl-caret {
            color: var(--pp-text-muted);
            font-size: 13px;
            transition: transform .18s ease;
            flex: 0 0 auto;
        }

        .tmpl-head-main[aria-expanded="true"] .tmpl-caret { transform: rotate(90deg); }

        .tmpl-titles { min-width: 0; }

        .tmpl-titles h6 {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 6px;
            margin: 0;
            font-size: 14px;
            font-weight: 700;
            color: var(--pp-text);
        }

        .tmpl-titles p {
            margin: 2px 0 0;
            font-size: 12px;
            color: var(--pp-text-muted);
        }

        .tmpl-tag {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            font-size: 10.5px;
            font-weight: 700;
            padding: 2px 8px;
            border-radius: 999px;
            color: #047857;
            background: color-mix(in srgb, #10b981 16%, var(--pp-surface));
        }

        .tmpl-tag.edited {
            color: var(--pp-accent);
            background: color-mix(in srgb, var(--pp-accent, #4f46e5) 14%, var(--pp-surface));
        }

        .tmpl-head-actions {
            display: flex;
            align-items: center;
            gap: 8px;
            flex: 0 0 auto;
        }

        .btn-ghost {
            border: 1px solid var(--pp-border);
            background: var(--pp-surface);
            color: var(--pp-text-muted);
            font-size: 12.5px;
            font-weight: 600;
            padding: 4px 10px;
        }

        .btn-ghost:hover {
            border-color: var(--pp-accent);
            color: var(--pp-accent);
            background: color-mix(in srgb, var(--pp-accent, #4f46e5) 8%, var(--pp-surface));
        }

        /* Toggle switch */
        .tmpl-switch {
            display: inline-flex;
            align-items: center;
            gap: 7px;
            cursor: pointer;
            user-select: none;
            margin: 0;
        }

        .tmpl-switch input { position: absolute; opacity: 0; width: 0; height: 0; }

        .tmpl-slider {
            position: relative;
            width: 38px;
            height: 21px;
            border-radius: 999px;
            background: color-mix(in srgb, var(--pp-text-muted) 45%, transparent);
            transition: background .18s ease;
            flex: 0 0 auto;
        }

        .tmpl-slider::before {
            content: "";
            position: absolute;
            top: 2px;
            left: 2px;
            width: 17px;
            height: 17px;
            border-radius: 50%;
            background: #fff;
            box-shadow: 0 1px 3px rgba(0, 0, 0, .3);
            transition: transform .18s ease;
        }

        .tmpl-switch input:checked + .tmpl-slider { background: #10b981; }
        .tmpl-switch input:checked + .tmpl-slider::before { transform: translateX(17px); }
        .tmpl-switch input:focus-visible + .tmpl-slider { outline: 2px solid var(--pp-accent); outline-offset: 2px; }

        .tmpl-switch-lbl {
            font-size: 11.5px;
            font-weight: 700;
            color: var(--pp-text-muted);
            min-width: 20px;
        }

        .tmpl-switch input:checked ~ .tmpl-switch-lbl { color: #047857; }

        /* Disabled template dims the card and its content */
        .tmpl-card.is-off .tmpl-titles h6,
        .tmpl-card.is-off .tmpl-titles p { opacity: .6; }
        .tmpl-card.is-off { border-style: dashed; }

        @media (max-width: 575.98px) {
            .tmpl-head { flex-wrap: wrap; }
            .tmpl-head-actions { width: 100%; justify-content: flex-end; }
        }
    </style>
</head>

<body>
    <!-- Top Navbar -->
    <nav class="navbar navbar-top navbar-dark bg-dark px-3 fixed-top shadow-sm">
        <div class="d-flex align-items-center">
            <a class="navbar-brand d-flex align-items-center" href="<?= $baseUrl ?>/projects">
                <?= \PpPhp\Core\Brand::lockup(34) ?>
            </a>
        </div>
        <div class="d-flex align-items-center gap-2">
            <?php include constant('BASE_PATH') . '/core/views/command-palette.php'; ?>
            <?php include constant('BASE_PATH') . '/core/views/keyboard-shortcuts.php'; ?>
            <?php include constant('BASE_PATH') . '/core/views/notification-bell.php'; ?>
            <?php include constant('BASE_PATH') . '/core/views/theme-toggle.php'; ?>
            <div class="dropdown">
                <a href="#" class="d-flex align-items-center text-white text-decoration-none dropdown-toggle" data-bs-toggle="dropdown">
                    <i class="bi bi-person-circle me-2"></i><span class="nav-username"><?= htmlspecialchars($user['username'] ?? 'Admin') ?></span>
                </a>
                <ul class="dropdown-menu dropdown-menu-dark dropdown-menu-end">
                    <?php if (\PpPhp\Core\Security::IsAdmin()): /* superadmin + owner */ ?>
                    <li><a class="dropdown-item" href="<?= $baseUrl ?>/users"><i class="bi bi-people me-2"></i>Manage Users</a></li>
                    <li><a class="dropdown-item" href="<?= $baseUrl ?>/platform/updates"><i class="bi bi-arrow-repeat me-2"></i>Updates</a></li>
                    <?php if (\PpPhp\Core\Security::IsOwner()): ?>
                    <li><a class="dropdown-item" href="<?= $baseUrl ?>/settings/core-config"><i class="bi bi-sliders2 me-2"></i>Core Configuration</a></li>
                    <?php endif; ?>
                    <?php include constant('BASE_PATH') . '/core/views/license-menu.php'; ?>
                    <li>
                        <hr class="dropdown-divider">
                    </li>
                    <?php endif; ?>
                    <li><a class="dropdown-item" href="<?= $baseUrl ?>/profile"><i class="bi bi-person me-2"></i>Profile</a></li>
                    <li><a class="dropdown-item" href="<?= $baseUrl ?>/logout"><i class="bi bi-box-arrow-right me-2"></i>Sign out</a></li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- Sidebar -->
    <nav class="sidebar d-none d-lg-flex flex-column py-3">
        <ul class="nav nav-pills flex-column mb-auto">
            <?php foreach ($menu as $item): ?>
                <li class="nav-item">
                    <a href="<?= htmlspecialchars($baseUrl . ($item['uri'] ?? '#')) ?>" class="nav-link <?= ($item['uri'] ?? '') === '/settings' ? 'active' : '' ?>">
                        <i class="bi bi-<?= htmlspecialchars($item['icon'] ?? 'circle') ?> me-2"></i><?= htmlspecialchars($item['label'] ?? '') ?>
                    </a>
                </li>
            <?php endforeach; ?>
        </ul>
        <div class="mt-auto px-3 pb-1"><?php include constant('BASE_PATH') . '/core/views/sidebar-version.php'; ?></div>
    </nav>

    <main class="set-main">
        <div class="set-topbar">
            <div class="set-head">
                <span class="set-head-ic"><i class="bi bi-gear-fill"></i></span>
                <div>
                    <h1>Settings</h1>
                    <p>Core engine configuration — how <?= htmlspecialchars(\PpPhp\Core\Brand::name()) ?> itself sends account emails and messages.</p>
                </div>
            </div>
            <div class="set-note set-note-inline">
                <i class="bi bi-info-circle-fill"></i>
                <div>These belong to <strong><?= htmlspecialchars(\PpPhp\Core\Brand::name()) ?> itself</strong> — sign-in emails, password resets and one-time
                    codes for your team. Separate from a project's <strong>Misc → Email/SMS</strong> and never
                    included in generated apps.
                </div>
            </div>
        </div>

        <div class="set-tabs" role="tablist">
            <button class="set-tab <?= $activeTab === 'email' ? 'active' : '' ?>" data-tab="email"><i class="bi bi-envelope-at"></i> Email Server</button>
            <button class="set-tab <?= $activeTab === 'templates' ? 'active' : '' ?>" data-tab="templates"><i class="bi bi-file-earmark-text"></i> Email Templates</button>
            <button class="set-tab <?= $activeTab === 'sms' ? 'active' : '' ?>" data-tab="sms"><i class="bi bi-chat-dots"></i> SMS</button>
            <a class="set-tab" href="<?= $baseUrl ?>/settings/storage"><i class="bi bi-cloud-arrow-up"></i> Storage</a>
            <?php if (\PpPhp\Core\Security::IsOwner()): ?>
            <a class="set-tab" href="<?= $baseUrl ?>/settings/core-config"><i class="bi bi-sliders2"></i> Core Configuration</a>
            <?php endif; ?>
        </div>

        <!-- ═══════════ EMAIL ═══════════ -->
        <section class="set-pane" data-pane="email" <?= $activeTab !== 'email' ? 'hidden' : '' ?>>
            <?php
                $pVerified = (bool) ($email['verified'] ?? false);
                $pAuth = (string) ($email['authType'] ?? 'basic');
                $pConn = $pAuth === 'xoauth2' && (($email['oauthRefreshToken'] ?? '') !== '');
                $pHas  = trim((string) ($email['host'] ?? '')) !== '' || ($pAuth === 'xoauth2' && ((($email['oauthClientId'] ?? '') !== '') || $pConn));
                $pBadge = $pVerified ? ['success', 'check-circle-fill', 'Verified'] : ($pHas ? ['warning', 'exclamation-circle', 'Not tested'] : ['secondary', 'dash-circle', 'Not configured']);
            ?>
            <div class="set-card mail-server" data-slot="0" data-verified="<?= $pVerified ? 1 : 0 ?>">
                <div class="set-card-head mail-server-head d-flex align-items-center justify-content-between" style="cursor:pointer">
                    <div>
                        <h6 class="mb-0">Primary mail server (SMTP)</h6>
                        <p class="mb-0">Used to send account emails and one-time codes.</p>
                    </div>
                    <div class="d-flex align-items-center gap-2">
                        <span class="badge text-bg-<?= $pBadge[0] ?> mail-badge"><i class="bi bi-<?= $pBadge[1] ?> me-1"></i><span class="mail-badge-text"><?= $pBadge[2] ?></span></span>
                        <button type="button" class="btn btn-sm btn-outline-secondary mail-edit" title="Edit" <?= $pVerified ? '' : 'hidden' ?>><i class="bi bi-pencil"></i></button>
                        <i class="bi bi-chevron-<?= $pVerified ? 'down' : 'up' ?> mail-chevron"></i>
                    </div>
                </div>
                <div class="set-card-body mail-server-body" <?= $pVerified ? 'hidden' : '' ?>>
                    <fieldset class="mail-fields border-0 p-0 m-0" <?= $pVerified ? 'disabled' : '' ?>>
                    <div class="row g-3">
                        <div class="col-12">
                            <div class="alert alert-warning py-2 px-3 mb-0 small" id="emProviderWarn" hidden></div>
                        </div>
                        <div class="col-md-4">
                            <label class="set-label" for="emProvider">Provider</label>
                            <select id="emProvider" class="form-select form-select-sm">
                                <?php
                                $byGroup = [];
                                foreach ($presets as $key => $p) { $byGroup[$p['group'] ?? 'Other'][$key] = $p; }
                                foreach ($byGroup as $grp => $items): ?>
                                    <optgroup label="<?= htmlspecialchars($grp) ?>">
                                        <?php foreach ($items as $key => $p): ?>
                                            <option value="<?= htmlspecialchars($key) ?>" <?= ($email['provider'] ?? 'custom') === $key ? 'selected' : '' ?>><?= htmlspecialchars($p['label'] ?? ucfirst($key)) ?></option>
                                        <?php endforeach; ?>
                                    </optgroup>
                                <?php endforeach; ?>
                            </select>
                            <div class="set-hint" id="emProviderHelp"></div>
                            <a class="set-hint d-inline-block mt-1" id="emProviderDocs" href="#" target="_blank" rel="noopener" hidden></a>
                        </div>
                        <div class="col-md-5">
                            <label class="set-label" for="emHost">SMTP host</label>
                            <input id="emHost" class="form-control form-control-sm" value="<?= $v($email, 'host') ?>" placeholder="smtp.example.com">
                        </div>
                        <div class="col-md-3">
                            <label class="set-label" for="emPort">Port</label>
                            <input id="emPort" type="number" class="form-control form-control-sm" value="<?= $v($email, 'port', '587') ?>" placeholder="587">
                        </div>
                        <div class="col-md-4">
                            <label class="set-label" for="emEncryption">Encryption</label>
                            <select id="emEncryption" class="form-select form-select-sm">
                                <?php foreach (['tls' => 'TLS', 'ssl' => 'SSL', 'none' => 'None'] as $k => $lbl): ?>
                                    <option value="<?= $k ?>" <?= ($email['encryption'] ?? 'tls') === $k ? 'selected' : '' ?>><?= $lbl ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4" data-basic-auth>
                            <label class="set-label" for="emUser" id="emUserLabel">Username</label>
                            <input id="emUser" class="form-control form-control-sm" value="<?= $v($email, 'username') ?>" placeholder="you@example.com" autocomplete="off">
                            <div class="set-hint" id="emUserHint"></div>
                        </div>
                        <div class="col-md-4" data-basic-auth>
                            <label class="set-label" for="emPass" id="emPassLabel">Password</label>
                            <input id="emPass" type="password" class="form-control form-control-sm" placeholder="<?= ($email['password'] ?? '') !== '' ? '•••••••• (saved)' : 'password' ?>" autocomplete="new-password">
                            <div class="set-hint" id="emPassHint">Leave blank to keep the saved password.</div>
                        </div>

                        <!-- OAuth 2.0 sign-in (shown for Gmail / Outlook / Microsoft 365) -->
                        <div class="col-12" id="emAuthMethodWrap" hidden>
                            <label class="set-label d-block mb-1">Authentication</label>
                            <div class="btn-group btn-group-sm" role="group" aria-label="Authentication method">
                                <input type="radio" class="btn-check" name="emAuthType" id="emAuthBasic" value="basic" <?= (($email['authType'] ?? 'basic') !== 'xoauth2') ? 'checked' : '' ?>>
                                <label class="btn btn-outline-secondary" for="emAuthBasic">App password</label>
                                <input type="radio" class="btn-check" name="emAuthType" id="emAuthOauth" value="xoauth2" <?= (($email['authType'] ?? '') === 'xoauth2') ? 'checked' : '' ?>>
                                <label class="btn btn-outline-secondary" for="emAuthOauth"><i class="bi bi-shield-lock me-1"></i>OAuth 2.0 sign-in</label>
                            </div>
                        </div>
                        <div class="col-12" id="emOauthPanel" hidden>
                            <div class="border rounded p-3" style="background:var(--bs-tertiary-bg,rgba(0,0,0,.03))">
                                <div class="small text-muted mb-2">Register an OAuth app once with <strong id="emOauthProviderName">your provider</strong>, paste the Client ID/Secret below, <strong>Save</strong>, then <strong>Connect</strong> the mailbox. No password is stored — only a revocable token.</div>
                                <div class="row g-2">
                                    <div class="col-md-6">
                                        <label class="set-label" for="emOauthClientId">Client ID</label>
                                        <input id="emOauthClientId" class="form-control form-control-sm" value="<?= $v($email, 'oauthClientId') ?>" autocomplete="off">
                                    </div>
                                    <div class="col-md-6">
                                        <label class="set-label" for="emOauthSecret">Client secret</label>
                                        <input id="emOauthSecret" type="password" class="form-control form-control-sm" placeholder="<?= ($email['oauthClientSecret'] ?? '') !== '' ? '•••••••• (saved)' : 'client secret' ?>" autocomplete="new-password">
                                        <div class="set-hint">Leave blank to keep the saved secret.</div>
                                    </div>
                                    <div class="col-12">
                                        <label class="set-label">Redirect URI <span class="text-muted fw-normal">— add this exact URL to your OAuth app</span></label>
                                        <div class="input-group input-group-sm">
                                            <input class="form-control" id="emOauthRedirect" readonly value="<?= htmlspecialchars(rtrim((string) ($baseUrl ?? ''), '/') . '/settings/email/oauth/callback') ?>">
                                            <button class="btn btn-outline-secondary" type="button" id="emOauthCopy"><i class="bi bi-clipboard"></i></button>
                                        </div>
                                    </div>
                                </div>
                                <?php $oauthConnected = (($email['authType'] ?? '') === 'xoauth2') && (($email['oauthRefreshToken'] ?? '') !== ''); ?>
                                <div class="d-flex align-items-center gap-2 mt-3 flex-wrap">
                                    <a class="btn btn-sm btn-primary" id="emOauthConnect" href="<?= htmlspecialchars(rtrim((string) ($baseUrl ?? ''), '/') . '/settings/email/oauth/start') ?>"><i class="bi bi-box-arrow-in-right me-1"></i> <?= $oauthConnected ? 'Reconnect mailbox' : 'Connect mailbox' ?></a>
                                    <span id="emOauthStatus" class="small <?= $oauthConnected ? 'text-success' : 'text-muted' ?>">
                                        <?php if ($oauthConnected): ?><i class="bi bi-check-circle-fill me-1"></i>Connected<?= ($email['oauthEmail'] ?? '') !== '' ? ': ' . htmlspecialchars((string) $email['oauthEmail']) : '' ?><?php else: ?>Not connected yet.<?php endif; ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <label class="set-label" for="emFrom">From address</label>
                            <input id="emFrom" type="email" class="form-control form-control-sm" value="<?= $v($email, 'fromAddress') ?>" placeholder="no-reply@example.com">
                        </div>
                        <div class="col-md-4">
                            <label class="set-label" for="emFromName">From name</label>
                            <input id="emFromName" class="form-control form-control-sm" value="<?= $v($email, 'fromName') ?>" placeholder="PPphp">
                        </div>
                        <div class="col-md-4">
                            <label class="set-label" for="emAppName">Application name</label>
                            <input id="emAppName" class="form-control form-control-sm" value="<?= $v($email, 'appName', 'PPphp') ?>" placeholder="PPphp">
                            <div class="set-hint">Used by <code>{app_name}</code> in templates.</div>
                        </div>
                        <div class="col-md-8">
                            <label class="set-label" for="emOwner"><i class="bi bi-person-badge me-1"></i>Owner email</label>
                            <input id="emOwner" type="email" class="form-control form-control-sm" value="<?= $v($email, 'ownerEmail') ?>" placeholder="<?= htmlspecialchars(\PpPhp\Core\PlatformSettings::DEFAULT_OWNER_EMAIL) ?>">
                            <div class="set-hint">Where owner notifications land — like someone asking to try <?= htmlspecialchars((string)($email['appName'] ?? 'PPphp')) ?>.
                                Leave blank to use <?= htmlspecialchars(\PpPhp\Core\PlatformSettings::DEFAULT_OWNER_EMAIL) ?>.</div>
                        </div>
                    </div>
                    </fieldset>
                    <div class="d-flex gap-2 mt-2">
                        <button type="button" class="btn btn-sm btn-outline-primary mail-test" data-slot="0"><i class="bi bi-send-check me-1"></i> Test &amp; lock this server</button>
                    </div>
                </div>
            </div>

                    <div class="mt-3 mb-1">
                        <h6 class="mb-0"><i class="bi bi-diagram-3 me-1"></i> Fallback servers <span class="text-muted fw-normal small">(optional)</span></h6>
                        <p class="set-hint mb-0">If the primary server can’t deliver, <?= htmlspecialchars(\PpPhp\Core\Brand::name()) ?> automatically tries these in order — so one provider being unreachable or rate-limited won’t stop your emails. Leave blank to disable.</p>
                    </div>
                    <?php
                    $emCallback = htmlspecialchars(rtrim((string) ($baseUrl ?? ''), '/') . '/settings/email/oauth/callback');
                    $fbs = array_values((array) ($email['fallbacks'] ?? []));
                    ?>
                    <?php for ($i = 0; $i < 2; $i++): $fb = (array) ($fbs[$i] ?? []); $slot = $i + 1;
                        $fVerified = (bool) ($fb['verified'] ?? false);
                        $fAuth     = (string) ($fb['authType'] ?? 'basic');
                        $fConn     = $fAuth === 'xoauth2' && (($fb['oauthRefreshToken'] ?? '') !== '');
                        $fHas      = trim((string) ($fb['host'] ?? '')) !== '' || ($fAuth === 'xoauth2' && ((($fb['oauthClientId'] ?? '') !== '') || $fConn));
                        $fBadge    = $fVerified ? ['success', 'check-circle-fill', 'Verified'] : ($fHas ? ['warning', 'exclamation-circle', 'Not tested'] : ['secondary', 'dash-circle', 'Not configured']);
                        $fProv     = (string) ($fb['provider'] ?? 'custom');
                    ?>
                    <div class="set-card mail-server mt-3" data-slot="<?= $slot ?>" data-verified="<?= $fVerified ? 1 : 0 ?>">
                        <div class="set-card-head mail-server-head" style="cursor:pointer">
                            <div><h6 class="mb-0">Fallback server <?= $i + 1 ?> <span class="text-muted fw-normal small">(optional)</span></h6></div>
                            <div class="d-flex align-items-center gap-2">
                                <span class="badge text-bg-<?= $fBadge[0] ?> mail-badge"><i class="bi bi-<?= $fBadge[1] ?> me-1"></i><span class="mail-badge-text"><?= $fBadge[2] ?></span></span>
                                <button type="button" class="btn btn-sm btn-outline-secondary mail-edit" title="Edit" <?= $fVerified ? '' : 'hidden' ?>><i class="bi bi-pencil"></i></button>
                                <i class="bi bi-chevron-<?= $fVerified ? 'down' : 'up' ?> mail-chevron"></i>
                            </div>
                        </div>
                        <div class="set-card-body mail-server-body" <?= $fVerified ? 'hidden' : '' ?>>
                            <fieldset class="mail-fields border-0 p-0 m-0" <?= $fVerified ? 'disabled' : '' ?>>
                                <div class="row g-2">
                                    <div class="col-md-4">
                                        <label class="set-label">Provider</label>
                                        <select class="form-select form-select-sm mail-provider" data-fb="<?= $i ?>" data-fb-key="provider">
                                            <?php foreach ($byGroup as $grp => $items): ?><optgroup label="<?= htmlspecialchars($grp) ?>"><?php foreach ($items as $pk => $pp): ?><option value="<?= htmlspecialchars($pk) ?>" <?= $fProv === $pk ? 'selected' : '' ?>><?= htmlspecialchars($pp['label'] ?? ucfirst($pk)) ?></option><?php endforeach; ?></optgroup><?php endforeach; ?>
                                        </select>
                                        <div class="set-hint mail-help"></div>
                                        <a class="set-hint d-inline-block mt-1 mail-docs" href="#" target="_blank" rel="noopener" hidden></a>
                                    </div>
                                    <div class="col-md-5" data-basic-auth><label class="set-label">SMTP host</label><input class="form-control form-control-sm" data-fb="<?= $i ?>" data-fb-key="host" value="<?= $v($fb, 'host') ?>" placeholder="smtp.example.com"></div>
                                    <div class="col-md-3" data-basic-auth><label class="set-label">Port</label><input type="number" class="form-control form-control-sm" data-fb="<?= $i ?>" data-fb-key="port" value="<?= $v($fb, 'port', '587') ?>"></div>
                                    <div class="col-md-4" data-basic-auth><label class="set-label">Encryption</label><select class="form-select form-select-sm" data-fb="<?= $i ?>" data-fb-key="encryption"><?php foreach (['tls' => 'TLS', 'ssl' => 'SSL', 'none' => 'None'] as $k => $lbl): ?><option value="<?= $k ?>" <?= (($fb['encryption'] ?? 'tls') === $k ? 'selected' : '') ?>><?= $lbl ?></option><?php endforeach; ?></select></div>

                                    <div class="col-12 mail-authmethod" hidden>
                                        <label class="set-label d-block mb-1">Authentication</label>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <input type="radio" class="btn-check mail-auth" name="emAuthFb<?= $i ?>" id="emAuthFb<?= $i ?>B" value="basic" <?= $fAuth !== 'xoauth2' ? 'checked' : '' ?>>
                                            <label class="btn btn-outline-secondary" for="emAuthFb<?= $i ?>B">App password</label>
                                            <input type="radio" class="btn-check mail-auth" name="emAuthFb<?= $i ?>" id="emAuthFb<?= $i ?>O" value="xoauth2" <?= $fAuth === 'xoauth2' ? 'checked' : '' ?>>
                                            <label class="btn btn-outline-secondary" for="emAuthFb<?= $i ?>O"><i class="bi bi-shield-lock me-1"></i>OAuth 2.0</label>
                                        </div>
                                    </div>

                                    <div class="col-md-4" data-basic-auth><label class="set-label mail-userlabel">Username</label><input class="form-control form-control-sm" data-fb="<?= $i ?>" data-fb-key="username" value="<?= $v($fb, 'username') ?>" autocomplete="off"></div>
                                    <div class="col-md-4" data-basic-auth><label class="set-label mail-passlabel">Password</label><input type="password" class="form-control form-control-sm" data-fb="<?= $i ?>" data-fb-key="password" placeholder="<?= (($fb['password'] ?? '') !== '' ? '•••••••• (saved)' : 'password') ?>" autocomplete="new-password"></div>
                                    <div class="col-md-4"><label class="set-label">From address</label><input type="email" class="form-control form-control-sm" data-fb="<?= $i ?>" data-fb-key="fromAddress" value="<?= $v($fb, 'fromAddress') ?>" placeholder="uses primary if blank"></div>

                                    <div class="col-12 mail-oauth-panel" hidden>
                                        <div class="border rounded p-2" style="background:var(--bs-body-bg,#fff)">
                                            <div class="small text-muted mb-2">Connect this fallback via <strong class="mail-oauth-name">OAuth</strong> — register an app, paste Client ID/Secret, <strong>Save</strong>, then <strong>Connect</strong>.</div>
                                            <div class="row g-2">
                                                <div class="col-md-6"><label class="set-label">Client ID</label><input class="form-control form-control-sm" data-fb="<?= $i ?>" data-fb-key="oauthClientId" value="<?= $v($fb, 'oauthClientId') ?>" autocomplete="off"></div>
                                                <div class="col-md-6"><label class="set-label">Client secret</label><input type="password" class="form-control form-control-sm" data-fb="<?= $i ?>" data-fb-key="oauthClientSecret" placeholder="<?= (($fb['oauthClientSecret'] ?? '') !== '' ? '•••••••• (saved)' : 'client secret') ?>" autocomplete="new-password"></div>
                                                <div class="col-12"><label class="set-label">Redirect URI</label><div class="input-group input-group-sm"><input class="form-control mail-redirect" readonly value="<?= $emCallback ?>"><button class="btn btn-outline-secondary mail-copy" type="button"><i class="bi bi-clipboard"></i></button></div></div>
                                            </div>
                                            <div class="d-flex align-items-center gap-2 mt-2 flex-wrap">
                                                <a class="btn btn-sm btn-primary mail-connect" href="<?= htmlspecialchars(rtrim((string) ($baseUrl ?? ''), '/') . '/settings/email/oauth/start?slot=' . $slot) ?>"><i class="bi bi-box-arrow-in-right me-1"></i> <?= $fConn ? 'Reconnect' : 'Connect' ?></a>
                                                <span class="small <?= $fConn ? 'text-success' : 'text-muted' ?>"><?php if ($fConn): ?><i class="bi bi-check-circle-fill me-1"></i>Connected<?= ($fb['oauthEmail'] ?? '') !== '' ? ': ' . htmlspecialchars((string) $fb['oauthEmail']) : '' ?><?php else: ?>Not connected<?php endif; ?></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </fieldset>
                            <div class="d-flex gap-2 mt-2">
                                <button type="button" class="btn btn-sm btn-outline-primary mail-test" data-slot="<?= $slot ?>"><i class="bi bi-send-check me-1"></i> Test &amp; lock this server</button>
                            </div>
                        </div>
                    </div>
                    <?php endfor; ?>

                    <div class="d-flex gap-2 mt-3 flex-wrap">
                        <button class="btn btn-sm btn-primary" id="btnSaveEmail"><i class="bi bi-save me-1"></i> Save all email settings</button>
                        <button class="btn btn-sm btn-outline-secondary" id="btnTestEmail"><i class="bi bi-send me-1"></i> Test failover chain</button>
                    </div>

                    <div class="mt-3 p-2 rounded border d-flex flex-wrap align-items-center gap-2" style="background:var(--bs-tertiary-bg,rgba(0,0,0,.03))">
                        <span class="small mb-0">
                            <i class="bi bi-arrow-repeat me-1"></i><strong>Retry queue</strong> —
                            <span id="mqPending"><?= (int) ($queuePending ?? 0) ?></span> pending,
                            <span id="mqFailed"><?= (int) ($queueFailed ?? 0) ?></span> failed.
                            <span class="text-muted">Emails that fail on every server are stored and retried automatically with backoff.</span>
                        </span>
                        <span class="ms-auto d-flex gap-2">
                            <button class="btn btn-sm btn-outline-secondary" id="btnProcessQueue"><i class="bi bi-play-circle me-1"></i> Process now</button>
                            <button class="btn btn-sm btn-outline-warning" id="btnRetryFailed"><i class="bi bi-arrow-counterclockwise me-1"></i> Retry failed</button>
                        </span>
                    </div>
        </section>

        <!-- ═══════════ TEMPLATES ═══════════ -->
        <section class="set-pane" data-pane="templates" <?= $activeTab !== 'templates' ? 'hidden' : '' ?>>
            <div class="set-note mb-3">
                <i class="bi bi-braces"></i>
                <div>Messages are <strong>HTML</strong> — <?= htmlspecialchars(\PpPhp\Core\Brand::name()) ?> wraps each one in a branded, mobile-friendly layout, so you
                    only write the content. Click into a field, then click a placeholder to insert it. Use
                    <strong>Preview</strong> to see the finished email with sample data.
                </div>
            </div>
            <?php foreach ($templates as $key => $t): $enabled = !empty($t['enabled']); ?>
                <div class="set-card tmpl-card<?= $enabled ? '' : ' is-off' ?>" data-tmpl="<?= htmlspecialchars($key) ?>" data-enabled="<?= $enabled ? '1' : '0' ?>">
                    <div class="set-card-head tmpl-head">
                        <div class="tmpl-head-main" data-bs-toggle="collapse"
                            data-bs-target="#collapse-<?= htmlspecialchars($key) ?>"
                            aria-expanded="false" aria-controls="collapse-<?= htmlspecialchars($key) ?>">
                            <i class="bi bi-chevron-right tmpl-caret"></i>
                            <div class="tmpl-titles">
                                <h6><?= htmlspecialchars($t['label']) ?>
                                    <?php if (($t['to'] ?? 'user') === 'owner'): ?>
                                        <span class="tmpl-tag"><i class="bi bi-person-badge"></i> to owner</span>
                                    <?php endif; ?>
                                    <span class="tmpl-tag edited" data-role="edited"<?= empty($t['customized']) ? ' hidden' : '' ?>><i class="bi bi-pencil"></i> edited</span>
                                </h6>
                                <p class="mb-0"><?= htmlspecialchars($t['hint']) ?></p>
                            </div>
                        </div>
                        <div class="tmpl-head-actions">
                            <label class="tmpl-switch" title="Enable or disable this email" onclick="event.stopPropagation();">
                                <input type="checkbox" class="tmpl-enabled" <?= $enabled ? 'checked' : '' ?>>
                                <span class="tmpl-slider"></span>
                                <span class="tmpl-switch-lbl"><?= $enabled ? 'On' : 'Off' ?></span>
                            </label>
                            <button class="btn btn-sm btn-ghost btn-reset" data-key="<?= htmlspecialchars($key) ?>"
                                title="Restore this email to its default content" onclick="event.stopPropagation();">
                                <i class="bi bi-arrow-counterclockwise"></i><span class="d-none d-md-inline ms-1">Reset</span>
                            </button>
                            <button class="btn btn-sm btn-ghost btn-preview" data-key="<?= htmlspecialchars($key) ?>"
                                onclick="event.stopPropagation();">
                                <i class="bi bi-eye"></i><span class="d-none d-md-inline ms-1">Preview</span>
                            </button>
                        </div>
                    </div>
                    <div class="collapse" id="collapse-<?= htmlspecialchars($key) ?>">
                        <div class="set-card-body">
                            <label class="set-label">Subject</label>
                            <input class="form-control form-control-sm tmpl-subject mb-3" value="<?= htmlspecialchars($t['subject']) ?>">
                            <label class="set-label">Message <span class="set-hint d-inline">(HTML)</span></label>
                            <textarea class="form-control form-control-sm tmpl-body" rows="9"><?= htmlspecialchars($t['body']) ?></textarea>
                            <div class="mt-2">
                                <span class="set-hint d-block mb-1">Placeholders for this email:</span>
                                <?php foreach (($t['vars'] ?? $placeholders) as $ph): ?><span class="ph-chip" data-ph="<?= htmlspecialchars($ph) ?>"><?= htmlspecialchars($ph) ?></span><?php endforeach; ?>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
            <button class="btn btn-sm btn-primary mt-3" id="btnSaveTemplates"><i class="bi bi-save me-1"></i> Save all templates</button>
        </section>

        <!-- ═══════════ SMS ═══════════ -->
        <section class="set-pane" data-pane="sms" <?= $activeTab !== 'sms' ? 'hidden' : '' ?>>
            <div class="set-card">
                <div class="set-card-head">
                    <h6>SMS gateway</h6>
                    <p>Optional — for sending one-time codes by text message.</p>
                </div>
                <div class="set-card-body">
                    <div class="set-note mb-3">
                        <i class="bi bi-info-circle-fill"></i>
                        <div>SMS delivery isn't wired into account flows yet. You can store your gateway details here now —
                            they'll be used as soon as text-message codes are switched on.</div>
                    </div>
                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="set-label" for="smProvider">Provider</label>
                            <input id="smProvider" class="form-control form-control-sm" value="<?= $v($sms, 'provider') ?>" placeholder="e.g. ppsms, twilio">
                        </div>
                        <div class="col-md-4">
                            <label class="set-label" for="smToken">API token</label>
                            <input id="smToken" type="password" class="form-control form-control-sm" placeholder="<?= ($sms['api_token'] ?? '') !== '' ? '•••••••• (saved)' : 'token' ?>" autocomplete="new-password">
                            <div class="set-hint">Leave blank to keep the saved token.</div>
                        </div>
                        <div class="col-md-4">
                            <label class="set-label" for="smFrom">Sender ID</label>
                            <input id="smFrom" class="form-control form-control-sm" value="<?= $v($sms, 'from') ?>" placeholder="PPPHP">
                        </div>
                    </div>
                    <button class="btn btn-sm btn-primary mt-3" id="btnSaveSms"><i class="bi bi-save me-1"></i> Save SMS settings</button>
                </div>
            </div>
        </section>
    </main>

    <script src="<?= $assetsUrl ?>/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        const baseUrl = <?= json_encode($baseUrl) ?>;
        const presets = <?= json_encode($presets, JSON_UNESCAPED_SLASHES) ?>;
    </script>
    <?= \PpPhp\Core\ModuleAssets::script('Settings', 'Views/scripts/settings.js') ?>
    <?php include constant('BASE_PATH') . '/core/views/flash-alert.php'; ?>
</body>

</html>