<?php
$tgEnabled = ($settings['telegram_enabled'] ?? '0') === '1';
$events = [
    'contact' => ['New contact message', 'A visitor submits the contact form.', '1'],
    'report'  => ['New content report', 'A visitor reports a video.', '1'],
    'user'    => ['New registration', 'A visitor creates an account.', '0'],
    'comment' => ['New comment', 'A visitor posts a comment.', '0'],
];
?>
<form method="POST" action="/admin/settings">
    <?= Router::csrfField() ?>
    <input type="hidden" name="_tab" value="advanced">
    <input type="hidden" name="_sub" value="telegram">

    <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 flex items-start justify-between gap-4">
                <h3 class="text-sm font-semibold text-gray-900 flex items-center gap-2">
                    <i class="fa-brands fa-telegram text-[#229ED9]"></i> Telegram notifications
                </h3>
                <label class="relative inline-flex items-center cursor-pointer shrink-0" title="Enable Telegram notifications">
                    <input type="checkbox" name="telegram_enabled" value="1" class="sr-only peer" <?= $tgEnabled ? 'checked' : '' ?>>
                    <div class="w-9 h-5 bg-gray-300 rounded-full peer peer-checked:bg-primary-600 transition-colors after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-transform peer-checked:after:translate-x-4 after:shadow-sm"></div>
                </label>
            </div>
            <div class="p-6 space-y-5">
                <div class="flex items-start gap-3 p-4 bg-blue-50 border border-blue-200 rounded-lg">
                    <i class="fa-solid fa-circle-info text-blue-500 mt-0.5"></i>
                    <div>
                        <p class="text-sm font-medium text-blue-900">How to set this up</p>
                        <ol class="text-xs text-blue-700 mt-1 list-decimal pl-4 space-y-0.5">
                            <li>In Telegram, message <a href="https://t.me/BotFather" target="_blank" class="underline">@BotFather</a> and send <code class="bg-white/70 px-1 rounded">/newbot</code> to get a <strong>bot token</strong>.</li>
                            <li>Start a chat with your new bot (or add it to a group) and send it any message.</li>
                            <li>Open <code class="bg-white/70 px-1 rounded">https://api.telegram.org/bot&lt;token&gt;/getUpdates</code> and copy the <strong>chat id</strong> from the response.</li>
                            <li>Paste both below, save, then hit <strong>Send test message</strong>.</li>
                        </ol>
                    </div>
                </div>

                <div>
                    <label for="telegram_bot_token" class="block text-sm font-medium text-gray-700 mb-1">Bot token</label>
                    <div class="relative max-w-lg">
                        <input type="password" id="telegram_bot_token" name="telegram_bot_token" value="<?= htmlspecialchars($settings['telegram_bot_token'] ?? '') ?>"
                               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" placeholder="123456789:ABCdefGhIJKlmNoPQRsTUVwxyz">
                        <button type="button" onclick="tpEyeTg('telegram_bot_token', 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>
                    <label for="telegram_chat_id" class="block text-sm font-medium text-gray-700 mb-1">Chat ID</label>
                    <input type="text" id="telegram_chat_id" name="telegram_chat_id" value="<?= htmlspecialchars($settings['telegram_chat_id'] ?? '') ?>"
                           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="123456789 or -100xxxxxxxxxx">
                    <p class="mt-1 text-xs text-gray-500">A personal chat is a positive number; a group/channel id starts with <code class="bg-gray-100 px-1 rounded">-100</code>.</p>
                </div>

                <div class="border-t border-gray-100 pt-4">
                    <div class="flex items-center gap-3">
                        <button type="button" id="testTgBtn" onclick="testTelegram()" 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">
                            <i class="fa-brands fa-telegram"></i> Send test message
                        </button>
                        <span id="testTgResult" class="text-sm"></span>
                    </div>
                    <p class="mt-1 text-xs text-gray-500">Uses the token &amp; chat id currently in the form — no need to save first.</p>
                </div>
            </div>
        </div>

        
        <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">Notify me about…</h3>
            </div>
            <div class="divide-y divide-gray-100">
                <?php foreach ($events as $ev => $meta):
                    $on = ($settings['telegram_event_' . $ev] ?? $meta[2]) === '1';
                ?>
                <label class="flex items-center justify-between gap-4 px-6 py-4 cursor-pointer hover:bg-gray-50 transition-colors">
                    <div>
                        <div class="text-sm font-medium text-gray-800"><?= htmlspecialchars($meta[0]) ?></div>
                        <div class="text-xs text-gray-500 mt-0.5"><?= htmlspecialchars($meta[1]) ?></div>
                    </div>
                    <span class="relative inline-flex items-center shrink-0">
                        <input type="checkbox" name="telegram_event_<?= $ev ?>" value="1" class="sr-only peer" <?= $on ? 'checked' : '' ?>>
                        <span class="w-9 h-5 bg-gray-300 rounded-full peer peer-checked:bg-primary-600 transition-colors after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:rounded-full after:h-4 after:w-4 after:transition-transform peer-checked:after:translate-x-4 after:shadow-sm"></span>
                    </span>
                </label>
                <?php endforeach; ?>
            </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 tpEyeTg(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 testTelegram() {
    const btn = document.getElementById('testTgBtn');
    const result = document.getElementById('testTgResult');
    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 || '';
    const token = document.getElementById('telegram_bot_token').value || '';
    const chat = document.getElementById('telegram_chat_id').value || '';
    fetch('/admin/settings/test-telegram', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest'},
        body: 'csrf_token=' + encodeURIComponent(csrf) + '&telegram_bot_token=' + encodeURIComponent(token) + '&telegram_chat_id=' + encodeURIComponent(chat)
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) { result.textContent = 'Test message sent! Check Telegram.'; result.className = 'text-sm text-green-600'; }
        else { result.textContent = data.error || 'Failed to send test message.'; 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>
