<?php
/**
 * Plugin Name: AI SEO Automation - AYSA
 * Description: Guided SEO research, technical review, on-page and off-page planning, and monitoring with explicit approvals for costs and site changes.
 * Version: 1.5.1
 * Requires at least: 5.9
 * Requires PHP: 8.0
 * WC requires at least: 10.9
 * WC tested up to: 11.0
 * Author: Aysa.ai
 * Author URI: https://aysa.ai
 * License: GPLv2 or later
 * License URI: http://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: aysaaiseo
 */

// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

function aysa_block_network_wide_activation() {
    wp_die(
        esc_html__('AYSA AI SEO does not support network-wide activation. Activate it separately on each site in the network.', 'aysaaiseo'),
        esc_html__('AYSA AI SEO activation', 'aysaaiseo'),
        array('back_link' => true)
    );
}

// WordPress includes the plugin before it invokes the activation hook. Refuse
// network activation during that sandbox include so bootstrap cannot create
// site-scoped tables, schedules, authentication, project, or Wallet state.
if (
    is_multisite()
    && defined('WP_SANDBOX_SCRAPING')
    && WP_SANDBOX_SCRAPING
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- WordPress core validates network activation before setting this sandbox marker.
    && isset($_GET['networkwide'])
) {
    aysa_block_network_wide_activation();
}

// Define plugin constants first
define('AYSA_VERSION', '1.5.1');
define('AYSA_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('AYSA_PLUGIN_URL', plugin_dir_url(__FILE__));
define('AYSA_PLUGIN_FILE', __FILE__);

if (!defined('AYSA_RELEASE_CHANNEL')) {
    // WordPress.org receives the stable public package. Existing private
    // cohorts can retain an explicit channel through their environment.
    define('AYSA_RELEASE_CHANNEL', getenv('AYSA_RELEASE_CHANNEL') ?: 'stable');
}

if (!defined('AYSA_BUILD_HASH')) {
    define('AYSA_BUILD_HASH', getenv('AYSA_BUILD_HASH') ?: ('local-' . AYSA_VERSION));
}

if (!defined('AYSA_PUBLIC_DISPLAY_VERSION')) {
    define('AYSA_PUBLIC_DISPLAY_VERSION', 'AYSA v1.5');
}

if (!defined('AYSA_API_EXPECTED_VERSION')) {
    define('AYSA_API_EXPECTED_VERSION', getenv('AYSA_API_EXPECTED_VERSION') ?: '');
}

if (!defined('AYSA_PUBLIC_BETA_SAFETY_MODE')) {
    define('AYSA_PUBLIC_BETA_SAFETY_MODE', true);
}

if (!defined('AYSA_SHOW_LEGACY_ADMIN_MENUS')) {
    define('AYSA_SHOW_LEGACY_ADMIN_MENUS', false);
}

if (!defined('AYSA_ADVERLINK_ORDERING_ENABLED')) {
    define('AYSA_ADVERLINK_ORDERING_ENABLED', false);
}

if (!defined('AYSA_OFFPAGE_EXTERNAL_WRITES_ENABLED')) {
    define('AYSA_OFFPAGE_EXTERNAL_WRITES_ENABLED', false);
}

if (!defined('AYSA_GBP_WRITES_ENABLED')) {
    define('AYSA_GBP_WRITES_ENABLED', false);
}

if (!defined('AYSA_TECHNICAL_DESTRUCTIVE_WRITES_ENABLED')) {
    define('AYSA_TECHNICAL_DESTRUCTIVE_WRITES_ENABLED', false);
}

if (!defined('AYSA_RAG_SITE_KNOWLEDGE_FULL_INGESTION_ENABLED')) {
    define('AYSA_RAG_SITE_KNOWLEDGE_FULL_INGESTION_ENABLED', false);
}

if (!defined('AYSA_AI_VISIBILITY_ENABLED')) {
    define('AYSA_AI_VISIBILITY_ENABLED', false);
}

if (!function_exists('aysa_release_metadata')) {
    function aysa_release_metadata() {
        return array(
            'display_name' => AYSA_PUBLIC_DISPLAY_VERSION,
            'plugin_version' => AYSA_VERSION,
            'build_hash' => AYSA_BUILD_HASH,
            'release_channel' => AYSA_RELEASE_CHANNEL,
            'api_expected_version' => AYSA_API_EXPECTED_VERSION,
            'public_beta_safety_mode' => (bool) AYSA_PUBLIC_BETA_SAFETY_MODE,
        );
    }
}

/**
 * Resolve the UI language selected in the canonical Agent8 session.
 *
 * The interface language is intentionally independent from the website
 * content language and WordPress locale. Until a user has selected a language
 * in Agent8, the existing product default remains Romanian.
 *
 * @param int $user_id Optional WordPress user id for deterministic readback.
 * @return string Normalized language tag.
 */
if (!function_exists('aysa_get_interface_language')) {
    function aysa_get_interface_language($user_id = 0) {
        $user_id = intval($user_id);
        if ($user_id <= 0 && function_exists('get_current_user_id')) {
            $user_id = intval(get_current_user_id());
        }
        $site_host = function_exists('home_url') && function_exists('wp_parse_url')
            ? strtolower((string) wp_parse_url(home_url('/'), PHP_URL_HOST))
            : '';
        if ($user_id <= 0 || $site_host === '' || !function_exists('get_user_meta')) {
            return 'ro';
        }

        $key = 'aysa_agent8_session_' . intval($user_id) . '_' . md5($site_host);
        $session = get_user_meta($user_id, $key, true);
        if (!is_array($session)) {
            return 'ro';
        }
        $language = $session['conversation_language']
            ?? $session['state']['meta']['language']
            ?? 'ro';
        $language = str_replace('_', '-', trim((string) $language));
        if ($language === '' || preg_match('/^[a-z]{2}(?:-[a-z]{2})?$/i', $language) !== 1) {
            return 'ro';
        }
        $parts = explode('-', $language, 2);
        return strtolower($parts[0]) . (isset($parts[1]) ? '-' . strtoupper($parts[1]) : '');
    }
}

/**
 * Return shell copy in the current Agent8 interface language.
 * Non-Romanian launch languages use the English product copy.
 */
if (!function_exists('aysa_interface_text')) {
    function aysa_interface_text($romanian, $english) {
        $language = strtolower((string) aysa_get_interface_language());
        return strpos($language, 'ro') === 0 ? (string) $romanian : (string) $english;
    }
}

// Plugin-level debug flag (do not force global WP_DEBUG from plugin code).
if (!defined('AYSA_DEBUG')) {
    define('AYSA_DEBUG', false);
}

if (!defined('AYSA_AGENT8_V3_QA_ENABLED')) {
    define('AYSA_AGENT8_V3_QA_ENABLED', false);
}

if (!function_exists('aysa_debug_log')) {
    function aysa_debug_log($message) {
        if (defined('AYSA_DEBUG') && AYSA_DEBUG) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Opt-in local debugging only; disabled by default and never contains credentials by contract.
            error_log((string) $message);
        }
    }
}

