<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Facebook Lead Integration</title>
</head>
<body>
    <h2>Connect Facebook Leads</h2>
    <a href="<?php echo base_url('facebookconnect/authenticate'); ?>">Login with Facebook</a>

    <h3>Select Page</h3>
    <select id="pages" onchange="fetchLeadForms()"></select>
    
    <h3>Select Lead Form</h3>
    <select id="leadForms"></select>
    
    <button onclick="subscribeWebhook()">Subscribe Webhook</button>

    <script>
        async function fetchPages() {
            let response = await fetch('<?php echo base_url('facebookconnect/pages'); ?>');
            let pages = await response.json();
            let dropdown = document.getElementById('pages');
            pages.forEach(page => {
                let option = document.createElement('option');
                option.value = page.id;
                option.textContent = page.name;
                dropdown.appendChild(option);
            });
        }

        async function fetchLeadForms() {
            let pageId = document.getElementById('pages').value;
            let response = await fetch(`<?php echo base_url('facebookconnect/leadForms/'); ?>${pageId}`);
            let forms = await response.json();
            let dropdown = document.getElementById('leadForms');
            dropdown.innerHTML = '';
            forms.forEach(form => {
                let option = document.createElement('option');
                option.value = form.id;
                option.textContent = form.name;
                dropdown.appendChild(option);
            });
        }

        async function subscribeWebhook() {
            let pageId = document.getElementById('pages').value;
            let response = await fetch(`<?php echo base_url('facebookconnect/subscribeWebhook/'); ?>${pageId}`, { method: 'POST' });
            let result = await response.text();
            alert(result);
        }

        fetchPages();
    </script>
</body>
</html>