<?php
/**
 * Main FajaedeSEO Class
 */

defined('ABSPATH') or exit;


class FajaedeSEO {
    /**
     * @var self|null
     */
    protected static $instance = null;
    /**
     * @var array
     */
    protected $container = [];

    public static function get_instance() {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function get_service(string $service_name) {
        return $this->container[$service_name] ?? null;
    }

    private function __construct() {
        $this->define_constants();
        $this->load_dependencies();
        $this->register_services();
        $this->setup_hooks();
    }

    private function define_constants() {
        // Already defined globally
    }

    private function load_dependencies() {
        // Core Logic
        require_once FAJAEDESEO_DIR . 'includes/helpers.php';                 // Statistieken & Tools
        require_once FAJAEDESEO_DIR . 'includes/class-pro-license.php';      // Licentiebeheer
        require_once FAJAEDESEO_DIR . 'includes/class-ai-service-manager.php'; // AI API Bridge (OpenAI)
        require_once FAJAEDESEO_DIR . 'includes/class-ai-endpoints.php';     // Modules (SEO, Keywords, Audit, etc.)
        require_once FAJAEDESEO_DIR . 'includes/class-pro-generator.php';    // AI Content Generator
        require_once FAJAEDESEO_DIR . 'includes/cron.php';                   // Scheduled Tasks
        require_once FAJAEDESEO_DIR . 'includes/class-fajaedeseo-sitemap.php'; // Sitemap Logica
        require_once FAJAEDESEO_DIR . 'includes/class-updater.php';          // Auto Updater
        require_once FAJAEDESEO_DIR . 'includes/class-vat-calculator.php';   // VAT Calculator (Belgian)
        require_once FAJAEDESEO_DIR . 'includes/class-invoice-generator.php'; // Invoice Generator with VAT

        // Payment Gateways
        require_once FAJAEDESEO_DIR . 'interface-payment-gateway.php';
        require_once FAJAEDESEO_DIR . 'class-mollie-gateway.php';
        // require_once FAJAEDESEO_DIR . 'includes/gateways/class-lemonsqueezy-gateway.php'; // For future refactor

        // Admin Modules
        if (is_admin()) {
            require_once FAJAEDESEO_DIR . 'includes/admin-ai-settings.php'; // AI Instellingen pagina
        }

        // Frontend Modules
        require_once FAJAEDESEO_DIR . 'frontend/meta-tags.php';
        require_once FAJAEDESEO_DIR . 'frontend/schema.php';

        // API Modules
    }

    private function register_services() {
        $this->container['ai_service_manager'] = new \FajaedeSEO_AI_Service_Manager();
        $this->container['module_seo'] = new \FajaedeSEO_Module_SEO();
        $this->container['module_keywords'] = new \FajaedeSEO_Module_Keywords();
        $this->container['module_serp'] = new \FajaedeSEO_Module_SERP();
        $this->container['module_audit'] = new \FajaedeSEO_Module_Audit();
        $this->container['module_payment'] = new \FajaedeSEO_Module_Payment();
        $this->container['sitemap_generator'] = new \FajaedeSEO_Sitemap_Generator();
        
        // Initialiseer de Updater
        $this->container['updater'] = new \FajaedeSEO_Updater('fajaedeseo-ai/fajaedeseo.php', FAJAEDESEO_VERSION, 'https://www.fajaede.nl/api/v1/update-check');

        // Initialiseer de actieve Payment Gateway
        $active_gateway_id = get_option('fajaedeseo_active_payment_gateway', 'mollie');
        $gateway_class = '';
        if ($active_gateway_id === 'mollie' && class_exists('FajaedeSEO_Mollie_Gateway')) {
            $gateway_class = 'FajaedeSEO_Mollie_Gateway';
        }

        if (!empty($gateway_class)) {
            $this->container['payment_gateway'] = new $gateway_class();
            $this->container['payment_gateway']->init();
        }
    }

    private function setup_hooks() {
        add_action('admin_init', [$this, 'check_plugin_version'], 1);
        add_action('init', [$this, 'init_modules']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('enqueue_block_editor_assets', [$this, 'enqueue_block_editor_assets'], 20);
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_scripts']);
        add_action('edit_form_advanced', [$this, 'auto_init_meta_fields']);
        add_filter('pre_get_document_title', [$this, 'filter_document_title'], 999);
        add_action('wp_head', [$this, 'render_frontend_meta'], 5);
        add_action('wp_head', [$this, 'render_frontend_schema'], 5);
        add_filter('get_canonical_url', [$this, 'filter_canonical_url'], 10, 2);
        if (isset($this->container['sitemap_generator'])) {
            $this->container['sitemap_generator']->register_hooks();
        }
        add_action('template_redirect', [$this, 'handle_template_redirect']);
        add_action('init', [$this, 'register_post_meta_fields']);
        add_action('admin_post_fajaedeseo_generate_disclaimer', [$this, 'admin_post_generate_disclaimer']);
        add_action('admin_post_fajaedeseo_generate_cookies_policy', [$this, 'admin_post_generate_cookies_policy']);
        add_action('admin_post_fajaedeseo_generate_privacy_policy', [$this, 'admin_post_generate_privacy_policy']);
        add_action('admin_post_fajaedeseo_generate_gdpr_compliance', [$this, 'admin_post_generate_gdpr_compliance']); // Register new content generation route
        add_action('admin_post_fajaedeseo_generate_terms_of_service', [$this, 'admin_post_generate_terms_of_service']);
        add_action('admin_post_fajaedeseo_generate_refund_policy', [$this, 'admin_post_generate_refund_policy']);
        add_action('admin_action_fajaedeseo_export_redirects', [$this, 'export_redirects_data']);
        add_action('init', [$this, 'handle_remote_login']);
        add_action('fajaedeseo_weekly_thursday_accounting_report', [$this, 'send_weekly_accounting_report']);
        add_shortcode('fajaedeseo_checkout', [$this, 'checkout_shortcode']);
        add_shortcode('fajaedeseo_checkout_success', [$this, 'checkout_success_shortcode']);
        add_shortcode('fajaedeseo_privacy_policy', [$this, 'policy_shortcode']);
        add_action('wp_loaded', [$this, 'schedule_initial_sitemap_generation']);
        add_action('save_post', [$this, 'clear_caches']);
        add_action('delete_post', [$this, 'clear_caches']);
        add_action('update_option_fajaedeseo_custom_sitemap_urls', [$this, 'clear_caches']);
        add_action('transition_post_status', [$this, 'clear_caches'], 10, 3);
        add_shortcode('fajaedeseo_disclaimer', [$this, 'policy_shortcode']);
        add_shortcode('fajaedeseo_cookies_policy', [$this, 'policy_shortcode']);
        add_shortcode('fajaedeseo_terms_of_service', [$this, 'policy_shortcode']);
        add_shortcode('fajaedeseo_refund_policy', [$this, 'policy_shortcode']);
        add_shortcode('fajaedeseo_gdpr_compliance', [$this, 'policy_shortcode']);
        add_shortcode('fajaedeseo_my_account', [$this, 'my_account_shortcode']);
        add_action('init', [$this, 'pro_performance_init']);
        add_filter('script_loader_tag', [$this, 'defer_scripts_and_font_swap'], 10, 3);
        add_filter('style_loader_tag', [$this, 'google_fonts_display_swap'], 10, 2);
        add_filter('the_content', [$this, 'content_optimizations'], 9999);
        add_filter('the_content', [$this, 'auto_keyword_linking'], 9998);
        add_action('wp_head', [$this, 'preload_lcp_image'], 1);
        add_action('wp_enqueue_scripts', [$this, 'conditional_scripts_unload'], 9999);
        add_action('admin_notices', [$this, 'detect_seo_plugin_conflicts']);
        add_action('admin_post_fajaedeseo_disable_schema', [$this, 'handle_disable_schema_action']);
        add_action('admin_post_fajaedeseo_dismiss_conflict_notice', [$this, 'handle_dismiss_conflict_notice']);
        add_action('wp_footer', [$this, 'inject_tracking_script']);
        add_action('wp_head', [$this, 'force_noindex_on_checkout'], 1);
    }

    public function activate() {
        \FajaedeSEO_Pro_License::create_table();
        $this->ensure_visitors_table();
        if (isset($this->container['sitemap_generator'])) {
            $this->container['sitemap_generator']->add_rewrite_rules();
        }
        flush_rewrite_rules();

        if (isset($this->container['sitemap_generator'])) {
            $this->container['sitemap_generator']->regenerate_sitemap_cache(true);
        }
    }

    public function ensure_visitors_table() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'fajaedeseo_visitors';
        // Cache de check om performance in wp-admin te behouden
        if (get_option('fajaedeseo_visitors_table_created') !== '2') {
            $charset_collate = $wpdb->get_charset_collate();
            $sql = "CREATE TABLE $table_name (
                id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
                lat decimal(10, 8) NOT NULL,
                lng decimal(11, 8) NOT NULL,
                country varchar(100) DEFAULT NULL,
                region varchar(100) DEFAULT NULL,
                city varchar(100) DEFAULT NULL,
                timestamp datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
                PRIMARY KEY  (id)
            ) $charset_collate;";
            require_once ABSPATH . 'wp-admin/includes/upgrade.php';
            dbDelta($sql);
            update_option('fajaedeseo_visitors_table_created', '2');
        }
    }

    public function check_plugin_version() {
        $saved_version = get_option('fajaedeseo_version', '0.0.0');
        if (version_compare($saved_version, FAJAEDESEO_VERSION, '<')) {
            // De plugin is zojuist geüpdatet naar een nieuwe versie.
            update_option('fajaedeseo_version', FAJAEDESEO_VERSION);
            
            // Gooi de WordPress update-cache agressief leeg om spook-meldingen direct te verwijderen voor de klant.
            delete_site_transient('update_plugins');
        }
    }

    public function init_modules() {
        $this->container['module_seo']->init();
        $this->container['module_keywords']->init();
        $this->container['module_serp']->init();
        $this->container['module_audit']->init();
        \FajaedeSEO_Pro_Generator::init(); // Initialize the Pro Generator
        $this->container['module_payment']->init();
        \FajaedeSEO_Module_Links::init();
        \FajaedeSEO_Module_Tracking::init();

        // Initialiseer de AI-instellingen voor de admin met global check
        if (is_admin() && class_exists('\FajaedeSEO_Admin_AI_Settings')) {
            \FajaedeSEO_Admin_AI_Settings::init();
        }
    }

