<?php
$webhookSafe  = esc($webhookUrl ?? '');
$cfg          = $config ?? [];
$numbers      = $numbers ?? [];
$connStatus   = $connectionStatus ?? null;
$listNumbersError = $listNumbersError ?? null;
$listNumbersAttempted = !empty($listNumbersAttempted);
$svcIsConfigured = !empty($svcIsConfigured);

$apiKeyId            = old('api_key_id',            $cfg['api_key_id']            ?? '');
$apiKeySecret        = old('api_key_secret',        $cfg['api_key_secret']        ?? '');
$webhookSecret       = old('webhook_signing_secret',$cfg['webhook_signing_secret']?? '');
$agentNumberId       = old('agent_number_id',       $cfg['agent_number_id']       ?? '');
$outboundCallerId    = old('outbound_caller_id',    $cfg['outbound_caller_id']    ?? '');
$enableTranscription = old('enable_transcription',  $cfg['enable_transcription']  ?? '1');
$enableRecording     = old('enable_recording',      $cfg['enable_recording']      ?? '1');
$autoSummarize       = old('auto_summarize',        $cfg['auto_summarize']        ?? '1');
?>

<div class="max-w-5xl mx-auto space-y-6">

    <div class="glass rounded-2xl p-6 border border-slate-200/70 shadow-sm">
        <div class="flex items-start justify-between gap-4">
            <div>
                <div class="flex items-center gap-3">
                    <div class="w-9 h-9 rounded-lg bg-gradient-to-br from-sky-500 to-indigo-600 text-white flex items-center justify-center shadow-sm">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M3 5a2 2 0 012-2h3.28a1 1 0 01.948.684l1.498 4.493a1 1 0 01-.502 1.21l-2.257 1.13a11.042 11.042 0 005.516 5.516l1.13-2.257a1 1 0 011.21-.502l4.493 1.498a1 1 0 01.684.949V19a2 2 0 01-2 2h-1C9.716 21 3 14.284 3 6V5z" />
                        </svg>
                    </div>
                    <div>
                        <h3 class="font-bold text-lg text-slate-800">CloudTalk Integration</h3>
                        <p class="text-sm text-slate-500">Configure your CloudTalk v1 API credentials to enable click-to-call, call recordings, transcripts, and AI-powered call summaries.</p>
                    </div>
                </div>
            </div>
            <div>
                <?php if ($connStatus !== null): ?>
                    <?php if (($connStatus['ok'] ?? false) === true): ?>
                        <span class="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-emerald-50 border border-emerald-200 text-emerald-700 text-xs font-medium">
                            <span class="w-2 h-2 rounded-full bg-emerald-500"></span>
                            <?= esc($connStatus['message']) ?>
                        </span>
                    <?php else: ?>
                        <span class="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-red-50 border border-red-200 text-red-700 text-xs font-medium">
                            <span class="w-2 h-2 rounded-full bg-red-500"></span>
                            <?= esc($connStatus['error'] ?? 'Connection failed.') ?>
                        </span>
                    <?php endif; ?>
                <?php else: ?>
                    <span class="inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-slate-50 border border-slate-200 text-slate-600 text-xs font-medium">
                        <span class="w-2 h-2 rounded-full bg-slate-400"></span>
                        Credentials not set yet
                    </span>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <?= form_open(site_url('/admin/cloudtalk-settings'), ['class' => 'glass rounded-2xl p-6 border border-slate-200/70 shadow-sm space-y-6', 'id' => 'cloudtalk-settings-form']) ?>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-5">
            <div class="md:col-span-1">
                <label class="block text-sm font-medium text-slate-700 mb-1.5">API Key ID <span class="text-red-500">*</span></label>
                <input type="text" name="api_key_id" value="<?= esc($apiKeyId) ?>"
                       placeholder="ct_api_id_..."
                       class="w-full px-4 py-2.5 rounded-xl border border-slate-200 bg-white focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 outline-none text-sm">
                <p class="mt-1 text-xs text-slate-500">CloudTalk v1 REST API Key ID (used as Basic Auth username).</p>
            </div>
            <div class="md:col-span-1">
                <label class="block text-sm font-medium text-slate-700 mb-1.5">API Key Secret <span class="text-red-500">*</span></label>
                <input type="password" name="api_key_secret" value="<?= esc($apiKeySecret) ?>" autocomplete="off"
                       placeholder="••••••••••••••••"
                       class="w-full px-4 py-2.5 rounded-xl border border-slate-200 bg-white focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 outline-none text-sm">
                <p class="mt-1 text-xs text-slate-500">CloudTalk v1 REST API Key Secret (used as Basic Auth password).</p>
            </div>
            <div class="md:col-span-1">
                <label class="block text-sm font-medium text-slate-700 mb-1.5">Webhook Signing Secret</label>
                <input type="password" name="webhook_signing_secret" value="<?= esc($webhookSecret) ?>" autocomplete="off"
                       placeholder="Optional — paste signing secret to verify CloudTalk webhooks"
                       class="w-full px-4 py-2.5 rounded-xl border border-slate-200 bg-white focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 outline-none text-sm">
                <p class="mt-1 text-xs text-slate-500">If set, we verify the X-CloudTalk-Signature header via HMAC-SHA256.</p>
            </div>
            <div class="md:col-span-1">
                <label class="block text-sm font-medium text-slate-700 mb-1.5">Default Outbound Number ID (optional)</label>
                <select name="agent_number_id" id="cloudtalk-agent-number-id" class="w-full px-4 py-2.5 rounded-xl border border-slate-200 bg-white focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 outline-none text-sm">
                    <option value="">— Auto (use agent's default number) —</option>
                    <?php foreach ($numbers as $n): $nid = (string) ($n['id'] ?? ''); ?>
                        <option value="<?= esc($nid) ?>" <?= $nid === $agentNumberId ? 'selected' : '' ?>>
                            #<?= esc($nid) ?> · <?= esc(($n['name'] ?? $n['number'])) ?> &lt;<?= esc($n['number']) ?>&gt;
                        </option>
                    <?php endforeach; ?>
                </select>
                <?php if (empty($numbers)): ?>
                    <?php if ($svcIsConfigured && $listNumbersAttempted && $listNumbersError): ?>
                        <div id="numbers-error-box-inline" class="mt-2 rounded-lg border border-rose-200 bg-rose-50 px-3 py-2 text-xs text-rose-700 space-y-1">
                            <div class="font-semibold text-rose-800">⚠ Could not load CloudTalk numbers list</div>
                            <div class="break-words whitespace-pre-wrap"><?= esc($listNumbersError) ?></div>
                            <div class="pt-1 border-t border-rose-200/60 text-rose-700">
                                <span class="font-semibold">Get Number ID manually:</span><br>
                                1. Open CloudTalk dashboard → Numbers page<br>
                                2. Click your purchased DID row → opens detail page<br>
                                3. URL bar shows <code class="bg-white/70 px-1 rounded">…/numbers/12345</code> → paste integer <code class="bg-white/70 px-1 rounded">12345</code> into dropdown above<br>
                                <span class="font-semibold text-rose-800">OR</span> click <button type="button" id="retry-test-connection-inline" class="underline font-semibold text-rose-800">Test Connection → it auto-populates this dropdown ↓</button>
                            </div>
                        </div>
                    <?php else: ?>
                        <p class="mt-1 text-xs text-slate-500">Save API credentials first to list your CloudTalk numbers. Then click <span class="font-semibold">Test Connection</span> to populate the dropdown live.</p>
                    <?php endif; ?>
                <?php endif; ?>
            </div>
            <div class="md:col-span-1">
                <label class="block text-sm font-medium text-slate-700 mb-1.5">Outbound Caller ID Number (optional)</label>
                <input type="text" name="outbound_caller_id" value="<?= esc($outboundCallerId) ?>"
                       placeholder="+15551234567"
                       class="w-full px-4 py-2.5 rounded-xl border border-slate-200 bg-white focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 outline-none text-sm">
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-3 gap-3">
            <label class="flex items-center gap-3 p-3 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 cursor-pointer">
                <input type="checkbox" name="enable_transcription" value="1" <?= $enableTranscription === '1' ? 'checked' : '' ?> class="w-4 h-4 rounded text-blue-600">
                <div>
                    <div class="text-sm font-medium text-slate-800">Call Transcription</div>
                    <div class="text-xs text-slate-500">Store transcripts when available.</div>
                </div>
            </label>
            <label class="flex items-center gap-3 p-3 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 cursor-pointer">
                <input type="checkbox" name="enable_recording" value="1" <?= $enableRecording === '1' ? 'checked' : '' ?> class="w-4 h-4 rounded text-blue-600">
                <div>
                    <div class="text-sm font-medium text-slate-800">Call Recording</div>
                    <div class="text-xs text-slate-500">Show recording playback in Lead history.</div>
                </div>
            </label>
            <label class="flex items-center gap-3 p-3 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 cursor-pointer">
                <input type="checkbox" name="auto_summarize" value="1" <?= $autoSummarize === '1' ? 'checked' : '' ?> class="w-4 h-4 rounded text-blue-600">
                <div>
                    <div class="text-sm font-medium text-slate-800">Auto-Summarize</div>
                    <div class="text-xs text-slate-500">Run AI summary when transcript arrives.</div>
                </div>
            </label>
        </div>

        <div class="glass rounded-2xl p-5 border border-slate-200/70 bg-gradient-to-br from-sky-50/70 to-indigo-50/70">
            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                <div class="min-w-0">
                    <p class="text-sm font-semibold text-slate-700">Webhook URL (copy into CloudTalk dashboard)</p>
                    <p class="text-xs text-slate-500 mt-0.5">Subscribe to events: <span class="font-mono text-slate-600">call.started</span>, <span class="font-mono text-slate-600">call.ended</span>, <span class="font-mono text-slate-600">recording.ready</span>, <span class="font-mono text-slate-600">transcript.ready</span>.</p>
                </div>
                <div class="flex gap-2">
                    <div class="flex-1 min-w-0 rounded-xl bg-white border border-slate-200 flex items-center">
                        <input id="webhook-url" readonly value="<?= esc($webhookSafe) ?>"
                               class="flex-1 px-4 py-2.5 rounded-l-xl border-0 bg-transparent outline-none text-xs font-mono text-slate-700 min-w-0">
                    </div>
                    <button type="button" id="copy-webhook"
                            class="shrink-0 inline-flex items-center gap-1.5 px-3.5 py-2.5 rounded-xl bg-slate-800 text-white text-xs font-medium hover:bg-slate-900">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
                        </svg>
                        Copy
                    </button>
                </div>
            </div>
        </div>

        <div class="flex flex-wrap items-center justify-between gap-3 pt-3">
            <button type="button" id="test-connection-btn"
                    class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl bg-white border border-slate-200 text-slate-700 text-sm font-medium hover:bg-slate-50 disabled:opacity-60">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
                Test Connection
            </button>
            <div class="flex items-center gap-2">
                <button type="submit" class="inline-flex items-center gap-2 px-5 py-2.5 rounded-xl bg-gradient-to-r from-blue-600 to-indigo-600 text-white text-sm font-semibold shadow-lg shadow-blue-500/20 hover:from-blue-700 hover:to-indigo-700">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" 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>
                    Save Settings
                </button>
            </div>
        </div>
    <?= form_close() ?>
</div>

<script>
(function(){
    var copyBtn = document.getElementById('copy-webhook');
    if (copyBtn) {
        copyBtn.addEventListener('click', function(){
            var inp = document.getElementById('webhook-url');
            if (!inp) return;
            var original = copyBtn.innerHTML;
            try {
                inp.select();
                inp.setSelectionRange(0, 999999);
                document.execCommand('copy');
                copyBtn.innerHTML = 'Copied!';
                copyBtn.classList.add('bg-emerald-600');
                setTimeout(function(){ copyBtn.innerHTML = original; copyBtn.classList.remove('bg-emerald-600'); }, 1500);
            } catch(e) {
                alert('Copy failed. Please copy manually.');
            }
        });
    }

    var testBtn = document.getElementById('test-connection-btn');
    function runTestConnection() {
        if (testBtn) testBtn.click();
    }
    if (testBtn) {
        testBtn.addEventListener('click', function(){
            testBtn.disabled = true;
            var form = document.getElementById('cloudtalk-settings-form');
            var fd = new FormData(form);
            fetch("<?= esc(site_url('/admin/cloudtalk/test-connection'), 'js') ?>", {
                method: 'POST',
                body: fd,
                credentials: 'same-origin',
                headers: { 'X-Requested-With': 'XMLHttpRequest' }
            }).then(function(r){ return r.json(); }).then(function(j){
                testBtn.disabled = false;
                if (j && j.ok) {
                    var lines = [];
                    lines.push('✅ Connection OK: ' + (j.message || 'Success'));
                    lines.push('');
                    if (typeof j.agents_count !== 'undefined') {
                        lines.push('CloudTalk AGENTS (' + (j.agents_count || 0) + ') — status = CloudTalk reported presence / availability for click-to-call:');
                        lines.push('——————————————————————————');
                        if (Array.isArray(j.agents) && j.agents.length) {
                            j.agents.forEach(function(a, i) {
                                var s = '  #' + (i + 1) + '  id=' + (a.id || '(none)');
                                if (a.name)  s += ' name=' + a.name;
                                if (a.email) s += ' email=' + a.email;
                                if (a.status) s += ' status=' + a.status;
                                if (a.invite_status) s += ' invite=' + a.invite_status;
                                lines.push(s);
                            });
                        } else {
                            lines.push('  (empty — /agents.json returned nothing)');
                        }
                        lines.push('');
                    }
                    if (typeof j.numbers_count !== 'undefined') {
                        lines.push('CloudTalk NUMBERS (' + (j.numbers_count || 0) + ') — paste the integer `id` column into Default Outbound Number ID if auto-pick is failing:');
                        lines.push('——————————————————————————');
                        if (Array.isArray(j.numbers) && j.numbers.length) {
                            j.numbers.forEach(function(n, i) {
                                var s = '  #' + (i + 1) + '  id=' + (n.id || '(no id — MISSING!!!)') + ' – name=' + (n.name || '(unnamed)') + ' number=' + (n.number || '?');
                                lines.push(s);
                            });
                            try {
                                var sel = document.getElementById('cloudtalk-agent-number-id');
                                if (sel) {
                                    var currentVal = sel.value;
                                    var optsHtml = '<option value="">— Auto (use agent\'s default number) —</option>';
                                    j.numbers.forEach(function(n) {
                                        var nid = String(n.id || '');
                                        if (!nid) return;
                                        var label = '#' + nid + ' · ' + (n.name || n.number || '') + ' <' + (n.number || '') + '>';
                                        optsHtml += '<option value="' + nid + '">' + label.replace(/</g, '&lt;').replace(/>/g, '&gt;') + '</option>';
                                    });
                                    sel.innerHTML = optsHtml;
                                    if (currentVal !== '' && currentVal !== null) {
                                        var foundCurrent = false;
                                        for (var oo = 0; oo < sel.options.length; oo++) { if (sel.options[oo].value === currentVal) { foundCurrent = true; sel.selectedIndex = oo; break; } }
                                        if (!foundCurrent) sel.selectedIndex = 0;
                                    }
                                    sel.classList.remove('border-slate-200');
                                    sel.classList.add('border-emerald-500', 'ring-2', 'ring-emerald-500/20');
                                    setTimeout(function(){ sel.classList.remove('border-emerald-500', 'ring-2', 'ring-emerald-500/20'); sel.classList.add('border-slate-200'); }, 2200);
                                    var errBox = document.getElementById('numbers-error-box-inline');
                                    if (errBox) errBox.style.display = 'none';
                                }
                            } catch (eRebuild) {}
                        } else {
                            lines.push('  (empty — /numbers.json returned nothing. Paste Number ID manually)');
                        }
                        lines.push('');
                    }
                    lines.push('Raw JSON for copy-paste:');
                    lines.push(JSON.stringify(j, null, 2));
                    alert(lines.join('\n'));
                } else {
                    alert('Connection failed: ' + ((j && j.error) ? j.error : 'Unknown error') + '\n\nRaw: ' + JSON.stringify(j || {}, null, 2)));
                }
            }).catch(function(e){
                testBtn.disabled = false;
                alert('Request error: ' + e);
            });
        });
    }

    var inlineRetry = document.getElementById('retry-test-connection-inline');
    if (inlineRetry) {
        inlineRetry.addEventListener('click', function(){ runTestConnection(); });
    }
})();
</script>
