<?php ob_start(); ?>
<?php
$_old           = $siteConfig ?? [];
$_siteName      = e($_old['site_name']       ?? '');
$_siteTagline   = e($_old['site_tagline']    ?? '');
$_contactEmail  = e($_old['contact_email']   ?? '');
$_selectedTheme = $_old['theme'] ?? 'default';
$_mailTransport  = $_old['mail_transport']      ?? 'mail';
$_mailFrom       = e($_old['mail_from_address'] ?? '');
$_mailFromName   = e($_old['mail_from_name']    ?? '');
$_smtpHost       = e($_old['smtp_host']         ?? '');
$_smtpPort       = e($_old['smtp_port']         ?? '587');
$_smtpUsername   = e($_old['smtp_username']     ?? '');
$_smtpEncryption = $_old['smtp_encryption'] ?? 'tls';
?>

<h2><?= __('installer.site_title') ?></h2>
<p><?= __('installer.site_text') ?></p>

<?php if (!empty($error)): ?>
<div class="alert alert-error"><?= e($error) ?></div>
<?php endif; ?>

<form method="POST" action="/installer/step/6">
    <?= $csrf->field() ?>
    <div class="form-group">
        <label for="site_name"><?= __('installer.site_name') ?></label>
        <input type="text" id="site_name" name="site_name" value="<?= $_siteName ?>" required>
    </div>
    <div class="form-group">
        <label for="site_tagline"><?= __('installer.site_tagline') ?></label>
        <input type="text" id="site_tagline" name="site_tagline" value="<?= $_siteTagline ?>">
    </div>
    <div class="form-group">
        <label for="contact_email"><?= __('installer.site_email') ?></label>
        <input type="email" id="contact_email" name="contact_email" value="<?= $_contactEmail ?>">
    </div>

    <div class="form-group">
        <label><?= __('installer.site_theme') ?></label>
        <div class="theme-selector">
            <?php foreach ($themes as $theme): ?>
            <label class="theme-option">
                <input type="radio" name="theme" value="<?= e($theme['slug']) ?>"
                    <?= ($theme['slug'] === $_selectedTheme) ? 'checked' : '' ?>>
                <div class="theme-card">
                    <strong><?= e($theme['name']) ?></strong>
                    <small><?= e($theme['description'] ?? '') ?></small>
                </div>
            </label>
            <?php endforeach; ?>
        </div>
    </div>

    <div class="form-section" style="margin-top:2rem; padding-top:1.5rem; border-top:1px solid #e0e0e0;">
        <h3 style="margin-top:0; font-size:1.1rem;">
            <?= __('installer.site_mail_title') ?>
            <small style="font-weight:normal; color:#888; font-size:.85rem;">&nbsp;<?= __('installer.site_mail_optional') ?></small>
        </h3>

        <div class="form-group">
            <label for="mail_transport"><?= __('installer.site_mail_transport') ?></label>
            <select id="mail_transport" name="mail_transport" onchange="toggleSmtpFields(this.value)">
                <option value="mail" <?= $_mailTransport === 'mail' ? 'selected' : '' ?>><?= __('installer.site_mail_php') ?></option>
                <option value="smtp" <?= $_mailTransport === 'smtp' ? 'selected' : '' ?>><?= __('installer.site_mail_smtp') ?></option>
            </select>
        </div>

        <div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem;">
            <div class="form-group">
                <label for="mail_from_address"><?= __('installer.site_mail_from') ?></label>
                <input type="email" id="mail_from_address" name="mail_from_address"
                       value="<?= $_mailFrom ?>" placeholder="noreply@yourdomain.com">
            </div>
            <div class="form-group">
                <label for="mail_from_name"><?= __('installer.site_mail_from_name') ?></label>
                <input type="text" id="mail_from_name" name="mail_from_name"
                       value="<?= $_mailFromName ?>" placeholder="My Website">
            </div>
        </div>

        <div id="smtp-fields" style="<?= $_mailTransport === 'smtp' ? '' : 'display:none;' ?>">
            <div class="form-group">
                <label for="smtp_host"><?= __('installer.site_smtp_host') ?></label>
                <input type="text" id="smtp_host" name="smtp_host"
                       value="<?= $_smtpHost ?>" placeholder="smtp.gmail.com">
            </div>
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem;">
                <div class="form-group">
                    <label for="smtp_port"><?= __('installer.site_smtp_port') ?></label>
                    <input type="number" id="smtp_port" name="smtp_port"
                           value="<?= $_smtpPort ?>" placeholder="587" min="1" max="65535">
                </div>
                <div class="form-group">
                    <label for="smtp_encryption"><?= __('installer.site_smtp_encryption') ?></label>
                    <select id="smtp_encryption" name="smtp_encryption">
                        <option value="tls"  <?= $_smtpEncryption === 'tls'  ? 'selected' : '' ?>><?= __('installer.site_smtp_tls') ?></option>
                        <option value="ssl"  <?= $_smtpEncryption === 'ssl'  ? 'selected' : '' ?>><?= __('installer.site_smtp_ssl') ?></option>
                        <option value="none" <?= $_smtpEncryption === 'none' ? 'selected' : '' ?>><?= __('installer.site_smtp_none') ?></option>
                    </select>
                </div>
            </div>
            <div style="display:grid; grid-template-columns:1fr 1fr; gap:1rem;">
                <div class="form-group">
                    <label for="smtp_username"><?= __('installer.site_smtp_user') ?></label>
                    <input type="text" id="smtp_username" name="smtp_username"
                           value="<?= $_smtpUsername ?>" placeholder="user@example.com" autocomplete="off">
                </div>
                <div class="form-group">
                    <label for="smtp_password"><?= __('installer.site_smtp_password') ?></label>
                    <div class="iw-pw-wrap">
                        <input type="password" id="smtp_password" name="smtp_password"
                               placeholder="password" autocomplete="new-password">
                        <button type="button" class="iw-pw-toggle" data-target="smtp_password" aria-label="Show password">
                            <svg class="iw-pw-eye" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"/><circle cx="12" cy="12" r="3"/></svg>
                            <svg class="iw-pw-eye-off" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:none"><path d="M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"/><path d="M14.084 14.158a3 3 0 0 1-4.242-4.242"/><path d="M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"/><path d="m2 2 20 20"/></svg>
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div id="test-mail-block" style="margin-top:1.25rem; padding:.875rem 1rem; background:#f8f9fa; border:1px solid #e0e0e0; border-radius:6px;">
            <strong style="font-size:.875rem;"><?= __('installer.site_mail_test') ?></strong>
            <div style="display:flex; gap:.5rem; align-items:center; margin-top:.6rem; flex-wrap:wrap;">
                <div class="form-group" style="margin:0; flex:1; min-width:200px;">
                    <input type="email" id="test_recipient" placeholder="<?= __('installer.site_mail_test_to') ?> you@example.com" style="margin:0;">
                </div>
                <button type="button" id="btn-test-mail" class="btn btn-secondary" style="white-space:nowrap; margin-top:0;">
                    <?= __('installer.site_mail_test_btn') ?>
                </button>
            </div>
            <div id="test-mail-result" style="display:none; margin-top:.6rem; padding:.5rem .75rem; border-radius:4px; font-size:.875rem;"></div>
        </div>

        <p style="font-size:.82rem; color:#999; margin-top:.5rem;">
            <?= __('installer.site_mail_note') ?>
        </p>
    </div>

    <div class="step-actions">
        <a href="/installer/step/5" class="btn btn-secondary"><?= __('installer.site_back') ?></a>
        <button type="submit" class="btn btn-primary"><?= __('installer.site_complete') ?></button>
    </div>
