<?php
/**
 * FajaedeSEO Agency Hub Dashboard
 */

defined('ABSPATH') or exit;

function fajaedeseo_render_agency_hub() {
    // Alleen toegankelijk voor ingelogde klanten op de master server
    if (!defined('FAJAEDE_MASTER_SERVER') || !FAJAEDE_MASTER_SERVER) { wp_die(esc_html__('Agency Hub is only available on the master server.', 'fajaedeseo-ai')); }

    if (!is_user_logged_in()) {
        wp_die(esc_html__('You must be logged in to view the Agency Hub.', 'fajaedeseo-ai'));
    }

    $current_user = wp_get_current_user();
    
    global $wpdb;
    $table = $wpdb->prefix . \FajaedeSEO_Pro_License::TABLE_NAME;

    // Zoek de agency licentie van deze klant
    $cache_key = 'fajaedeseo_agency_license_' . $current_user->ID;
    $license = wp_cache_get($cache_key, 'fajaedeseo');
    
    if (false === $license) {
        $license = $wpdb->get_row($wpdb->prepare("SELECT * FROM `" . esc_sql($table) . "` WHERE user_id = %d AND plan_level = %s AND status IN (%s, %s) ORDER BY id DESC LIMIT 1", $current_user->ID, \FajaedeSEO_Pro_License::PLAN_AGENCY, \FajaedeSEO_Pro_License::STATUS_ACTIVE, \FajaedeSEO_Pro_License::STATUS_REDEEMED), ARRAY_A); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
        wp_cache_set($cache_key, $license, 'fajaedeseo', 5 * MINUTE_IN_SECONDS);
    }

    ?>
    <div class="wrap fajaedeseo-agency-hub">
        <h1><?php esc_html_e('Agency Hub', 'fajaedeseo-ai'); ?></h1>
        
        <?php if (!$license) : ?>
            <div class="notice notice-warning">
                <p><?php esc_html_e('No active Agency license found for your account.', 'fajaedeseo-ai'); ?></p>
            </div>
            <p><?php esc_html_e('If you believe this is an error, please contact support.', 'fajaedeseo-ai'); ?></p>
        <?php else : ?>
            <div class="fajaedeseo-agency-dashboard">
                <div class="fajaedeseo-card">
                    <h2><?php esc_html_e('Welcome to your Agency Hub', 'fajaedeseo-ai'); ?>, <?php echo esc_html($current_user->display_name); ?>!</h2>
                    <p><?php esc_html_e('Here you can manage your client websites and monitor their SEO health in real-time.', 'fajaedeseo-ai'); ?></p>
                </div>

                <div class="fajaedeseo-card" style="margin-top: 20px;">
                    <h2><?php esc_html_e('Connected Client Sites', 'fajaedeseo-ai'); ?></h2>
                    
                    <?php 
                    $sites = !empty($license['site_url']) ? array_filter(array_map('trim', explode(',', $license['site_url']))) : [];
                    
                    if (empty($sites)) : ?>
                        <p><?php esc_html_e('You have not connected any client websites yet.', 'fajaedeseo-ai'); ?></p>
                        <p><?php esc_html_e('To connect a site, install the FajaedeSEO plugin on your client\'s WordPress site and activate your Agency license key.', 'fajaedeseo-ai'); ?></p>
                    <?php else : ?>
                        <p>
                            <button id="fajaedeseo-refresh-sites" class="button button-primary">
                                <?php esc_html_e('Refresh Site Data', 'fajaedeseo-ai'); ?>
                            </button>
                            <button id="fajaedeseo-bulk-pdf-btn" class="button button-secondary" style="margin-left: 10px;">
                                📄 <?php esc_html_e('Bulk Download All PDF Reports', 'fajaedeseo-ai'); ?>
                            </button>
                        </p>
                        <table class="wp-list-table widefat fixed striped">
                            <thead>
                                <tr>
                                    <th><?php esc_html_e('Website', 'fajaedeseo-ai'); ?></th>
                                    <th><?php esc_html_e('SEO Score', 'fajaedeseo-ai'); ?></th>
                                    <th><?php esc_html_e('Pages Indexed', 'fajaedeseo-ai'); ?></th>
                                    <th><?php esc_html_e('Page Speed', 'fajaedeseo-ai'); ?></th>
                                    <th><?php esc_html_e('Orphan Pages', 'fajaedeseo-ai'); ?></th>
                                    <th><?php esc_html_e('Actions', 'fajaedeseo-ai'); ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($sites as $site_url) : ?>
                                    <tr class="fajaedeseo-client-site" data-url="<?php echo esc_attr($site_url); ?>">
                                        <td><strong><a href="<?php echo esc_url($site_url); ?>" target="_blank"><?php echo esc_html($site_url); ?></a></strong></td>
                                        <td class="fseo-score"><span class="spinner is-active" style="float:none;"></span></td>
                                        <td class="fseo-indexed"><span class="spinner is-active" style="float:none;"></span></td>
                                        <td class="fseo-speed"><span class="spinner is-active" style="float:none;"></span></td>
                                        <td class="fseo-orphan"><span class="spinner is-active" style="float:none;"></span></td>
                                        <td>
                                            <button type="button" class="button button-primary button-small" onclick="fajaedeseoQuickLogin('<?php echo esc_js($site_url); ?>')" id="btn-login-<?php echo esc_attr(preg_replace('/[^a-z0-9]/i', '', $site_url)); ?>">
                                                ⚡ <?php esc_html_e('Quick Login', 'fajaedeseo-ai'); ?>
                                            </button>
                                            <a href="<?php echo esc_url(rtrim($site_url, '/') . '/wp-admin/'); ?>" target="_blank" class="button button-secondary button-small">
                                                <?php esc_html_e('WP Admin', 'fajaedeseo-ai'); ?>
                                            </a>
                                            <button type="button" class="button button-secondary button-small fseo-btn-analytics" disabled>
                                                📊 <?php esc_html_e('Analytics', 'fajaedeseo-ai'); ?>
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                        
                        <!-- Analytics Modal -->
                        <div id="fseo-modal" class="fseo-modal">
                            <div class="fseo-modal-content">
                                <span id="fseo-modal-close" class="fseo-close">&times;</span>
                                <h2 id="fseo-modal-title">Site Analytics</h2>
                                <hr style="border: 0; border-top: 1px solid #eee; margin-bottom: 20px;">
                                <div id="fseo-modal-body">
                                    <!-- Inhoud wordt dynamisch geladen via JS -->
                                </div>
                            </div>
                        </div>

                        <style>
                            .fajaedeseo-card { background: #fff; padding: 20px; border: 1px solid #ccd0d4; border-radius: 4px; box-shadow: 0 1px 1px rgba(0,0,0,.04); }
                            .fseo-badge { display: inline-block; padding: 3px 8px; border-radius: 3px; font-weight: bold; color: #fff; }
                            .fseo-badge.green { background-color: #28a745; }
                            .fseo-badge.orange { background-color: #fd7e14; }
                            .fseo-badge.red { background-color: #dc3545; }
                            .fseo-badge.gray { background-color: #6c757d; }
                            
                            /* Modal CSS */
                            .fseo-modal { display: none; position: fixed; z-index: 9999; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.6); backdrop-filter: blur(3px); }
                            .fseo-modal-content { background-color: #fff; margin: 5% auto; padding: 25px 30px; border-radius: 8px; width: 80%; max-width: 800px; box-shadow: 0 10px 30px rgba(0,0,0,0.2); position: relative; }
                            .fseo-close { color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer; line-height: 1; margin-top: -5px; }
                            .fseo-close:hover { color: #333; }
                        </style>

                        <script>
                            const masterLicenseHash = "<?php echo esc_js($license['code_hash']); ?>";
                            const siteDataStore = {};
                            
                            window.fajaedeseoQuickLogin = function(siteUrl) {
                                const safeId = siteUrl.replace(/[^a-z0-9]/gi, '');
                                const btn = document.getElementById('btn-login-' + safeId);
                                const originalText = btn.innerHTML;
                                
                                btn.disabled = true;
                                btn.innerHTML = '<span class="spinner is-active" style="float:none; margin:0;"></span>';

                                const apiUrl = siteUrl.replace(/\/$/, '') + '/wp-json/fajaedeseo/v1/agency-login';

                                fetch(apiUrl, {
                                    method: 'POST',
                                    headers: { 
                                        'Content-Type': 'application/json',
                                        'Accept': 'application/json'
                                    },
                                    body: JSON.stringify({ license_key: masterLicenseHash })
                                })
                                .then(response => response.json())
                                .then(data => {
                                    btn.disabled = false;
                                    btn.innerHTML = originalText;
                                    
                                    if (data.code && data.message) {
                                        alert('Login failed: ' + data.message);
                                        return;
                                    }
                                    
                                    if (data.login_url) {
                                        window.open(data.login_url, '_blank');
                                    } else {
                                        alert('Login failed: Invalid response from client site.');
                                    }
                                })
                                .catch(err => {
                                    btn.disabled = false;
                                    btn.innerHTML = originalText;
                                    alert('Connection error. Please ensure the FajaedeSEO plugin is active and updated on the client site.');
                                });
                            };

                            function openFseoModal(siteUrl, data) {
                                const modal = document.getElementById('fseo-modal');
                                document.getElementById('fseo-modal-title').textContent = '📊 Analytics Overview: ' + siteUrl;
                                
                                const safeSiteUrl = siteUrl.replace(/[^a-z0-9]/gi, '');
                                const score = data.seo_health.overall_score || 0;
                                const speed = data.seo_health.page_speed || 0;
                                const indexed = data.seo_health.pages_indexed || 0;
                                
                                const scoreColor = score >= 80 ? '#28a745' : (score >= 60 ? '#fd7e14' : '#dc3545');
                                const speedColor = speed >= 80 ? '#28a745' : (speed >= 60 ? '#fd7e14' : '#dc3545');

                                let html = '<div style="display: flex; gap: 20px; margin-bottom: 20px; flex-wrap: wrap;">';
                                html += `<div style="flex: 1; min-width: 150px; background: #f8f9fa; padding: 15px; border-radius: 6px; border: 1px solid #e2e8f0; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.02);">
                                            <h4 style="margin-top:0; color: #333;">SEO Health</h4>
                                            <div style="background: #e2e8f0; border-radius: 10px; height: 12px; margin: 10px 0; overflow: hidden;">
                                                <div style="width: ${score}%; background: ${scoreColor}; height: 100%; border-radius: 10px; transition: width 1s ease-in-out;"></div>
                                            </div>
                                            <strong style="color: ${scoreColor}; font-size: 18px;">${score}/100</strong>
                                         </div>`;
                                html += `<div style="flex: 1; min-width: 150px; background: #f8f9fa; padding: 15px; border-radius: 6px; border: 1px solid #e2e8f0; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.02);">
                                            <h4 style="margin-top:0; color: #333;">Page Speed</h4>
                                            <div style="background: #e2e8f0; border-radius: 10px; height: 12px; margin: 10px 0; overflow: hidden;">
                                                <div style="width: ${speed}%; background: ${speedColor}; height: 100%; border-radius: 10px; transition: width 1s ease-in-out;"></div>
                                            </div>
                                            <strong style="color: ${speedColor}; font-size: 18px;">${speed}/100</strong>
                                         </div>`;
                                html += `<div style="flex: 1; min-width: 150px; background: #f8f9fa; padding: 15px; border-radius: 6px; border: 1px solid #e2e8f0; text-align: center; box-shadow: 0 2px 4px rgba(0,0,0,0.02);">
                                            <h4 style="margin-top:0; color: #333;">Pages Indexed</h4>
                                            <div style="font-size: 28px; margin: 5px 0; line-height: 1;">📄</div>
                                            <strong style="font-size: 18px; color: #0073aa;">${indexed}</strong>
                                         </div>`;
                                html += '</div>';

                                html += '<div style="display: flex; gap: 20px; flex-wrap: wrap;">';
                                
                                // Orphan Pages Kolom
                                html += '<div style="flex: 1; min-width: 300px; background: #f8f9fa; padding: 15px; border-radius: 6px; border: 1px solid #e2e8f0;">';
                                html += '<h3 style="margin-top: 0;">🔗 Orphan Pages (' + data.technical.orphan_pages_count + ')</h3>';
                                if (data.technical.orphan_pages_count > 0) {
                                    html += '<p style="font-size: 12px; color: #666;">These pages have no internal links pointing to them. Connect them to improve crawlability.</p>';
                                    html += '<ul style="background: #fff; border: 1px solid #ddd; padding: 10px 10px 10px 25px; border-radius: 4px; max-height: 250px; overflow-y: auto;">';
                                    data.technical.orphan_pages_sample.forEach(page => {
                                        html += '<li style="margin-bottom: 5px;"><a href="' + page.url + '" target="_blank" style="text-decoration: none;">' + (page.title || 'No Title') + '</a></li>';
                                    });
                                    html += '</ul>';
                                    if (data.technical.orphan_pages_count > data.technical.orphan_pages_sample.length) html += '<p style="font-size: 11px; color: #888;">Showing top ' + data.technical.orphan_pages_sample.length + ' results.</p>';
                                } else {
                                    html += '<p style="color: #28a745; font-weight: bold;">Great! No orphan pages found.</p>';
                                }
                                html += '</div>';

                                // Traffic Kolom
                                html += '<div style="flex: 1; min-width: 300px; background: #f8f9fa; padding: 15px; border-radius: 6px; border: 1px solid #e2e8f0;">';
                                html += '<h3 style="margin-top: 0;">🌍 Top Visitor Countries</h3>';
                                if (data.traffic.geo_data && data.traffic.geo_data.countries && data.traffic.geo_data.countries.length > 0) {
                                    html += '<table class="wp-list-table widefat striped" style="background: #fff;">';
                                    html += '<thead><tr><th>Country</th><th>Visits</th></tr></thead><tbody>';
                                    data.traffic.geo_data.countries.forEach(c => {
                                        html += '<tr><td>' + c.name + '</td><td><strong>' + c.count + '</strong></td></tr>';
                                    });
                                    html += '</tbody></table>';
                                } else {
                                    html += '<p style="color: #666; font-style: italic;">No geographic data collected yet.</p>';
                                }
                                html += '</div>';

                                html += '</div>';
                                
                                // SERP Module
                                html += '<div style="margin-top: 20px; background: #fcfcff; padding: 15px; border-radius: 6px; border: 1px solid #cce5ff;">';
                                html += '<h3 style="margin-top: 0; color: #004085;">🔍 Quick SERP Competitor Analysis</h3>';
                                html += '<p style="font-size: 12px; color: #666;">Check the live top 5 Google results across the globe to see who your client is competing against.</p>';
                                html += `<div style="display: flex; gap: 10px; margin-bottom: 10px;">
                                            <input type="text" id="fseo-serp-keyword-${safeSiteUrl}" placeholder="Enter focus keyword..." style="flex: 1; padding: 5px 10px; border-radius: 4px; border: 1px solid #ccd0d4;">
                                            <select id="fseo-serp-gl-${safeSiteUrl}" style="max-width: 150px; border-radius: 4px; border: 1px solid #ccd0d4;">
                                                <option value="global">🌍 International</option>
                                                <option value="nl">🇳🇱 Netherlands</option>
                                                <option value="be">🇧🇪 Belgium</option>
                                                <option value="us" selected>🇺🇸 United States</option>
                                                <option value="gb">🇬🇧 United Kingdom</option>
                                                <option value="de">🇩🇪 Germany</option>
                                                <option value="fr">🇫🇷 France</option>
                                                <option value="es">🇪🇸 Spain</option>
                                            </select>
                                            <button type="button" class="button button-primary" onclick="window.fajaedeseoRunModalSerp('${safeSiteUrl}', '${siteUrl}')" id="btn-serp-${safeSiteUrl}">Analyze SERP</button>
                                         </div>`;
                                html += `<div id="fseo-modal-serp-results-${safeSiteUrl}"></div>`;
                                html += '</div>';
                                
                                html += '<div style="margin-top: 20px; text-align: right; border-top: 1px solid #eee; padding-top: 15px;">';
                                html += `<button type="button" class="button button-primary button-hero" onclick="fajaedeseoGeneratePdf('${siteUrl}')" id="btn-generate-pdf-${siteUrl.replace(/[^a-z0-9]/gi, '')}">`;
                                html += '📄 Generate White-Label PDF Report';
                                html += '</button>';
                                html += '</div>';
                                
                                document.getElementById('fseo-modal-body').innerHTML = html;
                                modal.style.display = 'block';
                            }
                            
                            window.fajaedeseoRunModalSerp = function(safeId, siteUrl) {
                                const keyword = document.getElementById('fseo-serp-keyword-' + safeId).value;
                                const glSelection = document.getElementById('fseo-serp-gl-' + safeId).value;
                                let gl = glSelection;
                                let hl = glSelection;
                                
                                if (glSelection === 'global') {
                                    gl = 'us'; // Internationale standaard
                                    hl = 'en';
                                } else if (gl === 'us' || gl === 'gb') {
                                    hl = 'en';
                                }

                                if (!keyword) { alert('Please enter a keyword'); return; }
                                
                                const btn = document.getElementById('btn-serp-' + safeId);
                                const resultsDiv = document.getElementById('fseo-modal-serp-results-' + safeId);
                                
                                btn.disabled = true;
                                btn.innerHTML = '<span class="spinner is-active" style="float:none; margin:0;"></span>';
                                
                                fetch('<?php echo esc_url(rest_url("fajaedeseo/v1/competitor-analysis")); ?>', {
                                    method: 'POST',
                                    headers: { 
                                        'Content-Type': 'application/json',
                                        'X-WP-Nonce': '<?php echo esc_js(wp_create_nonce("wp_rest")); ?>'
                                    },
                                    body: JSON.stringify({ keyword: keyword, gl: gl, hl: hl })
                                })
                                .then(response => response.json())
                                .then(res => {
                                    btn.disabled = false;
                                    btn.innerHTML = 'Analyze SERP';
                                    
                                    if (res.code && res.message) {
                                        resultsDiv.innerHTML = '<p style="color:red; font-size:12px;">Error: ' + res.message + '</p>';
                                        return;
                                    }
                                    
                                    if (res.serp && res.serp.results && res.serp.results.length > 0) {
                                        // Sla de SERP data op zodat de PDF Generator dit kan toevoegen als Hoofdstuk 5
                                        if (siteDataStore[siteUrl]) {
                                            siteDataStore[siteUrl].serp_data = {
                                                keyword: keyword,
                                                results: res.serp.results
                                            };
                                        }
                                        
                                        let serpTable = '<table class="wp-list-table widefat striped" style="background: #fff; margin-top: 10px; border-radius: 6px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">';
                                        serpTable += '<thead><tr><th style="width: 40px; text-align: center;">Pos</th><th>Competitor</th></tr></thead><tbody>';
                                        res.serp.results.forEach((r, index) => {
                                            let rankColor = index === 0 ? '#ffd700' : (index === 1 ? '#c0c0c0' : (index === 2 ? '#cd7f32' : '#0073aa'));
                                            serpTable += `<tr>
                                                <td style="text-align: center; vertical-align: middle;">
                                                    <span style="display:inline-block; width:24px; height:24px; line-height:24px; background: ${rankColor}; color: #fff; border-radius: 50%; font-weight: bold; font-size:12px;">${index + 1}</span>
                                                </td>
                                                <td>
                                                    <strong style="color: #0073aa; font-size: 13px;">${r.title}</strong><br>
                                                    <a href="${r.url}" target="_blank" style="color: #28a745; font-size: 11px; text-decoration: none;">${r.url}</a>
                                                    <p style="font-size: 11px; color: #555; margin: 4px 0 0 0;">${r.snippet}</p>
                                                </td>
                                            </tr>`;
                                        });
                                        serpTable += '</tbody></table>';
                                        resultsDiv.innerHTML = serpTable;
                                    } else {
                                        resultsDiv.innerHTML = '<p style="font-size:12px;">No results found.</p>';
                                    }
                                })
                                .catch(err => {
                                    btn.disabled = false;
                                    btn.innerHTML = 'Analyze SERP';
                                    resultsDiv.innerHTML = '<p style="color:red; font-size:12px;">Connection error.</p>';
                                });
                            };

                            window.fajaedeseoGeneratePdf = function(siteUrl) {
                                const data = siteDataStore[siteUrl];
                                if (!data) return;
                                
                                const btnId = 'btn-generate-pdf-' + siteUrl.replace(/[^a-z0-9]/gi, '');
                                const btn = document.getElementById(btnId);
                                if (btn) {
                                    btn.disabled = true;
                                    btn.innerHTML = '<span class="spinner is-active" style="float:none; margin:0;"></span> Generating PDF...';
                                }
                                
                                fetch('<?php echo esc_url(rest_url('fajaedeseo/v1/agency-generate-pdf')); ?>', {
                                    method: 'POST',
                                    headers: { 
                                        'Content-Type': 'application/json',
                                        'X-WP-Nonce': '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>'
                                    },
                                    body: JSON.stringify({ client_data: data })
                                })
                                .then(response => response.json())
                                .then(res => {
                                    if (res && res.pdf) {
                                        const linkSource = `data:application/pdf;base64,${res.pdf}`;
                                        const downloadLink = document.createElement("a");
                                        downloadLink.href = linkSource;
                                        downloadLink.download = "seo-audit-report-" + siteUrl.replace(/[^a-z0-9]/gi, '') + ".pdf";
                                        downloadLink.click();
                                    } else {
                                        alert("Failed to generate PDF: " + (res.message || "Unknown error"));
                                    }
                                    if (btn) {
                                        btn.disabled = false;
                                        btn.innerHTML = '📄 Generate White-Label PDF Report';
                                    }
                                })
                                .catch(err => {
                                    alert("Connection error: " + err.message);
                                    if (btn) {
                                        btn.disabled = false;
                                        btn.innerHTML = '📄 Generate White-Label PDF Report';
                                    }
                                });
                            };

                            function fajaedeseoCrawlSites() {
                                const rows = document.querySelectorAll('.fajaedeseo-client-site');
                                
                                rows.forEach(row => {
                                    const siteUrl = row.getAttribute('data-url');
                                    const apiUrl = siteUrl.replace(/\/$/, '') + '/wp-json/fajaedeseo/v1/agency-status';
                                    
                                    const scoreCell = row.querySelector('.fseo-score');
                                    const indexedCell = row.querySelector('.fseo-indexed');
                                    const speedCell = row.querySelector('.fseo-speed');
                                    const orphanCell = row.querySelector('.fseo-orphan');
                                    const analyticsBtn = row.querySelector('.fseo-btn-analytics');
                                    
                                    // Zet spinners terug
                                    scoreCell.innerHTML = '<span class="spinner is-active" style="float:none;"></span>';
                                    indexedCell.innerHTML = '<span class="spinner is-active" style="float:none;"></span>';
                                    speedCell.innerHTML = '<span class="spinner is-active" style="float:none;"></span>';
                                    orphanCell.innerHTML = '<span class="spinner is-active" style="float:none;"></span>';
                                    analyticsBtn.disabled = true;

                                    fetch(apiUrl, {
                                        method: 'POST',
                                        headers: { 
                                            'Content-Type': 'application/json',
                                            'Accept': 'application/json',
                                            'X-WP-Nonce': '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>'
                                        },
                                        credentials: 'same-origin',
                                        body: JSON.stringify({ license_key: masterLicenseHash })
                                    })
                                    .then(response => response.json())
                                    .then(data => {
                                        if (data.code && data.message) {
                                            // API Error (bijv. plugin niet actief op klant site of foute licentie)
                                            scoreCell.innerHTML = `<span style="color:#d63638; font-size:11px;">${data.message}</span>`;
                                            indexedCell.innerHTML = '-'; speedCell.innerHTML = '-'; orphanCell.innerHTML = '-';
                                            return;
                                        }
                                        
                                        // Data ophalen en kleuren toewijzen
                                        const score = data.seo_health.overall_score;
                                        const speed = data.seo_health.page_speed;
                                        const orphans = data.technical.orphan_pages_count;
                                        const indexed = data.seo_health.pages_indexed;
                                        
                                        // Store data for PDF generation
                                        siteDataStore[siteUrl] = data;

                                        scoreCell.innerHTML = `<span class="fseo-badge ${score >= 80 ? 'green' : (score >= 60 ? 'orange' : 'red')}">${score}%</span>`;
                                        speedCell.innerHTML = `<span class="fseo-badge ${speed >= 80 ? 'green' : (speed >= 60 ? 'orange' : 'red')}">${speed}/100</span>`;
                                        orphanCell.innerHTML = `<span class="fseo-badge ${orphans === 0 ? 'green' : (orphans < 5 ? 'orange' : 'red')}">${orphans} pages</span>`;
                                        indexedCell.innerHTML = `<strong>${indexed}</strong>`;
                                        
                                        // Koppel de data aan de knop
                                        analyticsBtn.disabled = false;
                                        analyticsBtn.onclick = () => openFseoModal(siteUrl, data);
                                    })
                                    .catch(err => {
                                        scoreCell.innerHTML = `<span style="color:#d63638; font-size:11px;">Connection Failed</span>`;
                                        indexedCell.innerHTML = '-'; speedCell.innerHTML = '-'; orphanCell.innerHTML = '-';
                                    });
                                });
                            }

                            document.addEventListener('DOMContentLoaded', function() {
                                const refreshBtn = document.getElementById('fajaedeseo-refresh-sites');
                                if (refreshBtn) refreshBtn.addEventListener('click', fajaedeseoCrawlSites);
                                
                                const bulkPdfBtn = document.getElementById('fajaedeseo-bulk-pdf-btn');
                                if (bulkPdfBtn) {
                                    bulkPdfBtn.addEventListener('click', function() {
                                        const urls = Object.keys(siteDataStore);
                                        if (urls.length === 0) {
                                            alert("Please wait for the site data to finish loading.");
                                            return;
                                        }
                                        
                                        if (!confirm(`Are you sure you want to generate PDF reports for ${urls.length} sites? This will download multiple files to your computer.`)) {
                                            return;
                                        }
                                        
                                        let index = 0;
                                        bulkPdfBtn.disabled = true;
                                        bulkPdfBtn.innerHTML = 'Generating PDFs...';
                                        
                                        function downloadNext() {
                                            if (index >= urls.length) {
                                                bulkPdfBtn.disabled = false;
                                                bulkPdfBtn.innerHTML = '📄 Bulk Download All PDF Reports';
                                                return;
                                            }
                                            window.fajaedeseoGeneratePdf(urls[index]);
                                            index++;
                                            setTimeout(downloadNext, 2000); // Wacht 2 sec tussen downloads
                                        }
                                        downloadNext();
                                    });
                                }
                                
                                // Start direct met crawlen bij het openen van het dashboard
                                fajaedeseoCrawlSites();
                                
                                // Modal sluiten logica
                                const modal = document.getElementById('fseo-modal');
                                document.getElementById('fseo-modal-close').onclick = function() {
                                    modal.style.display = "none";
                                }
                                window.onclick = function(event) {
                                    if (event.target == modal) {
                                        modal.style.display = "none";
                                    }
                                }
                            });
                        </script>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>
    <?php
}