<?php
use App\Models\Setting;
$driver = $settings['whatsapp']['whatsapp_driver'] ?? 'self_hosted_qr';
$webhookUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost:8000') . '/webhook';
?>
<div class="p-8 max-w-4xl mx-auto space-y-8">

    <!-- Header -->
    <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
            <h1 class="text-2xl font-bold text-white tracking-tight">WhatsApp API & Connection Settings</h1>
            <p class="text-slate-400 text-xs">Choose how to link your WhatsApp number (Free QR Code Web engine, Paid Gateway, or Meta Cloud API).</p>
        </div>
        <a href="/settings/simulator" class="bg-purple-500 hover:bg-purple-600 text-white text-xs font-semibold px-4 py-2 rounded-xl transition shadow-lg shadow-purple-500/20 flex items-center space-x-1.5 self-start sm:self-auto">
            <i class="fa-solid fa-flask text-xs"></i>
            <span>Open Webhook Simulator</span>
        </a>
    </div>

    <!-- Main Configuration Form -->
    <form method="POST" action="/settings" class="space-y-6">

        <!-- Connection Driver Selection -->
        <div class="bg-slate-900 border border-slate-800 rounded-3xl p-6 shadow-xl space-y-4">
            <h3 class="font-bold text-white text-sm">1. Choose Connection Method</h3>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                
                <!-- Option 1: Free Self-Hosted WhatsApp Web QR Engine (Recommended) -->
                <label class="p-4 rounded-2xl border cursor-pointer transition flex flex-col justify-between <?= ($driver === 'self_hosted_qr' || $driver === 'local_qr' || empty($driver)) ? 'bg-emerald-500/10 border-emerald-500/50' : 'bg-slate-950/60 border-slate-800 hover:border-slate-700' ?>">
                    <div class="space-y-2">
                        <div class="flex items-center justify-between">
                            <input type="radio" name="whatsapp_driver" value="self_hosted_qr" onchange="toggleDriver(this.value)" <?= ($driver === 'self_hosted_qr' || $driver === 'local_qr' || empty($driver)) ? 'checked' : '' ?> class="text-emerald-500 bg-slate-900 border-slate-700 focus:ring-emerald-500">
                            <span class="text-[9px] bg-emerald-500/20 text-emerald-400 font-bold px-1.5 py-0.5 rounded">100% Free Forever</span>
                        </div>
                        <span class="font-bold text-white text-xs block">🆓 Free WhatsApp Web QR</span>
                        <p class="text-[11px] text-slate-400 leading-relaxed">
                            Scan direct WhatsApp Web QR code using your phone. Zero cost, no monthly fees, no Meta account required.
                        </p>
                    </div>
                </label>

                <!-- Option 2: Remote / Cloud Gateway (UltraMsg) -->
                <label class="p-4 rounded-2xl border cursor-pointer transition flex flex-col justify-between <?= ($driver === 'gateway' || $driver === 'ultramsg') ? 'bg-emerald-500/10 border-emerald-500/50' : 'bg-slate-950/60 border-slate-800 hover:border-slate-700' ?>">
                    <div class="space-y-2">
                        <div class="flex items-center justify-between">
                            <input type="radio" name="whatsapp_driver" value="gateway" onchange="toggleDriver(this.value)" <?= ($driver === 'gateway' || $driver === 'ultramsg') ? 'checked' : '' ?> class="text-emerald-500 bg-slate-900 border-slate-700 focus:ring-emerald-500">
                            <span class="text-[9px] bg-blue-500/20 text-blue-400 font-bold px-1.5 py-0.5 rounded">Cloud Hosted</span>
                        </div>
                        <span class="font-bold text-white text-xs block">🌐 Cloud Gateway (UltraMsg)</span>
                        <p class="text-[11px] text-slate-400 leading-relaxed">
                            Connect via UltraMsg or external QR API with Instance ID & Token.
                        </p>
                    </div>
                </label>

                <!-- Option 3: Official Meta Cloud API -->
                <label class="p-4 rounded-2xl border cursor-pointer transition flex flex-col justify-between <?= ($driver === 'meta') ? 'bg-emerald-500/10 border-emerald-500/50' : 'bg-slate-950/60 border-slate-800 hover:border-slate-700' ?>">
                    <div class="space-y-2">
                        <div class="flex items-center justify-between">
                            <input type="radio" name="whatsapp_driver" value="meta" onchange="toggleDriver(this.value)" <?= ($driver === 'meta') ? 'checked' : '' ?> class="text-emerald-500 bg-slate-900 border-slate-700 focus:ring-emerald-500">
                            <span class="text-[9px] bg-purple-500/20 text-purple-400 font-bold px-1.5 py-0.5 rounded">Meta Official</span>
                        </div>
                        <span class="font-bold text-white text-xs block">☁️ Meta WhatsApp Cloud API</span>
                        <p class="text-[11px] text-slate-400 leading-relaxed">
                            Official Graph API (requires Meta Developer Account & Business Verification).
                        </p>
                    </div>
                </label>

            </div>
        </div>

        <!-- 2A. Free Self-Hosted WhatsApp Web QR Box -->
        <div id="box-self_hosted_qr" class="<?= ($driver !== 'self_hosted_qr' && $driver !== 'local_qr' && !empty($driver)) ? 'hidden' : '' ?> bg-slate-900 border border-slate-800 rounded-3xl p-6 shadow-xl space-y-6">
            <div class="flex items-center justify-between border-b border-slate-800 pb-3">
                <div>
                    <h3 class="font-bold text-white text-sm">2. Scan WhatsApp Web QR Code (Free Engine)</h3>
                    <p class="text-xs text-slate-400 mt-0.5">Direct multi-device connection without middleman services.</p>
                </div>
                <button type="button" onclick="QrEngine.checkStatus()" class="text-xs text-emerald-400 hover:text-emerald-300 font-semibold flex items-center space-x-1">
                    <i class="fa-solid fa-arrows-rotate"></i>
                    <span>Refresh Status</span>
                </button>
            </div>

            <!-- Live Status & QR Display Box -->
            <div class="bg-slate-950 border border-slate-800 rounded-2xl p-6 flex flex-col items-center justify-center text-center space-y-4">
                
                <!-- Status Badge -->
                <div id="qr-status-badge" class="inline-flex items-center space-x-2 px-3 py-1.5 rounded-full text-xs font-semibold bg-slate-800 text-slate-400 border border-slate-700">
                    <span class="w-2 h-2 rounded-full bg-slate-500"></span>
                    <span>Checking server status...</span>
                </div>

                <!-- QR Code Container -->
                <div id="qr-code-wrapper" class="hidden">
                    <div class="p-3 bg-white rounded-2xl inline-block shadow-2xl">
                        <img id="qr-code-img" src="" alt="WhatsApp QR Code" class="w-56 h-56 mx-auto">
                    </div>
                    <p class="text-xs text-slate-300 font-semibold mt-3">
                        📱 Open WhatsApp $\rightarrow$ <span class="text-emerald-400 font-bold">Linked Devices</span> $\rightarrow$ <span class="text-emerald-400 font-bold">Link a Device</span> and scan this QR code.
                    </p>
                </div>

                <!-- Connected State Box -->
                <div id="qr-connected-wrapper" class="hidden space-y-3">
                    <div class="w-16 h-16 rounded-2xl bg-emerald-500/20 border border-emerald-500/40 mx-auto flex items-center justify-center text-emerald-400 text-3xl">
                        <i class="fa-solid fa-circle-check"></i>
                    </div>
                    <h4 class="text-base font-bold text-white">WhatsApp Connected & Active!</h4>
                    <p id="qr-connected-phone" class="text-xs text-slate-400 font-mono">Linked Number: +1234567890</p>
                    <button type="button" onclick="QrEngine.logout()" class="text-xs bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/30 px-3.5 py-2 rounded-xl transition">
                        Disconnect / Unlink Device
                    </button>
                </div>

                <!-- Offline Server Helper -->
                <div id="qr-offline-wrapper" class="hidden space-y-3 max-w-md">
                    <div class="w-12 h-12 rounded-xl bg-amber-500/10 border border-amber-500/20 mx-auto flex items-center justify-center text-amber-400 text-xl">
                        <i class="fa-solid fa-triangle-exclamation"></i>
                    </div>
                    <h4 class="text-sm font-bold text-white">WhatsApp QR Server Not Running</h4>
                    <p class="text-xs text-slate-400">
                        To launch your free WhatsApp Web engine on port 3000, simply double-click <code class="text-emerald-400 bg-slate-900 px-1.5 py-0.5 rounded">start-whatsapp-qr.bat</code> inside your project directory.
                    </p>
                </div>

            </div>
        </div>

        <!-- 2B. Cloud Gateway Settings Box (UltraMsg) -->
        <div id="box-gateway" class="<?= ($driver !== 'gateway' && $driver !== 'ultramsg') ? 'hidden' : '' ?> bg-slate-900 border border-slate-800 rounded-3xl p-6 shadow-xl space-y-5">
            <div class="border-b border-slate-800 pb-3">
                <h3 class="font-bold text-white text-sm">2. Cloud Gateway Configuration (UltraMsg)</h3>
                <p class="text-xs text-slate-400 mt-0.5">Enter credentials from your UltraMsg or custom gateway provider.</p>
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs text-slate-400 mb-1 font-semibold">Instance ID</label>
                    <input type="text" name="gateway_instance_id" value="<?= htmlspecialchars($settings['gateway']['gateway_instance_id'] ?? '') ?>" placeholder="e.g. instance105820" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs font-mono text-white focus:outline-none focus:border-emerald-500">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1 font-semibold">API Token</label>
                    <input type="password" name="gateway_token" value="<?= htmlspecialchars($settings['gateway']['gateway_token'] ?? '') ?>" placeholder="e.g. abcdef123456" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs font-mono text-white focus:outline-none focus:border-emerald-500">
                </div>
            </div>

            <div>
                <label class="block text-xs text-slate-400 mb-1 font-semibold">Gateway Base API URL</label>
                <input type="text" name="gateway_api_url" value="<?= htmlspecialchars($settings['gateway']['gateway_api_url'] ?? 'https://api.ultramsg.com') ?>" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs font-mono text-white focus:outline-none focus:border-emerald-500">
            </div>
        </div>

        <!-- 2C. Meta Cloud API Settings Box -->
        <div id="box-meta" class="<?= ($driver !== 'meta') ? 'hidden' : '' ?> bg-slate-900 border border-slate-800 rounded-3xl p-6 shadow-xl space-y-5">
            <div class="border-b border-slate-800 pb-3">
                <h3 class="font-bold text-white text-sm">2. Meta WhatsApp Cloud API Credentials</h3>
                <p class="text-xs text-slate-400 mt-0.5">Enter credentials from developers.facebook.com</p>
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs text-slate-400 mb-1">Phone Number ID</label>
                    <input type="text" name="whatsapp_phone_number_id" value="<?= htmlspecialchars($settings['meta']['whatsapp_phone_number_id'] ?? '') ?>" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white font-mono focus:outline-none focus:border-emerald-500">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1">WhatsApp Business Account ID (WABA ID)</label>
                    <input type="text" name="whatsapp_waba_id" value="<?= htmlspecialchars($settings['meta']['whatsapp_waba_id'] ?? '') ?>" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white font-mono focus:outline-none focus:border-emerald-500">
                </div>
            </div>

            <div>
                <label class="block text-xs text-slate-400 mb-1">System User Permanent Access Token</label>
                <input type="password" name="whatsapp_access_token" value="<?= htmlspecialchars($settings['meta']['whatsapp_access_token'] ?? '') ?>" placeholder="EAA..." class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white font-mono focus:outline-none focus:border-emerald-500">
            </div>

            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs text-slate-400 mb-1">App Secret</label>
                    <input type="password" name="whatsapp_app_secret" value="<?= htmlspecialchars($settings['meta']['whatsapp_app_secret'] ?? '') ?>" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white font-mono focus:outline-none focus:border-emerald-500">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1">Verify Token</label>
                    <input type="text" name="whatsapp_verify_token" value="<?= htmlspecialchars($settings['meta']['whatsapp_verify_token'] ?? 'whatsapp_crm_secure_token_2026') ?>" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white font-mono focus:outline-none focus:border-emerald-500">
                </div>
            </div>
        </div>

        <!-- 3. General Application Preferences -->
        <div class="bg-slate-900 border border-slate-800 rounded-3xl p-6 shadow-xl space-y-4">
            <h3 class="font-bold text-white text-sm">3. General Preferences</h3>
            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                    <label class="block text-xs text-slate-400 mb-1">CRM App Name</label>
                    <input type="text" name="app_name" value="<?= htmlspecialchars($settings['general']['app_name'] ?? 'WhatsApp CRM') ?>" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-emerald-500">
                </div>
                <div>
                    <label class="block text-xs text-slate-400 mb-1">Timezone</label>
                    <input type="text" name="timezone" value="<?= htmlspecialchars($settings['general']['timezone'] ?? 'Asia/Kolkata') ?>" class="w-full bg-slate-950 border border-slate-800 rounded-xl px-3 py-2 text-xs text-white focus:outline-none focus:border-emerald-500">
                </div>
            </div>
        </div>

        <button type="submit" class="bg-emerald-500 hover:bg-emerald-600 text-slate-950 text-xs font-bold py-3 px-8 rounded-xl transition shadow-lg shadow-emerald-500/20 cursor-pointer">
            Save All Settings
        </button>
    </form>

