<?php $mailMethod = $settings['mail_method'] ?? 'php'; ?>
<form method="POST" action="/admin/settings">
    <?= Router::csrfField() ?>
    <input type="hidden" name="_tab" value="advanced">
    <input type="hidden" name="_sub" value="email">

    <div class="space-y-6">

        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
            <div class="px-6 py-4 border-b border-gray-200">
                <h3 class="text-sm font-semibold text-gray-900 flex items-center gap-2">
                    <svg class="w-4 h-4 text-gray-500" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/></svg>
                    Email delivery
                </h3>
            </div>
            <div class="p-6 space-y-5">

                <div>
                    <label for="contact_email" class="block text-sm font-medium text-gray-700 mb-1">Contact email</label>
                    <input type="email" id="contact_email" name="contact_email" value="<?= htmlspecialchars($settings['contact_email'] ?? '') ?>"
                           class="w-full max-w-lg px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none"
                           placeholder="contact@example.com">
                    <p class="mt-1 text-xs text-gray-500">Receives contact form submissions, report alerts and test emails. Defaults to your admin account email if empty.</p>
                </div>

                
                <div class="border-t border-gray-100 pt-5">
                    <label for="mail_method" class="block text-sm font-medium text-gray-700 mb-1">Mail provider</label>
                    <select id="mail_method" name="mail_method" onchange="tpMailProvider(this.value)"
                            class="w-full max-w-lg px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none">
                        <?php
                        $providers = [
                            'php'      => 'PHP mail() — server default',
                            'smtp'     => 'SMTP — works with any provider',
                            'resend'   => 'Resend (API)',
                            'mailgun'  => 'Mailgun (API)',
                            'brevo'    => 'Brevo / Sendinblue (API)',
                            'postmark' => 'Postmark (API)',
                            'sendgrid' => 'SendGrid (API)',
                        ];
                        foreach ($providers as $pk => $plabel): ?>
                            <option value="<?= $pk ?>" <?= $mailMethod === $pk ? 'selected' : '' ?>><?= $plabel ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="mt-1 text-xs text-gray-500">PHP mail() works on most hosting. For reliable delivery use SMTP or a transactional API (Resend, Postmark…).</p>
                </div>

                
                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 max-w-lg">
                    <div>
                        <label for="smtp_from_email" class="block text-sm font-medium text-gray-700 mb-1">From email</label>
                        <input type="email" id="smtp_from_email" name="smtp_from_email" value="<?= htmlspecialchars($settings['smtp_from_email'] ?? '') ?>"
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none"
                               placeholder="noreply@example.com">
                    </div>
                    <div>
                        <label for="smtp_from_name" class="block text-sm font-medium text-gray-700 mb-1">From name</label>
                        <input type="text" id="smtp_from_name" name="smtp_from_name" value="<?= htmlspecialchars($settings['smtp_from_name'] ?? '') ?>"
                               class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none"
                               placeholder="<?= htmlspecialchars($settings['site_name'] ?? 'TubePress') ?>">
                    </div>
                </div>

                
                <div class="tp-method border-t border-gray-100 pt-5" data-method="smtp" style="<?= $mailMethod === 'smtp' ? '' : 'display:none' ?>">
                    <div class="space-y-4">
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label for="smtp_host" class="block text-sm font-medium text-gray-700 mb-1">SMTP host</label>
                                <input type="text" id="smtp_host" name="smtp_host" value="<?= htmlspecialchars($settings['smtp_host'] ?? '') ?>"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" placeholder="smtp.gmail.com">
                            </div>
                            <div>
                                <label for="smtp_port" class="block text-sm font-medium text-gray-700 mb-1">Port</label>
                                <input type="number" id="smtp_port" name="smtp_port" value="<?= htmlspecialchars($settings['smtp_port'] ?? '587') ?>"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" min="1" max="65535" placeholder="587">
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">Encryption</label>
                            <?php $enc = $settings['smtp_encryption'] ?? 'tls'; ?>
                            <div class="flex flex-wrap gap-4">
                                <?php foreach (['none' => 'None', 'tls' => 'TLS (recommended)', 'ssl' => 'SSL'] as $ev => $el): ?>
                                    <label class="flex items-center gap-2 cursor-pointer">
                                        <input type="radio" name="smtp_encryption" value="<?= $ev ?>" <?= ($enc === $ev || ($ev === 'tls' && $enc === '')) ? 'checked' : '' ?> class="w-4 h-4 text-primary-600 focus:ring-primary-500">
                                        <span class="text-sm text-gray-700"><?= $el ?></span>
                                    </label>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label for="smtp_user" class="block text-sm font-medium text-gray-700 mb-1">Username</label>
                                <input type="text" id="smtp_user" name="smtp_user" value="<?= htmlspecialchars($settings['smtp_user'] ?? '') ?>"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" autocomplete="off" placeholder="your@gmail.com">
                            </div>
                            <div>
                                <label for="smtp_pass" class="block text-sm font-medium text-gray-700 mb-1">Password</label>
                                <div class="relative">
                                    <input type="password" id="smtp_pass" name="smtp_pass" value="<?= htmlspecialchars($settings['smtp_pass'] ?? '') ?>"
                                           class="w-full px-3 py-2 pr-10 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" autocomplete="off">
                                    <button type="button" onclick="tpEye('smtp_pass', this)" class="absolute inset-y-0 right-0 flex items-center px-3 text-gray-400 hover:text-gray-600">
                                        <svg class="w-4 h-4 eye-show" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
                                        <svg class="w-4 h-4 eye-hide hidden" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M17.94 17.94A10.07 10.07 0 0 1 12 20c-7 0-11-8-11-8a18.45 18.45 0 0 1 5.06-5.94M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 8 11 8a18.5 18.5 0 0 1-2.16 3.19m-6.72-1.07a3 3 0 1 1-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
                                    </button>
                                </div>
                            </div>
                        </div>
                        <p class="text-xs text-gray-500"><strong>Gmail:</strong> smtp.gmail.com, port 587, TLS — use an <a href="https://myaccount.google.com/apppasswords" target="_blank" class="text-primary-600 underline">App Password</a>.</p>
                    </div>
                </div>

                
                <div class="tp-method border-t border-gray-100 pt-5" data-method="resend" style="<?= $mailMethod === 'resend' ? '' : 'display:none' ?>">
                    <label for="mail_resend_key" class="block text-sm font-medium text-gray-700 mb-1">Resend API key</label>
                    <input type="password" id="mail_resend_key" name="mail_resend_key" value="<?= htmlspecialchars($settings['mail_resend_key'] ?? '') ?>"
                           class="w-full max-w-lg px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" autocomplete="off" placeholder="re_xxxxxxxxxxxxxxxx">
                    <p class="mt-1 text-xs text-gray-500">Create a key at <a href="https://resend.com/api-keys" target="_blank" class="text-primary-600 underline">resend.com/api-keys</a>. The “From email” domain must be verified in Resend.</p>
                </div>

                
                <div class="tp-method border-t border-gray-100 pt-5" data-method="mailgun" style="<?= $mailMethod === 'mailgun' ? '' : 'display:none' ?>">
                    <div class="space-y-4 max-w-lg">
                        <div>
                            <label for="mail_mailgun_key" class="block text-sm font-medium text-gray-700 mb-1">Mailgun API key</label>
                            <input type="password" id="mail_mailgun_key" name="mail_mailgun_key" value="<?= htmlspecialchars($settings['mail_mailgun_key'] ?? '') ?>"
                                   class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" autocomplete="off" placeholder="key-xxxxxxxx">
                        </div>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <div>
                                <label for="mail_mailgun_domain" class="block text-sm font-medium text-gray-700 mb-1">Sending domain</label>
                                <input type="text" id="mail_mailgun_domain" name="mail_mailgun_domain" value="<?= htmlspecialchars($settings['mail_mailgun_domain'] ?? '') ?>"
                                       class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" placeholder="mg.example.com">
                            </div>
                            <div>
                                <label for="mail_mailgun_region" class="block text-sm font-medium text-gray-700 mb-1">Region</label>
                                <?php $mgr = $settings['mail_mailgun_region'] ?? 'us'; ?>
                                <select id="mail_mailgun_region" name="mail_mailgun_region" class="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none">
                                    <option value="us" <?= $mgr !== 'eu' ? 'selected' : '' ?>>US</option>
                                    <option value="eu" <?= $mgr === 'eu' ? 'selected' : '' ?>>EU</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <p class="mt-1 text-xs text-gray-500">Find your API key and domain in your <a href="https://app.mailgun.com/" target="_blank" class="text-primary-600 underline">Mailgun dashboard</a>.</p>
                </div>

                
                <div class="tp-method border-t border-gray-100 pt-5" data-method="brevo" style="<?= $mailMethod === 'brevo' ? '' : 'display:none' ?>">
                    <label for="mail_brevo_key" class="block text-sm font-medium text-gray-700 mb-1">Brevo API key (v3)</label>
                    <input type="password" id="mail_brevo_key" name="mail_brevo_key" value="<?= htmlspecialchars($settings['mail_brevo_key'] ?? '') ?>"
                           class="w-full max-w-lg px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" autocomplete="off" placeholder="xkeysib-xxxxxxxx">
                    <p class="mt-1 text-xs text-gray-500">Generate a v3 key under <a href="https://app.brevo.com/settings/keys/api" target="_blank" class="text-primary-600 underline">Brevo → SMTP &amp; API → API Keys</a>. Authorise the “From email” as a sender.</p>
                </div>

                
                <div class="tp-method border-t border-gray-100 pt-5" data-method="postmark" style="<?= $mailMethod === 'postmark' ? '' : 'display:none' ?>">
                    <label for="mail_postmark_token" class="block text-sm font-medium text-gray-700 mb-1">Postmark server token</label>
                    <input type="password" id="mail_postmark_token" name="mail_postmark_token" value="<?= htmlspecialchars($settings['mail_postmark_token'] ?? '') ?>"
                           class="w-full max-w-lg px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" autocomplete="off" placeholder="xxxxxxxx-xxxx-xxxx">
                    <p class="mt-1 text-xs text-gray-500">Server → API Tokens in your <a href="https://account.postmarkapp.com/" target="_blank" class="text-primary-600 underline">Postmark account</a>. The “From email” must use a confirmed Sender Signature.</p>
                </div>

                
                <div class="tp-method border-t border-gray-100 pt-5" data-method="sendgrid" style="<?= $mailMethod === 'sendgrid' ? '' : 'display:none' ?>">
                    <label for="mail_sendgrid_key" class="block text-sm font-medium text-gray-700 mb-1">SendGrid API key</label>
                    <input type="password" id="mail_sendgrid_key" name="mail_sendgrid_key" value="<?= htmlspecialchars($settings['mail_sendgrid_key'] ?? '') ?>"
                           class="w-full max-w-lg px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-primary-500 focus:border-primary-500 outline-none" autocomplete="off" placeholder="SG.xxxxxxxx">
                    <p class="mt-1 text-xs text-gray-500">Create a key with “Mail Send” permission in <a href="https://app.sendgrid.com/settings/api_keys" target="_blank" class="text-primary-600 underline">SendGrid → API Keys</a>. Verify the “From email” as a Single Sender.</p>
                </div>

                
                <div class="border-t border-gray-100 pt-4">
                    <div class="flex items-center gap-3">
                        <button type="button" id="testEmailBtn" onclick="testEmail()" class="inline-flex items-center gap-2 px-3 py-1.5 bg-gray-100 text-gray-700 text-sm font-medium rounded-lg hover:bg-gray-200 transition-colors">
                            <svg class="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 2L11 13"/><path d="M22 2L15 22 11 13 2 9 22 2z"/></svg>
                            Send test email
                        </button>
                        <span id="testEmailResult" class="text-sm"></span>
                    </div>
                    <p class="mt-1 text-xs text-gray-500">Sends a test email to your contact email using the saved configuration. Save changes first.</p>
                </div>
            </div>
        </div>
    </div>

    <div class="mt-6">
        <button type="submit" class="inline-flex items-center px-4 py-2 bg-primary-600 text-white text-sm font-medium rounded-lg hover:bg-primary-700 transition-colors">Save changes</button>
    </div>