if (!function_exists('aysa_debug_export')) {
    function aysa_debug_export($value, $return = true) {
        $encoded = wp_json_encode($value);
        if (false === $encoded) {
            $encoded = '[unserializable]';
        }

        if ($return) {
            return $encoded;
        }

        echo esc_html($encoded);
    }
}

// Default environment is production. Local API routing is no longer supported.
if (!defined('AYSA_API_ENVIRONMENT')) {
    define('AYSA_API_ENVIRONMENT', 'production');
}

// Include the API configuration
require_once AYSA_PLUGIN_DIR . 'includes/config/aysa-api-config.php';

// Use the centralized API configuration instead of hardcoded URL
define('AYSA_API_BASE_URL', Aysa_API_Config::get_base_url());


if (!function_exists('aysa_is_local_api_lock_enabled')) {
    function aysa_is_local_api_lock_enabled() {
        return false;
    }
}

if (!function_exists('aysa_get_local_api_base')) {
    function aysa_get_local_api_base() {
        $base = rtrim((string) AYSA_API_BASE_URL, '/');
        return $base !== '' ? $base : 'https://api.aysa.ai';
    }
}

function aysa_print_api_runtime_rewrite_script() {
    if (!is_admin() || aysa_is_local_api_lock_enabled()) {
        return;
    }
    echo '';
}
add_action('admin_head', 'aysa_print_api_runtime_rewrite_script', 1);