    public function add_admin_menu() {
        add_menu_page(
            __('Fajaede SEO', 'fajaedeseo-ai'),
            __('Fajaede SEO', 'fajaedeseo-ai'),
            'manage_options',
            'fajaedeseo-seo', // Consistent slug matching the tabs
            [$this, 'render_settings_page'], // Use a class method for rendering
            'dashicons-chart-line',
            80 // Positie in het menu
        );

        add_submenu_page(
            'fajaedeseo-seo',
            __('Dashboard', 'fajaedeseo-ai'),
            __('Dashboard', 'fajaedeseo-ai'),
            'manage_options',
            'fajaedeseo-seo',
            [$this, 'render_settings_page']
        );

        // Master Server: Agency Hub for clients
        if (defined('FAJAEDE_MASTER_SERVER') && FAJAEDE_MASTER_SERVER) {
            add_menu_page(
                __('Agency Hub', 'fajaedeseo-ai'),
                __('Agency Hub', 'fajaedeseo-ai'),
                'manage_options', // Tijdelijk verborgen voor klanten zolang de upsell wordt gebouwd
                'fajaedeseo-agency-hub',
                [$this, 'render_agency_hub_page'],
                'dashicons-networking'
            );
        }
    }

    public function register_settings() {
        $this->process_sitemap_flush();
        $this->process_redirects();

        if (class_exists('\FajaedeSEO_Pro_License')) {
            \FajaedeSEO_Pro_License::ensure_table_schema();
        }

        // Handle Cancellation
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified inside check_admin_referer.
        if (isset($_POST['fajaedeseo_cancel_nonce']) && check_admin_referer('fajaedeseo_cancel_license', 'fajaedeseo_cancel_nonce')) {
            if (current_user_can('manage_options')) {
                update_option('fajaedeseo_pro_license_auto_renew', '0');
                add_settings_error(
                    'fajaedeseo_pro_license_key',
                    'license_cancelled',
                    __('Auto-renewal cancelled. Your license remains valid until the end of the period.', 'fajaedeseo-ai'),
                    'success'
                );
            }
        }

        register_setting('fajaedeseo_settings_group', 'fajaedeseo_robots_txt', ['sanitize_callback' => 'sanitize_textarea_field']);
        register_setting('fajaedeseo_social_settings_group', 'fajaedeseo_twitter_handle', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_social_settings_group', 'fajaedeseo_facebook_handle', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_social_settings_group', 'fajaedeseo_fb_admins', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_social_settings_group', 'fajaedeseo_fb_app_id', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_sitemap_settings_group', 'fajaedeseo_custom_sitemap_urls', ['sanitize_callback' => 'sanitize_textarea_field']);

        register_setting('fajaedeseo_settings_group', 'fajaedeseo_active_payment_gateway', ['sanitize_callback' => 'sanitize_key']);
        register_setting('fajaedeseo_autolinking_settings_group', 'fajaedeseo_auto_links', ['sanitize_callback' => 'sanitize_textarea_field']);
        register_setting('fajaedeseo_settings_group', 'fajaedeseo_disable_schema', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_settings_group', 'fajaedeseo_accountant_email', ['sanitize_callback' => fn($v) => sanitize_email((string)$v)]);
        register_setting('fajaedeseo_settings_group', 'fajaedeseo_ls_api_key', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_settings_group', 'fajaedeseo_ls_store_id', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_settings_group', 'fajaedeseo_ls_webhook_secret', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_settings_group', 'fajaedeseo_ls_variant_pro', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_settings_group', 'fajaedeseo_ls_variant_premium', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_settings_group', 'fajaedeseo_ls_variant_agency', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_settings_group', 'fajaedeseo_mollie_api_key', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_settings_group', 'fajaedeseo_company_vat_number', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_settings_group', 'fajaedeseo_voluntary_oss', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);

        register_setting('fajaedeseo_settings_group', 'fajaedeseo_agency_logo', ['sanitize_callback' => 'esc_url_raw']);
        register_setting('fajaedeseo_settings_group', 'fajaedeseo_agency_color', ['sanitize_callback' => 'sanitize_hex_color']);
        register_setting('fajaedeseo_settings_group', 'fajaedeseo_company_city', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_settings_group', 'fajaedeseo_company_region', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_settings_group', 'fajaedeseo_company_lat', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_settings_group', 'fajaedeseo_company_lng', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        
        register_setting('fajaedeseo_license_settings_group', 'fajaedeseo_pro_license_key', [
            'sanitize_callback' => function($value) {
                if (!current_user_can('manage_options') || empty($value)) return $value;
                $result = \FajaedeSEO_Pro_License::redeem_license($value);
                add_settings_error('fajaedeseo_pro_license_key', 'license_msg', $result['message'], $result['success'] ? 'success' : 'error');
                return $value;
            }
        ]);

        register_setting('fajaedeseo_home_settings_group', 'fajaedeseo_home_seo_title', ['sanitize_callback' => fn($v) => sanitize_text_field((string)$v)]);
        register_setting('fajaedeseo_home_settings_group', 'fajaedeseo_home_seo_desc', ['sanitize_callback' => 'sanitize_textarea_field']);
    }

    /**
     * Registers meta fields for the block editor.
     * Must run on 'init' hook to be available for REST API requests.
     */
    public function register_post_meta_fields() {
        $types = get_post_types(['public' => true, 'show_ui' => true]);
        $meta_keys = [
            '_fajaedeseo_meta_title' => 'string',
            '_fajaedeseo_meta_desc' => 'string',
            '_fajaedeseo_focus_keyword' => 'string',
            '_fajaedeseo_seo_score' => 'integer',
            '_fajaedeseo_robots_index' => 'string',
            '_fajaedeseo_robots_follow' => 'string',
            '_fajaedeseo_schema_type' => 'string',
            '_fajaedeseo_canonical' => 'string',
            '_fajaedeseo_pro_lcp_optimized' => 'boolean',
            '_fajaedeseo_pro_lazy_load' => 'boolean',
            '_fajaedeseo_pro_defer_ads' => 'boolean',
            '_fajaedeseo_pro_optimize_assets' => 'boolean',
            '_fajaedeseo_pro_font_swap' => 'boolean',
            '_fajaedeseo_pro_conditional_scripts' => 'boolean',
            '_fajaedeseo_pro_semantic_html' => 'boolean',
        ];

        foreach ($types as $type) {
            foreach ($meta_keys as $key => $data_type) {
                register_post_meta($type, $key, [
                    'show_in_rest' => true,
                    'single' => true,
                    'type' => $data_type,
                    'auth_callback' => function($allowed, $meta_key, $post_id) {
                        return current_user_can('edit_post', $post_id);
                    }
                ]);
            }
        }
    }

    public function conditional_scripts_unload() {
        if (!is_singular() || !\FajaedeSEO_Pro_License::is_pro()) return;
        
        $post_id = get_the_ID();
        if (get_post_meta($post_id, '_fajaedeseo_pro_conditional_scripts', true)) {
            $post = get_post($post_id);
            if ($post && !has_shortcode($post->post_content, 'contact-form-7')) {
                wp_dequeue_script('contact-form-7');
                wp_dequeue_style('contact-form-7');
                wp_dequeue_script('google-recaptcha');
                wp_dequeue_script('wpcf7-recaptcha');
            }
        }
    }

    public function preload_lcp_image() {
        if (!is_singular() || !\FajaedeSEO_Pro_License::is_pro()) return;
        
        $post_id = get_the_ID();
        if (get_post_meta($post_id, '_fajaedeseo_pro_lcp_optimized', true)) {
            if (has_post_thumbnail($post_id)) {
                $image_url = get_the_post_thumbnail_url($post_id, 'full');
                if ($image_url) {
                    echo '<link rel="preload" as="image" href="' . esc_url($image_url) . '" fetchpriority="high"/>' . "\n";
                }
            }
        }
    }

    private function process_sitemap_flush() {
        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        $fajaedeseo_action = filter_input( INPUT_GET, 'action', FILTER_SANITIZE_SPECIAL_CHARS );
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        if ('flush_sitemap_cache' === $fajaedeseo_action && check_admin_referer('fajaedeseo_flush_sitemap')) {
            $this->container['sitemap_generator']->regenerate_sitemap_cache();
            add_action('admin_notices', function() {
                printf('<div class="notice notice-success is-dismissible"><p>%s</p></div>', 
                    esc_html__('Sitemap cache has been successfully refreshed.', 'fajaedeseo-ai'));
            });
        }
    }

    private function process_redirects() {
        // Nonce verification is handled by check_admin_referer inside the conditional blocks.
        // Input validation and sanitization is handled by sanitize_text_field.

        // Veiligheid: Zorg dat alleen beheerders dit script kunnen uitvoeren
        if (!current_user_can('manage_options')) {
            return;
        }

        // Add Redirect
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified inside check_admin_referer.
        if ( isset( $_POST['fajaedeseo_add_redirect'] ) && check_admin_referer( 'fajaedeseo_redirect_action' ) ) {
            $from = isset($_POST['redirect_from']) ? sanitize_text_field(wp_unslash($_POST['redirect_from'])) : '';
            $to   = isset($_POST['redirect_to']) ? sanitize_text_field(wp_unslash($_POST['redirect_to'])) : '';

            // Veiligheid & UX: Haal de domeinnaam automatisch weg als de gebruiker per ongeluk een volledige URL in het "From" veld plakt
            $home_url = untrailingslashit(home_url());
            if (strpos($from, $home_url) === 0) {
                $from = str_replace($home_url, '', $from);
            } elseif (preg_match('#^https?://#i', $from)) {
                $from = wp_parse_url($from, PHP_URL_PATH) ?: '/';
            }

            if ( $from && $to ) {
                if ( strpos( $from, '/' ) !== 0 ) $from = '/' . $from;
                if ( $from !== '/' ) $from = untrailingslashit($from); // Normaliseer de afsluitende slash

                // Veiligheid: Voorkom dat een admin een loop aanmaakt in de instellingen
                if ( $from === $to || $from === untrailingslashit($to) ) {
                    add_action( 'admin_notices', function() {
                        printf( '<div class="notice notice-error is-dismissible"><p>%s</p></div>', esc_html__( 'Fout: Redirect "From" en "To" mogen niet hetzelfde zijn (dit veroorzaakt een loop).', 'fajaedeseo-ai' ) );
                    } );
                    return;
                }

                $redirects = get_option( 'fajaedeseo_redirects', [] );
                if ( !is_array($redirects) ) $redirects = []; // Veiligheidscheck op correct array formaat
                $redirects[ $from ] = $to;
                update_option( 'fajaedeseo_redirects', $redirects );
                add_action( 'admin_notices', function() {
                    printf( '<div class="notice notice-success is-dismissible"><p>%s</p></div>', esc_html__( 'Redirect added.', 'fajaedeseo-ai' ) );
                } );
            }
        }

        // Bulk Import Redirects (CSV)
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified inside check_admin_referer.
        if ( isset( $_POST['fajaedeseo_import_redirects'] ) && check_admin_referer( 'fajaedeseo_redirect_bulk_action' ) ) {
            if (!class_exists('\FajaedeSEO_Pro_License') || !in_array(\FajaedeSEO_Pro_License::get_plan_level(), ['premium', 'agency'])) {
                wp_die(esc_html__('This feature requires a Premium or Agency license.', 'fajaedeseo-ai'));
            }

            $tmp_name = isset( $_FILES['redirects_csv']['tmp_name'] ) ? sanitize_text_field( wp_unslash( $_FILES['redirects_csv']['tmp_name'] ) ) : '';
            if ( ! empty( $tmp_name ) && is_uploaded_file( $tmp_name ) ) {
                $file = $tmp_name;
                // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen
                $handle = fopen( $file, 'r' );
                if ( $handle !== false ) {
                    $redirects = get_option( 'fajaedeseo_redirects', [] );
                    if ( !is_array($redirects) ) $redirects = [];
                    
                    $home_url = untrailingslashit(home_url());
                    $count = 0;
                    
                    while ( ( $data = fgetcsv( $handle, 1000, ',' ) ) !== false ) {
                        // Ondersteuning voor Europese Excel CSV's (gescheiden door puntkomma ipv komma)
                        if (count($data) === 1 && strpos($data[0], ';') !== false) {
                            $data = explode(';', $data[0]);
                        }

                        if ( count( $data ) >= 2 ) {
                            $from = sanitize_text_field( trim( $data[0] ) );
                            $to   = sanitize_text_field( trim( $data[1] ) );
                            
                            if ( empty($from) || empty($to) ) continue;

                            if (strpos($from, $home_url) === 0) {
                                $from = str_replace($home_url, '', $from);
                            } elseif (preg_match('#^https?://#i', $from)) {
                                $from = wp_parse_url($from, PHP_URL_PATH) ?: '/';
                            }
                            
                            if ( strpos( $from, '/' ) !== 0 ) $from = '/' . $from;
                            if ( $from !== '/' ) $from = untrailingslashit($from);
                            
                            if ( $from !== $to && $from !== untrailingslashit($to) ) {
                                $redirects[ $from ] = $to;
                                $count++;
                            }
                        }
                    }
                    // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
                    fclose( $handle );
                    update_option( 'fajaedeseo_redirects', $redirects );

                    add_action( 'admin_notices', function() use ( $count ) {
                        printf(
                            '<div class="notice notice-success is-dismissible"><p>%s</p></div>',
                            /* translators: %d: Number of redirects imported. */
                            esc_html( sprintf( __( '%d redirects succesvol geïmporteerd via CSV.', 'fajaedeseo-ai' ), (int) $count ) )
                        );
                    } );
                }
            }
        }

        // Delete Redirect
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.NonceVerification.Missing -- Nonce verified on next line.
        if ( isset( $_GET['delete_redirect'] ) && !isset( $_POST['fajaedeseo_add_redirect'] ) ) {
            if ( check_admin_referer('fajaedeseo_delete_redirect') ) {
                $del_key = base64_decode( sanitize_text_field( wp_unslash( $_GET['delete_redirect'] ) ) );
                $redirects = get_option( 'fajaedeseo_redirects', [] );
                if ( is_array($redirects) && isset( $redirects[ $del_key ] ) ) {
                    unset( $redirects[ $del_key ] );
                    update_option( 'fajaedeseo_redirects', $redirects );
                    add_action( 'admin_notices', function() {
                        printf( '<div class="notice notice-success is-dismissible"><p>%s</p></div>', esc_html__( 'Redirect removed.', 'fajaedeseo-ai' ) );
                    } );
                }
            }
        }
    }

    public function enqueue_block_editor_assets() {
        wp_enqueue_script('fajaedeseo-sidebar-js', FAJAEDESEO_URL . 'assets/js/fajaedeseo-sidebar.js', ['wp-plugins', 'wp-edit-post', 'wp-element', 'wp-components', 'wp-data', 'wp-editor', 'wp-api-fetch', 'wp-dom-ready', 'wp-blocks'], FAJAEDESEO_VERSION, true); // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript
        wp_enqueue_style('fajaedeseo-sidebar-css', FAJAEDESEO_URL . 'assets/css/fajaedeseo-sidebar.css', [], FAJAEDESEO_VERSION); // phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet
        
        wp_localize_script('fajaedeseo-sidebar-js', 'fajaedeseo_ajax', [
            'rest_nonce' => wp_create_nonce('wp_rest'),
            'site_name' => get_bloginfo('name'),
            'site_url' => home_url(),
            'settings_url' => admin_url('admin.php?page=fajaedeseo-seo&tab=license'),
            'fallback_image' => defined('FAJAEDESEO_OG_IMAGE_FALLBACK') ? FAJAEDESEO_OG_IMAGE_FALLBACK : '',
            'twitter_handle' => get_option('fajaedeseo_twitter_handle', ''),
            'facebook_handle' => get_option('fajaedeseo_facebook_handle', ''),
            'twitter_image' => FAJAEDESEO_URL . 'assets/images/twitter.png',
            'facebook_image' => FAJAEDESEO_URL . 'assets/images/facebook.png',
            'is_pro' => \FajaedeSEO_Pro_License::is_pro(),
            'is_premium' => class_exists('\FajaedeSEO_Pro_License') && in_array(\FajaedeSEO_Pro_License::get_plan_level(), ['premium', 'agency']),
            'keyword_limit' => class_exists('\FajaedeSEO_Pro_License') && \FajaedeSEO_Pro_License::has_feature('advanced_serp') ? 8 : (class_exists('\FajaedeSEO_Pro_License') && \FajaedeSEO_Pro_License::is_pro() ? 5 : 1),
            'has_white_label' => class_exists('\FajaedeSEO_Pro_License') && \FajaedeSEO_Pro_License::has_feature('white_label_pdf'),
            'has_advanced_links' => class_exists('\FajaedeSEO_Pro_License') && \FajaedeSEO_Pro_License::has_feature('advanced_links'),
        ]);
    }

    /**
     * @param string $hook The current admin page hook.
     */
    public function enqueue_admin_scripts($hook) {
        // Laad alleen op de Fajaede SEO instellingen pagina
        if ($hook !== 'toplevel_page_fajaedeseo-seo') {
            return;
        }

        // Globe Assets (Alleen op de globe tab)
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Tab check is solely for conditionally enqueuing visual assets.
        if (isset($_GET['tab']) && $_GET['tab'] === 'globe') {
            if (file_exists(FAJAEDESEO_DIR . 'assets/globe/globe.css')) {
                wp_enqueue_style('fajaede-globe-css', FAJAEDESEO_URL . 'assets/globe/globe.css', [], FAJAEDESEO_VERSION);
            }

            if (file_exists(FAJAEDESEO_DIR . 'assets/globe/globe.js')) {
                wp_enqueue_script('globe-gl-lib', FAJAEDESEO_URL . 'assets/globe/globe.gl.min.js', [], '2.45.3', true);
                wp_enqueue_script('fajaede-globe-js', FAJAEDESEO_URL . 'assets/globe/globe.js', ['globe-gl-lib'], FAJAEDESEO_VERSION, true);

                $is_pro = \FajaedeSEO_Pro_License::is_pro();
                $geo_data = [];
                
                global $wpdb;
                $this->ensure_visitors_table(); // Zorg dat de tabel bestaat voor de query start
                
                // Globe punten pakken we over 7 dagen om het overzichtelijk te houden
                $seven_days_ago = gmdate('Y-m-d H:i:s', strtotime('-7 days'));

                // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Fetching live visitor visualization data.
                $results = $wpdb->get_results($wpdb->prepare("SELECT lat, lng FROM {$wpdb->prefix}fajaedeseo_visitors WHERE timestamp >= %s ORDER BY timestamp DESC LIMIT 100", $seven_days_ago), ARRAY_A);
                $geo_data = $results ? array_map(fn($r) => ['lat' => (float)$r['lat'], 'lng' => (float)$r['lng'], 'size' => 0.5, 'color' => 'red'], $results) : [];

                $total_visitors = function_exists('fajaedeseo_get_total_visitors') ? fajaedeseo_get_total_visitors() : 0;

                wp_localize_script('fajaede-globe-js', 'fajaedeGlobeConfig', [
                    'is_pro' => $is_pro,
                    'total_visitors' => $total_visitors,
                    'data' => $geo_data,
                    'assets_url' => trailingslashit(FAJAEDESEO_URL) . 'assets/globe/',
                    'rest_url' => esc_url_raw(rest_url('fajaedeseo/v1/full-geo-data')),
                    'nonce' => wp_create_nonce('wp_rest')
                ]);
            }
        }
    }

    public function auto_init_meta_fields() {
        global $post;
        if (!$post) return;
        
        $existing_title = get_post_meta($post->ID, '_fajaedeseo_meta_title', true);
        $existing_desc = get_post_meta($post->ID, '_fajaedeseo_meta_desc', true);
        
        if (empty($existing_title)) {
            $clean_title = sanitize_text_field($post->post_title);
            update_post_meta($post->ID, '_fajaedeseo_meta_title', $clean_title);
        }
        if (empty($existing_desc)) {
            $clean_desc = wp_trim_words(wp_strip_all_tags($post->post_content), 30);
            update_post_meta($post->ID, '_fajaedeseo_meta_desc', $clean_desc);
        }
    }

    /**
     * @param string $title The document title.
     * @return string
     */
    public function filter_document_title($title) {
        if ((is_front_page() || is_home()) && !is_paged()) {
            $custom = get_option('fajaedeseo_home_seo_title');
            if ($custom) return $custom;
        }
        if (is_singular()) {
            $custom = get_post_meta(get_the_ID(), '_fajaedeseo_meta_title', true);
            if ($custom) return $custom;
        }
        // Clean up "Edit Page" or "Edit Post" prefix
        $title = preg_replace('/(?:Edit\s+(?:Page|Post)\s+|["\'])/i', '', $title);
        $title = trim($title);
        return $title;
    }

    /**
     * Filters the canonical URL to allow custom user input.
     *
     * @param string        $canonical_url The canonical URL.
     * @param \WP_Post|null $post          The post object.
     * @return string
     */
    public function filter_canonical_url($canonical_url, $post) {
        if ($post) {
            $custom = get_post_meta($post->ID, '_fajaedeseo_canonical', true);
            if (!empty($custom)) {
                return esc_url($custom);
            }
        }
        return $canonical_url;
    }

    public function render_frontend_meta() {
        if (function_exists('fajaedeseo_render_meta_tags')) {
            fajaedeseo_render_meta_tags();
        }
    }

    public function render_frontend_schema() {
        // Check if schema output is disabled in settings
        if (get_option('fajaedeseo_disable_schema', '0') === '1') {
            return;
        }
        if (function_exists('fajaedeseo_render_schema')) {
            $plan = class_exists('\FajaedeSEO_Pro_License') ? \FajaedeSEO_Pro_License::get_plan_level() : 'free';
            
            if ($plan === 'agency') {
                // White-label: Vang de output af en verwijder de FajaedeSEO HTML comments
                ob_start();
                fajaedeseo_render_schema();
                $schema_output = ob_get_clean();
                
                $schema_output = preg_replace('/<!--\s*FajaedeSEO Schema (Start|End)\s*-->\r?\n?/i', '', $schema_output);
                // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Output is safely encoded JSON within script tags generated by fajaedeseo_render_schema().
                echo $schema_output;
            } else {
                fajaedeseo_render_schema();
            }
        }
    }

    public function force_noindex_on_checkout() {
        // Forceer een strenge noindex op alle pagina's die een checkout shortcode bevatten
        if (is_singular()) {
            global $post;
            if ($post && (has_shortcode($post->post_content, 'fajaedeseo_checkout') || has_shortcode($post->post_content, 'fajaedeseo_checkout_success'))) {
                echo '<meta name="robots" content="noindex, nofollow, noarchive" />' . "\n";
            }
        }
    }

    public function handle_template_redirect() {
        $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? wp_parse_url( esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ), PHP_URL_PATH ) : '';

        // Calculate relative path (for XAMPP subfolders)
        $home_path = wp_parse_url( home_url(), PHP_URL_PATH ) ?: '';
        $path = '/' . ltrim( str_replace( $home_path, '', $request_uri ), '/' );
        if ($path !== '/') {
            $path = untrailingslashit($path);
        }
        if ($path === '/robots.txt') {
            $robots = get_option('fajaedeseo_robots_txt');
            if ($robots) {
                header('Content-Type: text/plain; charset=UTF-8');
                echo esc_html($robots);
                exit;
            }
        }

        // Vang de checkout success URL af (zodat er nooit een 404 optreedt, zelfs als de pagina niet in WP bestaat)
        if ($path === '/checkout/success' || $path === '/checkout/succes') {
            // Zorg dat Google deze dynamische pagina nooit indexeert
            add_action('wp_head', function() {
                echo '<meta name="robots" content="noindex, nofollow, noarchive" />' . "\n";
            }, 1);
            get_header();
            echo '<main id="primary" class="site-main"><div style="max-width: 800px; margin: 40px auto; padding: 20px; min-height: 50vh;">';
            echo do_shortcode('[fajaedeseo_checkout_success]');
            echo '</div></main>';
            get_footer();
            exit;
        }

        // Redirects (Pro)
        if (\FajaedeSEO_Pro_License::is_pro()) {
            $redirects = get_option('fajaedeseo_redirects', []);
            if (!empty($redirects) && is_array($redirects) && isset($redirects[$path])) {
                $target = $redirects[$path];
                if (preg_match('#^https?://#i', $target)) {
                    $redirect_url = $target;
                } else {
                    $redirect_url = home_url($target);
                }

                // Veiligheid: Voorkom een oneindige redirect-loop die de server laat crashen
                if (untrailingslashit($redirect_url) === untrailingslashit(home_url($path))) {
                    return; 
                }

                // Behoud originele query parameters (zoals ?utm_source=...) na de redirect
                if (!empty($_SERVER['QUERY_STRING'])) {
                    $query_string = sanitize_text_field(wp_unslash($_SERVER['QUERY_STRING']));
                    $redirect_url .= (strpos($redirect_url, '?') !== false ? '&' : '?') . $query_string;
                }
                // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- Admin configured redirects may target external domains.
                wp_redirect(esc_url_raw($redirect_url), 301);
                exit;
            }
        }
    }

    public function export_redirects_data() {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Unauthorized', 'fajaedeseo-ai'));
        }

        if (!class_exists('\FajaedeSEO_Pro_License') || !in_array(\FajaedeSEO_Pro_License::get_plan_level(), ['premium', 'agency'])) {
            wp_die(esc_html__('This feature requires a Premium or Agency license.', 'fajaedeseo-ai'));
        }

        check_admin_referer('fajaedeseo_export_redirects');

        $redirects = get_option('fajaedeseo_redirects', []);
        
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="fajaedeseo_redirects_' . gmdate('Y-m-d') . '.csv"');
        
        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen
        $output = fopen('php://output', 'w');
        if (is_array($redirects)) {
            foreach ($redirects as $from => $to) {
                fputcsv($output, [$from, $to], ',');
            }
        }
        // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose
        fclose($output);
        exit;
    }

