<?php
/**
 * FajaedeSEO Admin Settings Page (Updated)
 */

defined('ABSPATH') or exit;

function fajaedeseo_render_settings_page() {
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    $active_tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'dashboard';
    ?> 
    <div class="wrap">
        <?php settings_errors(); ?>
        <h1><?php echo esc_html__('Fajaede SEO Settings', 'fajaedeseo-ai'); ?></h1>
        <nav class="nav-tab-wrapper"> 
            <a href="<?php echo esc_url(admin_url('admin.php?page=fajaedeseo-seo&tab=dashboard')); ?>" class="nav-tab <?php echo $active_tab == 'dashboard' ? 'nav-tab-active' : ''; ?>">Dashboard</a> 
            <a href="<?php echo esc_url(admin_url('admin.php?page=fajaedeseo-seo&tab=general')); ?>" class="nav-tab <?php echo $active_tab == 'general' ? 'nav-tab-active' : ''; ?>">General</a> 
            <a href="<?php echo esc_url(admin_url('admin.php?page=fajaedeseo-seo&tab=homepage')); ?>" class="nav-tab <?php echo $active_tab == 'homepage' ? 'nav-tab-active' : ''; ?>">Homepage</a> 
            <a href="<?php echo esc_url(admin_url('admin.php?page=fajaedeseo-seo&tab=social')); ?>" class="nav-tab <?php echo $active_tab == 'social' ? 'nav-tab-active' : ''; ?>">Social</a> 
            <a href="<?php echo esc_url(admin_url('admin.php?page=fajaedeseo-seo&tab=legal-documents')); ?>" class="nav-tab <?php echo (in_array($active_tab, ['legal-documents', 'privacy-policy', 'cookies-policy', 'disclaimer', 'gdpr-compliance', 'terms-of-service', 'refund-policy'])) ? 'nav-tab-active' : ''; ?>">Legal Documents</a>
            <a href="<?php echo esc_url(admin_url('admin.php?page=fajaedeseo-seo&tab=redirects')); ?>" class="nav-tab <?php echo $active_tab == 'redirects' ? 'nav-tab-active' : ''; ?>">Redirects (Pro)</a>
            <a href="<?php echo esc_url(admin_url('admin.php?page=fajaedeseo-seo&tab=autolinking')); ?>" class="nav-tab <?php echo $active_tab == 'autolinking' ? 'nav-tab-active' : ''; ?>">Auto Links (Premium)</a>
            <a href="<?php echo esc_url(admin_url('admin.php?page=fajaedeseo-seo&tab=sitemap')); ?>" class="nav-tab <?php echo $active_tab == 'sitemap' ? 'nav-tab-active' : ''; ?>">Sitemap (Premium)</a>
            <a href="<?php echo esc_url(admin_url('admin.php?page=fajaedeseo-seo&tab=globe')); ?>" class="nav-tab <?php echo $active_tab == 'globe' ? 'nav-tab-active' : ''; ?>">Live Globe</a>
            <a href="<?php echo esc_url(admin_url('admin.php?page=fajaedeseo-seo&tab=license')); ?>" class="nav-tab <?php echo $active_tab == 'license' ? 'nav-tab-active' : ''; ?>">License</a>
        </nav>
        <?php
        if ($active_tab == 'dashboard') fajaedeseo_render_dashboard();
        elseif ($active_tab == 'general') fajaedeseo_render_general();
        elseif ($active_tab == 'redirects') {
            if (class_exists('\FajaedeSEO_Pro_License') && \FajaedeSEO_Pro_License::is_pro() && function_exists('fajaedeseo_render_redirects_tab')) {
                fajaedeseo_render_redirects_tab();
            } else {
                // Fallback or message for Pro feature not available
                echo '<div class="notice notice-warning"><p>' . esc_html__('Redirects is a Pro feature. Please activate your license.', 'fajaedeseo-ai') . '</p></div>';
            }
        }
        elseif ($active_tab == 'homepage') fajaedeseo_render_homepage();
        elseif ($active_tab == 'social') fajaedeseo_render_social();
        elseif ($active_tab == 'privacy-policy') fajaedeseo_render_privacy_policy_tab();
        elseif ($active_tab == 'cookies-policy') fajaedeseo_render_cookies_policy_tab();
        elseif ($active_tab == 'legal-documents') fajaedeseo_render_legal_documents_tab();
        elseif ($active_tab == 'disclaimer') fajaedeseo_render_disclaimer_tab();
        elseif ($active_tab == 'gdpr-compliance') fajaedeseo_render_gdpr_compliance_tab();
        elseif ($active_tab == 'terms-of-service') fajaedeseo_render_terms_of_service_tab();
        elseif ($active_tab == 'refund-policy') fajaedeseo_render_refund_policy_tab();
        elseif ($active_tab == 'autolinking') fajaedeseo_render_autolinking_tab();
        elseif ($active_tab == 'globe') fajaedeseo_render_globe();
        elseif ($active_tab == 'sitemap') fajaedeseo_render_sitemap_tab();
        elseif ($active_tab == 'license') fajaedeseo_render_license_tab();
        ?>
    </div>
    <?php
}

function fajaedeseo_render_sitemap_tab() {
    $custom_urls = get_option('fajaedeseo_custom_sitemap_urls', '');
    $is_premium = class_exists('\FajaedeSEO_Pro_License') && in_array(\FajaedeSEO_Pro_License::get_plan_level(), ['premium', 'agency']);
    ?>
    <form method="post" action="options.php">
        <?php settings_fields('fajaedeseo_sitemap_settings_group'); ?>
        <h2><?php echo esc_html__('Custom Sitemap URLs', 'fajaedeseo-ai'); ?></h2>
        <p><?php echo esc_html__('Add pages hosted outside of WordPress (e.g., custom HTML pages, external shop portals) to your XML Sitemap to ensure Google indexes them.', 'fajaedeseo-ai'); ?></p>
        
        <?php if (!$is_premium) : ?>
            <div class="notice notice-warning inline"><p><?php esc_html_e('Custom Sitemap URLs is a Premium feature. Please upgrade your license to include external pages.', 'fajaedeseo-ai'); ?></p></div>
        <?php else : ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row"><label for="fajaedeseo_custom_sitemap_urls"><?php echo esc_html__('External URLs', 'fajaedeseo-ai'); ?></label></th>
                    <td>
                        <textarea id="fajaedeseo_custom_sitemap_urls" name="fajaedeseo_custom_sitemap_urls" rows="10" class="large-text code" placeholder="https://www.yourdomain.com/custom-landing-page.html&#10;https://www.yourdomain.com/shop/"><?php echo esc_textarea($custom_urls); ?></textarea>
                        <p class="description"><?php echo esc_html__('Enter one absolute URL per line. These URLs will be appended to your dynamically generated XML sitemap.', 'fajaedeseo-ai'); ?></p>
                    </td>
                </tr>
            </table>
            <?php submit_button(); ?>
        <?php endif; ?>
    </form>
    <?php
}

/**
 * Renders the Legal Documents overview tab.
 */