function aysa_force_local_api_for_wp_http($preempt, $args, $url) {
    return $preempt;
}
add_filter('pre_http_request', 'aysa_force_local_api_for_wp_http', 10, 3);

// Include the main plugin class
require_once AYSA_PLUGIN_DIR . 'includes/class-aysa.php';

// Include the authentication manager
require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-auth-manager.php';
require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-google-oauth-manager.php';
require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-google-business-profile-manager.php';

// Include the cron handler
require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-cron.php';

// Include the support handlers
require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-support-handlers.php';

// Include the SEO history classes
require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-seo-history.php';
require_once AYSA_PLUGIN_DIR . 'admin/class-aysa-seo-history-admin.php';
require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-seo-history-ajax.php';

// Include the association status class
require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-association-status.php';

// Include the sidebar SEO button class
require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-sidebar-seo-button.php';

// Include the AYSA Permalink Handler for AJAX requests
require_once AYSA_PLUGIN_DIR . 'includes/ajax/class-aysa-permalink-handler.php';

// Include the Content Strategy Create Post AJAX handler
require_once AYSA_PLUGIN_DIR . 'includes/ajax/class-aysa-content-strategy-create-post.php';

// Include the Content Strategy Manager
require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-content-strategy-manager.php';

// Include the email approval publisher
require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-content-email-publisher.php';
require_once AYSA_PLUGIN_DIR . 'includes/ai-visibility/class-aysa-ai-visibility-api-client.php';
require_once AYSA_PLUGIN_DIR . 'includes/ai-visibility/class-aysa-ai-visibility-ajax-controller.php';
require_once AYSA_PLUGIN_DIR . 'includes/ai-visibility/class-aysa-ai-visibility-intervention-correlation.php';
require_once AYSA_PLUGIN_DIR . 'includes/ai-visibility/class-aysa-ai-visibility-commerce-snapshot.php';
require_once AYSA_PLUGIN_DIR . 'includes/ai-visibility/class-aysa-ai-visibility-knowledge-snapshot.php';
require_once AYSA_PLUGIN_DIR . 'includes/ai-visibility/class-aysa-ai-visibility-i18n.php';
require_once AYSA_PLUGIN_DIR . 'includes/ai-visibility/class-aysa-ai-visibility-module.php';

// Include the content filter remover
if (file_exists(AYSA_PLUGIN_DIR . 'includes/class-aysa-content-filter-remover.php')) {
    require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-content-filter-remover.php';
    if (defined('WP_DEBUG') && WP_DEBUG) {
        aysa_debug_log('AYSA: Content filter remover file included successfully');
    }
} else {
    if (defined('WP_DEBUG') && WP_DEBUG) {
        aysa_debug_log('AYSA: Content filter remover file not found at: ' . AYSA_PLUGIN_DIR . 'includes/class-aysa-content-filter-remover.php');
    }
}

// Include the global exclusions manager
if (file_exists(AYSA_PLUGIN_DIR . 'includes/class-aysa-global-exclusions.php')) {
    require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-global-exclusions.php';
    if (defined('WP_DEBUG') && WP_DEBUG) {
        aysa_debug_log('AYSA: Global exclusions manager file included successfully');
    }
} else {
    if (defined('WP_DEBUG') && WP_DEBUG) {
        aysa_debug_log('AYSA: Global exclusions manager file not found at: ' . AYSA_PLUGIN_DIR . 'includes/class-aysa-global-exclusions.php');
    }
}

// Schema Generator removed - using frontend implementation

// Include Schema Manager
require_once AYSA_PLUGIN_DIR . 'includes/schema-manager.php';
require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-onpage-workspace.php';

// Include the link purchase manager
if (file_exists(AYSA_PLUGIN_DIR . 'includes/class-aysa-link-purchase-manager.php')) {
    require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-link-purchase-manager.php';
    if (defined('WP_DEBUG') && WP_DEBUG) {
        aysa_debug_log('AYSA: Link purchase manager file included successfully');
    }
} else {
    if (defined('WP_DEBUG') && WP_DEBUG) {
        aysa_debug_log('AYSA: Link purchase manager file not found at: ' . AYSA_PLUGIN_DIR . 'includes/class-aysa-link-purchase-manager.php');
    }
}