</form>

<script>
function toggleSmtpFields(transport) {
    var el = document.getElementById('smtp-fields');
    if (el) el.style.display = (transport === 'smtp') ? '' : 'none';
}
document.addEventListener('DOMContentLoaded', function () {
    var sel = document.getElementById('mail_transport');
    if (sel) toggleSmtpFields(sel.value);

    var btnTest   = document.getElementById('btn-test-mail');
    var resultBox = document.getElementById('test-mail-result');
    var btnLabel  = <?= json_encode(__('installer.site_mail_test_btn')) ?>;

    if (btnTest) {
        btnTest.addEventListener('click', function () {
            var recipient = (document.getElementById('test_recipient')?.value || '').trim();
            if (!recipient) {
                showTestResult(false, <?= json_encode(__('installer.site_mail_enter_email')) ?>);
                return;
            }

            btnTest.disabled = true;
            btnTest.textContent = <?= json_encode(__('installer.site_mail_sending')) ?>;
            resultBox.style.display = 'none';

            var body = new URLSearchParams({
                test_recipient:     recipient,
                mail_transport:     document.getElementById('mail_transport')?.value     || 'mail',
                mail_from_address:  document.getElementById('mail_from_address')?.value  || '',
                mail_from_name:     document.getElementById('mail_from_name')?.value     || '',
                smtp_host:          document.getElementById('smtp_host')?.value          || '',
                smtp_port:          document.getElementById('smtp_port')?.value          || '587',
                smtp_username:      document.getElementById('smtp_username')?.value      || '',
                smtp_password:      document.getElementById('smtp_password')?.value      || '',
                smtp_encryption:    document.getElementById('smtp_encryption')?.value    || 'tls',
            });

            fetch('/installer/test-mail', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: body.toString(),
            })
            .then(function (r) { return r.json(); })
            .then(function (data) {
                showTestResult(data.ok, data.message || (data.ok ? <?= json_encode(__('installer.site_mail_sent')) ?> : <?= json_encode(__('installer.site_mail_failed')) ?>));
            })
            .catch(function () {
                showTestResult(false, <?= json_encode(__('installer.site_mail_request_failed')) ?>);
            })
            .finally(function () {
                btnTest.disabled    = false;
                btnTest.textContent = btnLabel;
            });
        });
    }

    function showTestResult(ok, msg) {
        resultBox.textContent    = msg;
        resultBox.style.display  = 'block';
        resultBox.style.background = ok ? '#dcfce7' : '#fff3cd';
        resultBox.style.color      = ok ? '#166534' : '#856404';
        resultBox.style.border     = '1px solid ' + (ok ? '#bbf7d0' : '#ffd06f');
    }
});
</script>

<?php $content = ob_get_clean(); include __DIR__ . '/layout.php'; ?>
