<?php
/**
 * Plugin Name: AI SEO Automation – AYSA
 * Plugin URI: https://aysa.ai
 * Description: Get more clients from Google automatically. AYSA handles your SEO through a simple chat — content, optimization, and growth included.
 * Version: 1.3.81
 * Author: Aysa.ai
 * Author URI: https://aysa.ai
 * License: GPL v2
 * Text Domain: aysa
 */

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

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

// 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', true);
}

if (!function_exists('aysa_debug_log')) {
    function aysa_debug_log($message) {
        if (defined('AYSA_DEBUG') && AYSA_DEBUG) {
            error_log((string) $message);
        }
    }
}

// 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 updater class
require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-updater.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 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 run_aysa() {
    // 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);
    run_aysa();
    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();
    }
}

// Initialize the simplified updater - based on Adverlink approach
function aysa_init_updater() {
    // Prevent multiple updater initializations
    static $updater_initialized = false;
    
    if ($updater_initialized) {
        return;
    }
    
    $updater = new Aysa_Updater(
        AYSA_PLUGIN_FILE,
        Aysa_API_Config::get_endpoint_url('version_check')
    );
    
    // Store updater instance globally
    $GLOBALS['aysa_updater'] = $updater;
    
    $updater_initialized = true;
}
add_action('plugins_loaded', 'aysa_init_updater');

// Add admin action to force update check
add_action('wp_ajax_aysa_force_update_check', 'aysa_force_update_check_callback');

function aysa_force_update_check_callback() {
    if (!current_user_can('manage_options')) {
        wp_send_json_error('Insufficient permissions');
        return;
    }
    $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash((string) $_POST['nonce'])) : '';
    if ($nonce === '' || !wp_verify_nonce($nonce, 'aysa_force_update_check')) {
        wp_send_json_error('Invalid nonce');
        return;
    }
    
    if (isset($GLOBALS['aysa_updater'])) {
        $GLOBALS['aysa_updater']->force_update_check();
        wp_send_json_success('Update check forced successfully');
    } else {
        wp_send_json_error('Updater not initialized');
    }
}

// Add update notice to force clear cache if needed
add_action('admin_notices', 'aysa_show_update_notice');

function aysa_show_update_notice() {
    $screen = get_current_screen();
    if ($screen && $screen->id === 'plugins' && current_user_can('manage_options')) {
        // Check if we have an update available but it's not showing
        if (isset($GLOBALS['aysa_updater'])) {
            $remote_info = $GLOBALS['aysa_updater']->get_plugin_metadata_from_api();
            if ($remote_info && version_compare(AYSA_VERSION, $remote_info->new_version, '<')) {
                $update_plugins = get_site_transient('update_plugins');
                $plugin_basename = plugin_basename(AYSA_PLUGIN_FILE);
                if (!isset($update_plugins->response[$plugin_basename])) {
                    echo '<div class="notice notice-info is-dismissible">';
                    echo '<p><strong>Aysa Plugin:</strong> An update is available but not visible. ';
                    echo '<a href="#" onclick="aysaForceUpdateCheck(); return false;">Click here to refresh update check</a></p>';
                    echo '</div>';
                    
                    echo '<script>
                    function aysaForceUpdateCheck() {
                        jQuery.post(ajaxurl, {
                            action: "aysa_force_update_check",
                            nonce: "' . esc_js(wp_create_nonce('aysa_force_update_check')) . '"
                        }, function(response) {
                            if (response.success) {
                                location.reload();
                            } else {
                                var message = "Update check failed.";
                                if (response && response.data) {
                                    message = (typeof response.data === "string") ? response.data : JSON.stringify(response.data);
                                }
                                alert(message);
                            }
                        });
                    }
                    </script>';
                }
            }
        }
    }
}

/**
 * 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;
    $page = isset($_GET['page']) ? sanitize_key((string) $_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') {
            $taxonomy = isset($_GET['taxonomy']) ? sanitize_key((string) $_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');
    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);
    
    // Enqueue media script
    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,
        'auth_token' => get_option('aysa_auth_token', ''),
        '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,
        'auth_token' => get_option('aysa_auth_token', ''),
        'site_url' => get_site_url(),
        'language_optimize' => $current_language_optimize,
        'global_language_optimize' => $global_language_fallback,
        'api_config' => Aysa_API_Config::get_js_config()
    ));
    
    // Also localize the media script
    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,
        'auth_token' => get_option('aysa_auth_token', ''),
        '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;
    $page = isset($_GET['page']) ? sanitize_key((string) $_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') {
            $taxonomy = isset($_GET['taxonomy']) ? sanitize_key((string) $_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(wp_unslash((string) $_POST['nonce'])) : '';
    if (!wp_verify_nonce($nonce, 'aysa_setup_nonce')) {
        wp_die(__('Security check failed', 'aysa'));
    }
    
    // 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');
    aysa_debug_log('Request keys: ' . implode(',', array_keys($_POST)));
    
    // Verify nonce
    $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash((string) $_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(wp_unslash((string) $_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(wp_unslash((string) $_POST['nonce'])) : '';
    if (!wp_verify_nonce($provided_nonce, 'aysa_cron_nonce')) {
        wp_send_json_error(__('Nonce verification failed', 'aysa'));
        return;
    }
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error(__('Insufficient permissions', 'aysa'));
        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() {
    // 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();
    
    // 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');
    
    // Flush rewrite rules
    flush_rewrite_rules();
}