// Content Strategy AJAX handler removed - using direct API calls from frontend

// Initialize the plugin
function aysa_run() {
    // Prevent multiple initializations
    static $plugin_instance = null;
    
    if ($plugin_instance === null) {
        $plugin_instance = new Aysa();
        $plugin_instance->run();
        
        // Initialize association status management
        if (class_exists('Aysa_Association_Status')) {
            $association_status = new Aysa_Association_Status();
            $association_status->maybe_create_table();
        }
        
        // Initialize content filter remover to disable WordPress/WooCommerce sanitization
        if (class_exists('Aysa_Content_Filter_Remover')) {
            Aysa_Content_Filter_Remover::init();
            if (defined('WP_DEBUG') && WP_DEBUG) {
                aysa_debug_log('AYSA: Content filter remover initialized successfully');
            }
        } else {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                aysa_debug_log('AYSA: Content filter remover class not found');
            }
        }
    }
    
    return $plugin_instance;
}

// Only initialize if not already done
if (!defined('AYSA_INITIALIZED')) {
    define('AYSA_INITIALIZED', true);
    aysa_run();
    if (class_exists('Aysa_Google_OAuth_Manager')) {
        Aysa_Google_OAuth_Manager::get_instance();
    }
    if (class_exists('Aysa_Google_Business_Profile_Manager')) {
        Aysa_Google_Business_Profile_Manager::get_instance();
    }
    if (class_exists('Aysa_Content_Email_Publisher')) {
        Aysa_Content_Email_Publisher::init();
    }
    if (class_exists('Aysa_AI_Visibility_Module')) {
        Aysa_AI_Visibility_Module::boot();
    }
}

/**
 * Enqueue scripts for admin page
 */