</form>

<script>
function tpMailProvider(v) {
    document.querySelectorAll('.tp-method').forEach(function (el) {
        el.style.display = (el.getAttribute('data-method') === v) ? '' : 'none';
    });
}
function tpEye(id, btn) {
    var i = document.getElementById(id);
    i.type = i.type === 'password' ? 'text' : 'password';
    btn.querySelector('.eye-show').classList.toggle('hidden');
    btn.querySelector('.eye-hide').classList.toggle('hidden');
}
function testEmail() {
    const btn = document.getElementById('testEmailBtn');
    const result = document.getElementById('testEmailResult');
    btn.disabled = true; btn.style.opacity = '0.6';
    result.textContent = 'Sending...'; result.className = 'text-sm text-gray-500';
    const csrf = document.querySelector('input[name="csrf_token"]')?.value || '';
    fetch('/admin/settings/test-email', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest'},
        body: 'csrf_token=' + encodeURIComponent(csrf)
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) { result.textContent = 'Test email sent successfully!'; result.className = 'text-sm text-green-600'; }
        else { result.textContent = data.error || 'Failed to send test email.'; result.className = 'text-sm text-red-600'; }
    })
    .catch(() => { result.textContent = 'Network error. Please try again.'; result.className = 'text-sm text-red-600'; })
    .finally(() => { btn.disabled = false; btn.style.opacity = '1'; });
}
</script>