</div>

<script>
function toggleDriver(val) {
    document.getElementById('box-self_hosted_qr').classList.add('hidden');
    document.getElementById('box-gateway').classList.add('hidden');
    document.getElementById('box-meta').classList.add('hidden');

    if (val === 'meta') {
        document.getElementById('box-meta').classList.remove('hidden');
    } else if (val === 'gateway' || val === 'ultramsg') {
        document.getElementById('box-gateway').classList.remove('hidden');
    } else {
        document.getElementById('box-self_hosted_qr').classList.remove('hidden');
        QrEngine.checkStatus();
    }
}

const QrEngine = {
    interval: null,

    init() {
        this.checkStatus();
        this.interval = setInterval(() => this.checkStatus(), 3000);
    },

    async checkStatus() {
        try {
            const res = await fetch('/api/settings/local-qr-status');
            const data = await res.json();

            const badge = document.getElementById('qr-status-badge');
            const qrWrapper = document.getElementById('qr-code-wrapper');
            const connectedWrapper = document.getElementById('qr-connected-wrapper');
            const offlineWrapper = document.getElementById('qr-offline-wrapper');

            if (!data.success || data.status === 'server_offline') {
                badge.className = 'inline-flex items-center space-x-2 px-3 py-1.5 rounded-full text-xs font-semibold bg-amber-500/10 text-amber-400 border border-amber-500/20';
                badge.innerHTML = '<span class="w-2 h-2 rounded-full bg-amber-400"></span><span>QR Server Offline (Port 3000)</span>';
                qrWrapper.classList.add('hidden');
                connectedWrapper.classList.add('hidden');
                offlineWrapper.classList.remove('hidden');
                return;
            }

            offlineWrapper.classList.add('hidden');

            if (data.status === 'connected') {
                badge.className = 'inline-flex items-center space-x-2 px-3 py-1.5 rounded-full text-xs font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/30';
                badge.innerHTML = '<span class="w-2 h-2 rounded-full bg-emerald-400 animate-pulse"></span><span>🟢 WhatsApp Connected</span>';
                
                qrWrapper.classList.add('hidden');
                connectedWrapper.classList.remove('hidden');
                if (data.user?.phone) {
                    document.getElementById('qr-connected-phone').innerText = `Linked Phone: +${data.user.phone}`;
                }
            } else if (data.status === 'qr_ready' && data.qr_image) {
                badge.className = 'inline-flex items-center space-x-2 px-3 py-1.5 rounded-full text-xs font-semibold bg-blue-500/10 text-blue-400 border border-blue-500/30';
                badge.innerHTML = '<span class="w-2 h-2 rounded-full bg-blue-400 animate-ping"></span><span>Scan QR Code with Phone</span>';
                
                connectedWrapper.classList.add('hidden');
                qrWrapper.classList.remove('hidden');
                document.getElementById('qr-code-img').src = data.qr_image;
            } else {
                badge.className = 'inline-flex items-center space-x-2 px-3 py-1.5 rounded-full text-xs font-semibold bg-slate-800 text-slate-300';
                badge.innerHTML = '<span class="w-2 h-2 rounded-full bg-slate-400 animate-pulse"></span><span>Initializing WhatsApp Socket...</span>';
            }
        } catch (e) {
            // Server offline
        }
    },

    async logout() {
        if (!confirm('Unlink this WhatsApp account from CRM?')) return;
        await fetch('/api/settings/local-qr-logout', { method: 'POST' });
        App.toast('Logged out from WhatsApp', 'info');
        this.checkStatus();
    }
};

document.addEventListener('DOMContentLoaded', () => {
    QrEngine.init();
});
</script>