function aysa_enqueue_admin_scripts() {
    // The modern admin asset pipeline is handled by Aysa_Admin::enqueue_scripts/enqueue_styles.
    // Keep this legacy loader dormant to prevent duplicate JS/CSS and conflicting handlers.
    if (class_exists('Aysa_Admin')) {
        return;
    }

    $screen = function_exists('get_current_screen') ? get_current_screen() : null;
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reviewed callback inventory: this read-only/core lifecycle request is authenticated by WordPress or an enclosing guard and performs no unapproved write.
    $page = isset($_GET['page']) ? sanitize_key((string) wp_unslash($_GET['page'])) : '';
    $is_aysa_page = (strpos($page, 'aysa') === 0)
        || ($screen && isset($screen->id) && is_string($screen->id) && strpos($screen->id, 'aysa') !== false);

    $is_supported_editor = false;
    if ($screen && isset($screen->base) && is_string($screen->base)) {
        if ($screen->base === 'post' && isset($screen->post_type)) {
            $is_supported_editor = in_array((string) $screen->post_type, array('post', 'page', 'product'), true);
        } elseif ($screen->base === 'term') {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reviewed callback inventory: this read-only/core lifecycle request is authenticated by WordPress or an enclosing guard and performs no unapproved write.
            $taxonomy = isset($_GET['taxonomy']) ? sanitize_key((string) wp_unslash($_GET['taxonomy'])) : '';
            $is_supported_editor = in_array($taxonomy, array('category', 'product_cat'), true);
        }
    }

    if (!$is_aysa_page && !$is_supported_editor) {
        return;
    }

    // Enqueue admin styles
    wp_enqueue_style('aysa-admin', plugin_dir_url(__FILE__) . 'admin/css/aysa-admin.css', array(), AYSA_VERSION);
    wp_enqueue_style('aysa-ui-core', plugin_dir_url(__FILE__) . 'assets/css/aysa-ui-core.css', array('aysa-admin'), AYSA_VERSION);
    
    // Enqueue jQuery UI and Dialog
    wp_enqueue_script('jquery-ui-core');
    wp_enqueue_script('jquery-ui-dialog');
    
    // Enqueue admin script
    wp_enqueue_script('aysa-admin', plugin_dir_url(__FILE__) . 'admin/js/aysa-admin.js', array('jquery'), AYSA_VERSION, true);
    
    // Enqueue keywords script
    wp_enqueue_script('aysa-keywords', plugin_dir_url(__FILE__) . 'assets/js/aysa-admin.js', array('jquery'), AYSA_VERSION, true);
    
    if (!class_exists('Aysa_Media')) {
        require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-media.php';
    }
    // The legacy direct media generator is local-QA-only. Production Image
    // ALT is available through the canonical Agent8 approval/billing lane.
    $aysa_legacy_media_alt_enabled = Aysa_Media::legacy_alt_generator_enabled();
    if ($aysa_legacy_media_alt_enabled) {
        wp_enqueue_script('aysa-media', plugin_dir_url(__FILE__) . 'assets/js/aysa-media.js', array('jquery', 'jquery-ui-dialog'), AYSA_VERSION, true);
    }
    
    // Enqueue actions script for SEO suggestions and redirects
    wp_enqueue_script('aysa-actions', plugin_dir_url(__FILE__) . 'admin/js/aysa-actions.js', array('jquery'), AYSA_VERSION, true);
    
    // Enqueue SEO history scripts
    wp_enqueue_script('aysa-seo-history', plugin_dir_url(__FILE__) . 'assets/js/aysa-seo-history.js', array('jquery'), AYSA_VERSION, true);
    wp_enqueue_script('aysa-seo-generator-core', plugin_dir_url(__FILE__) . 'assets/js/aysa-seo-generator-core.js', array('jquery', 'aysa-actions'), AYSA_VERSION, true);
    wp_enqueue_script('aysa-seo-generator', plugin_dir_url(__FILE__) . 'assets/js/aysa-seo-generator.js', array('jquery', 'aysa-seo-generator-core'), AYSA_VERSION, true);
    wp_enqueue_script('aysa-seo-integration', plugin_dir_url(__FILE__) . 'assets/js/aysa-seo-integration.js', array('jquery', 'aysa-seo-generator-core'), AYSA_VERSION, true);
    
    // Localize script with AJAX URL
    wp_localize_script('aysa-admin', 'aysa_ajax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'admin_url' => admin_url(),
        'nonce' => wp_create_nonce('aysa-ajax-nonce'),
        'api_base_url' => AYSA_API_BASE_URL,
        'site_url' => get_site_url(),
        'api_config' => Aysa_API_Config::get_js_config()
    ));
    
    // Localize SEO history script with AJAX data
    wp_localize_script('aysa-seo-history', 'aysaSeoHistoryAjax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('aysa_seo_history_nonce'),
        'user_id' => get_current_user_id(),
        'user_name' => wp_get_current_user()->display_name,
        'site_url' => get_site_url()
    ));
    
    // Instantiate Aysa_Media to get language settings
    if (!class_exists('Aysa_Media')) {
        require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-media.php';
    }
    $aysa_media_instance = Aysa_Media::get_instance();
    $current_language_optimize = $aysa_media_instance->get_context_language_optimize(); // Folosește direct metoda publică
    $global_language_fallback = $aysa_media_instance->get_global_language_optimize(); // Folosește direct metoda publică

    // Also localize the actions script with the same data
    wp_localize_script('aysa-actions', 'aysaParams', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'admin_url' => admin_url(),
        'nonce' => wp_create_nonce('aysa-ajax-nonce'),
        'api_base_url' => AYSA_API_BASE_URL,
        'site_url' => get_site_url(),
        'language_optimize' => $current_language_optimize,
        'global_language_optimize' => $global_language_fallback,
        'api_config' => Aysa_API_Config::get_js_config()
    ));
    
    if ($aysa_legacy_media_alt_enabled) {
        wp_localize_script('aysa-media', 'aysa_ajax', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('aysa_nonce'),
            'api_base_url' => AYSA_API_BASE_URL,
            'api_config' => Aysa_API_Config::get_js_config()
        ));
    }
}
add_action('admin_enqueue_scripts', 'aysa_enqueue_admin_scripts');

