<?php
$encryptionOptions = ['tls' => 'TLS', 'ssl' => 'SSL', '' => 'None'];
$cfg = $config ?? [];
$notifyAgents = !empty($cfg['notify_agent_ids']) ? (array)json_decode($cfg['notify_agent_ids'], true) : [];
if (!is_array($notifyAgents)) $notifyAgents = [];
$notifyAgents = array_values(array_filter(array_map('intval', $notifyAgents)));
$notifyAdmins = !empty($cfg['notify_admin_ids']) ? (array)json_decode($cfg['notify_admin_ids'], true) : [];
if (!is_array($notifyAdmins)) $notifyAdmins = [];
$notifyAdmins = array_values(array_filter(array_map('intval', $notifyAdmins)));
?>

<div class="space-y-6">
    <div class="flex flex-wrap items-center justify-between gap-3">
        <div>
            <h2 class="text-lg font-bold text-slate-800">Booking SMTP &amp; Notifications</h2>
            <p class="text-sm text-slate-500">Configure outgoing email settings and manage booking notification recipients.</p>
        </div>
    </div>

    <div class="glass rounded-2xl shadow-sm border border-slate-200/60 p-6">
        <div class="flex items-start gap-3 mb-5">
            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-sky-500 to-indigo-500 text-white flex items-center justify-center shadow-md shadow-sky-500/20 flex-shrink-0">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" /></svg>
            </div>
            <div class="flex-1">
                <h3 class="text-base font-semibold text-slate-800">SMTP Server Settings</h3>
                <p class="text-[11px] text-slate-500 mt-0.5">These credentials are used to send booking confirmations, cancellations, and alerts.</p>
            </div>
        </div>
        <form method="post" action="<?= site_url('/admin/booking-smtp') ?>" id="smtpForm" class="space-y-4">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="save">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">SMTP Host</label>
                    <input type="text" name="smtp_host" value="<?= esc($cfg['smtp_host'] ?? '') ?>" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-mono focus:ring-2 focus:ring-sky-500/30 focus:border-sky-500 outline-none transition" placeholder="smtp.example.com">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">SMTP Port</label>
                    <input type="number" name="smtp_port" value="<?= esc($cfg['smtp_port'] ?? '587') ?>" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-mono focus:ring-2 focus:ring-sky-500/30 focus:border-sky-500 outline-none transition" placeholder="587">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">SMTP Username</label>
                    <input type="text" name="smtp_user" value="<?= esc($cfg['smtp_user'] ?? '') ?>" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-mono focus:ring-2 focus:ring-sky-500/30 focus:border-sky-500 outline-none transition" placeholder="user@example.com">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">SMTP Password</label>
                    <input type="password" name="smtp_pass" value="<?= esc($cfg['smtp_pass'] ?? '') ?>" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm font-mono focus:ring-2 focus:ring-sky-500/30 focus:border-sky-500 outline-none transition" placeholder="••••••••">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">From Email</label>
                    <input type="email" name="from_email" value="<?= esc($cfg['from_email'] ?? '') ?>" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm focus:ring-2 focus:ring-sky-500/30 focus:border-sky-500 outline-none transition" placeholder="bookings@yourcompany.com">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">From Name</label>
                    <input type="text" name="from_name" value="<?= esc($cfg['from_name'] ?? '') ?>" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm focus:ring-2 focus:ring-sky-500/30 focus:border-sky-500 outline-none transition" placeholder="Your Company Bookings">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Encryption</label>
                    <select name="smtp_encryption" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm focus:ring-2 focus:ring-sky-500/30 focus:border-sky-500 outline-none transition">
                        <?php foreach ($encryptionOptions as $val => $label): ?>
                            <option value="<?= esc($val) ?>" <?= ($cfg['smtp_encryption'] ?? 'tls') === $val ? 'selected' : '' ?>><?= esc($label) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
            <div class="flex flex-wrap items-center gap-3 pt-2">
                <button type="submit" class="px-6 py-2.5 rounded-xl text-sm font-semibold text-white bg-gradient-to-r from-sky-600 to-indigo-600 shadow-md hover:shadow-lg transition">
                    Save SMTP Settings
                </button>
                <button type="button" id="btnTestConnection" class="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-semibold bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 transition">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" /></svg>
                    Test Connection
                </button>
                <button type="button" id="btnSendTestMail" class="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl text-sm font-semibold bg-gradient-to-r from-emerald-50 to-teal-50 hover:from-emerald-100 hover:to-teal-100 text-emerald-800 border border-emerald-200 transition">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" /></svg>
                    Send Test Email
                </button>
            </div>
            <div id="smtpTestResult" class="hidden"></div>
        </form>
    </div>

    <div class="glass rounded-2xl shadow-sm border border-slate-200/60 p-6">
        <div class="flex items-start gap-3 mb-5">
            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-violet-500 to-fuchsia-500 text-white flex items-center justify-center shadow-md shadow-violet-500/20 flex-shrink-0">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" /></svg>
            </div>
            <div class="flex-1">
                <h3 class="text-base font-semibold text-slate-800">Notifications</h3>
                <p class="text-[11px] text-slate-500 mt-0.5">Control who receives notifications when bookings are created, cancelled, or updated.</p>
            </div>
        </div>
        <form method="post" action="<?= site_url('/admin/booking-smtp') ?>" id="notifyForm" class="space-y-5">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="save_notifications">

            <div class="p-4 rounded-2xl bg-gradient-to-br from-violet-50/70 to-white border border-violet-100">
                <div class="flex items-center justify-between flex-wrap gap-3">
                    <div>
                        <p class="text-sm font-bold text-violet-900">Enable Notifications</p>
                        <p class="text-[11px] text-violet-600 mt-0.5">Globally toggle all booking-related email notifications.</p>
                    </div>
                    <label class="relative inline-flex items-center cursor-pointer">
                        <input type="checkbox" name="enable_notifications" value="1" <?= !empty($cfg['enable_notifications']) ? 'checked' : '' ?> class="sr-only peer">
                        <div class="w-12 h-7 bg-slate-200 rounded-full peer peer-checked:bg-gradient-to-r peer-checked:from-violet-600 peer-checked:to-fuchsia-600 transition after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-white after:rounded-full after:h-6 after:w-6 after:transition-all peer-checked:after:translate-x-5 shadow-sm"></div>
                    </label>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">
                        Notify Agents
                        <span class="text-[10px] text-slate-400 font-normal ml-1">(<?= count($notifyAgents) ?> selected)</span>
                    </label>
                    <div class="rounded-xl border border-slate-300 bg-white max-h-56 overflow-y-auto scrollbar-thin">
                        <?php if (empty($agents)): ?>
                            <div class="p-4 text-center text-[11px] text-slate-500">No agents defined.</div>
                        <?php else: ?>
                            <?php foreach ($agents as $u):
                                $uid = (int)$u['id'];
                                $checked = in_array($uid, $notifyAgents, true);
                            ?>
                                <label class="flex items-start gap-2.5 px-3 py-2 border-b border-slate-100 last:border-b-0 hover:bg-slate-50 transition cursor-pointer">
                                    <input type="checkbox" name="notify_agent_ids[]" value="<?= $uid ?>" <?= $checked ? 'checked' : '' ?> class="mt-0.5 w-4 h-4 text-violet-600 rounded">
                                    <div class="flex-1 min-w-0">
                                        <span class="text-[12px] font-medium text-slate-800 truncate block"><?= esc($u['full_name'] ?? $u['username'] ?? 'Agent') ?></span>
                                        <span class="text-[10px] text-slate-500"><?= esc($u['email'] ?? '') ?></span>
                                    </div>
                                </label>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">
                        Notify Admins
                        <span class="text-[10px] text-slate-400 font-normal ml-1">(<?= count($notifyAdmins) ?> selected)</span>
                    </label>
                    <div class="rounded-xl border border-slate-300 bg-white max-h-56 overflow-y-auto scrollbar-thin">
                        <?php if (empty($admins)): ?>
                            <div class="p-4 text-center text-[11px] text-slate-500">No admins defined.</div>
                        <?php else: ?>
                            <?php foreach ($admins as $u):
                                $uid = (int)$u['id'];
                                $checked = in_array($uid, $notifyAdmins, true);
                            ?>
                                <label class="flex items-start gap-2.5 px-3 py-2 border-b border-slate-100 last:border-b-0 hover:bg-slate-50 transition cursor-pointer">
                                    <input type="checkbox" name="notify_admin_ids[]" value="<?= $uid ?>" <?= $checked ? 'checked' : '' ?> class="mt-0.5 w-4 h-4 text-violet-600 rounded">
                                    <div class="flex-1 min-w-0">
                                        <span class="text-[12px] font-medium text-slate-800 truncate block"><?= esc($u['full_name'] ?? $u['username'] ?? 'Admin') ?></span>
                                        <span class="text-[10px] text-slate-500"><?= esc($u['email'] ?? '') ?></span>
                                    </div>
                                </label>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
                <div>
                    <div class="p-4 rounded-2xl bg-gradient-to-br from-emerald-50/70 to-white border border-emerald-100 mb-3">
                        <div class="flex items-center justify-between flex-wrap gap-3">
                            <div>
                                <p class="text-sm font-bold text-emerald-900">Lead Notification</p>
                                <p class="text-[11px] text-emerald-600 mt-0.5">Send confirmation &amp; cancellation emails to leads.</p>
                            </div>
                            <label class="relative inline-flex items-center cursor-pointer">
                                <input type="checkbox" name="enable_lead_notification" value="1" <?= !empty($cfg['enable_lead_notification']) ? 'checked' : '' ?> class="sr-only peer">
                                <div class="w-12 h-7 bg-slate-200 rounded-full peer peer-checked:bg-gradient-to-r peer-checked:from-emerald-500 peer-checked:to-teal-500 transition after:content-[''] after:absolute after:top-0.5 after:left-0.5 after:bg-white after:rounded-full after:h-6 after:w-6 after:transition-all peer-checked:after:translate-x-5 shadow-sm"></div>
                            </label>
                        </div>
                    </div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">From Email (Lead Emails)</label>
                    <input type="email" name="lead_from_email" value="<?= esc($cfg['lead_from_email'] ?? $cfg['from_email'] ?? '') ?>" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm focus:ring-2 focus:ring-emerald-500/30 focus:border-emerald-500 outline-none transition" placeholder="noreply@yourcompany.com">
                </div>
                <div class="space-y-4">
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">Booking Default Location URL</label>
                        <input type="url" name="booking_location_url" value="<?= esc($cfg['booking_location_url'] ?? '') ?>" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm focus:ring-2 focus:ring-sky-500/30 focus:border-sky-500 outline-none transition" placeholder="https://zoom.us/j/... or https://maps.google.com/...">
                    </div>
                    <div>
                        <label class="block text-xs font-semibold text-slate-600 mb-1.5">Email Logo URL</label>
                        <input type="url" name="email_logo_url" value="<?= esc($cfg['email_logo_url'] ?? '') ?>" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm focus:ring-2 focus:ring-sky-500/30 focus:border-sky-500 outline-none transition" placeholder="https://yourcompany.com/logo.png">
                    </div>
                </div>
            </div>

            <div class="flex justify-end pt-2">
                <button type="submit" class="px-6 py-2.5 rounded-xl text-sm font-semibold text-white bg-gradient-to-r from-violet-600 to-fuchsia-600 shadow-md hover:shadow-lg transition">
                    Save Notification Settings
                </button>
            </div>
        </form>
    </div>

    <div class="glass rounded-2xl shadow-sm border border-slate-200/60 p-6">
        <div class="flex items-start gap-3 mb-4">
            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-amber-500 to-orange-500 text-white flex items-center justify-center shadow-md shadow-amber-500/20 flex-shrink-0">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
            </div>
            <div class="flex-1">
                <h3 class="text-base font-semibold text-slate-800">Quick Tips</h3>
                <p class="text-[11px] text-slate-500 mt-0.5">Common SMTP provider settings.</p>
            </div>
        </div>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-3 text-[11px]">
            <div class="p-3.5 rounded-xl bg-gradient-to-br from-red-50 to-white border border-red-100">
                <p class="font-extrabold text-red-800 mb-1">Gmail / Google Workspace</p>
                <div class="space-y-0.5 text-slate-600 font-mono">Host: smtp.gmail.com</div>
                <div class="space-y-0.5 text-slate-600 font-mono">Port: 587 (TLS)</div>
                <div class="mt-1 text-slate-500">Use an App Password if 2FA is enabled.</div>
            </div>
            <div class="p-3.5 rounded-xl bg-gradient-to-br from-blue-50 to-white border border-blue-100">
                <p class="font-extrabold text-blue-800 mb-1">Office 365 / Outlook</p>
                <div class="space-y-0.5 text-slate-600 font-mono">Host: smtp.office365.com</div>
                <div class="space-y-0.5 text-slate-600 font-mono">Port: 587 (TLS)</div>
                <div class="mt-1 text-slate-500">Authenticate with your full email address.</div>
            </div>
            <div class="p-3.5 rounded-xl bg-gradient-to-br from-violet-50 to-white border border-violet-100">
                <p class="font-extrabold text-violet-800 mb-1">SendGrid / Mailgun / SES</p>
                <div class="space-y-0.5 text-slate-600 font-mono">Host varies by provider</div>
                <div class="space-y-0.5 text-slate-600 font-mono">Port: 587 (TLS) or 465 (SSL)</div>
                <div class="mt-1 text-slate-500">Use your provider's SMTP credentials.</div>
            </div>
        </div>
    </div>