function fajaedeseo_render_legal_documents_tab() {
    ?>
    <h2><?php echo esc_html__('Legal Documents Overview', 'fajaedeseo-ai'); ?></h2>
    <p><?php echo esc_html__('Manage all your legal documents here. Pro features offer advanced customization and compliance.', 'fajaedeseo-ai'); ?></p>

    <table class="wp-list-table widefat fixed striped">
        <thead>
            <tr>
                <th scope="col"><?php echo esc_html__('Document', 'fajaedeseo-ai'); ?></th>
                <th scope="col"><?php echo esc_html__('Status', 'fajaedeseo-ai'); ?></th>
                <th scope="col"><?php echo esc_html__('Shortcode', 'fajaedeseo-ai'); ?></th>
                <th scope="col"><?php echo esc_html__('Actions', 'fajaedeseo-ai'); ?></th>
            </tr>
        </thead>
        <tbody>
            <?php
            $documents = [
                'privacy_policy' => [
                    'name' => __('Privacy Policy', 'fajaedeseo-ai'),
                    'option' => 'fajaedeseo_privacy_policy_content',
                    'shortcode' => '[fajaedeseo_privacy_policy]',
                    'tab' => 'privacy-policy',
                    'pro_feature' => false,
                ],
                'cookies_policy' => [
                    'name' => __('Cookies Policy', 'fajaedeseo-ai'),
                    'option' => 'fajaedeseo_cookies_policy_content',
                    'shortcode' => '[fajaedeseo_cookies_policy]',
                    'tab' => 'cookies-policy',
                    'pro_feature' => true,
                ],
                'disclaimer' => [
                    'name' => __('Disclaimer', 'fajaedeseo-ai'),
                    'option' => 'fajaedeseo_disclaimer_content',
                    'shortcode' => '[fajaedeseo_disclaimer]',
                    'tab' => 'disclaimer',
                    'pro_feature' => true,
                ],
                'terms_of_service' => [
                    'name' => __('Terms of Service', 'fajaedeseo-ai'),
                    'option' => 'fajaedeseo_terms_of_service_content',
                    'shortcode' => '[fajaedeseo_terms_of_service]',
                    'tab' => 'terms-of-service',
                    'pro_feature' => true,
                ],
                'gdpr_compliance' => [
                    'name' => __('GDPR/AVG Compliance', 'fajaedeseo-ai'),
                    'option' => 'fajaedeseo_gdpr_compliance_content',
                    'shortcode' => '[fajaedeseo_gdpr_compliance]',
                    'tab' => 'gdpr-compliance',
                    'pro_feature' => true,
                ],
                'refund_policy' => [
                    'name' => __('Refund & Cancellation Policy', 'fajaedeseo-ai'),
                    'option' => 'fajaedeseo_refund_policy_content',
                    'shortcode' => '[fajaedeseo_refund_policy]',
                    'tab' => 'refund-policy',
                    'pro_feature' => true,
                ],
            ];

            foreach ($documents as $key => $doc) {
                $content = get_option($doc['option'], '');
                $status = empty($content) ? __('Not Generated', 'fajaedeseo-ai') : __('Generated', 'fajaedeseo-ai');
                $status_class = empty($content) ? 'status-red' : 'status-green';
                $is_pro_active = class_exists('\FajaedeSEO_Pro_License') && \FajaedeSEO_Pro_License::is_pro();
                $can_edit = !$doc['pro_feature'] || $is_pro_active;
                ?>
                <tr>
                    <td><?php echo esc_html($doc['name']); ?></td>
                    <td>
                        <span class="status-badge <?php echo esc_attr($status_class); ?>">
                            <?php echo esc_html($status); ?>
                        </span>
                        <?php if ($doc['pro_feature'] && !$is_pro_active) : ?>
                            <span class="status-badge status-pro"><?php esc_html_e('Pro Feature', 'fajaedeseo-ai'); ?></span>
                        <?php endif; ?>
                    </td>
                    <td><code><?php echo esc_html($doc['shortcode']); ?></code></td>
                    <td>
                        <?php if ($can_edit) : ?>
                            <a href="<?php echo esc_url(admin_url('admin.php?page=fajaedeseo-seo&tab=' . $doc['tab'])); ?>" class="button button-secondary button-small">
                                <?php esc_html_e('Generate/Edit', 'fajaedeseo-ai'); ?>
                            </a>
                        <?php else : ?>
                            <a href="<?php echo esc_url(admin_url('admin.php?page=fajaedeseo-seo&tab=license')); ?>" class="button button-primary button-small">
                                <?php esc_html_e('Upgrade to Pro', 'fajaedeseo-ai'); ?>
                            </a>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php } ?>
        </tbody>
    </table>
    <style>
        .status-badge { display: inline-block; padding: 3px 8px; border-radius: 3px; font-size: 11px; font-weight: bold; margin-right: 5px; }
        .status-green { background-color: #d4edda; color: #155724; }
        .status-red { background-color: #f8d7da; color: #721c24; }
        .status-pro { background-color: #e0e0e0; color: #555; }
    </style>
    <?php
}

/**
 * Generic renderer for a policy generator tab.
 * Reduces code duplication for all legal document tabs.
 *
 * @param array $config Configuration for the policy tab.
 */
function fajaedeseo_render_policy_generator_tab(array $config) {
    $key = $config['key'];
    $title = $config['title'];
    $description = $config['description'];
    $pro_feature = $config['pro_feature'] ?? false;
    $fields = $config['fields'] ?? [];

    if ($pro_feature && (!class_exists('\FajaedeSEO_Pro_License') || !\FajaedeSEO_Pro_License::is_pro())) {
        /* translators: %s: Title of the feature */
        echo '<div class="notice notice-warning"><p>' . sprintf(esc_html__('%s is a Pro feature. Please activate your license.', 'fajaedeseo-ai'), esc_html($title)) . '</p></div>';
        return;
    }

    // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if (isset($_GET["fajaedeseo_{$key}_generated"]) && '1' === $_GET["fajaedeseo_{$key}_generated"] && wp_verify_nonce(isset($_GET['_wpnonce']) ? sanitize_key($_GET['_wpnonce']) : '', "fajaedeseo_generate_{$key}")) {
        /* translators: %s: Title of the feature */
        printf('<div class="notice notice-success is-dismissible"><p>%s</p></div>', sprintf(esc_html__('%s generated and saved successfully!', 'fajaedeseo-ai'), esc_html($title)));
    }

    $generated_content = get_option("fajaedeseo_{$key}_content", '');
    ?>
    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
        <input type="hidden" name="action" value="fajaedeseo_generate_<?php echo esc_attr($key); ?>" />
        <h2><?php echo esc_html($title); ?></h2>
        <p><?php echo esc_html($description); ?></p>
        <table class="form-table">
            <?php foreach ($fields as $field) :
                $field_id = $field['id'];
                $field_label = $field['label'];
                $field_type = $field['type'];
                $field_default = $field['default'] ?? '';
                $field_value = get_option($field_id, $field_default);
                ?>
                <tr valign="top">
                    <th scope="row"><label for="<?php echo esc_attr($field_id); ?>"><?php echo esc_html($field_label); ?></label></th>
                    <td>
                        <?php if ($field_type === 'textarea') : ?>
                            <textarea id="<?php echo esc_attr($field_id); ?>" name="<?php echo esc_attr($field_id); ?>" rows="4" class="large-text"><?php echo esc_textarea($field_value); ?></textarea>
                        <?php elseif ($field_type === 'checkbox') : ?>
                            <?php foreach ($field['options'] as $option) : ?>
                                <label><input type="checkbox" name="<?php echo esc_attr($option['id']); ?>" value="1" <?php checked(get_option($option['id'], $option['default']), '1'); ?> /> <?php echo esc_html($option['label']); ?></label><br>
                            <?php endforeach; ?>
                        <?php elseif ($field_type === 'select') : ?>
                            <select id="<?php echo esc_attr($field_id); ?>" name="<?php echo esc_attr($field_id); ?>">
                                <?php foreach ($field['options'] as $value => $label) : ?>
                                    <option value="<?php echo esc_attr($value); ?>" <?php selected($field_value, $value); ?>><?php echo esc_html($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        <?php else : ?>
                            <input type="<?php echo esc_attr($field_type); ?>" id="<?php echo esc_attr($field_id); ?>" name="<?php echo esc_attr($field_id); ?>" value="<?php echo esc_attr($field_value); ?>" class="regular-text"/>
                        <?php endif; ?>
                        <?php if (!empty($field['description'])) : ?>
                            <p class="description"><?php echo esc_html($field['description']); ?></p>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </table>
        <?php wp_nonce_field("fajaedeseo_generate_{$key}", 'fajaedeseo_generate_policy_nonce'); ?>
        <?php
        /* translators: %s: Title of the legal document */
        submit_button(sprintf(__('Generate & Save %s', 'fajaedeseo-ai'), $title));
        ?>
    </form>

    <?php if (!empty($generated_content)) : ?>
        <div style="margin-top:30px; border: 1px solid #ccd0d4; padding: 20px; background: #fff; border-left: 4px solid #0073aa;">
            <h3><?php
            /* translators: %s: Title of the legal document */
            printf(esc_html__('Generated %s Preview', 'fajaedeseo-ai'), esc_html($title));
            ?></h3>
            <div style="background: #f8f9fa; padding: 15px; border: 1px solid #ddd; max-height: 400px; overflow-y: scroll; margin-bottom: 20px;">
                <?php echo wp_kses_post($generated_content); ?>
            </div>
            <p><strong><?php echo esc_html__('How to use:', 'fajaedeseo-ai'); ?></strong></p>
            <p><?php
                printf(
                    /* translators: %s: Shortcode snippet */
                    esc_html__('To display this policy on any page or post, simply use the shortcode: %s', 'fajaedeseo-ai'),
                    '<code>[fajaedeseo_' . esc_html($key) . ']</code>'
                ); ?></p>
        </div>
    <?php endif; ?>
    <?php
}

// --- Disclaimer Render Function ---
function fajaedeseo_render_disclaimer_tab() {
    fajaedeseo_render_policy_generator_tab([
        'key' => 'disclaimer',
        'title' => __('Disclaimer Generator', 'fajaedeseo-ai'),
        'description' => __('Generate a basic disclaimer for your website. Remember to review and customize it to ensure full compliance with relevant laws.', 'fajaedeseo-ai'),
        'pro_feature' => true,
        'fields' => [
            ['id' => 'fajaedeseo_company_name', 'label' => __('Company Name', 'fajaedeseo-ai'), 'type' => 'text', 'default' => get_bloginfo('name')],
            ['id' => 'fajaedeseo_website_url', 'label' => __('Website URL', 'fajaedeseo-ai'), 'type' => 'url', 'default' => home_url()],
            ['id' => 'fajaedeseo_company_email', 'label' => __('Contact Email', 'fajaedeseo-ai'), 'type' => 'email', 'default' => get_option('admin_email')],
            ['id' => 'fajaedeseo_company_address', 'label' => __('Company Address', 'fajaedeseo-ai'), 'type' => 'text'],
        ]
    ]);
}

// --- GDPR Compliance Render Function ---
function fajaedeseo_render_gdpr_compliance_tab() {
    fajaedeseo_render_policy_generator_tab([
        'key' => 'gdpr_compliance',
        'title' => __('GDPR/AVG Compliance Generator', 'fajaedeseo-ai'),
        'description' => __('Generate a basic GDPR/AVG compliance statement for your website. Remember to review and customize it to ensure full compliance with relevant laws.', 'fajaedeseo-ai'),
        'pro_feature' => true,
        'fields' => [
            ['id' => 'fajaedeseo_company_name', 'label' => __('Company Name', 'fajaedeseo-ai'), 'type' => 'text', 'default' => get_bloginfo('name')],
            ['id' => 'fajaedeseo_website_url', 'label' => __('Website URL', 'fajaedeseo-ai'), 'type' => 'url', 'default' => home_url()],
            ['id' => 'fajaedeseo_company_email', 'label' => __('Contact Email', 'fajaedeseo-ai'), 'type' => 'email', 'default' => get_option('admin_email')],
            ['id' => 'fajaedeseo_company_address', 'label' => __('Company Address', 'fajaedeseo-ai'), 'type' => 'text'],
            ['id' => 'fajaedeseo_gdpr_dpia_required_group', 'label' => __('DPIA Required', 'fajaedeseo-ai'), 'type' => 'checkbox', 'options' => [
                ['id' => 'fajaedeseo_gdpr_dpia_required', 'label' => __('Conduct Data Protection Impact Assessment (DPIA) for high-risk processing.', 'fajaedeseo-ai'), 'default' => '0'],
            ]],
        ]
    ]);
}

// --- Terms of Service Render Function ---
function fajaedeseo_render_terms_of_service_tab() {
    fajaedeseo_render_policy_generator_tab([
        'key' => 'terms_of_service',
        'title' => __('Terms of Service Generator', 'fajaedeseo-ai'),
        'description' => __('Generate basic Terms of Service for your website. Remember to review and customize it to ensure full compliance with relevant laws.', 'fajaedeseo-ai'),
        'pro_feature' => true,
        'fields' => [
            ['id' => 'fajaedeseo_company_name', 'label' => __('Company Name', 'fajaedeseo-ai'), 'type' => 'text', 'default' => get_bloginfo('name')],
            ['id' => 'fajaedeseo_website_url', 'label' => __('Website URL', 'fajaedeseo-ai'), 'type' => 'url', 'default' => home_url()],
            ['id' => 'fajaedeseo_company_email', 'label' => __('Contact Email', 'fajaedeseo-ai'), 'type' => 'email', 'default' => get_option('admin_email')],
            ['id' => 'fajaedeseo_company_address', 'label' => __('Company Address', 'fajaedeseo-ai'), 'type' => 'text'],
        ]
    ]);
}

// --- Refund & Cancellation Policy Render Function ---
function fajaedeseo_render_refund_policy_tab() {
    fajaedeseo_render_policy_generator_tab([
        'key' => 'refund_policy',
        'title' => __('Refund & Cancellation Policy Generator', 'fajaedeseo-ai'),
        'description' => __('Configure your specific cancellation conditions and generate your policy.', 'fajaedeseo-ai'),
        'pro_feature' => true,
        'fields' => [
            ['id' => 'fajaedeseo_refunds_offered', 'label' => __('Do you offer refunds?', 'fajaedeseo-ai'), 'type' => 'select', 'default' => '14_days', 'options' => [
                'no' => __('No Refunds (All sales are final)', 'fajaedeseo-ai'),
                '14_days' => __('Yes, 14-Day Money Back Guarantee', 'fajaedeseo-ai'),
                '30_days' => __('Yes, 30-Day Money Back Guarantee', 'fajaedeseo-ai'),
            ]],
            ['id' => 'fajaedeseo_refund_conditions', 'label' => __('Refund Conditions', 'fajaedeseo-ai'), 'type' => 'textarea', 'description' => __('Optional: Specify under which conditions the refund applies.', 'fajaedeseo-ai')],
            ['id' => 'fajaedeseo_cancellation_method', 'label' => __('How to Cancel', 'fajaedeseo-ai'), 'type' => 'select', 'default' => 'account', 'options' => [
                'account' => __('Via Account Dashboard', 'fajaedeseo-ai'),
                'support' => __('Via Support Email', 'fajaedeseo-ai'),
                'both' => __('Both Account & Email', 'fajaedeseo-ai'),
            ]],
            ['id' => 'fajaedeseo_cancellation_period', 'label' => __('Cancellation Period', 'fajaedeseo-ai'), 'type' => 'select', 'default' => 'end_of_period', 'options' => [
                'immediate' => __('Immediately upon request', 'fajaedeseo-ai'),
                'end_of_period' => __('At the end of the current billing cycle', 'fajaedeseo-ai'),
            ]],
            ['id' => 'fajaedeseo_proration', 'label' => __('Proration', 'fajaedeseo-ai'), 'type' => 'select', 'default' => 'no_proration', 'options' => [
                'no_proration' => __('No pro-rated refunds for unused time', 'fajaedeseo-ai'),
                'pro_rated' => __('Pro-rated refunds available for unused time', 'fajaedeseo-ai'),
            ]],
        ]
    ]);
}

function fajaedeseo_render_dashboard() {
    $pages_indexed = fajaedeseo_get_indexed_pages_count();
    $is_pro = class_exists('\FajaedeSEO_Pro_License') && \FajaedeSEO_Pro_License::is_pro();
    $plan_tier = class_exists('\FajaedeSEO_Pro_License') ? \FajaedeSEO_Pro_License::get_plan_level() : 'free';
    $page_speed = $is_pro ? fajaedeseo_get_page_speed_score() : null;
    $overall_score = $is_pro ? fajaedeseo_get_overall_seo_score() : null;
    $sitemap_last_updated = get_option('fajaedeseo_sitemap_last_updated');
    $sitemap_last_updated_string = $sitemap_last_updated ? wp_date('j F Y H:i:s', $sitemap_last_updated) : __('Not generated yet', 'fajaedeseo-ai');
    $flush_sitemap_url = wp_nonce_url(admin_url('admin.php?page=fajaedeseo-seo&action=flush_sitemap_cache'), 'fajaedeseo_flush_sitemap');
    ?>
    <h2><?php esc_html_e('SEO Overview', 'fajaedeseo-ai'); ?></h2>
    <table class="widefat striped" style="max-width:400px;">
        <tr><td><?php esc_html_e('Pages Indexed:', 'fajaedeseo-ai'); ?></td><td><?php echo esc_html($pages_indexed); ?></td></tr>
        <tr><td><?php esc_html_e('License Status:', 'fajaedeseo-ai'); ?></td><td><?php echo $is_pro ? '✅ ' . esc_html__('Active', 'fajaedeseo-ai') . ' (' . esc_html(ucfirst($plan_tier)) . ')' : '❌ ' . esc_html__('Inactive (Free)', 'fajaedeseo-ai'); ?></td></tr>
        <?php if ($is_pro) : ?>
            <tr><td><?php esc_html_e('Page Speed:', 'fajaedeseo-ai'); ?></td><td><?php echo esc_html($page_speed); ?>/100</td></tr>
            <tr><td><?php esc_html_e('Overall SEO Score:', 'fajaedeseo-ai'); ?></td><td><?php echo esc_html($overall_score); ?>%</td></tr>
        <?php else : ?>
            <tr><td><?php esc_html_e('Page Speed:', 'fajaedeseo-ai'); ?></td><td><span style="color:#888;">🔒 <?php esc_html_e('Locked (Pro)', 'fajaedeseo-ai'); ?></span></td></tr>
            <tr><td><?php esc_html_e('Overall SEO Score:', 'fajaedeseo-ai'); ?></td><td><span style="color:#888;">🔒 <?php esc_html_e('Locked (Pro)', 'fajaedeseo-ai'); ?></span></td></tr>
        <?php endif; ?>
    </table>

    <h2><?php echo esc_html__('XML Sitemap', 'fajaedeseo-ai'); ?></h2>
    <p><?php
        printf(
            /* translators: %s: Sitemap URL */
            esc_html__('The sitemap is available at: %s', 'fajaedeseo-ai'), 
            '<a href="' . esc_url(home_url('/fajaede-sitemap-index.xml')) . '" target="_blank" rel="noopener noreferrer">' . esc_html(home_url('/fajaede-sitemap-index.xml')) . '</a>'
        ); ?></p>
    <p><?php echo esc_html__('Last updated:', 'fajaedeseo-ai'); ?> <strong><?php echo esc_html($sitemap_last_updated_string); ?></strong><br>
        <a href="<?php echo esc_url($flush_sitemap_url); ?>" class="button button-secondary" style="margin-top:10px;"><?php echo esc_html__('Refresh Sitemap Cache', 'fajaedeseo-ai'); ?></a>
    </p>
    <?php
}

// --- Social Render Function ---
function fajaedeseo_render_social() {
    $is_premium_agency = class_exists('\FajaedeSEO_Pro_License') && in_array(\FajaedeSEO_Pro_License::get_plan_level(), ['premium', 'agency']);
    ?>
    <form method="post" action="options.php">
        <?php settings_fields('fajaedeseo_social_settings_group'); ?>
        <h2><?php echo esc_html__('Social Handles', 'fajaedeseo-ai'); ?></h2>
        <table class="form-table">
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_twitter_handle"><?php echo esc_html__('Twitter', 'fajaedeseo-ai'); ?></label></th> 
                <td><input type="text" id="fajaedeseo_twitter_handle" name="fajaedeseo_twitter_handle" value="<?php echo esc_attr(get_option('fajaedeseo_twitter_handle', '')); ?>" class="regular-text"/></td> 
            </tr>
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_facebook_handle"><?php echo esc_html__('Facebook', 'fajaedeseo-ai'); ?></label></th> 
                <td><input type="text" id="fajaedeseo_facebook_handle" name="fajaedeseo_facebook_handle" value="<?php echo esc_attr(get_option('fajaedeseo_facebook_handle', '')); ?>" class="regular-text"/></td> 
            </tr>
        </table>

        <h2><?php echo esc_html__('Advanced Facebook Integration', 'fajaedeseo-ai'); ?></h2>
        <p><?php echo esc_html__('Connect your site to Facebook Insights and Apps using advanced Open Graph tags.', 'fajaedeseo-ai'); ?></p>
        <?php if (!$is_premium_agency) : ?>
            <div class="notice notice-warning inline"><p><?php esc_html_e('Advanced Facebook Integration (fb:admins & fb:pages) is a Premium feature. Please upgrade your license.', 'fajaedeseo-ai'); ?></p></div>
        <?php else : ?>
        <table class="form-table">
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_fb_admins"><?php echo esc_html__('Facebook Admins (fb:admins)', 'fajaedeseo-ai'); ?></label></th> 
                <td>
                    <input type="text" id="fajaedeseo_fb_admins" name="fajaedeseo_fb_admins" value="<?php echo esc_attr(get_option('fajaedeseo_fb_admins', '')); ?>" class="regular-text"/>
                    <p class="description"><?php esc_html_e('Comma-separated Facebook User IDs to link to Facebook Insights.', 'fajaedeseo-ai'); ?></p>
                </td> 
            </tr>
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_fb_app_id"><?php echo esc_html__('Facebook Pages / App ID (fb:pages)', 'fajaedeseo-ai'); ?></label></th> 
                <td>
                    <input type="text" id="fajaedeseo_fb_app_id" name="fajaedeseo_fb_app_id" value="<?php echo esc_attr(get_option('fajaedeseo_fb_app_id', '')); ?>" class="regular-text"/>
                    <p class="description"><?php esc_html_e('Your Facebook Page ID or App ID.', 'fajaedeseo-ai'); ?></p>
                </td> 
            </tr>
        </table>
        <?php endif; ?>
        
        <?php submit_button(); ?>
    </form>
    <?php
}

/**
 * Renders the Cookies Policy tab content.
 */
function fajaedeseo_render_cookies_policy_tab() {
    fajaedeseo_render_policy_generator_tab([
        'key' => 'cookies_policy',
        'title' => __('Cookies Policy Generator', 'fajaedeseo-ai'),
        'description' => __('Generate a basic cookies policy for your website. Remember to review and customize it to ensure full compliance with relevant laws.', 'fajaedeseo-ai'),
        'pro_feature' => true,
        'fields' => [
            ['id' => 'fajaedeseo_company_name', 'label' => __('Company Name', 'fajaedeseo-ai'), 'type' => 'text', 'default' => get_bloginfo('name')],
            ['id' => 'fajaedeseo_website_url', 'label' => __('Website URL', 'fajaedeseo-ai'), 'type' => 'url', 'default' => home_url()],
            ['id' => 'fajaedeseo_company_email', 'label' => __('Contact Email', 'fajaedeseo-ai'), 'type' => 'email', 'default' => get_option('admin_email')],
            ['id' => 'fajaedeseo_cookie_types_group', 'label' => __('Cookie Types', 'fajaedeseo-ai'), 'type' => 'checkbox', 'options' => [
                ['id' => 'fajaedeseo_cookies_necessary', 'label' => __('Necessary Cookies (essential for site function)', 'fajaedeseo-ai'), 'default' => '1'],
                ['id' => 'fajaedeseo_cookies_functional', 'label' => __('Functional Cookies (enhance user experience)', 'fajaedeseo-ai'), 'default' => '1'],
                ['id' => 'fajaedeseo_cookies_analytics', 'label' => __('Analytics Cookies (track site usage)', 'fajaedeseo-ai'), 'default' => '1'],
                ['id' => 'fajaedeseo_cookies_marketing', 'label' => __('Marketing Cookies (for advertising)', 'fajaedeseo-ai'), 'default' => '1'],
            ]],
        ]
    ]);
}

// --- Privacy Policy Render Function ---
function fajaedeseo_render_privacy_policy_tab() {
    if (isset($_GET['fajaedeseo_privacy_generated']) && '1' === $_GET['fajaedeseo_privacy_generated'] && wp_verify_nonce(isset($_GET['_wpnonce']) ? sanitize_key($_GET['_wpnonce']) : '', 'fajaedeseo_generate_privacy_policy')) {
        printf('<div class="notice notice-success is-dismissible"><p>%s</p></div>', esc_html__('Privacy Policy generated and saved successfully!', 'fajaedeseo-ai'));
    }

    $company_name = get_option('fajaedeseo_company_name', get_bloginfo('name'));
    $company_address = get_option('fajaedeseo_company_address', '');
    $company_email = get_option('fajaedeseo_company_email', get_option('admin_email'));
    $website_url = get_option('fajaedeseo_website_url', home_url());
    $data_collected_personal = get_option('fajaedeseo_data_collected_personal', '0');
    $data_collected_usage = get_option('fajaedeseo_data_collected_usage', '0');
    $data_sharing_third_parties = get_option('fajaedeseo_data_sharing_third_parties', '0');
    $data_sharing_analytics = get_option('fajaedeseo_data_sharing_analytics', '0');
    $data_sharing_ads = get_option('fajaedeseo_data_sharing_ads', '0');
    $data_security_measures = get_option('fajaedeseo_data_security_measures', __('We implement various security measures to maintain the safety of your personal information.', 'fajaedeseo-ai'));
    $user_rights_access = get_option('fajaedeseo_user_rights_access', '1');
    $user_rights_deletion = get_option('fajaedeseo_user_rights_deletion', '1');
    $cookies_used = get_option('fajaedeseo_cookies_used', __('We use cookies to enhance your experience on our website.', 'fajaedeseo-ai'));
    $contact_info_policy = get_option('fajaedeseo_contact_info_policy', __('If you have any questions about this Privacy Policy, please contact us.', 'fajaedeseo-ai'));
    $generated_policy_content = get_option('fajaedeseo_privacy_policy_content', '');
    ?>
    <form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
        <input type="hidden" name="action" value="fajaedeseo_generate_privacy_policy" />
        <h2><?php echo esc_html__('Privacy Policy Generator', 'fajaedeseo-ai'); ?></h2>
        <p><?php esc_html_e('Generate a basic privacy policy for your website. Remember to review and customize it to ensure full compliance with relevant laws.', 'fajaedeseo-ai'); ?></p>
        <table class="form-table">
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_company_name"><?php echo esc_html__('Company Name', 'fajaedeseo-ai'); ?></label></th>
                <td><input type="text" id="fajaedeseo_company_name" name="fajaedeseo_company_name" value="<?php echo esc_attr($company_name); ?>" class="regular-text"/></td>
            </tr>
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_company_address"><?php echo esc_html__('Company Address', 'fajaedeseo-ai'); ?></label></th>
                <td><input type="text" id="fajaedeseo_company_address" name="fajaedeseo_company_address" value="<?php echo esc_attr($company_address); ?>" class="regular-text"/></td>
            </tr>
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_company_email"><?php echo esc_html__('Company Email', 'fajaedeseo-ai'); ?></label></th>
                <td><input type="email" id="fajaedeseo_company_email" name="fajaedeseo_company_email" value="<?php echo esc_attr($company_email); ?>" class="regular-text"/></td>
            </tr>
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_website_url"><?php echo esc_html__('Website URL', 'fajaedeseo-ai'); ?></label></th>
                <td><input type="url" id="fajaedeseo_website_url" name="fajaedeseo_website_url" value="<?php echo esc_attr($website_url); ?>" class="regular-text"/></td>
            </tr>
            <tr valign="top">
                <th scope="row"><?php echo esc_html__('Data Collection', 'fajaedeseo-ai'); ?></th>
                <td>
                    <label><input type="checkbox" name="fajaedeseo_data_collected_personal" value="1" <?php checked(get_option('fajaedeseo_data_collected_personal', '0'), '1'); ?> /> <?php echo esc_html__('Collects personal data (e.g., name, email)', 'fajaedeseo-ai'); ?></label><br>
                    <label><input type="checkbox" name="fajaedeseo_data_collected_usage" value="1" <?php checked(get_option('fajaedeseo_data_collected_usage', '0'), '1'); ?> /> <?php echo esc_html__('Collects usage data (e.g., IP address, browser type)', 'fajaedeseo-ai'); ?></label>
                </td>
            </tr>
            <tr valign="top">
                <th scope="row"><?php echo esc_html__('Data Sharing', 'fajaedeseo-ai'); ?></th>
                <td>
                    <label><input type="checkbox" name="fajaedeseo_data_sharing_third_parties" value="1" <?php checked(get_option('fajaedeseo_data_sharing_third_parties', '0'), '1'); ?> /> <?php echo esc_html__('Shares data with third-party service providers', 'fajaedeseo-ai'); ?></label><br>
                    <label><input type="checkbox" name="fajaedeseo_data_sharing_analytics" value="1" <?php checked(get_option('fajaedeseo_data_sharing_analytics', '0'), '1'); ?> /> <?php echo esc_html__('Uses analytics services (e.g., Google Analytics)', 'fajaedeseo-ai'); ?></label><br>
                    <label><input type="checkbox" name="fajaedeseo_data_sharing_ads" value="1" <?php checked(get_option('fajaedeseo_data_sharing_ads', '0'), '1'); ?> /> <?php echo esc_html__('Uses data for advertising/retargeting', 'fajaedeseo-ai'); ?></label>
                </td>
            </tr>
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_data_security_measures"><?php echo esc_html__('Data Security Measures', 'fajaedeseo-ai'); ?></label></th>
                <td><textarea id="fajaedeseo_data_security_measures" name="fajaedeseo_data_security_measures" rows="4" class="large-text"><?php echo esc_textarea($data_security_measures); ?></textarea></td>
            </tr>
            <tr valign="top">
                <th scope="row"><?php echo esc_html__('User Rights', 'fajaedeseo-ai'); ?></th>
                <td>
                    <label><input type="checkbox" name="fajaedeseo_user_rights_access" value="1" <?php checked(get_option('fajaedeseo_user_rights_access', '1'), '1'); ?> /> <?php echo esc_html__('Users can request access to their data', 'fajaedeseo-ai'); ?></label><br>
                    <label><input type="checkbox" name="fajaedeseo_user_rights_deletion" value="1" <?php checked(get_option('fajaedeseo_user_rights_deletion', '1'), '1'); ?> /> <?php echo esc_html__('Users can request deletion of their data', 'fajaedeseo-ai'); ?></label>
                </td>
            </tr>
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_cookies_used"><?php echo esc_html__('Cookies Used', 'fajaedeseo-ai'); ?></label></th>
                <td><textarea id="fajaedeseo_cookies_used" name="fajaedeseo_cookies_used" rows="4" class="large-text"><?php echo esc_textarea($cookies_used); ?></textarea></td>
            </tr>
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_contact_info_policy"><?php echo esc_html__('Contact Information for Policy', 'fajaedeseo-ai'); ?></label></th>
                <td><textarea id="fajaedeseo_contact_info_policy" name="fajaedeseo_contact_info_policy" rows="4" class="large-text"><?php echo esc_textarea($contact_info_policy); ?></textarea></td>
            </tr>
        </table>
        <?php wp_nonce_field('fajaedeseo_generate_privacy_policy', 'fajaedeseo_generate_policy_nonce'); ?>
        <?php submit_button(__('Generate & Save Privacy Policy', 'fajaedeseo-ai')); ?>
    </form>

    <?php if (!empty($generated_policy_content)) : ?>
        <div style="margin-top:30px; border: 1px solid #ccd0d4; padding: 20px; background: #fff; border-left: 4px solid #0073aa;">
            <h3><?php echo esc_html__('Generated Privacy Policy Preview', 'fajaedeseo-ai'); ?></h3>
            <div style="background: #f8f9fa; padding: 15px; border: 1px solid #ddd; max-height: 400px; overflow-y: scroll; margin-bottom: 20px;">
                <?php echo wp_kses_post($generated_policy_content); ?>
            </div>
            <p><strong><?php echo esc_html__('How to use:', 'fajaedeseo-ai'); ?></strong></p>
            <p><?php
                printf(
                    /* translators: %s: Shortcode snippet */
                    esc_html__('To display this policy on any page or post, simply use the shortcode: %s', 'fajaedeseo-ai'),
                    '<code>[fajaedeseo_privacy_policy]</code>'
                ); ?></p>
        </div>
    <?php endif; ?>
    <?php
}
function fajaedeseo_render_general() {
    $robots_default = "User-agent: *\nDisallow: /wp-admin/\nAllow: /wp-admin/admin-ajax.php\n\nSitemap: " . home_url('/fajaede-sitemap-index.xml'); 
    $robots = get_option('fajaedeseo_robots_txt', $robots_default); 
    $disable_schema = get_option('fajaedeseo_disable_schema', '0');
    ?>
    <form method="post" action="options.php">
        <?php settings_fields('fajaedeseo_settings_group'); ?>
        
        <h2><?php echo esc_html__('Search Engine Configuration', 'fajaedeseo-ai'); ?></h2>
        <table class="form-table">
            <tr valign="top"> 
                <th scope="row"><label for="fajaedeseo_robots_txt"><?php echo esc_html__('Virtual Robots.txt', 'fajaedeseo-ai'); ?></label></th> 
                <td> 
                    <textarea id="fajaedeseo_robots_txt" name="fajaedeseo_robots_txt" rows="8" class="large-text code"><?php echo esc_textarea($robots); ?></textarea> 
                    <p class="description"><?php echo esc_html__('Adjust your robots.txt. This overrides the default WordPress file if no physical file exists on the server.', 'fajaedeseo-ai'); ?></p>
                </td>
            </tr>
            <tr valign="top">
                <th scope="row"><?php echo esc_html__('Schema.org (JSON-LD)', 'fajaedeseo-ai'); ?></th>
                <td>
                    <input type="hidden" name="fajaedeseo_disable_schema" value="0" />
                    <label><input type="checkbox" name="fajaedeseo_disable_schema" value="1" <?php checked($disable_schema, '1'); ?> /> <?php echo esc_html__('Disable automatic Schema output', 'fajaedeseo-ai'); ?></label>
                </td>
            </tr>
        </table>

        <h2><?php echo esc_html__('Local SEO (Geo Tags)', 'fajaedeseo-ai'); ?></h2>
        <p><?php echo esc_html__('Configure your business location. Premium & Agency users will automatically output Geo & ICBM meta tags to improve local search rankings.', 'fajaedeseo-ai'); ?></p>
        <?php 
        $is_premium_agency = class_exists('\FajaedeSEO_Pro_License') && in_array(\FajaedeSEO_Pro_License::get_plan_level(), ['premium', 'agency']);
        if (!$is_premium_agency) : ?>
            <div class="notice notice-warning inline"><p><?php esc_html_e('Local SEO (Geo Tags) is a Premium feature. Please upgrade your license.', 'fajaedeseo-ai'); ?></p></div>
        <?php else : ?>
        <table class="form-table">
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_company_city"><?php echo esc_html__('City', 'fajaedeseo-ai'); ?></label></th>
                <td><input type="text" id="fajaedeseo_company_city" name="fajaedeseo_company_city" value="<?php echo esc_attr(get_option('fajaedeseo_company_city')); ?>" class="regular-text" placeholder="e.g. Rotterdam" /></td>
            </tr>
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_company_region"><?php echo esc_html__('Region / Country', 'fajaedeseo-ai'); ?></label></th>
                <td><input type="text" id="fajaedeseo_company_region" name="fajaedeseo_company_region" value="<?php echo esc_attr(get_option('fajaedeseo_company_region')); ?>" class="regular-text" placeholder="e.g. Nederland or NL-ZH" /></td>
            </tr>
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_company_lat"><?php echo esc_html__('Latitude', 'fajaedeseo-ai'); ?></label></th>
                <td><input type="text" id="fajaedeseo_company_lat" name="fajaedeseo_company_lat" value="<?php echo esc_attr(get_option('fajaedeseo_company_lat')); ?>" class="regular-text" placeholder="e.g. 51.9225" /></td>
            </tr>
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_company_lng"><?php echo esc_html__('Longitude', 'fajaedeseo-ai'); ?></label></th>
                <td><input type="text" id="fajaedeseo_company_lng" name="fajaedeseo_company_lng" value="<?php echo esc_attr(get_option('fajaedeseo_company_lng')); ?>" class="regular-text" placeholder="e.g. 4.47917" /></td>
            </tr>
        </table>
        <?php endif; ?>

        <?php if ($is_premium_agency && \FajaedeSEO_Pro_License::get_plan_level() === 'agency') : ?>
            <h2><?php echo esc_html__('White-Label Agency Settings', 'fajaedeseo-ai'); ?></h2>
            <p><?php echo esc_html__('Configure the branding for your PDF reports.', 'fajaedeseo-ai'); ?></p>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row"><label for="fajaedeseo_agency_logo"><?php echo esc_html__('Agency Logo URL', 'fajaedeseo-ai'); ?></label></th>
                    <td>
                        <input type="url" id="fajaedeseo_agency_logo" name="fajaedeseo_agency_logo" value="<?php echo esc_attr(get_option('fajaedeseo_agency_logo')); ?>" class="regular-text" placeholder="https://www.fajaede.nl/logo.png" />
                        <p class="description"><?php echo esc_html__('Enter the direct link to your agency logo (PNG or JPG). This will be displayed on the cover of your generated PDF reports.', 'fajaedeseo-ai'); ?></p>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><label for="fajaedeseo_agency_color"><?php echo esc_html__('Primary Brand Color', 'fajaedeseo-ai'); ?></label></th>
                    <td>
                        <input type="color" id="fajaedeseo_agency_color" name="fajaedeseo_agency_color" value="<?php echo esc_attr(get_option('fajaedeseo_agency_color', '#0073aa')); ?>" />
                        <p class="description"><?php echo esc_html__('Select the primary color for headings and accents in the PDF report.', 'fajaedeseo-ai'); ?></p>
                    </td>
                </tr>
            </table>
        <?php endif; ?>

        <?php if (defined('FAJAEDE_MASTER_SERVER') && FAJAEDE_MASTER_SERVER) : ?>
            <h2><?php echo esc_html__('Payment Gateway Integration', 'fajaedeseo-ai'); ?></h2>
            <p><?php echo esc_html__('Configure your payment provider to automatically sell and activate licenses.', 'fajaedeseo-ai'); ?></p>
            <table class="form-table">
                 <tr valign="top">
                    <th scope="row"><label for="fajaedeseo_active_payment_gateway"><?php echo esc_html__( 'Active Gateway', 'fajaedeseo-ai' ); ?></label></th>
                    <td>
                        <select id="fajaedeseo_active_payment_gateway" name="fajaedeseo_active_payment_gateway">
                            <option value="mollie" <?php selected( get_option( 'fajaedeseo_active_payment_gateway' ), 'mollie' ); ?>>Mollie</option>
                            <option value="lemonsqueezy" <?php selected( get_option( 'fajaedeseo_active_payment_gateway' ), 'lemonsqueezy' ); ?>>Lemon Squeezy</option>
                        </select>
                    </td>
                </tr>
                <?php
                // Render de specifieke velden voor de geselecteerde gateway.
                // Dit vereist dat de gateway-klassen geladen zijn.
                $gateway_classes = [
                    'mollie' => 'FajaedeSEO_Mollie_Gateway',
                    // 'lemonsqueezy' => 'FajaedeSEO_LemonSqueezy_Gateway', // Toekomstige refactor
                ];

                foreach ($gateway_classes as $id => $class) {
                    if (class_exists($class) && method_exists($class, 'render_settings_fields')) {
                        $gateway = new $class();
                        $gateway->render_settings_fields();
                    }
                }
                ?>
            </table>
        <?php endif; ?>
        
        <?php if (defined('FAJAEDE_MASTER_SERVER') && FAJAEDE_MASTER_SERVER) : ?>
            <h2><?php echo esc_html__('VAT & OSS Compliance', 'fajaedeseo-ai'); ?></h2>
            <p><?php echo esc_html__('Configure your company VAT number and OSS compliance settings.', 'fajaedeseo-ai'); ?></p>
            <?php
            $eu_turnover = class_exists('\FajaedeSEO_VAT_Calculator') ? \FajaedeSEO_VAT_Calculator::get_year_eu_turnover() : 0.0;
            $oss_threshold = 10000;
            $threshold_exceeded = $eu_turnover >= $oss_threshold;
            
            if ($threshold_exceeded) {
                echo '<div class="notice notice-warning inline" style="border-left-color: #f56e28;"><p><strong>' . esc_html__('⚠️ Je EU‑B2C‑omzet is boven €10.000.', 'fajaedeseo-ai') . '</strong><br>' . esc_html__('Je moet je registreren voor OSS (Union OSS) bij de Belgische fiscus.', 'fajaedeseo-ai') . '<br>' . esc_html__('Onze plugin rekent vanaf nu automatisch klantland‑btw, maar de registratie en OSS‑aangifte zijn jouw verantwoordelijkheid.', 'fajaedeseo-ai') . '</p></div>';
            } else {
                /* translators: 1: Current EU sales amount, 2: OSS Threshold amount */
                echo '<div class="notice notice-info inline"><p>' . sprintf(esc_html__('Current EU cross-border B2C sales: €%1$s (Threshold: €%2$s).', 'fajaedeseo-ai'), number_format($eu_turnover, 2), number_format($oss_threshold, 2)) . '</p></div>';
            }
            ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row"><label for="fajaedeseo_company_vat_number"><?php echo esc_html__('Company VAT Number', 'fajaedeseo-ai'); ?></label></th>
                    <td>
                        <input type="text" id="fajaedeseo_company_vat_number" name="fajaedeseo_company_vat_number" value="<?php echo esc_attr(get_option('fajaedeseo_company_vat_number')); ?>" class="regular-text" placeholder="BE0123456789" />
                        <p class="description"><?php esc_html_e('Your Belgian company VAT number. This will be shown on invoices.', 'fajaedeseo-ai'); ?></p>
                    </td>
                </tr>
                <tr valign="top">
                    <th scope="row"><?php echo esc_html__('Voluntary OSS (Full OSS Style)', 'fajaedeseo-ai'); ?></th>
                    <td>
                        <fieldset>
                            <label for="fajaedeseo_voluntary_oss">
                                <input name="fajaedeseo_voluntary_oss" type="checkbox" id="fajaedeseo_voluntary_oss" value="1" <?php checked(get_option('fajaedeseo_voluntary_oss'), '1'); ?> />
                                <?php echo esc_html__('Always apply customer country VAT for EU B2C sales (even below €10k threshold)', 'fajaedeseo-ai'); ?>
                            </label>
                            <p class="description"><?php esc_html_e('By default, if you are below the €10k threshold, Belgian VAT (21%) is applied to all EU B2C sales. Enable this if you voluntarily choose to apply destination VAT for all EU sales.', 'fajaedeseo-ai'); ?></p>
                        </fieldset>
                    </td>
                </tr>
            </table>
        <?php endif; ?>

        <h2><?php echo esc_html__('Automated Accounting', 'fajaedeseo-ai'); ?></h2>
        <p><?php echo esc_html__('Automatically send your monthly sales via CSV to your accountant.', 'fajaedeseo-ai'); ?></p>
        <?php 
        $is_agency = class_exists('\FajaedeSEO_Pro_License') && \FajaedeSEO_Pro_License::get_plan_level() === 'agency';
        if (!$is_agency) : ?>
            <div class="notice notice-warning inline"><p><?php esc_html_e('Automated Accounting is an Agency feature. Please upgrade your license.', 'fajaedeseo-ai'); ?></p></div>
        <?php else : ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row"><label for="fajaedeseo_accountant_email"><?php echo esc_html__('Accountant Email', 'fajaedeseo-ai'); ?></label></th>
                    <td><input type="email" id="fajaedeseo_accountant_email" name="fajaedeseo_accountant_email" value="<?php echo esc_attr(get_option('fajaedeseo_accountant_email')); ?>" class="regular-text" placeholder="admin@myaccountant.com" /></td>
                </tr>
            </table>
            
            <button type="button" id="fajaedeseo-download-csv-btn" class="button button-secondary">
                <?php esc_html_e('Download Sales CSV Now', 'fajaedeseo-ai'); ?>
            </button>
            <button type="button" id="fajaedeseo-test-email-btn" class="button">
                <?php esc_html_e('Stuur Test E-mail', 'fajaedeseo-ai'); ?>
            </button>
            <button type="button" id="fajaedeseo-clean-db-btn" class="button" style="color: #dc3545; border-color: #dc3545;">
                <?php esc_html_e('🗑️ Verwijder Testdata (€0,00)', 'fajaedeseo-ai'); ?>
            </button>
            <span id="fajaedeseo-csv-spinner" class="spinner"></span>
            <p id="fajaedeseo-csv-msg" style="color: #d63638; display: none; margin-top: 10px;"></p>
            
            <script>
            document.addEventListener('DOMContentLoaded', function() {
                const btn = document.getElementById('fajaedeseo-download-csv-btn');
                if (!btn) return;
                btn.addEventListener('click', function() {
                    const spinner = document.getElementById('fajaedeseo-csv-spinner');
                    const msg = document.getElementById('fajaedeseo-csv-msg');
                    spinner.classList.add('is-active');
                    msg.style.display = 'none';
                    btn.disabled = true;

                    fetch('<?php echo esc_url(rest_url('fajaedeseo/v1/accounting-export')); ?>', {
                        method: 'GET',
                        headers: {
                            'X-WP-Nonce': '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>'
                        }
                    })
                    .then(res => res.json())
                    .then(data => {
                        spinner.classList.remove('is-active');
                        btn.disabled = false;
                        
                        if (data.code && data.message) {
                            msg.textContent = data.message;
                            msg.style.display = 'block';
                            return;
                        }

                        if (data.csv && data.filename) {
                            const linkSource = 'data:text/csv;base64,' + data.csv;
                            const downloadLink = document.createElement('a');
                            downloadLink.href = linkSource;
                            downloadLink.download = data.filename;
                            downloadLink.click();
                        }
                    })
                    .catch(err => {
                        spinner.classList.remove('is-active');
                        btn.disabled = false;
                        msg.textContent = 'Er is een fout opgetreden bij het exporteren.';
                        msg.style.display = 'block';
                    });
                });

                const testBtn = document.getElementById('fajaedeseo-test-email-btn');
                if (testBtn) {
                    testBtn.addEventListener('click', function() {
                        const spinner = document.getElementById('fajaedeseo-csv-spinner');
                        const msg = document.getElementById('fajaedeseo-csv-msg');
                        spinner.classList.add('is-active');
                        msg.style.display = 'none';
                        testBtn.disabled = true;

                        fetch('<?php echo esc_url(rest_url('fajaedeseo/v1/accounting-test-email')); ?>', {
                            method: 'POST',
                            headers: { 'X-WP-Nonce': '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>' }
                        })
                        .then(res => res.json())
                        .then(data => {
                            spinner.classList.remove('is-active');
                            testBtn.disabled = false;
                            msg.textContent = data.message || 'Test verzonden.';
                            msg.style.color = data.success ? '#28a745' : '#d63638';
                            msg.style.display = 'block';
                        })
                        .catch(err => {
                            spinner.classList.remove('is-active');
                            testBtn.disabled = false;
                            msg.textContent = 'Er is een fout opgetreden bij het communiceren met de server.';
                            msg.style.color = '#d63638';
                            msg.style.display = 'block';
                        });
                    });
                }

                const cleanBtn = document.getElementById('fajaedeseo-clean-db-btn');
                if (cleanBtn) {
                    cleanBtn.addEventListener('click', function() {
                        if (!confirm('Weet je zeker dat je alle oude test-transacties met een bedrag van €0,00 definitief uit de database wilt verwijderen? Dit kan niet ongedaan worden gemaakt.')) return;
                        
                        const spinner = document.getElementById('fajaedeseo-csv-spinner');
                        const msg = document.getElementById('fajaedeseo-csv-msg');
                        spinner.classList.add('is-active');
                        msg.style.display = 'none';
                        cleanBtn.disabled = true;

                        fetch('<?php echo esc_url(rest_url('fajaedeseo/v1/clean-test-data')); ?>', {
                            method: 'POST',
                            headers: { 'X-WP-Nonce': '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>' }
                        })
                        .then(res => res.json())
                        .then(data => {
                            spinner.classList.remove('is-active');
                            cleanBtn.disabled = false;
                            msg.textContent = data.message || 'Database opgeschoond.';
                            msg.style.color = data.success ? '#28a745' : '#d63638';
                            msg.style.display = 'block';
                        })
                        .catch(err => {
                            spinner.classList.remove('is-active');
                            cleanBtn.disabled = false;
                            msg.textContent = 'Er is een fout opgetreden bij het opschonen.';
                            msg.style.color = '#d63638';
                            msg.style.display = 'block';
                        });
                    });
                }
            });
            </script>
            <br><br>
        <?php endif; ?>

        <?php submit_button(); ?>
    </form>
    <?php
}

function fajaedeseo_render_autolinking_tab() {
    $auto_links = get_option('fajaedeseo_auto_links', '');
    $has_advanced_links = class_exists('\FajaedeSEO_Pro_License') && \FajaedeSEO_Pro_License::has_feature('advanced_links');
    ?>
    <form method="post" action="options.php">
        <?php settings_fields('fajaedeseo_autolinking_settings_group'); ?>
        <h2><?php echo esc_html__('Automatic Keyword Linking', 'fajaedeseo-ai'); ?></h2>
        <p><?php echo esc_html__('Automatically link specific keywords in your content to specified URLs.', 'fajaedeseo-ai'); ?></p>
        <?php if (!$has_advanced_links) : ?>
            <div class="notice notice-warning"><p><?php esc_html_e('Auto Linking is a Premium feature. Please upgrade your license.', 'fajaedeseo-ai'); ?></p></div>
        <?php else : ?>
            <table class="form-table">
                <tr valign="top">
                    <th scope="row"><label for="fajaedeseo_auto_links"><?php echo esc_html__('Keyword Rules', 'fajaedeseo-ai'); ?></label></th>
                    <td>
                        <textarea id="fajaedeseo_auto_links" name="fajaedeseo_auto_links" rows="10" class="large-text code" placeholder="keyword|https://fajaede.nl/page"><?php echo esc_textarea($auto_links); ?></textarea>
                        <p class="description"><?php echo esc_html__('Enter one rule per line in the format: keyword|URL. (e.g. SEO services|https://fajaede.nl/seo). The keyword will be linked automatically once per article.', 'fajaedeseo-ai'); ?></p>
                    </td>
                </tr>
            </table>
            <?php submit_button(); ?>
        <?php endif; ?>
    </form>
    <?php
}

function fajaedeseo_render_homepage() {
    ?>
    <form method="post" action="options.php">
        <?php settings_fields('fajaedeseo_home_settings_group'); ?>
        <h2><?php echo esc_html__('Homepage SEO', 'fajaedeseo-ai'); ?></h2>
        <table class="form-table">
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_home_seo_title"><?php echo esc_html__('Meta Title', 'fajaedeseo-ai'); ?></label></th>
                <td>
                    <input type="text" id="fajaedeseo_home_seo_title" name="fajaedeseo_home_seo_title" value="<?php echo esc_attr(get_option('fajaedeseo_home_seo_title', get_bloginfo('name'))); ?>" class="regular-text"/>
                    <div id="fajaedeseo_home_title_count" style="font-size: 11px; margin-top: 4px;"></div>
                </td>
            </tr>
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_home_seo_desc"><?php echo esc_html__('Meta Description', 'fajaedeseo-ai'); ?></label></th>
                <td>
                    <textarea id="fajaedeseo_home_seo_desc" name="fajaedeseo_home_seo_desc" rows="4" class="regular-text"><?php echo esc_textarea(get_option('fajaedeseo_home_seo_desc', get_bloginfo('description'))); ?></textarea>
                    <div id="fajaedeseo_home_desc_count" style="font-size: 11px; margin-top: 4px;"></div>
                </td>
            </tr>
        </table>
        <?php submit_button(); ?>
    </form>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const titleInput = document.getElementById('fajaedeseo_home_seo_title');
            const descInput = document.getElementById('fajaedeseo_home_seo_desc');
            const titleCount = document.getElementById('fajaedeseo_home_title_count');
            const descCount = document.getElementById('fajaedeseo_home_desc_count');

            function updateCount(input, counter, max) {
                if (!input || !counter) return;
                const len = input.value.length;
                counter.textContent = len + ' / ' + max + ' chars';
                if (len === 0) {
                    counter.style.color = '#dc3545'; // Rood (leeg)
                } else if (len <= max) {
                    counter.style.color = '#28a745'; // Groen (goed)
                } else {
                    counter.style.color = '#dc3545'; // Rood (te lang)
                }
            }

            if (titleInput) {
                titleInput.addEventListener('input', () => updateCount(titleInput, titleCount, 60));
                updateCount(titleInput, titleCount, 60); // Initieel uitvoeren
            }
            if (descInput) {
                descInput.addEventListener('input', () => updateCount(descInput, descCount, 160));
                updateCount(descInput, descCount, 160); // Initieel uitvoeren
            }
        });
    </script>
    <?php
}

function fajaedeseo_render_globe() {
    $is_pro = class_exists('\FajaedeSEO_Pro_License') && \FajaedeSEO_Pro_License::is_pro();
    $geo_data_json = fajaedeseo_get_geo_data();
    $geo_data = $geo_data_json ? json_decode($geo_data_json, true) : ['countries' => [], 'regions' => [], 'cities' => []];
    ?>
    <h2><?php echo esc_html__('Live Visitor Globe', 'fajaedeseo-ai'); ?></h2>
    <p><?php echo esc_html__('Real-time visualization of your site visitors.', 'fajaedeseo-ai'); ?></p>
    
    <div id="fajaedeseo-globe-wrapper" style="background:#000; padding:20px; border-radius:8px; box-shadow:0 4px 20px rgba(0,0,0,0.2); position:relative; min-height:600px; display:flex; align-items:center; justify-content:center; margin-bottom: 30px;"> 
        <div id="fajaedeseo-globe-ui" style="display:none; position:absolute; top:20px; right:20px; z-index:10; background:rgba(255,255,255,0.1); padding:10px; border-radius:8px; backdrop-filter:blur(5px);"> 
            <button id="fajaedeseo-globe-toggle-rotate" class="button button-secondary"><?php esc_html_e('Stop Rotation', 'fajaedeseo-ai'); ?></button> 
            <input type="range" id="fajaedeseo-globe-speed-slider" min="0.1" max="5" step="0.1" value="0.5" style="vertical-align: middle; margin-left: 10px;"> 
            <span style="color:#fff; font-size:11px; margin-left:5px;"><?php esc_html_e('Speed', 'fajaedeseo-ai'); ?></span>
        </div>

        <button id="fajaedeseo-globe-start-btn" class="button button-primary button-hero"><?php esc_html_e('Launch Live Globe', 'fajaedeseo-ai'); ?></button> 

        <div id="fajaedeseo-globe-container" style="width:100%; height:600px; position:relative; overflow:hidden; display:none;"></div> 
    </div>

    <div class="fajaedeseo-geo-stats" style="display: flex; flex-wrap: wrap; gap: 20px; margin-top: 30px; margin-bottom: 30px;">
        <!-- Countries -->
        <div style="flex: 1; min-width: 250px; background: #fff; padding: 20px; border: 1px solid #ccd0d4; border-radius: 4px; box-shadow: 0 1px 1px rgba(0,0,0,.04);">
            <h3 style="margin-top: 0; border-bottom: 1px solid #eee; padding-bottom: 10px;">🌍 <?php esc_html_e('Top Countries', 'fajaedeseo-ai'); ?></h3>
            <?php if (!empty($geo_data['countries'])) : ?>
                <ul style="margin: 0; padding: 0; list-style: none;">
                    <?php foreach ($geo_data['countries'] as $c) : ?>
                        <li style="padding: 8px 0; border-bottom: 1px solid #f5f5f5; display: flex; justify-content: space-between;">
                            <span><?php echo esc_html($c['name']); ?></span>
                            <strong><?php echo esc_html($c['count']); ?></strong>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php else : ?>
                <p style="color: #666; font-style: italic; text-align: center; padding: 20px 0;"><?php esc_html_e('No data yet.', 'fajaedeseo-ai'); ?></p>
            <?php endif; ?>
        </div>

        <!-- Regions (Pro) -->
        <div style="flex: 1; min-width: 250px; background: #fff; padding: 20px; border: 1px solid #ccd0d4; border-radius: 4px; box-shadow: 0 1px 1px rgba(0,0,0,.04);">
            <h3 style="margin-top: 0; border-bottom: 1px solid #eee; padding-bottom: 10px;">🗺️ <?php esc_html_e('Top Regions', 'fajaedeseo-ai'); ?></h3>
            <?php if ($is_pro) : ?>
                <?php if (!empty($geo_data['regions'])) : ?>
                    <ul style="margin: 0; padding: 0; list-style: none;">
                        <?php foreach ($geo_data['regions'] as $c) : ?>
                            <li style="padding: 8px 0; border-bottom: 1px solid #f5f5f5; display: flex; justify-content: space-between;">
                                <span><?php echo esc_html($c['name']); ?></span>
                                <strong><?php echo esc_html($c['count']); ?></strong>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php else : ?>
                    <p style="color: #666; font-style: italic; text-align: center; padding: 20px 0;"><?php esc_html_e('No data yet.', 'fajaedeseo-ai'); ?></p>
                <?php endif; ?>
            <?php else : ?>
                <div style="text-align: center; padding: 20px 0; color: #888;">
                    <p style="font-size: 24px; margin-bottom: 10px;">🔒</p>
                    <p style="font-style: italic;"><?php esc_html_e('Locked (Pro)', 'fajaedeseo-ai'); ?></p>
                </div>
            <?php endif; ?>
        </div>

        <!-- Cities (Pro) -->
        <div style="flex: 1; min-width: 250px; background: #fff; padding: 20px; border: 1px solid #ccd0d4; border-radius: 4px; box-shadow: 0 1px 1px rgba(0,0,0,.04);">
            <h3 style="margin-top: 0; border-bottom: 1px solid #eee; padding-bottom: 10px;">🏙️ <?php esc_html_e('Top Cities', 'fajaedeseo-ai'); ?></h3>
            <?php if ($is_pro) : ?>
                <?php if (!empty($geo_data['cities'])) : ?>
                    <ul style="margin: 0; padding: 0; list-style: none;">
                        <?php foreach ($geo_data['cities'] as $c) : ?>
                            <li style="padding: 8px 0; border-bottom: 1px solid #f5f5f5; display: flex; justify-content: space-between;">
                                <span><?php echo esc_html($c['name']); ?></span>
                                <strong><?php echo esc_html($c['count']); ?></strong>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php else : ?>
                    <p style="color: #666; font-style: italic; text-align: center; padding: 20px 0;"><?php esc_html_e('No data yet.', 'fajaedeseo-ai'); ?></p>
                <?php endif; ?>
            <?php else : ?>
                <div style="text-align: center; padding: 20px 0; color: #888;">
                    <p style="font-size: 24px; margin-bottom: 10px;">🔒</p>
                    <p style="font-style: italic;"><?php esc_html_e('Locked (Pro)', 'fajaedeseo-ai'); ?></p>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Uitgebreide Bezoekerslocaties Modal -->
    <div style="text-align: center; margin-bottom: 40px;">
        <button type="button" id="fseo-open-geo-modal" class="button button-primary button-hero">🌍 <?php esc_html_e('Bekijk Volledige Locaties (7 / 30 Dagen)', 'fajaedeseo-ai'); ?></button>
    </div>

    <div id="fseo-geo-modal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.6); z-index:99999; align-items:center; justify-content:center; backdrop-filter:blur(3px);">
        <div style="background:#fff; width:900px; max-width:90%; max-height:85vh; border-radius:8px; padding:25px; box-shadow:0 5px 15px rgba(0,0,0,0.3); position:relative; display:flex; flex-direction:column;">
            <span id="fseo-geo-close" style="position:absolute; top:15px; right:20px; cursor:pointer; font-size:28px; font-weight:bold; color:#666; line-height:1;">&times;</span>
            <h2 style="margin-top:0;"><?php esc_html_e('Uitgebreide Bezoekerslocaties', 'fajaedeseo-ai'); ?></h2>
            
            <div style="margin-bottom:20px;">
                <button class="button fseo-geo-filter button-primary" data-days="30"><?php esc_html_e('Afgelopen 30 Dagen', 'fajaedeseo-ai'); ?></button>
                <button class="button fseo-geo-filter" data-days="7"><?php esc_html_e('Afgelopen 7 Dagen', 'fajaedeseo-ai'); ?></button>
            </div>
            
            <div id="fseo-geo-content" style="display:flex; gap:20px; overflow-y:auto; flex:1; flex-wrap:wrap;">
                <p><?php esc_html_e('Gegevens inladen...', 'fajaedeseo-ai'); ?></p>
            </div>
        </div>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const btnOpen = document.getElementById('fseo-open-geo-modal');
        const modal = document.getElementById('fseo-geo-modal');
        const btnClose = document.getElementById('fseo-geo-close');
        const contentDiv = document.getElementById('fseo-geo-content');
        
        if(!btnOpen || !modal) return;

        btnOpen.addEventListener('click', function(e) {
            e.preventDefault();
            modal.style.display = 'flex';
            loadGeoData(30); // Standaard 30 dagen inladen
        });

        btnClose.addEventListener('click', () => modal.style.display = 'none');
        
        // Sluit modal als je buiten het witte vlak klikt
        modal.addEventListener('click', function(e) {
            if(e.target === modal) modal.style.display = 'none';
        });

        document.querySelectorAll('.fseo-geo-filter').forEach(btn => {
            btn.addEventListener('click', function(e) {
                e.preventDefault();
                document.querySelectorAll('.fseo-geo-filter').forEach(b => b.classList.remove('button-primary'));
                this.classList.add('button-primary');
                loadGeoData(this.dataset.days);
            });
        });

        function loadGeoData(days) {
            contentDiv.innerHTML = '<p><?php esc_html_e('Gegevens inladen vanaf de server...', 'fajaedeseo-ai'); ?></p>';
            
            if (typeof fajaedeGlobeConfig === 'undefined') {
                contentDiv.innerHTML = '<p style="color:red;"><?php esc_html_e('Configuratie niet gevonden. Werkt de globe momenteel?', 'fajaedeseo-ai'); ?></p>';
                return;
            }

            fetch(fajaedeGlobeConfig.rest_url + '?days=' + days, {
                headers: { 'X-WP-Nonce': fajaedeGlobeConfig.nonce }
            })
            .then(res => res.json())
            .then(data => {
                const renderList = (title, items) => {
                    let list = `<div style="flex:1; min-width:250px; background:#f8fafc; padding:15px; border-radius:6px; border:1px solid #e2e8f0; margin-bottom:10px;">
                        <h3 style="margin-top:0; border-bottom:1px solid #cbd5e1; padding-bottom:8px;">${title}</h3>
                        <ul style="margin:0; padding-left:0; list-style:none;">`;
                    
                    if(items && items.length > 0) {
                        items.forEach((i, index) => {
                            let rank = index + 1;
                            list += `<li style="padding:8px 0; border-bottom:1px solid #e2e8f0; display:flex; justify-content:space-between;">
                                <span><strong>${rank}.</strong> ${i.name}</span>
                                <span style="background:#0073aa; color:#fff; padding:2px 8px; border-radius:12px; font-size:12px;">${i.count}</span>
                            </li>`;
                        });
                    } else {
                        list += `<li style="padding:8px 0; color:#64748b; font-style:italic;"><?php esc_html_e('Geen data (Alleen in FajaedeSEO Pro)', 'fajaedeseo-ai'); ?></li>`;
                    }
                    list += `</ul></div>`;
                    return list;
                };

                contentDiv.innerHTML = 
                    renderList('<?php esc_html_e('Landen', 'fajaedeseo-ai'); ?>', data.countries) + 
                    renderList('<?php esc_html_e('Regio\'s', 'fajaedeseo-ai'); ?>', data.regions) + 
                    renderList('<?php esc_html_e('Steden', 'fajaedeseo-ai'); ?>', data.cities);
            })
            .catch(err => {
                contentDiv.innerHTML = '<p style="color:red;"><?php esc_html_e('Er is een fout opgetreden bij het laden van de gegevens.', 'fajaedeseo-ai'); ?></p>';
            });
        }
    });
    </script>
    <?php
}