function aysa_add_admin_ui_body_class($classes) {
    $screen = function_exists('get_current_screen') ? get_current_screen() : null;
    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reviewed callback inventory: this read-only/core lifecycle request is authenticated by WordPress or an enclosing guard and performs no unapproved write.
    $page = isset($_GET['page']) ? sanitize_key((string) wp_unslash($_GET['page'])) : '';
    $is_aysa_page = (strpos($page, 'aysa') === 0)
        || ($screen && isset($screen->id) && is_string($screen->id) && strpos($screen->id, 'aysa') !== false);

    $is_supported_editor = false;
    if ($screen && isset($screen->base) && is_string($screen->base)) {
        if ($screen->base === 'post' && isset($screen->post_type)) {
            $is_supported_editor = in_array((string) $screen->post_type, array('post', 'page', 'product'), true);
        } elseif ($screen->base === 'term') {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reviewed callback inventory: this read-only/core lifecycle request is authenticated by WordPress or an enclosing guard and performs no unapproved write.
            $taxonomy = isset($_GET['taxonomy']) ? sanitize_key((string) wp_unslash($_GET['taxonomy'])) : '';
            $is_supported_editor = in_array($taxonomy, array('category', 'product_cat'), true);
        }
    }

    if ($is_aysa_page || $is_supported_editor) {
        $classes .= ' aysa-admin-ui';
    }

    return $classes;
}
add_filter('admin_body_class', 'aysa_add_admin_ui_body_class');

// Register AJAX actions
add_action('wp_ajax_aysa_get_items', 'aysa_get_items_callback');
add_action('wp_ajax_aysa_trigger_cron_processing', 'aysa_trigger_cron_processing_callback');
add_action('wp_head', 'aysa_output_google_site_verification_meta', 1);

// AJAX handler to mark setup as completed
add_action('wp_ajax_aysa_mark_setup_completed', 'aysa_mark_setup_completed_callback');

function aysa_mark_setup_completed_callback() {
    // Verify nonce
    $nonce = isset($_POST['nonce']) ? sanitize_text_field((string) wp_unslash($_POST['nonce'])) : '';
    if (!wp_verify_nonce($nonce, 'aysa_setup_nonce')) {
        wp_die(esc_html__('Security check failed', 'aysaaiseo'));
    }

    if (!current_user_can('manage_options')) {
        wp_send_json_error(esc_html__('Insufficient permissions', 'aysaaiseo'), 403);
        return;
    }
    
    // Mark setup as completed
    update_option('aysa_setup_completed', true);
    
    wp_send_json_success(array('message' => 'Setup marked as completed'));
}

/**
 * Output Google Search Console ownership verification meta tag.
 * Keep this tag in <head> while the property needs verification continuity.
 */
function aysa_output_google_site_verification_meta() {
    if (is_admin()) {
        return;
    }

    $verification_token = (string) get_option('aysa_google_site_verification_token', '');
    if ($verification_token === '') {
        return;
    }
    echo '<meta name="google-site-verification" content="' . esc_attr($verification_token) . '" />' . "\n";
}