</div>

<script>
(function () {
    const btnConn   = document.getElementById('btnTestConnection');
    const btnMail   = document.getElementById('btnSendTestMail');
    const resultEl  = document.getElementById('smtpTestResult');
    const form      = document.getElementById('smtpForm');

    function collectSmtpData() {
        const fd = new FormData();
        const mapping = ['smtp_host','smtp_port','smtp_user','smtp_pass','from_email','from_name','smtp_encryption'];
        mapping.forEach(k => {
            const el = form.querySelector('[name="' + k + '"]');
            if (el) fd.append(k, el.value);
        });
        const csrfName = '<?= csrf_token() ?>';
        const csrfHash = '<?= csrf_hash() ?>';
        fd.append(csrfName, csrfHash);
        return fd;
    }

    function setResult(ok, text) {
        resultEl.classList.remove('hidden');
        resultEl.className = 'mt-4 rounded-2xl p-4 border ' +
            (ok ? 'bg-emerald-50/70 border-emerald-200/80' : 'bg-rose-50/70 border-rose-200/80');
        resultEl.innerHTML =
            '<div class="flex items-center gap-3">' +
                (ok
                    ? '<div class="w-9 h-9 rounded-xl bg-emerald-500 text-white flex items-center justify-center flex-shrink-0"><svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" /></svg></div>'
                    : '<div class="w-9 h-9 rounded-xl bg-rose-500 text-white flex items-center justify-center flex-shrink-0"><svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg></div>') +
                '<div class="flex-1 min-w-0">' +
                    '<p class="text-sm font-bold ' + (ok ? 'text-emerald-800' : 'text-rose-800') + '">' + (ok ? 'Success' : 'Failed') + '</p>' +
                    '<p class="text-[12px] ' + (ok ? 'text-emerald-700' : 'text-rose-700') + ' mt-0.5">' + text + '</p>' +
                '</div>' +
            '</div>';
    }

    function busyBtn(btn, busy, label) {
        if (busy) {
            btn.disabled = true;
            btn.classList.add('opacity-60', 'cursor-not-allowed');
            btn._orig = btn.innerHTML;
            btn.innerHTML = '<svg class="animate-spin w-4 h-4 mr-2 inline" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>' + label;
        } else {
            btn.disabled = false;
            btn.classList.remove('opacity-60', 'cursor-not-allowed');
            if (btn._orig) btn.innerHTML = btn._orig;
        }
    }

    btnConn?.addEventListener('click', async () => {
        busyBtn(btnConn, true, 'Connecting...');
        resultEl.classList.add('hidden');
        try {
            const resp = await fetch('<?= site_url('/admin/booking-smtp/test-connection') ?>', {
                method: 'POST',
                headers: { 'X-Requested-With': 'XMLHttpRequest' },
                body: collectSmtpData(),
                credentials: 'same-origin',
            });
            let data;
            try { data = await resp.json(); } catch (e) { data = { ok: false, message: 'Bad response from server.' }; }
            setResult(!!data.ok, data.message || (data.ok ? 'SMTP server connection successful.' : 'Unknown error.'));
        } catch (e) {
            setResult(false, 'Network error: ' + e.message);
        } finally {
            busyBtn(btnConn, false);
        }
    });

    btnMail?.addEventListener('click', async () => {
        busyBtn(btnMail, true, 'Sending...');
        resultEl.classList.add('hidden');
        try {
            const resp = await fetch('<?= site_url('/admin/booking-smtp/test-mail') ?>', {
                method: 'POST',
                headers: { 'X-Requested-With': 'XMLHttpRequest' },
                body: collectSmtpData(),
                credentials: 'same-origin',
            });
            let data;
            try { data = await resp.json(); } catch (e) { data = { ok: false, message: 'Bad response from server.' }; }
            setResult(!!data.ok, data.message || (data.ok ? 'Test email queued successfully.' : 'Unknown error.'));
        } catch (e) {
            setResult(false, 'Network error: ' + e.message);
        } finally {
            busyBtn(btnMail, false);
        }
    });
})();
</script>