/**
 * Renders the Redirects tab content.
 */
function fajaedeseo_render_redirects_tab() {
    $redirects = get_option('fajaedeseo_redirects', []);
    ?>
    <h2><?php esc_html_e('301 Redirect Manager', 'fajaedeseo-ai'); ?></h2>
    <p><?php esc_html_e('Easily manage 301 redirects to fix 404 errors and improve SEO.', 'fajaedeseo-ai'); ?></p>

    <h3><?php esc_html_e('Add New Redirect', 'fajaedeseo-ai'); ?></h3>
    <form method="post" action="<?php echo esc_url(admin_url('admin.php?page=fajaedeseo-seo&tab=redirects')); ?>">
        <?php wp_nonce_field('fajaedeseo_redirect_action'); ?>
        <table class="form-table">
            <tr valign="top">
                <th scope="row"><label for="redirect_from"><?php esc_html_e('Redirect From (Relative url)', 'fajaedeseo-ai'); ?></label></th>
                <td>
                    <input type="text" id="redirect_from" name="redirect_from" value="" class="regular-text" placeholder="/old-page" required />
                    <p class="description"><?php esc_html_e('Enter the old url (e.g., /old-page).', 'fajaedeseo-ai'); ?></p>
                </td>
            </tr>
            <tr valign="top">
                <th scope="row"><label for="redirect_to"><?php esc_html_e('Redirect To (Relative or Absolute url)', 'fajaedeseo-ai'); ?></label></th>
                <td>
                    <input type="text" id="redirect_to" name="redirect_to" value="" class="regular-text" placeholder="/new-page or https://fajaede.nl/new-page" required />
                    <p class="description"><?php esc_html_e('Enter the new url.', 'fajaedeseo-ai'); ?></p>
                </td>
            </tr>
        </table>
        <?php submit_button(__('Add Redirect', 'fajaedeseo-ai'), 'primary', 'fajaedeseo_add_redirect'); ?>
    </form>

    <?php $is_premium = class_exists('\FajaedeSEO_Pro_License') && in_array(\FajaedeSEO_Pro_License::get_plan_level(), ['premium', 'agency']); ?>

    <hr>
    <h3><?php esc_html_e('Bulk Import Redirects (CSV)', 'fajaedeseo-ai'); ?></h3>
    <p><?php esc_html_e('Upload a CSV file to import multiple redirects at once. The file should contain two columns (without headers): old_url,new_url', 'fajaedeseo-ai'); ?></p>
    
    <?php if (!$is_premium) : ?>
        <div class="notice notice-warning inline"><p><?php esc_html_e('Bulk CSV Import & Export is a Premium feature. Please upgrade your license to automate url migrations.', 'fajaedeseo-ai'); ?></p></div>
    <?php else : ?>
        <form method="post" action="<?php echo esc_url(admin_url('admin.php?page=fajaedeseo-seo&tab=redirects')); ?>" enctype="multipart/form-data">
            <?php wp_nonce_field('fajaedeseo_redirect_bulk_action'); ?>
            <input type="file" name="redirects_csv" accept=".csv" required style="margin-bottom: 10px;" /><br>
            <?php submit_button(__('Import CSV', 'fajaedeseo-ai'), 'secondary', 'fajaedeseo_import_redirects'); ?>
        </form>
    <?php endif; ?>
    <hr>

    <div style="display: flex; justify-content: space-between; align-items: center;">
        <h3 style="margin: 0;"><?php esc_html_e('Existing Redirects', 'fajaedeseo-ai'); ?></h3>
        <?php if ($is_premium) : ?>
            <?php $export_url = wp_nonce_url(admin_url('admin.php?action=fajaedeseo_export_redirects'), 'fajaedeseo_export_redirects'); ?>
            <a href="<?php echo esc_url($export_url); ?>" class="button button-secondary"><?php esc_html_e('Export to CSV', 'fajaedeseo-ai'); ?></a>
        <?php endif; ?>
    </div>
    <br>
    <?php if (empty($redirects)) : ?>
        <p><?php esc_html_e('No redirects configured yet.', 'fajaedeseo-ai'); ?></p>
    <?php else : ?>
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th scope="col"><?php esc_html_e('From url', 'fajaedeseo-ai'); ?></th>
                    <th scope="col"><?php esc_html_e('To url', 'fajaedeseo-ai'); ?></th>
                    <th scope="col"><?php esc_html_e('Actions', 'fajaedeseo-ai'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($redirects as $from => $to) : ?>
                    <tr>
                        <td><code><?php echo esc_html($from); ?></code></td>
                        <td><code><?php echo esc_html($to); ?></code></td>
                        <td>
                            <?php
                            $delete_url = wp_nonce_url(
                                add_query_arg(
                                    array(
                                        'page' => 'fajaedeseo-seo',
                                        'tab' => 'redirects',
                                        'delete_redirect' => base64_encode($from) // Encode for URL safety
                                    ),
                                    admin_url('admin.php')
                                ),
                                'fajaedeseo_delete_redirect'
                            );
                            ?>
                            <a href="<?php echo esc_url($delete_url); ?>" class="button button-small button-link-delete"><?php esc_html_e('Delete', 'fajaedeseo-ai'); ?></a>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
    <?php
}

function fajaedeseo_render_license_tab() {
    $license_key = get_option('fajaedeseo_pro_license_key', '');
    $license_status = get_option('fajaedeseo_pro_license_status', 'inactive');
    $is_valid = ($license_status === 'valid');
    $expires_at = get_option('fajaedeseo_pro_license_expires', '');
    $plan_tier = get_option('fajaedeseo_pro_license_tier', 'free');
    ?>
    
    <?php if (!$is_valid) : ?>
        <div class="fajaedeseo-pricing-wrapper" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px; margin: 20px 0 40px 0;">
            <!-- Free Card -->
            <div style="background: #fff; padding: 20px; border: 1px solid #ccc; border-radius: 5px;">
                <h3 style="margin-top:0; font-size: 16px;">Free (€0)</h3>
                <p><strong>Free forever!</strong></p>
                <ul style="list-style-type: none; padding: 0; margin-bottom: 20px; line-height: 1.6; color: #555;">
                    <li>✓ Real-time SEO Scoring & Colors</li>
                    <li>✓ Writing Tips (Density & Readability)</li>
                    <li>✓ 3D Live Visitor Globe (Countries)</li>
                    <li>✓ Basic Meta Tags & Keywords</li>
                </ul>
                <button class="button button-disabled" disabled style="width: 100%; text-align: center;">Current Plan</button>
            </div>
            <!-- Pro Card -->
            <div style="background: #fff; padding: 20px; border: 1px solid #ccc; border-radius: 5px;">
                <h3 style="margin-top:0; font-size: 16px;">Pro (€79/yr)</h3>
                <p><strong>The foundation for professionals.</strong></p>
                <ul style="list-style-type: none; padding: 0; margin-bottom: 20px; line-height: 1.6; color: #555;">
                    <li>✓ AI Content (OpenAI)</li>
                    <li>✓ gpt-image-2-2026-04-21 Images</li>
                    <li>✓ Sitemaps, Redirects & Schema</li>
                    <li>✓ Performance optimizations</li>
                </ul>
                <a href="<?php echo esc_url('https://www.fajaede.nl/pro-features/'); ?>" target="_blank" rel="noopener noreferrer" class="button button-secondary" style="width: 100%; text-align: center;">Upgrade to Pro</a>
            </div>
            <!-- Premium Card -->
            <div style="background: #f0f6fc; padding: 20px; border: 2px solid #2271b1; border-radius: 5px; position: relative;">
                <div style="position: absolute; top: -12px; right: 10px; background: #2271b1; color: white; padding: 3px 10px; font-size: 11px; border-radius: 12px; font-weight: bold;"><?php esc_html_e('Best Value', 'fajaedeseo-ai'); ?></div>
                <h3 style="margin-top:0; color: #2271b1; font-size: 16px;">Premium (€149/yr)</h3>
                <p><strong>For serious marketers.</strong></p>
                <ul style="list-style-type: none; padding: 0; margin-bottom: 20px; line-height: 1.6; color: #555;">
                    <li><strong>✓ Automate your entire SEO workflow</strong></li>
                    <li>✓ Everything in Pro</li>
                    <li>✓ Real-Time Google Data (SERP)</li>
                    <li>✓ Bulk Meta Generation</li>
                    <li>✓ Advanced Monitoring</li>
                </ul>
                <a href="<?php echo esc_url('https://www.fajaede.nl/premium-plan/'); ?>" target="_blank" rel="noopener noreferrer" class="button button-primary" style="width: 100%; text-align: center;">Get Premium</a>
            </div>
            <!-- Agency Card -->
            <div style="background: #fff; padding: 20px; border: 1px solid #ccc; border-radius: 5px;">
                <h3 style="margin-top:0; font-size: 16px;">Agency (€399/yr)</h3>
                <p><strong>The ultimate toolkit for web agencies.</strong></p>
                <ul style="list-style-type: none; padding: 0; margin-bottom: 20px; line-height: 1.6; color: #555;">
                    <li><strong>✓ Everything in Premium</strong></li>
                    <li>✓ Unlimited Client Websites</li>
                    <li>✓ White-label PDF Audits (Your Logo)</li>
                    <li>✓ Central Multi-site Dashboard</li>
                    <li>✓ Automated Accounting</li>
                </ul>
                <a href="<?php echo esc_url('https://www.fajaede.nl/agency-plan/'); ?>" target="_blank" rel="noopener noreferrer" class="button button-secondary" style="width: 100%; text-align: center;">Get Agency</a>
            </div>
        </div>
    <?php endif; ?>

    <?php if ($is_valid && $plan_tier === 'agency') : ?>
        <?php
        global $wpdb;
        $table = $wpdb->prefix . 'fajaedeseo_licenses';
        $code_hash = \FajaedeSEO_Pro_License::hash_code($license_key);
        
        $cache_key = 'fajaedeseo_license_row_' . md5($code_hash);
        $license_row = wp_cache_get($cache_key, 'fajaedeseo');
        
        if (false === $license_row) {
            $license_row = $wpdb->get_row($wpdb->prepare("SELECT site_url, created_at, status FROM `" . esc_sql($table) . "` WHERE code_hash = %s", $code_hash)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
            wp_cache_set($cache_key, $license_row, 'fajaedeseo', 5 * MINUTE_IN_SECONDS);
        }
        
        $active_domains = [];
        if ($license_row && !empty($license_row->site_url)) {
            $urls = array_map('trim', explode(',', $license_row->site_url));
            foreach ($urls as $url) {
                if (!empty($url)) {
                    $active_domains[] = (object) [
                        'site_url' => $url,
                        'created_at' => $license_row->created_at,
                        'status' => $license_row->status
                    ];
                }
            }
        }
        ?>
        <div style="margin: 20px 0; padding: 15px; border: 1px solid #ccd0d4; background: #fff; border-left: 4px solid #8224e3; box-shadow: 0 1px 1px rgba(0,0,0,.04);">
            <h3 style="margin-top: 0;">🏢 <?php esc_html_e('Agency Multi-site Dashboard', 'fajaedeseo-ai'); ?></h3>
            <p><?php esc_html_e('Overview of all activated domains under your Agency license.', 'fajaedeseo-ai'); ?></p>
            <div style="max-height: 300px; overflow-y: auto; border: 1px solid #eee;">
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Website URL', 'fajaedeseo-ai'); ?></th>
                            <th><?php esc_html_e('Activation Date', 'fajaedeseo-ai'); ?></th>
                            <th><?php esc_html_e('Status', 'fajaedeseo-ai'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($active_domains)) : ?>
                            <?php foreach ($active_domains as $site) : ?>
                                <tr>
                                    <td><strong><?php echo esc_html($site->site_url); ?></strong></td>
                                    <td><?php echo esc_html($site->created_at); ?></td>
                                    <td>
                                        <?php if ($site->status === 'active' || $site->status === 'redeemed') : ?>
                                            <span style="color: green; font-weight: 500;">✔ <?php esc_html_e('Active', 'fajaedeseo-ai'); ?></span>
                                        <?php else : ?>
                                            <span style="color: red; font-weight: 500;">✖ <?php echo esc_html(ucfirst($site->status)); ?></span>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else : ?>
                            <tr><td colspan="3"><?php esc_html_e('No websites linked yet.', 'fajaedeseo-ai'); ?></td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    <?php endif; ?>

    <form method="post" action="options.php">
        <?php settings_fields('fajaedeseo_license_settings_group'); ?>
        <h2><?php echo esc_html__('Pro License & Monitoring', 'fajaedeseo-ai'); ?></h2>
        
        <div style="margin-bottom:20px; padding:15px; background:#f9f9f9; border-left:4px solid #ddd; border-radius:3px;">
            <p><strong><?php echo esc_html__('Status:', 'fajaedeseo-ai'); ?></strong>
                <?php if ($is_valid) : ?>
                    <span style="color:#155724; background:#d4edda; padding:3px 8px; border-radius:3px; font-weight:bold;">✓ <?php echo esc_html__('ACTIVE', 'fajaedeseo-ai'); ?></span>
                <?php else : ?>
                    <span style="color:#856404; background:#fff3cd; padding:3px 8px; border-radius:3px; font-weight:bold;">— <?php echo esc_html__('INACTIVE', 'fajaedeseo-ai'); ?></span>
                <?php endif; ?>
                
                <?php if ($is_valid && $expires_at) : ?>
                    <br><br>
                    <strong><?php echo esc_html__('Valid until:', 'fajaedeseo-ai'); ?></strong> <?php echo esc_html(date_i18n(get_option('date_format'), strtotime($expires_at))); ?>
                <?php endif; ?>
            </p>
        </div>
        
        <table class="form-table">
            <tr valign="top">
                <th scope="row"><label for="fajaedeseo_pro_license_key"><?php echo esc_html__('License Key', 'fajaedeseo-ai'); ?></label></th>
                <td>
                    <input type="text" id="fajaedeseo_pro_license_key" name="fajaedeseo_pro_license_key" value="<?php echo esc_attr($license_key); ?>" class="regular-text" placeholder="FSEO-XXXX-XXXX-XXXX" autocomplete="off"/>
                    <p class="description"><?php echo esc_html__('Enter your license key to activate Pro features like the Live Globe and AI suggestions.', 'fajaedeseo-ai'); ?></p>
                </td>
            </tr>
        </table>
        <?php submit_button(__('Activate License', 'fajaedeseo-ai')); ?>

    </form>
    <?php
}