function aysa_get_items_callback() {
    // Debug log
    aysa_debug_log('aysa_get_items_callback called');
    // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Reviewed callback inventory: this request read is downstream of the handler nonce and capability guard, a shared guarded delegate, or the authenticated WordPress core save/query flow.
    aysa_debug_log('Request keys: ' . implode(',', array_keys($_POST)));
    
    // Verify nonce
    $nonce = isset($_POST['nonce']) ? sanitize_text_field((string) wp_unslash($_POST['nonce'])) : '';
    if ($nonce === '' || !wp_verify_nonce($nonce, 'aysa_get_items_nonce')) {
        aysa_debug_log('Nonce verification failed');
        wp_send_json_error('Nonce verification failed');
        return;
    }
    
    $type = isset($_POST['type']) ? sanitize_text_field((string) wp_unslash($_POST['type'])) : '';
    aysa_debug_log('Requested type: ' . $type);
    
    $items = array();
    
    switch($type) {
        case 'Category':
            // Get WooCommerce categories
            $terms = get_terms(array(
                'taxonomy' => 'product_cat',
                'hide_empty' => false,
            ));
            
            if (is_wp_error($terms)) {
                aysa_debug_log('Error getting categories: ' . $terms->get_error_message());
                wp_send_json_error('Error getting categories');
                return;
            }
            
            foreach($terms as $term) {
                $term_link = get_term_link($term);
                $term_url = !is_wp_error($term_link) ? $term_link : '';
                $items[] = array(
                    'id' => $term->term_id,
                    'name' => $term->name,
                    'url' => $term_url,
                    'slug' => $term->slug,
                    'description' => wp_strip_all_tags((string) $term->description)
                );
            }
            break;
            
        case 'Product':
            // Get WooCommerce products
            $args = array(
                'post_type' => 'product',
                'posts_per_page' => -1,
                'post_status' => 'publish'
            );
            $products = get_posts($args);
            
            if (!is_array($products)) {
                aysa_debug_log('Error getting products');
                wp_send_json_error('Error getting products');
                return;
            }
            
            foreach($products as $product) {
                $items[] = array(
                    'id' => $product->ID,
                    'name' => $product->post_title,
                    'url' => get_permalink($product->ID),
                    'slug' => $product->post_name,
                    'description' => wp_strip_all_tags(wp_trim_words((string) $product->post_content, 40, ''))
                );
            }
            break;
            
        case 'Page':
            // Get WordPress pages
            $args = array(
                'post_type' => 'page',
                'posts_per_page' => -1,
                'post_status' => 'publish'
            );
            $pages = get_posts($args);
            
            if (!is_array($pages)) {
                aysa_debug_log('Error getting pages');
                wp_send_json_error('Error getting pages');
                return;
            }
            
            foreach($pages as $page) {
                $items[] = array(
                    'id' => $page->ID,
                    'name' => $page->post_title,
                    'url' => get_permalink($page->ID),
                    'slug' => $page->post_name,
                    'description' => wp_strip_all_tags(wp_trim_words((string) $page->post_content, 40, ''))
                );
            }
            break;
            
        default:
            aysa_debug_log('Invalid type requested: ' . $type);
            wp_send_json_error('Invalid type requested');
            return;
    }
    
    aysa_debug_log('Sending response with ' . count($items) . ' items');
    wp_send_json_success($items);
}

/**
 * AJAX callback to trigger cron processing manually
 */
function aysa_trigger_cron_processing_callback() {
    // Verify nonce
    $provided_nonce = isset($_POST['nonce']) ? sanitize_text_field((string) wp_unslash($_POST['nonce'])) : '';
    if (!wp_verify_nonce($provided_nonce, 'aysa_cron_nonce')) {
        wp_send_json_error(__('Nonce verification failed', 'aysaaiseo'));
        return;
    }
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('Insufficient permissions', 'aysaaiseo'));
        return;
    }
    
    try {
        do_action('aysa_process_association_tasks');
        wp_send_json_success('Association processing triggered successfully');
    } catch (Exception $e) {
        aysa_debug_log('[AYSA CRON] Manual trigger error: ' . $e->getMessage());
        wp_send_json_error('Error triggering cron processing: ' . $e->getMessage());
    }
}

register_activation_hook(__FILE__, 'aysa_activate');
register_deactivation_hook(__FILE__, 'aysa_deactivate');

function aysa_activate($network_wide = false) {
    if (is_multisite() && $network_wide) {
        aysa_block_network_wide_activation();
    }

    // Create necessary database tables
    require_once plugin_dir_path(__FILE__) . 'includes/class-aysa-seo-history.php';
    $seo_history = new Aysa_Seo_History();
    $seo_history->create_table();

    require_once plugin_dir_path(__FILE__) . 'includes/class-aysa-wallet-manager.php';
    Aysa_Wallet_Manager::activate();

    require_once plugin_dir_path(__FILE__) . 'includes/class-aysa-internal-linking-workspace.php';
    Aysa_Internal_Linking_Workspace::maybe_upgrade_schema();
    
    // Initialize automation manager and schedule tasks
    require_once plugin_dir_path(__FILE__) . 'includes/automation/class-aysa-automation-manager.php';
    $automation_manager = new Aysa_Automation_Manager();
    $automation_manager->schedule_automation_tasks();
    
    // Flush rewrite rules
    flush_rewrite_rules();
}

function aysa_deactivate() {
    // Clear scheduled tasks
    wp_clear_scheduled_hook('aysa_automated_seo_generation');
    wp_clear_scheduled_hook('aysa_daily_automation_cleanup');
    wp_clear_scheduled_hook('aysa_wallet_sync_cron');
    if (class_exists('Aysa_Content_Email_Publisher')) {
        Aysa_Content_Email_Publisher::deactivate();
    }
    
    // Flush rewrite rules
    flush_rewrite_rules();
}