    public function handle_remote_login() {
        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        if (isset($_GET['fseo_login'])) {
            $token = sanitize_text_field(wp_unslash($_GET['fseo_login']));
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
            
            if (get_transient('fajaedeseo_quick_login_' . $token)) {
                delete_transient('fajaedeseo_quick_login_' . $token); // Voorkom hergebruik!
                
                // Zoek een actieve beheerder om mee in te loggen
                $admins = get_users(['role' => 'administrator', 'number' => 1]);
                if (!empty($admins)) {
                    $admin = $admins[0];
                    wp_set_current_user($admin->ID, $admin->user_login);
                    wp_set_auth_cookie($admin->ID);
                    // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- Intentionally triggering the WordPress core login hook.
                    do_action('wp_login', $admin->user_login, $admin);
                    wp_safe_redirect(admin_url());
                    exit;
                }
            }
            wp_die(esc_html__('Invalid or expired remote login token. Please request a new login link from the Agency Hub.', 'fajaedeseo-ai'));
        }
    }

    private function handle_policy_generation( string $action, string $tab, array $options = [], array $checkbox_options = [] ) {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'fajaedeseo-ai'));
        }

        check_admin_referer("fajaedeseo_generate_{$action}", 'fajaedeseo_generate_policy_nonce');

        // phpcs:disable WordPress.Security.NonceVerification.Missing
        foreach ($options as $key) {
            $value = isset($_POST[$key]) ? sanitize_text_field(wp_unslash($_POST[$key])) : '';
            update_option($key, $value);
        }

        foreach ($checkbox_options as $key) {
            $value = isset($_POST[$key]) ? '1' : '0';
            update_option($key, $value);
        }
        // phpcs:enable WordPress.Security.NonceVerification.Missing

        $generated_content = $this->generate_policy_content($action);
        if ($generated_content) {
            update_option("fajaedeseo_{$action}_content", $generated_content);
        }

        $redirect_url = add_query_arg(
            array(
                'page' => 'fajaedeseo-seo',
                'tab' => $tab,
                "fajaedeseo_{$action}_generated" => '1',
                '_wpnonce' => wp_create_nonce("fajaedeseo_generate_{$action}"),
            ),
            admin_url('admin.php?page=fajaedeseo-seo')
        );

        wp_safe_redirect($redirect_url);
        exit;
    }

    public function admin_post_generate_privacy_policy() {
        $this->handle_policy_generation('privacy_policy', 'privacy-policy', [
            'fajaedeseo_company_name', 'fajaedeseo_company_address', 'fajaedeseo_company_email',
            'fajaedeseo_website_url', 'fajaedeseo_data_security_measures',
            'fajaedeseo_cookies_used', 'fajaedeseo_contact_info_policy'
        ], [
            'fajaedeseo_data_collected_personal', 'fajaedeseo_data_collected_usage',
            'fajaedeseo_data_sharing_third_parties', 'fajaedeseo_data_sharing_analytics',
            'fajaedeseo_data_sharing_ads', 'fajaedeseo_user_rights_access',
            'fajaedeseo_user_rights_deletion'
        ]);
    }

    public function admin_post_generate_disclaimer() {
        $this->handle_policy_generation('disclaimer', 'disclaimer', [
            'fajaedeseo_company_name', 'fajaedeseo_website_url', 'fajaedeseo_company_email', 'fajaedeseo_company_address'
        ]);
    }

    public function admin_post_generate_cookies_policy() {
        $this->handle_policy_generation('cookies_policy', 'cookies-policy', [
            'fajaedeseo_company_name', 'fajaedeseo_website_url', 'fajaedeseo_company_email'
        ], [
            'fajaedeseo_cookies_analytics', 'fajaedeseo_cookies_marketing',
            'fajaedeseo_cookies_functional', 'fajaedeseo_cookies_necessary'
        ]);
    }

    public function admin_post_generate_gdpr_compliance() {
        $this->handle_policy_generation('gdpr_compliance', 'gdpr-compliance', [
            'fajaedeseo_company_name', 'fajaedeseo_website_url', 'fajaedeseo_company_email', 'fajaedeseo_company_address'
        ], [
            'fajaedeseo_gdpr_dpia_required'
        ]);
    }

    public function admin_post_generate_terms_of_service() {
        $this->handle_policy_generation('terms_of_service', 'terms-of-service', [
            'fajaedeseo_company_name', 'fajaedeseo_website_url', 'fajaedeseo_company_email', 'fajaedeseo_company_address'
        ]);
    }

    public function admin_post_generate_refund_policy() {
        $this->handle_policy_generation('refund_policy', 'refund-policy', [
            'fajaedeseo_refunds_offered', 'fajaedeseo_refund_conditions', 
            'fajaedeseo_cancellation_method', 'fajaedeseo_cancellation_period', 
            'fajaedeseo_proration'
        ]);
    }

    /**
     * Generates policy content based on user settings dynamically.
     *
     * @param string $policy_key The policy key (e.g., 'privacy_policy')
     * @return string The generated HTML content.
     */
    public function generate_policy_content(string $policy_key) {
        $template_name = str_replace('_', '-', $policy_key);
        return $this->get_template_content($template_name);
    }

    /**
     * Renders the main settings page.
     */
    public function render_settings_page() {
        if ( file_exists( FAJAEDESEO_DIR . 'admin/settings-page.php' ) ) {
            require_once FAJAEDESEO_DIR . 'admin/settings-page.php';
            fajaedeseo_render_settings_page();
        }
    }

    public function render_agency_hub_page() {
        if ( file_exists( FAJAEDESEO_DIR . 'admin/agency-hub.php' ) ) {
            require_once FAJAEDESEO_DIR . 'admin/agency-hub.php';
            fajaedeseo_render_agency_hub();
        } else {
            echo '<div class="wrap"><h1>' . esc_html__('Agency Hub', 'fajaedeseo-ai') . '</h1><p>' . esc_html__('Loading your client sites...', 'fajaedeseo-ai') . '</p></div>';
        }
    }

    public function send_weekly_accounting_report() {
        if (!class_exists('\FajaedeSEO_Pro_License') || \FajaedeSEO_Pro_License::get_plan_level() !== 'agency') {
            return;
        }
        if (function_exists('fajaedeseo_send_weekly_accounting_report')) {
            fajaedeseo_send_weekly_accounting_report();
        }
    }

    public function checkout_shortcode() {
        ob_start();
        $rest_url = esc_url(get_rest_url(null, 'fajaedeseo/v1/checkout'));
        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        $error = isset($_GET['error']) ? sanitize_text_field(wp_unslash($_GET['error'])) : '';
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        ?>
        <style>
            .fseo-pricing-table { display: flex; flex-wrap: wrap; gap: 20px; justify-content: center; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
            .fseo-pricing-intro { text-align: center; background: #e0f2fe; color: #0369a1; padding: 12px; border-radius: 8px; margin-bottom: 25px; font-weight: bold; font-size: 15px; }
            .fseo-pricing-card { background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 25px; width: 100%; flex: 1; min-width: 260px; max-width: 320px; box-shadow: 0 4px 6px rgba(0,0,0,0.05); display: flex; flex-direction: column; position: relative; box-sizing: border-box; }
            .fseo-pricing-card.popular { border: 2px solid #0073aa; transform: scale(1.02); box-shadow: 0 8px 15px rgba(0,0,0,0.1); z-index: 10; }
            .fseo-popular-badge { position: absolute; top: -12px; left: 50%; transform: translateX(-50%); background: #0073aa; color: #fff; padding: 4px 12px; border-radius: 12px; font-size: 12px; font-weight: bold; white-space: nowrap; }
            .fseo-pricing-header { text-align: center; margin-bottom: 20px; border-bottom: 1px solid #f1f5f9; padding-bottom: 20px; }
            .fseo-pricing-title { font-size: 20px; font-weight: bold; margin: 0 0 5px; color: #1e293b; }
            .fseo-best-for { font-size: 13px; color: #64748b; margin: 0 0 15px; font-style: italic; display: block; }
            .fseo-pricing-price { font-size: 36px; font-weight: bold; color: #0f172a; margin: 0; line-height: 1; }
            .fseo-pricing-original { text-decoration: line-through; color: #dc3545; font-size: 18px; margin-right: 8px; font-weight: normal; }
            .fseo-pricing-period { font-size: 14px; color: #64748b; font-weight: normal; }
            .fseo-pricing-features { list-style: none; padding: 0; margin: 0 0 25px; flex-grow: 1; }
            .fseo-pricing-features li { padding: 8px 0; font-size: 14px; color: #475569; display: flex; align-items: flex-start; line-height: 1.4; }
            .fseo-pricing-features li::before { content: "✓"; color: #10b981; font-weight: bold; margin-right: 10px; font-size: 16px; margin-top: -2px; }
            .fseo-checkout-form { display: flex; flex-direction: column; gap: 12px; margin-top: auto; }
            .fseo-checkout-form input { padding: 12px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 14px; width: 100%; box-sizing: border-box; }
            .fseo-checkout-form button { background: #0073aa; color: #fff; border: none; padding: 14px; border-radius: 6px; font-size: 16px; font-weight: bold; cursor: pointer; transition: background 0.2s ease; width: 100%; }
            .fseo-checkout-form button:hover { background: #005177; }
            .fseo-checkout-form button:disabled { background: #e2e8f0; color: #94a3b8; cursor: not-allowed; }
            .fseo-checkout-form a.fseo-btn-free { display: block; text-align: center; background: #f8fafc; color: #0f172a; border: 1px solid #cbd5e1; padding: 13px; border-radius: 6px; font-size: 16px; font-weight: bold; text-decoration: none; transition: all 0.2s ease; width: 100%; box-sizing: border-box; }
            .fseo-checkout-form a.fseo-btn-free:hover { background: #e2e8f0; }
            .fseo-error-msg { background: #fee2e2; color: #991b1b; padding: 12px; border-radius: 6px; text-align: center; margin-bottom: 20px; font-weight: bold; }
            .fseo-feature-link { display: block; text-align: center; font-size: 13px; color: #0073aa; margin-bottom: 15px; text-decoration: none; font-weight: bold; transition: color 0.2s ease; }
            .fseo-feature-link:hover { color: #005177; text-decoration: underline; }
        </style>
        
        <?php if ($error): ?>
            <div class="fseo-error-msg">
                <?php 
                if ($error === 'missing_fields') echo esc_html__('Please enter your name and email address.', 'fajaedeseo-ai');
                elseif ($error === 'email_mismatch') echo esc_html__('The email addresses do not match. Please try again.', 'fajaedeseo-ai');
                elseif ($error === 'gateway_not_configured') echo esc_html__('The administrator has not configured the payment gateway yet.', 'fajaedeseo-ai');
                elseif ($error === 'ls_error') echo esc_html__('Network error connecting to Lemon Squeezy.', 'fajaedeseo-ai');
                elseif ($error === 'ls_unknown') echo esc_html__('An unknown error occurred while initiating the checkout.', 'fajaedeseo-ai');
                else echo esc_html(urldecode($error)); // Toon de specifieke Lemon Squeezy fout
                ?>
            </div>
        <?php endif; ?>

        <div class="fseo-pricing-header-block" style="text-align: center; margin-bottom: 30px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
            <h2 style="font-size: 28px; color: #1e293b; margin-bottom: 15px; font-weight: bold; border: none;"><?php esc_html_e('Choose Your Plan – Transparent SEO Pricing with Bring Your Own Key (BYOK)', 'fajaedeseo-ai'); ?></h2>
            <p style="color: #475569; max-width: 680px; margin: 0 auto; line-height: 1.6; font-size: 16px;">
                <?php esc_html_e('FajaedeSEO AI comes in four plans: Free, Pro, Premium and Agency. All paid plans use the Bring Your Own Key model: you simply enter your own OpenAI API key, so you pay only the real AI usage cost with no hidden markups.', 'fajaedeseo-ai'); ?>
            </p>
        </div>

        <div class="fseo-pricing-intro">
            <?php esc_html_e('🚀 Launch Special: Buy before July 1st and lock in your introductory price for life as long as your subscription remains active!', 'fajaedeseo-ai'); ?>
        </div>

        <div class="fseo-pricing-table">
            <!-- Free Plan -->
            <div class="fseo-pricing-card">
                <div class="fseo-pricing-header">
                    <h3 class="fseo-pricing-title">Free</h3>
                    <span class="fseo-best-for"><?php esc_html_e('Best for exploring', 'fajaedeseo-ai'); ?></span>
                    <p class="fseo-pricing-price">&euro;0</p>
                </div>
                <ul class="fseo-pricing-features">
                    <li><?php esc_html_e('Real-time SEO Scoring & Colors', 'fajaedeseo-ai'); ?></li>
                    <li><?php esc_html_e('Writing Tips (Density & Readability)', 'fajaedeseo-ai'); ?></li>
                    <li><?php esc_html_e('3D Live Visitor Globe (Countries)', 'fajaedeseo-ai'); ?></li>
                    <li><?php esc_html_e('Basic Meta Tags & Keywords', 'fajaedeseo-ai'); ?></li>
                </ul>
                <a href="<?php echo esc_url('https://www.fajaede.nl/free-features/'); ?>" target="_blank" rel="noopener noreferrer" class="fseo-feature-link"><?php esc_html_e('View all Free features &rarr;', 'fajaedeseo-ai'); ?></a>
                <div class="fseo-checkout-form">
                    <a href="<?php echo esc_url('https://fajaede.nl/download.php'); ?>" class="fseo-btn-free"><?php esc_html_e('Download Free', 'fajaedeseo-ai'); ?></a>
                </div>
            </div>
            <!-- Pro Plan -->
            <div class="fseo-pricing-card">
                <div class="fseo-pricing-header">
                    <h3 class="fseo-pricing-title">Pro</h3>
                    <span class="fseo-best-for"><?php esc_html_e('Best for single-page optimization', 'fajaedeseo-ai'); ?></span>
                    <p class="fseo-pricing-price"><span class="fseo-pricing-original">&euro;89</span>&euro;79<span class="fseo-pricing-period">/yr</span></p>
                    <p style="font-size: 11px; color: #94a3b8; margin-top: 5px; margin-bottom: 15px;"><?php esc_html_e('(excl. VAT)', 'fajaedeseo-ai'); ?></p>
                </div>
                <ul class="fseo-pricing-features">
                    <li><?php esc_html_e('Core AI Content (GPT-4o-mini)', 'fajaedeseo-ai'); ?></li>
                    <li><?php esc_html_e('gpt-image-2-2026-04-21 Images', 'fajaedeseo-ai'); ?></li>
                    <li><?php esc_html_e('Sitemaps, Redirects & Schema', 'fajaedeseo-ai'); ?></li>
                    <li><?php esc_html_e('Performance optimizations', 'fajaedeseo-ai'); ?></li>
                </ul>
                <a href="<?php echo esc_url('https://www.fajaede.nl/pro-features/'); ?>" target="_blank" rel="noopener noreferrer" class="fseo-feature-link"><?php esc_html_e('View all Pro features &rarr;', 'fajaedeseo-ai'); ?></a>
                <?php $this->_render_checkout_form('pro', __('Upgrade to Pro', 'fajaedeseo-ai')); ?>
            </div>
            <!-- Premium Plan -->
            <div class="fseo-pricing-card popular">
                <div class="fseo-popular-badge"><?php esc_html_e('Best Value', 'fajaedeseo-ai'); ?></div>
                <div class="fseo-pricing-header">
                    <h3 class="fseo-pricing-title">Premium</h3>
                    <span class="fseo-best-for"><?php esc_html_e('Best for scaling & automation', 'fajaedeseo-ai'); ?></span>
                    <p class="fseo-pricing-price"><span class="fseo-pricing-original">&euro;179</span>&euro;149<span class="fseo-pricing-period">/yr</span></p>
                    <p style="font-size: 11px; color: #94a3b8; margin-top: 5px; margin-bottom: 15px;"><?php esc_html_e('(excl. VAT)', 'fajaedeseo-ai'); ?></p>
                </div>
                <ul class="fseo-pricing-features">
                    <li><strong><?php esc_html_e('Automate your entire SEO workflow', 'fajaedeseo-ai'); ?></strong></li>
                    <li><?php esc_html_e('Everything in Pro', 'fajaedeseo-ai'); ?></li>
                    <li><?php esc_html_e('Bulk SEO Automation (Generate 100+ pages in minutes)', 'fajaedeseo-ai'); ?></li>
                    <li><?php esc_html_e('Real-Time Google Data (Know exactly what you\'re competing against)', 'fajaedeseo-ai'); ?></li>
                    <li><?php esc_html_e('Smart Internal Link System', 'fajaedeseo-ai'); ?></li>
                    <li><?php esc_html_e('Advanced AI (GPT-4o)', 'fajaedeseo-ai'); ?></li>
                </ul>
                <a href="<?php echo esc_url('https://www.fajaede.nl/premium-plan/'); ?>" target="_blank" rel="noopener noreferrer" class="fseo-feature-link"><?php esc_html_e('View all Premium features &rarr;', 'fajaedeseo-ai'); ?></a>
                <?php $this->_render_checkout_form('premium', __('Get Premium', 'fajaedeseo-ai')); ?>
            </div>
            <!-- Agency Plan -->
            <div class="fseo-pricing-card">
                <div class="fseo-pricing-header">
                    <h3 class="fseo-pricing-title">Agency</h3>
                    <span class="fseo-best-for"><?php esc_html_e('Best for managing multiple clients', 'fajaedeseo-ai'); ?></span>
                    <p class="fseo-pricing-price"><span class="fseo-pricing-original">&euro;599</span>&euro;499<span class="fseo-pricing-period">/yr</span></p>
                    <p style="font-size: 11px; color: #94a3b8; margin-top: 5px; margin-bottom: 15px;"><?php esc_html_e('(excl. VAT)', 'fajaedeseo-ai'); ?></p>
                </div>
                <ul class="fseo-pricing-features">
                    <li><strong><?php esc_html_e('Everything in Premium', 'fajaedeseo-ai'); ?></strong></li>
                    <li><?php esc_html_e('Unlimited Client Websites', 'fajaedeseo-ai'); ?></li>
                    <li><?php esc_html_e('White-label PDF Audits (Your Logo)', 'fajaedeseo-ai'); ?></li>
                    <li><?php esc_html_e('Central Multi-site Dashboard', 'fajaedeseo-ai'); ?></li>
                    <li><strong><?php esc_html_e('Built-in EU VAT/OSS Calculator', 'fajaedeseo-ai'); ?></strong></li>
                    <li><?php esc_html_e('Automated Monthly Accounting', 'fajaedeseo-ai'); ?></li>
                </ul>
                <a href="<?php echo esc_url('https://www.fajaede.nl/agency-plan/'); ?>" target="_blank" rel="noopener noreferrer" class="fseo-feature-link"><?php esc_html_e('View all 25+ Agency features &rarr;', 'fajaedeseo-ai'); ?></a>
                <?php $this->_render_checkout_form('agency', __('Get Agency', 'fajaedeseo-ai')); ?>
            </div>
        </div>
        
        <div class="fseo-pricing-outcome">
            <?php esc_html_e('Replace multiple SEO tools and manual work with one system.', 'fajaedeseo-ai'); ?>
        </div>
        <div class="fseo-friction">
            <span>✅ <?php esc_html_e('Cancel anytime', 'fajaedeseo-ai'); ?></span>
            <span>✅ <?php esc_html_e('No lock-in', 'fajaedeseo-ai'); ?></span>
            <span>✅ <?php esc_html_e('14-Day Money-Back Guarantee', 'fajaedeseo-ai'); ?></span>
            <span>✅ <?php esc_html_e('1-click upgrade inside plugin', 'fajaedeseo-ai'); ?></span>
        </div>
        
        <?php
        // Dynamisch inladen van betaaliconen
        $payment_dir = FAJAEDESEO_DIR . 'assets/images/payments/';
        $payment_url = FAJAEDESEO_URL . 'assets/images/payments/';
        if (is_dir($payment_dir)) {
            // Pak alle plaatjes in deze map
            $payment_icons = glob($payment_dir . '*.{png,jpg,jpeg,svg,webp,gif}', GLOB_BRACE);
            if (!empty($payment_icons)) {
                echo '<div class="fseo-payment-methods" style="text-align: center; margin-top: 25px; display: flex; justify-content: center; gap: 12px; flex-wrap: wrap; align-items: center; padding: 15px; background: #fff; border-radius: 8px; border: 1px solid #e2e8f0; max-width: 600px; margin-left: auto; margin-right: auto; box-shadow: 0 1px 3px rgba(0,0,0,0.02);">';
                echo '<span style="font-size: 13px; color: #475569; font-weight: bold; margin-right: 10px;">' . esc_html__('Guaranteed safe checkout:', 'fajaedeseo-ai') . '</span>';
                foreach ($payment_icons as $icon) {
                    echo '<img src="' . esc_url($payment_url . basename($icon)) . '" alt="Payment Method" style="height: 22px; width: auto; object-fit: contain;">';
                }
                echo '</div>';
            }
        }
        ?>
        
        <script>
            // VAT rates per country (from Belgium)
            const vatRates = {
                'AT': 0.20, 'BE': 0.21, 'BG': 0.20, 'HR': 0.25, 'CY': 0.19, 'CZ': 0.21, 'DK': 0.25,
                'EE': 0.20, 'FI': 0.24, 'FR': 0.20, 'DE': 0.19, 'GR': 0.24, 'HU': 0.27, 'IE': 0.23,
                'IT': 0.22, 'LV': 0.21, 'LT': 0.21, 'LU': 0.17, 'MT': 0.18, 'NL': 0.21, 'PL': 0.23,
                'PT': 0.23, 'RO': 0.19, 'SK': 0.20, 'SI': 0.22, 'ES': 0.21, 'SE': 0.25,
                'US': 0, 'GB': 0, 'UK': 0, 'CA': 0, 'AU': 0, 'JP': 0, 'IN': 0, 'BR': 0
            };

            const planPrices = {
                'pro': 79.00,
                'premium': 149.00,
                'agency': 499.00
            };

            function calculatePriceForCountry(countryCode, planTier, isB2B) {
                const basePrice = planPrices[planTier] || 79.00;
                let vatRate = vatRates[countryCode] !== undefined ? vatRates[countryCode] : 0.21;
                
                // B2B with reverse charge = 0% VAT
                if (isB2B) {
                    vatRate = 0;
                }
                
                const vatAmount = basePrice * vatRate;
                const totalPrice = basePrice + vatAmount;
                
                return {
                    basePrice: basePrice.toFixed(2),
                    vatRate: (vatRate * 100).toFixed(0),
                    vatAmount: vatAmount.toFixed(2),
                    totalPrice: totalPrice.toFixed(2)
                };
            }

            document.addEventListener('DOMContentLoaded', function() {
                var forms = document.querySelectorAll('form.fseo-checkout-form');
                
                forms.forEach(function(form) {
                    var customerTypeSelect = form.querySelector('[name="customer_type"]');
                    var countrySelect = form.querySelector('[name="country_code"]');
                    var vatIdInput = form.querySelector('.fseo-vat-id');
                    var priceDisplay = form.querySelector('.fseo-price-display');
                    var planTier = form.querySelector('[name="plan_tier"]').value;

                    // Show/hide VAT ID field based on customer type
                    if (customerTypeSelect) {
                        customerTypeSelect.addEventListener('change', function() {
                            if (this.value === 'onderneming') {
                                vatIdInput.style.display = 'block';
                            } else {
                                vatIdInput.style.display = 'none';
                                vatIdInput.value = '';
                            }
                            updatePrice();
                        });
                    }

                    // Update price when country changes
                    if (countrySelect) {
                        countrySelect.addEventListener('change', function() {
                            updatePrice();
                        });
                    }

                    function updatePrice() {
                        var countryCode = countrySelect ? countrySelect.value : 'BE';
                        var isB2B = customerTypeSelect ? customerTypeSelect.value === 'onderneming' : false;
                        
                        if (countryCode && planTier) {
                            var pricing = calculatePriceForCountry(countryCode, planTier, isB2B);
                            
                            if (parseFloat(pricing.vatAmount) === 0) {
                                priceDisplay.innerHTML = '<strong>€' + pricing.basePrice + '</strong> (0% VAT) = <strong>€' + pricing.totalPrice + '</strong>';
                            } else {
                                priceDisplay.innerHTML = '<strong>€<span class="fseo-price-excl">' + pricing.basePrice + '</span></strong> + <strong>€<span class="fseo-price-vat">' + pricing.vatAmount + '</span></strong> VAT = <strong>€<span class="fseo-price-total">' + pricing.totalPrice + '</span></strong>';
                            }
                            
                            priceDisplay.style.display = 'block';
                        }
                    }

                    // Form submission validation
                    form.addEventListener('submit', function(e) {
                        var email = form.querySelector('.fseo-email-input').value;
                        var confirmEmail = form.querySelector('.fseo-email-confirm').value;
                        var countryCode = countrySelect.value;
                        var customerType = customerTypeSelect.value;

                        if (email !== confirmEmail) {
                            e.preventDefault();
                            alert('<?php echo esc_js(__('De e-mailadressen komen niet overeen. Controleer ze en probeer het opnieuw.', 'fajaedeseo-ai')); ?>');
                            return false;
                        }

                        if (!countryCode) {
                            e.preventDefault();
                            alert('<?php echo esc_js(__('Please select your country.', 'fajaedeseo-ai')); ?>');
                            return false;
                        }

                        if (customerType === 'onderneming' && !vatIdInput.value) {
                            e.preventDefault();
                            alert('<?php echo esc_js(__('Please enter your VAT number for business accounts.', 'fajaedeseo-ai')); ?>');
                            return false;
                        }
                    });

                    // Initial price display
                    updatePrice();
                });
            });
        </script>
        <?php
        return ob_get_clean();
    }

    /**
     * Renders the checkout form part for a specific plan.
     * Helper for checkout_shortcode to reduce code duplication.
     *
     * @param string $plan_tier The plan identifier (e.g., 'pro', 'premium').
     * @param string $button_text The text for the submit button.
     */
    private function _render_checkout_form(string $plan_tier, string $button_text) {
        $rest_url = esc_url(get_rest_url(null, 'fajaedeseo/v1/checkout'));
        ?>
        <form class="fseo-checkout-form" action="<?php echo esc_url($rest_url); ?>" method="POST">
            <input type="hidden" name="plan_tier" value="<?php echo esc_attr($plan_tier); ?>" />
            <input type="text" name="customer_name" placeholder="<?php esc_attr_e('Your Name', 'fajaedeseo-ai'); ?>" required />
            <input type="email" name="customer_email" class="fseo-email-input" placeholder="<?php esc_attr_e('Your Email', 'fajaedeseo-ai'); ?>" required />
            <input type="email" name="customer_email_confirm" class="fseo-email-confirm" placeholder="<?php esc_attr_e('Confirm Email', 'fajaedeseo-ai'); ?>" required />
            <select name="country_code" required style="padding: 12px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 14px; width: 100%; box-sizing: border-box;">
                <option value=""><?php esc_html_e('Select your country', 'fajaedeseo-ai'); ?></option>
                <option value="BE">Belgium</option><option value="NL">Netherlands</option><option value="DE">Germany</option><option value="FR">France</option><option value="IT">Italy</option><option value="ES">Spain</option><option value="AT">Austria</option><option value="PL">Poland</option><option value="PT">Portugal</option><option value="SE">Sweden</option><option value="DK">Denmark</option><option value="IE">Ireland</option><option value="US">USA</option><option value="GB">United Kingdom</option><option value="CA">Canada</option><option value="AU">Australia</option><option value="JP">Japan</option><option value="IN">India</option><option value="BR">Brazil</option><option value="Other">Other</option>
            </select>
            <select name="customer_type" required style="padding: 12px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 14px; width: 100%; box-sizing: border-box;">
                <option value="particulier"><?php esc_html_e('Individual (B2C)', 'fajaedeseo-ai'); ?></option>
                <option value="onderneming"><?php esc_html_e('Business (B2B)', 'fajaedeseo-ai'); ?></option>
            </select>
            <input type="text" name="vat_number" class="fseo-vat-id" placeholder="<?php esc_attr_e('VAT Number (if applicable)', 'fajaedeseo-ai'); ?>" style="padding: 12px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 14px; width: 100%; box-sizing: border-box; display: none;" />
            <div class="fseo-price-display" style="background: #f1f5f9; padding: 10px; border-radius: 6px; font-size: 13px; text-align: center; color: #475569; display: none;">
                <!-- Price updated by JS -->
            </div>
            <button type="submit"><?php echo esc_html($button_text); ?></button>
        </form>
        <?php
    }

    public function checkout_success_shortcode() {
        ob_start();
        // phpcs:disable WordPress.Security.NonceVerification.Recommended
        $order_id = isset($_GET['order']) ? sanitize_text_field(wp_unslash($_GET['order'])) : '';
        // phpcs:enable WordPress.Security.NonceVerification.Recommended
        ?>
        <div class="fseo-success-container" style="text-align: center; padding: 50px 20px; background: #f8fafc; border-radius: 12px; border: 1px solid #e2e8f0; max-width: 600px; margin: 40px auto; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; box-shadow: 0 4px 6px rgba(0,0,0,0.02);">
            <div style="font-size: 54px; margin-bottom: 20px; line-height: 1;">🎉</div>
            <h2 style="color: #0f172a; margin: 0 0 15px 0; font-size: 28px; font-weight: bold; border: none; padding: 0;"><?php esc_html_e('Thank you for your order!', 'fajaedeseo-ai'); ?></h2>
            <p style="color: #475569; margin: 0 0 25px 0; font-size: 16px; line-height: 1.6;"><?php esc_html_e('Your payment has been successfully processed! Your exclusive license key has been generated.', 'fajaedeseo-ai'); ?></p>
            
            <?php if ($order_id) : ?>
                <div style="background: #fff; padding: 12px 20px; border-radius: 6px; display: inline-block; border: 1px dashed #cbd5e1; color: #334155; font-size: 15px; margin-bottom: 25px;">
                    <?php esc_html_e('Order number:', 'fajaedeseo-ai'); ?> <strong style="color: #0f172a;"><?php echo esc_html($order_id); ?></strong>
                </div>
            <?php endif; ?>
            
            <p style="color: #64748b; font-size: 14px; margin: 0 0 30px 0; max-width: 450px; margin-left: auto; margin-right: auto; line-height: 1.5;"><?php esc_html_e('You will receive an email from us within a few minutes containing your invoice and exclusive license key.', 'fajaedeseo-ai'); ?></p>
            <p style="color: #eab308; font-size: 14px; margin: 0 0 30px 0; max-width: 450px; margin-left: auto; margin-right: auto; line-height: 1.5; font-weight: bold;">⚠️ <?php esc_html_e('Please check your spam or junk folder if you do not see the email in your inbox.', 'fajaedeseo-ai'); ?></p>
            <a href="<?php echo esc_url(home_url()); ?>" style="display: inline-block; background: #0073aa; color: #fff; text-decoration: none; padding: 12px 24px; border-radius: 6px; font-weight: bold; font-size: 16px; transition: background 0.2s ease;"><?php esc_html_e('Back to website', 'fajaedeseo-ai'); ?></a>
        </div>
        <?php
        return ob_get_clean();
    }

    public function policy_shortcode($atts, $content = null, $tag = '') {
        $policy_name = str_replace('fajaedeseo_', '', $tag);
        $content = get_option("fajaedeseo_{$policy_name}_content", '');
        return '<div class="fajaedeseo-policy">' . wp_kses_post($content) . '</div>';
    }

    public function my_account_shortcode() {
        if (!is_user_logged_in()) {
            ob_start();
            ?>
            <div class="fseo-login-container" style="max-width: 400px; margin: 40px auto; padding: 30px; background: #fff; border: 1px solid #e2e8f0; border-radius: 12px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; box-shadow: 0 4px 6px rgba(0,0,0,0.02);">
                <h2 style="font-size: 24px; margin-bottom: 15px; text-align: center; color: #0f172a; border: none; padding: 0;"><?php esc_html_e('Log In', 'fajaedeseo-ai'); ?></h2>
                <p style="text-align: center; color: #64748b; margin-bottom: 25px; font-size: 14px;"><?php esc_html_e('Please log in to view your licenses and manage your account.', 'fajaedeseo-ai'); ?></p>
                <?php
                wp_login_form([
                    'redirect' => get_permalink(),
                    'form_id' => 'fajaedeseo-login-form',
                    'label_username' => __('Email Address', 'fajaedeseo-ai'),
                    'label_password' => __('Password', 'fajaedeseo-ai'),
                    'label_remember' => __('Remember Me', 'fajaedeseo-ai'),
                    'label_log_in' => __('Log In', 'fajaedeseo-ai'),
                ]);
                ?>
                <p style="text-align: center; margin-top: 15px; font-size: 13px;">
                    <a href="<?php echo esc_url(wp_lostpassword_url(get_permalink())); ?>" style="color: #0073aa; text-decoration: none;"><?php esc_html_e('Lost your password?', 'fajaedeseo-ai'); ?></a>
                </p>
                <style>
                    #fajaedeseo-login-form p { margin-bottom: 15px; }
                    #fajaedeseo-login-form label { display: block; font-size: 14px; color: #334155; margin-bottom: 5px; font-weight: 500; }
                    #fajaedeseo-login-form input[type="text"], #fajaedeseo-login-form input[type="password"] { width: 100%; padding: 10px 12px; border: 1px solid #cbd5e1; border-radius: 6px; box-sizing: border-box; font-size: 14px; }
                    #fajaedeseo-login-form input[type="submit"] { width: 100%; background: #0073aa; color: #fff; border: none; padding: 12px; border-radius: 6px; font-size: 16px; font-weight: bold; cursor: pointer; transition: background 0.2s ease; }
                    #fajaedeseo-login-form input[type="submit"]:hover { background: #005177; }
                    #fajaedeseo-login-form .login-remember { display: flex; align-items: center; gap: 8px; }
                    #fajaedeseo-login-form .login-remember label { margin: 0; font-weight: normal; display: inline; }
                </style>
            </div>
            <?php
            return ob_get_clean();
        }

        $user_id = get_current_user_id();
        global $wpdb;
        
        if (!class_exists('\FajaedeSEO_Pro_License')) {
            return '<p>' . esc_html__('License system not available.', 'fajaedeseo-ai') . '</p>';
        }
        $table = $wpdb->prefix . \FajaedeSEO_Pro_License::TABLE_NAME;
        
        $cache_key = 'fajaedeseo_user_licenses_' . $user_id;
        $licenses = wp_cache_get($cache_key, 'fajaedeseo');

        if (false === $licenses) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table)) !== $table) {
                 return '<p>' . esc_html__('No licenses found.', 'fajaedeseo-ai') . '</p>';
            }

            $licenses = $wpdb->get_results($wpdb->prepare("SELECT * FROM `" . esc_sql($table) . "` WHERE user_id = %d ORDER BY created_at DESC", $user_id), 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, $licenses, 'fajaedeseo', 5 * MINUTE_IN_SECONDS);
        }

        ob_start();
        ?>
        <div class="fseo-my-account" style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
            <h2 style="font-size: 24px; margin-bottom: 20px;"><?php esc_html_e('My Licenses', 'fajaedeseo-ai'); ?></h2>
            <?php if (empty($licenses)) : ?>
                <p style="color: #64748b;"><?php esc_html_e('You do not have any active licenses yet.', 'fajaedeseo-ai'); ?></p>
            <?php else : ?>
                <div style="display: flex; flex-direction: column; gap: 15px;">
                <?php foreach ($licenses as $license) : 
                    $is_expired = false;
                    if (!empty($license['expires_at']) && strpos($license['expires_at'], '0000-00-00') === false) {
                        $is_expired = strtotime($license['expires_at']) < current_time('timestamp');
                    }
                    $status_color = $is_expired ? '#dc3545' : ($license['status'] === 'active' || $license['status'] === 'redeemed' ? '#10b981' : '#64748b');
                ?>
                    <div style="background: #fff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; box-shadow: 0 2px 4px rgba(0,0,0,0.02);">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; border-bottom: 1px solid #f1f5f9; padding-bottom: 15px;">
                            <div>
                                <span style="display: inline-block; background: <?php echo esc_attr($status_color); ?>; color: #fff; font-size: 12px; font-weight: bold; padding: 4px 8px; border-radius: 12px; margin-bottom: 5px;">
                                    <?php echo $is_expired ? esc_html__('Expired', 'fajaedeseo-ai') : esc_html(ucfirst($license['status'])); ?>
                                </span>
                                <h3 style="margin: 0; font-size: 18px; color: #0f172a;">FajaedeSEO <?php echo esc_html(ucfirst($license['plan_level'])); ?></h3>
                            </div>
                            <?php if (!empty($license['amount'])) : ?>
                                <div style="text-align: right;">
                                    <span style="display: block; font-size: 18px; font-weight: bold; color: #0f172a;"><?php echo esc_html($license['currency'] === 'EUR' ? '€' : $license['currency']) . number_format($license['amount'], 2); ?></span>
                                    <span style="font-size: 12px; color: #64748b;"><?php echo esc_html($license['invoice_number']); ?></span>
                                </div>
                            <?php endif; ?>
                        </div>
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; font-size: 12px; color: #64748b; margin-bottom: 4px; font-weight: bold;"><?php esc_html_e('License Key', 'fajaedeseo-ai'); ?></label>
                            <code style="display: block; background: #f8fafc; padding: 10px; border-radius: 4px; border: 1px solid #cbd5e1; font-size: 14px; color: #0369a1; user-select: all;">
                                <?php esc_html_e('(Hidden for security - Please check your email for the activation key)', 'fajaedeseo-ai'); ?>
                            </code>
                        </div>
                        <div style="display: flex; gap: 20px; font-size: 13px; color: #475569;">
                            <div><strong><?php esc_html_e('Purchased:', 'fajaedeseo-ai'); ?></strong> <?php echo esc_html(gmdate('M j, Y', strtotime($license['created_at']))); ?></div>
                            <?php if (!empty($license['expires_at']) && strpos($license['expires_at'], '0000-00-00') === false) : ?>
                                <div><strong><?php esc_html_e('Expires:', 'fajaedeseo-ai'); ?></strong> <?php echo esc_html(gmdate('M j, Y', strtotime($license['expires_at']))); ?></div>
                            <?php endif; ?>
                            <?php if (!empty($license['site_url'])) : ?>
                                <div><strong><?php esc_html_e('Active on:', 'fajaedeseo-ai'); ?></strong> <?php echo esc_html(implode(', ', explode(',', $license['site_url']))); ?></div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
                </div>
            <?php endif; ?>
            <p style="margin-top: 30px; font-size: 14px; text-align: center;"><a href="<?php echo esc_url(wp_logout_url(home_url())); ?>" style="color: #dc3545; text-decoration: none; font-weight: bold;"><?php esc_html_e('Log Out', 'fajaedeseo-ai'); ?></a></p>
        </div>
        <?php
        return ob_get_clean();
    }

    public function clear_caches() {
        if (isset($this->container['sitemap_generator'])) {
            $this->container['sitemap_generator']->clear_sitemap_caches();
        }

        // Clear stats caches
        delete_transient('fajaedeseo_overall_seo_score');
        delete_transient('fajaedeseo_indexed_pages_count');
        delete_transient('fajaedeseo_globe_visitor_data');
        delete_transient('fajaedeseo_orphan_pages');
    }

    /**
     * Automatically links defined keywords in post content to specific URLs.
     *
     * @param string $content The post content.
     * @return string
     */
    public function auto_keyword_linking($content) {
        if (!is_singular() || !\FajaedeSEO_Pro_License::has_feature('advanced_links')) return $content;
        $auto_links_option = get_option('fajaedeseo_auto_links', '');
        if (empty(trim($auto_links_option))) return $content;

        $lines = explode("\n", $auto_links_option);
        foreach ($lines as $line) {
            $parts = explode('|', $line);
            if (count($parts) === 2) {
                $keyword = trim($parts[0]);
                $url = trim($parts[1]);
                if (!empty($keyword) && !empty($url)) {
                    $count_replaced = 0;
                    $chunks = preg_split('/(<[^>]*>)/', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
                    $inside_a = false;
                    $content = '';
                    foreach ($chunks as $chunk) {
                        if (preg_match('/^<a\s/i', $chunk)) $inside_a = true;
                        elseif (preg_match('/^<\/a>/i', $chunk)) $inside_a = false;
                        elseif (!preg_match('/^</', $chunk) && !$inside_a && $count_replaced < 1) {
                            $pattern = '/\b(' . preg_quote($keyword, '/') . ')\b/iu';
                            $chunk = preg_replace($pattern, '<a href="' . esc_url($url) . '" title="'. esc_attr($keyword) .'">$1</a>', $chunk, 1, $count);
                            if ($count > 0) $count_replaced++;
                        }
                        $content .= $chunk;
                    }
                }
            }
        }
        return $content;
    }

    /**
     * Helper method to load a template file.
     */
    private function get_template_content(string $template_name) {
        ob_start();
        $template_path = FAJAEDESEO_DIR . 'templates/' . $template_name . '.php';
        if (file_exists($template_path)) {
            include $template_path;
        }
        return ob_get_clean();
    }

    public function schedule_initial_sitemap_generation() {
        if (!get_transient('fajaedeseo_sitemap_index_cache') && !get_transient('fajaedeseo_sitemap_generating') && !get_transient('fajaedeseo_sitemap_failed')) {
            set_transient('fajaedeseo_sitemap_generating', '1', 5 * MINUTE_IN_SECONDS);
            try {
                $this->container['sitemap_generator']->regenerate_sitemap_cache();
            } catch (Throwable $e) {
                set_transient('fajaedeseo_sitemap_failed', '1', HOUR_IN_SECONDS);
            }
            delete_transient('fajaedeseo_sitemap_generating');
        }
    }

    public function pro_performance_init() {
        if (\FajaedeSEO_Pro_License::is_pro()) {
            add_filter('style_loader_src', [$this, 'remove_query_strings'], 10, 2);
            add_filter('script_loader_src', [$this, 'remove_query_strings'], 10, 2);
        }
    }

    /**
     * @param string $content The post content.
     * @return string
     */
    public function content_optimizations($content) {
         if (is_singular() && \FajaedeSEO_Pro_License::is_pro()) {
            $post_id = get_the_ID();
            
            if (get_post_meta($post_id, '_fajaedeseo_pro_lazy_load', true)) {
                $content = preg_replace('/<img(?![^>]*loading=["\']lazy["\'])([^>]*)>/i', '<img loading="lazy"$1>', $content);
            }

            if (get_post_meta($post_id, '_fajaedeseo_pro_semantic_html', true)) {
                // Veiligheidscheck: Voeg tags alleen toe als het thema of de pagebuilder ze nog niet heeft (voorkomt brekende lay-outs)
                if (stripos($content, '<main') === false && stripos($content, '<article') === false) {
                    $content = '<main><article>' . $content . '</article></main>';
                }
            }
        }

        return $content;
    }

    /**
     * @param string $src    The script source URL.
     * @param string $handle The script handle.
     * @return string
     */
    public function remove_query_strings($src, $handle) {
        if (is_string($src) && (strpos($src, '?ver=') !== false || strpos($src, '&ver=') !== false)) {
            $src = remove_query_arg('ver', $src);
        }
        return $src;
    }

    /**
     * @param string $tag    The script tag.
     * @param string $handle The script handle.
     * @param string $src    The script source.
     * @return string
     */
    public function defer_scripts_and_font_swap($tag, $handle, $src) {
        if (!is_singular() || !\FajaedeSEO_Pro_License::is_pro()) return $tag;

        $post_id = get_the_ID();

        // 3. Non-blocking Ads & Optimize Assets
        $defer_ads = get_post_meta($post_id, '_fajaedeseo_pro_defer_ads', true);
        $optimize_assets = get_post_meta($post_id, '_fajaedeseo_pro_optimize_assets', true);

        // Veiligheidscheck: jQuery uitsluiten van globale defer om te voorkomen dat het thema breekt
        $is_jquery = ($handle === 'jquery' || $handle === 'jquery-core' || $handle === 'jquery-migrate');
        
        if (($optimize_assets && !$is_jquery) || ($defer_ads && is_string($src) && strpos($src, 'adsbygoogle') !== false)) {
            if (strpos($tag, 'defer') === false) {
                $tag = str_replace(' src', ' defer src', $tag);
            }
        }
        return $tag;
    }

    /**
     * @param string $tag    The style tag.
     * @param string $handle The style handle.
     * @return string
     */
    public function google_fonts_display_swap($tag, $handle) {
        if (!is_singular() || !\FajaedeSEO_Pro_License::is_pro()) return $tag;

        if (is_string($tag) && get_post_meta(get_the_ID(), '_fajaedeseo_pro_font_swap', true)) {
            if (strpos($tag, 'fonts.googleapis.com') !== false && strpos($tag, 'display=swap') === false) {
                $tag = preg_replace('/href=(["\'])(.*?fonts\.googleapis\.com.*?)\1/', 'href=$1$2&display=swap$1', $tag);
            }
        }
        return $tag;
    }

    public function detect_seo_plugin_conflicts() {
        if (!current_user_can('manage_options')) {
            return;
        }

        if (get_transient('fajaedeseo_dismiss_conflict_notice')) {
            return;
        }

        if (get_option('fajaedeseo_disable_schema', '0') === '1') {
            return;
        }

        $conflict_plugin = '';
        if (defined('WPSEO_VERSION')) {
            $conflict_plugin = 'Yoast SEO';
        } elseif (class_exists('RankMath')) {
            $conflict_plugin = 'Rank Math SEO';
        } elseif (class_exists('AIOSEO\Plugin\AIOSEO') || defined('AIOSEO_VERSION')) {
            $conflict_plugin = 'All in One SEO';
        } elseif (defined('SEOPRESS_VERSION')) {
            $conflict_plugin = 'SEOPress';
        } elseif (defined('THE_SEO_FRAMEWORK_VERSION')) {
            $conflict_plugin = 'The SEO Framework';
        }

        if (!empty($conflict_plugin)) {
            $disable_schema_url = wp_nonce_url(admin_url('admin-post.php?action=fajaedeseo_disable_schema'), 'fajaedeseo_disable_schema_nonce');
            $dismiss_url = wp_nonce_url(admin_url('admin-post.php?action=fajaedeseo_dismiss_conflict_notice'), 'fajaedeseo_dismiss_notice_nonce');
            
            ?>
            <div class="notice notice-warning" style="border-left-color: #ffb900;">
                <p><strong><?php esc_html_e('FajaedeSEO: SEO Plugin Conflict Detected', 'fajaedeseo-ai'); ?></strong></p>
                <p>
                    <?php 
                    /* translators: %s: Name of the conflicting SEO plugin */
                    printf(esc_html__('We see that %s is active. Running two SEO plugins that both output Schema data can confuse Google and harm your rankings.', 'fajaedeseo-ai'), '<strong>' . esc_html($conflict_plugin) . '</strong>'); 
                    ?>
                </p>
                <p>
                    <a href="<?php echo esc_url($disable_schema_url); ?>" class="button button-primary"><?php esc_html_e('Disable FajaedeSEO Schema', 'fajaedeseo-ai'); ?></a>
                    <a href="<?php echo esc_url(admin_url('plugins.php')); ?>" class="button"><?php 
                        /* translators: %s: Name of the conflicting SEO plugin */
                        printf(esc_html__('Go to Plugins to Deactivate %s', 'fajaedeseo-ai'), esc_html($conflict_plugin)); 
                    ?></a>
                    <a href="<?php echo esc_url($dismiss_url); ?>" style="text-decoration: none; margin-left: 10px;"><?php esc_html_e('Dismiss for 30 days', 'fajaedeseo-ai'); ?></a>
                </p>
            </div>
            <?php
        }
    }

    public function handle_disable_schema_action() {
        if (!current_user_can('manage_options')) wp_die('Unauthorized');
        check_admin_referer('fajaedeseo_disable_schema_nonce');
        update_option('fajaedeseo_disable_schema', '1');
        wp_safe_redirect(wp_get_referer() ? wp_get_referer() : admin_url('admin.php?page=fajaedeseo-seo'));
        exit;
    }

    public function handle_dismiss_conflict_notice() {
        if (!current_user_can('manage_options')) wp_die('Unauthorized');
        check_admin_referer('fajaedeseo_dismiss_notice_nonce');
        set_transient('fajaedeseo_dismiss_conflict_notice', '1', 30 * DAY_IN_SECONDS);
        wp_safe_redirect(wp_get_referer() ? wp_get_referer() : admin_url('admin.php?page=fajaedeseo-seo'));
        exit;
    }

    public function inject_tracking_script() {
        // Track geen ingelogde beheerders om de statistieken zuiver te houden
        if (is_user_logged_in() && current_user_can('manage_options')) return;
        ?>
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            // SessionStorage zorgt dat we een bezoeker maar 1x per browsersessie tellen
            if (!sessionStorage.getItem('fseo_tracked')) {
                fetch('<?php echo esc_url(rest_url('fajaedeseo/v1/track-visitor')); ?>', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ url: window.location.href })
                }).then(() => {
                    sessionStorage.setItem('fseo_tracked', '1');
                }).catch(e => console.error('FajaedeSEO Tracking failed', e));
            }
        });
        </script>
        <?php
    }
}
