<?php
if (!defined('ABSPATH')) {
    exit;
}


class Aysa {
    protected $loader;
    protected $plugin_name;
    protected $version;
    
    // Define plugin constants
    const PLUGIN_ID = 'aysa';

    public function __construct() {
        $this->plugin_name = 'aysa';
        $this->version = AYSA_VERSION;
        
        $this->load_dependencies();
        $this->define_admin_hooks();
        $this->define_public_hooks();
        $this->define_ajax_hooks();
    }

    private function load_dependencies() {
        // Load required files
        require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-loader.php';
        require_once AYSA_PLUGIN_DIR . 'admin/class-aysa-admin.php';
        require_once AYSA_PLUGIN_DIR . 'public/class-aysa-public.php';
        
        // Load the product metabox controller
        require_once AYSA_PLUGIN_DIR . 'includes/controllers/admin/class-product-metabox.php';
        
        // Load the keywords controller
        require_once AYSA_PLUGIN_DIR . 'includes/controllers/admin/class-keywords.php';

        // Load Agent8 V3 admin proxy controller
        require_once AYSA_PLUGIN_DIR . 'includes/controllers/admin/class-agent8-v3-proxy-controller.php';

        // Load API projection sync controller
        require_once AYSA_PLUGIN_DIR . 'includes/controllers/admin/class-projection-sync-controller.php';

        // Load Monitoring admin controller
        require_once AYSA_PLUGIN_DIR . 'includes/controllers/admin/class-monitoring-admin-controller.php';

        // Load Off Page admin controller
        require_once AYSA_PLUGIN_DIR . 'includes/controllers/admin/class-offpage-admin-controller.php';
        
        // Load the media handling class
        require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-media.php';
        
        // Load the meta tags class
        require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-seo-backend-adapter.php';
        require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-meta-tags.php';
        
        // Load the structured data class (DISABLED - manual schema only)
        // require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-structured-data.php';
        
        // Load optimization metrics class
        require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-optimization-metrics.php';
        
        require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-audit-logger.php';
        require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-error-center.php';
        require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-confidence-scorer.php';
        require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-automation-reporter.php';
        require_once AYSA_PLUGIN_DIR . 'includes/config/aysa-automation-config.php';
        require_once AYSA_PLUGIN_DIR . 'includes/config/aysa-api-config.php';
        require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-wallet-manager.php';
        
        // Load automation framework
        if (file_exists(AYSA_PLUGIN_DIR . 'includes/automation/class-aysa-automation-manager.php')) {
            require_once AYSA_PLUGIN_DIR . 'includes/automation/class-aysa-automation-manager.php';
        }
        
        // Load the credits component
        $components_file = AYSA_PLUGIN_DIR . 'includes/components/class-aysa-credits-component.php';
        if (file_exists($components_file)) {
            require_once $components_file;
        } else {
            // Log error or create directory if needed
            $components_dir = AYSA_PLUGIN_DIR . 'includes/components';
            if (!file_exists($components_dir)) {
                wp_mkdir_p($components_dir);
            }
        }
        
        // Load the credit analytics AJAX handler
        require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-credit-analytics-ajax.php';
        Aysa_Wallet_Manager::get_instance();
        
        // Load the Elementor handler
        require_once AYSA_PLUGIN_DIR . 'includes/class-aysa-elementor-handler.php';

        // Include the internationalization file
        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-aysa-i18n.php';

        // Include the 404 tracker file
        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-aysa-404-tracker.php';
        
        // Include the banned keywords manager
        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-aysa-banned-keywords-manager.php';
        
        // Include the internal linking system
        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-aysa-internal-linking.php';
        require_once plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-aysa-internal-linking-workspace.php';
        
        // Initialize internal linking - needed for AJAX handlers in admin too
        new Aysa_Internal_Linking();
        
        // Include debug script for internal linking (remove in production)
        // Disabled - causes button conflicts
        // require_once plugin_dir_path( dirname( __FILE__ ) ) . 'test-internal-linking-debug.php';

        $this->loader = new Aysa_Loader();
    }

    private function define_admin_hooks() {
        // First, make the admin object globally accessible
        global $aysa_admin;
        
        // Create the admin object
        $plugin_admin = new Aysa_Admin($this->get_plugin_name(), $this->get_version());
        
        // Set the global variable
        $aysa_admin = $plugin_admin;

        // Add admin menu
        $this->loader->add_action('admin_menu', $plugin_admin, 'add_plugin_admin_menu');
        
        // Register admin styles and scripts
        $this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_styles');
        $this->loader->add_action('admin_enqueue_scripts', $plugin_admin, 'enqueue_scripts');
        
        // Initialize the product metabox controller
        $product_metabox = new Product_Metabox();
        
        // Initialize the keywords controller
        $keywords_controller = new Keywords_Controller();
        
        // Initialize the credit analytics AJAX handler
        new Aysa_Credit_Analytics_Ajax();
        
        // Initialize the sidebar SEO button
        new Aysa_Sidebar_Seo_Button();
    }

    private function define_public_hooks() {
        $plugin_public = new Aysa_Public($this->get_plugin_name(), $this->get_version());

        // Register public styles and scripts
        $this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_styles');
        $this->loader->add_action('wp_enqueue_scripts', $plugin_public, 'enqueue_scripts');
        $this->loader->add_action('wp_head', $plugin_public, 'print_seo_appendix_styles');
        $this->loader->add_filter('the_content', $plugin_public, 'append_seo_appendix_to_content', 99);
        $this->loader->add_action('wp_footer', $plugin_public, 'render_seo_appendix_footer', 99);
        // Handle front-end 301 redirects with high priority (before WP canonical redirect)
        $this->loader->add_action('template_redirect', $plugin_public, 'handle_frontend_redirect', 1);
        // Disable WP canonical redirects (to allow plugin to intercept index.php URLs)
        $this->loader->add_filter('redirect_canonical', $plugin_public, 'disable_canonical_redirect');
    }

    /**
     * Register the AJAX handlers needed for the plugin
     *
     * @since    1.0.0
     * @access   private
     */
    private function define_ajax_hooks() {
        // Existing AJAX hooks
        
        // Add new AJAX hooks for dropdown functionality
        add_action('wp_ajax_aysa_get_categories', array($this, 'ajax_get_categories'));
        add_action('wp_ajax_aysa_assign_category', array($this, 'ajax_assign_category'));

        // Add AJAX actions for environment management
        add_action('wp_ajax_aysa_save_api_environment', array($this, 'save_api_environment'));
        add_action('wp_ajax_aysa_test_api_connection', array($this, 'test_api_connection'));
        
        // Add AJAX handlers for entity association
        add_action('wp_ajax_aysa_get_posts', array($this, 'ajax_get_posts'));
        add_action('wp_ajax_aysa_get_pages', array($this, 'ajax_get_pages'));
        add_action('wp_ajax_aysa_get_wp_categories', array($this, 'ajax_get_wp_categories'));
        add_action('wp_ajax_aysa_get_products', array($this, 'ajax_get_products'));
        add_action('wp_ajax_aysa_detect_entity_from_url', array($this, 'ajax_detect_entity_from_url'));
    }

    public function run() {
        $this->loader->run();
        
        // Initialize the 404 error tracker
        $tracker = new Aysa_404_Tracker($this->get_plugin_name(), $this->get_version());
        $tracker->init();
        
        // Initialize the media handling functionality using singleton
        Aysa_Media::get_instance();
        
        // Initialize meta tags as early as possible (before 'init' hook)
        add_action('plugins_loaded', array($this, 'init_meta_tags'), 1);
        
        // Initialize structured data
        add_action('plugins_loaded', array($this, 'init_structured_data'), 2);
        
        // Initialize QA framework
        add_action('plugins_loaded', array($this, 'init_qa_framework'), 3);
        
        // Initialize automation framework
        add_action('plugins_loaded', array($this, 'init_automation_framework'), 4);
        
        // Initialize optimization metrics
        add_action('plugins_loaded', array($this, 'init_optimization_metrics'), 5);
        
        // Initialize SEO history functionality
        add_action('plugins_loaded', array($this, 'init_seo_history'), 6);
        
        // Initialize banned keywords manager
        add_action('plugins_loaded', array($this, 'init_banned_keywords_manager'), 7);
    }

    /**
     * Initialize the meta tags functionality
     */
    public function init_meta_tags() {
        static $meta_tags_initialized = false;
        
        if ($meta_tags_initialized) {
            return;
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log("AYSA SEO: Initializing meta tags class from plugins_loaded hook");
        }

        // Initialize the meta tags functionality
        new Aysa_Meta_Tags();
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log("AYSA SEO: Meta Tags class initialized");
        }
        
        $meta_tags_initialized = true;
    }
    
    /**
     * Initialize the structured data functionality
     */
    public function init_structured_data() {
        static $structured_data_initialized = false;
        
        if ($structured_data_initialized) {
            return;
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log("AYSA SEO: Structured data class DISABLED - manual schema only");
        }
        
        // Initialize the structured data functionality (DISABLED - manual schema only)
        // new AYSA_Structured_Data();
        
        $structured_data_initialized = true;
    }
    
    public function init_qa_framework() {
        static $qa_framework_initialized = false;
        
        if ($qa_framework_initialized) {
            return;
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log("AYSA SEO: Initializing QA framework from plugins_loaded hook");
        }
        
        // Initialize audit logger
        if (class_exists('Aysa_Audit_Logger')) {
            $audit_logger = new Aysa_Audit_Logger();
            $audit_logger->init();
        }
        
        // Initialize confidence scorer
        if (class_exists('Aysa_Confidence_Scorer')) {
            new Aysa_Confidence_Scorer();
        }
        
        // Initialize automation reporter
        if (class_exists('Aysa_Automation_Reporter')) {
            new Aysa_Automation_Reporter();
        }
        
        $qa_framework_initialized = true;
    }
    
    public function init_automation_framework() {
        static $automation_framework_initialized = false;
        
        if ($automation_framework_initialized) {
            return;
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log("AYSA SEO: Initializing automation framework from plugins_loaded hook");
        }
        
        // Initialize automation manager
        if (class_exists('Aysa_Automation_Manager')) {
            $automation_manager = new Aysa_Automation_Manager();
            $automation_manager->init();
        }
        
        $automation_framework_initialized = true;
    }
    
    public function init_optimization_metrics() {
        static $optimization_metrics_initialized = false;
        
        if ($optimization_metrics_initialized) {
            return;
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log("AYSA SEO: Initializing optimization metrics from plugins_loaded hook");
        }
        
        // Initialize optimization metrics calculator
        if (class_exists('Aysa_Optimization_Metrics')) {
            $metrics_calculator = new Aysa_Optimization_Metrics();
            $metrics_calculator->schedule_metrics_tasks();
        }
        
        $optimization_metrics_initialized = true;
    }
    
    public function init_seo_history() {
        static $seo_history_initialized = false;
        
        if ($seo_history_initialized) {
            return;
        }
        
        if (defined('WP_DEBUG') && WP_DEBUG) {
            aysa_debug_log("AYSA SEO: Initializing SEO history from plugins_loaded hook");
        }
        
        // Initialize SEO history database table
        if (class_exists('Aysa_Seo_History')) {
            $seo_history = new Aysa_Seo_History();
            $seo_history->create_table();
        }
        
        // Initialize SEO history admin interface
        if (class_exists('Aysa_Seo_History_Admin') && is_admin()) {
            new Aysa_Seo_History_Admin();
        }
        
        // Initialize SEO history AJAX handlers (both admin and frontend)
        if (class_exists('Aysa_Seo_History_Ajax')) {
            new Aysa_Seo_History_Ajax();
        }
        
        $seo_history_initialized = true;
    }
    
    /**
     * Initialize banned keywords manager
     *
     * @since    1.0.0
     */
    public function init_banned_keywords_manager() {
        static $banned_keywords_initialized = false;
        
        if ($banned_keywords_initialized) {
            aysa_debug_log("AYSA: Banned keywords manager already initialized");
            return;
        }
        
        aysa_debug_log("AYSA: Initializing banned keywords manager from plugins_loaded hook");
        
        // Initialize banned keywords manager
        if (class_exists('Aysa_Banned_Keywords_Manager')) {
            aysa_debug_log("AYSA: Aysa_Banned_Keywords_Manager class found, creating instance");
            $manager = new Aysa_Banned_Keywords_Manager();
            aysa_debug_log("AYSA: Banned keywords manager instance created successfully");
        } else {
            aysa_debug_log("AYSA: ERROR - Aysa_Banned_Keywords_Manager class not found!");
            // Try to include it manually
            $class_file = plugin_dir_path( dirname( __FILE__ ) ) . 'includes/class-aysa-banned-keywords-manager.php';
            if (file_exists($class_file)) {
                aysa_debug_log("AYSA: Trying to manually include: " . $class_file);
                require_once($class_file);
                if (class_exists('Aysa_Banned_Keywords_Manager')) {
                    aysa_debug_log("AYSA: Class loaded successfully after manual include");
                    $manager = new Aysa_Banned_Keywords_Manager();
                    aysa_debug_log("AYSA: Banned keywords manager instance created after manual include");
                } else {
                    aysa_debug_log("AYSA: ERROR - Class still not available after manual include");
                }
            } else {
                aysa_debug_log("AYSA: ERROR - Class file not found at: " . $class_file);
            }
        }
        
        $banned_keywords_initialized = true;
    }

    public function get_plugin_name() {
        return $this->plugin_name;
    }

    public function get_version() {
        return $this->version;
    }
    
    /**
     * Get the plugin url
     * 
     * @return string
     */
    public static function get_plugin_url() {
        return AYSA_PLUGIN_URL;
    }

    /**
     * AJAX handler to get categories for keywords
     *
     * @since    1.0.0
     * @access   public
     */
    public function ajax_get_categories() {
        // Check nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'aysa_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed.'));
        }

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'You do not have permission to perform this action.'));
        }

        // Get keyword ID
        $keyword_id = isset($_POST['keyword_id']) ? intval($_POST['keyword_id']) : 0;
        if (!$keyword_id) {
            wp_send_json_error(array('message' => 'Invalid keyword ID.'));
        }

        // Get categories
        $categories = $this->get_categories_for_dropdown();
        
        wp_send_json_success(array(
            'categories' => $categories,
            'keyword_id' => $keyword_id
        ));
    }

    /**
     * AJAX handler to assign a category to a keyword
     *
     * @since    1.0.0
     * @access   public
     */
    public function ajax_assign_category() {
        // Check nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'aysa_nonce')) {
            wp_send_json_error(array('message' => 'Security check failed.'));
        }

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'You do not have permission to perform this action.'));
        }

        // Get parameters
        $keyword_id = isset($_POST['keyword_id']) ? intval($_POST['keyword_id']) : 0;
        $category_id = isset($_POST['category_id']) ? intval($_POST['category_id']) : 0;

        if (!$keyword_id || !$category_id) {
            wp_send_json_error(array('message' => 'Invalid keyword or category ID.'));
        }

        // Assign category to keyword
        $result = $this->assign_keyword_category($keyword_id, $category_id);
        
        if ($result) {
            wp_send_json_success(array('message' => 'Category assigned successfully.'));
        } else {
            wp_send_json_error(array('message' => 'Failed to assign category.'));
        }
    }

    /**
     * Helper method to get all categories formatted for dropdown
     *
     * @since    1.0.0
     * @access   private
     * @return   array    Array of category objects with id and name
     */
    private function get_categories_for_dropdown() {
        $categories = array();
        
        // Get all categories from the database
        global $wpdb;
        $table_name = $wpdb->prefix . 'aysa_categories';
        
        $results = $wpdb->get_results(
            "SELECT id, name FROM $table_name ORDER BY name ASC",
            ARRAY_A
        );
        
        if ($results) {
            $categories = $results;
        }
        
        return $categories;
    }

    /**
     * Helper method to assign a category to a keyword
     *
     * @since    1.0.0
     * @access   private
     * @param    int       $keyword_id    The keyword ID
     * @param    int       $category_id   The category ID
     * @return   boolean   True on success, false on failure
     */
    private function assign_keyword_category($keyword_id, $category_id) {
        global $wpdb;
        $keywords_table = $wpdb->prefix . 'aysa_keywords';
        
        $result = $wpdb->update(
            $keywords_table,
            array('category_id' => $category_id),
            array('id' => $keyword_id),
            array('%d'),
            array('%d')
        );
        
        return ($result !== false);
    }

    /**
     * AJAX handler to save API environment
     */
    public function save_api_environment() {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'aysa_save_api_environment_nonce')) {
            wp_send_json_error('Nonce verification failed');
            return;
        }
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        $environment = sanitize_text_field($_POST['environment'] ?? '');
        
        if (!$environment || !Aysa_API_Config::set_environment($environment)) {
            wp_send_json_error('Invalid environment specified');
            return;
        }
        
        wp_send_json_success(array(
            'message' => 'API environment saved successfully',
            'environment' => $environment,
            'base_url' => Aysa_API_Config::get_base_url()
        ));
    }
    
    /**
     * AJAX handler to test API connection
     */
    public function test_api_connection() {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'aysa_test_api_connection_nonce')) {
            wp_send_json_error('Nonce verification failed');
            return;
        }
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
            return;
        }
        
        $start_time = microtime(true);
        $base_url = Aysa_API_Config::get_base_url();
        
        // Test the base URL
        $response = wp_remote_get($base_url, array(
            'timeout' => 10,
            'sslverify' => false
        ));
        
        $end_time = microtime(true);
        $response_time = round(($end_time - $start_time) * 1000);
        
        if (is_wp_error($response)) {
            wp_send_json_error('Connection failed: ' . $response->get_error_message());
            return;
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        
        if ($status_code >= 200 && $status_code < 300) {
            wp_send_json_success(array(
                'message' => 'Connection successful',
                'environment' => Aysa_API_Config::get_environment(),
                'base_url' => $base_url,
                'status_code' => $status_code,
                'response_time' => $response_time
            ));
        } else {
            wp_send_json_error('Server responded with status code: ' . $status_code);
        }
    }
    
    /**
     * AJAX handler to get posts for entity association
     */
    public function ajax_get_posts() {
        // Check nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'aysa_get_posts_nonce')) {
            wp_send_json_error('Security check failed');
        }

        // Check permissions
        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Insufficient permissions');
        }

        // Get posts
        $posts = get_posts(array(
            'post_type' => 'post',
            'post_status' => 'publish',
            'numberposts' => 100,
            'orderby' => 'title',
            'order' => 'ASC'
        ));

        $posts_data = array();
        foreach ($posts as $post) {
            $posts_data[] = array(
                'id' => $post->ID,
                'title' => $post->post_title,
                'url' => get_permalink($post->ID)
            );
        }

        wp_send_json_success($posts_data);
    }
    
    /**
     * AJAX handler to get pages for entity association
     */
    public function ajax_get_pages() {
        // Check nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'aysa_get_pages_nonce')) {
            wp_send_json_error('Security check failed');
        }

        // Check permissions
        if (!current_user_can('edit_pages')) {
            wp_send_json_error('Insufficient permissions');
        }

        // Get pages
        $pages = get_pages(array(
            'post_status' => 'publish',
            'number' => 100,
            'sort_column' => 'post_title',
            'sort_order' => 'ASC'
        ));

        $pages_data = array();
        foreach ($pages as $page) {
            $pages_data[] = array(
                'id' => $page->ID,
                'title' => $page->post_title,
                'url' => get_permalink($page->ID)
            );
        }

        wp_send_json_success($pages_data);
    }
    
    /**
     * AJAX handler to get categories for entity association
     */
    public function ajax_get_wp_categories() {
        // Check nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'aysa_get_categories_nonce')) {
            wp_send_json_error('Security check failed');
        }

        // Check permissions
        if (!current_user_can('manage_categories')) {
            wp_send_json_error('Insufficient permissions');
        }

        // Get categories
        $categories = get_categories(array(
            'hide_empty' => false,
            'number' => 100,
            'orderby' => 'name',
            'order' => 'ASC'
        ));

        $categories_data = array();
        foreach ($categories as $category) {
            $categories_data[] = array(
                'id' => $category->term_id,
                'title' => $category->name,
                'url' => get_category_link($category->term_id)
            );
        }

        wp_send_json_success($categories_data);
    }
    
    /**
     * AJAX handler to get products for entity association (WooCommerce)
     */
    public function ajax_get_products() {
        // Check nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'aysa_get_products_nonce')) {
            wp_send_json_error('Security check failed');
        }

        // Check permissions
        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Insufficient permissions');
        }

        // Check if WooCommerce is active
        if (!class_exists('WooCommerce')) {
            wp_send_json_error('WooCommerce is not active');
        }

        // Get products
        $products = get_posts(array(
            'post_type' => 'product',
            'post_status' => 'publish',
            'numberposts' => 100,
            'orderby' => 'title',
            'order' => 'ASC'
        ));

        $products_data = array();
        foreach ($products as $product) {
            $products_data[] = array(
                'id' => $product->ID,
                'title' => $product->post_title,
                'url' => get_permalink($product->ID)
            );
        }

        wp_send_json_success($products_data);
    }
    
    /**
     * AJAX handler to detect entity from URL
     */
    public function ajax_detect_entity_from_url() {
        // Check nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'aysa_detect_entity_nonce')) {
            wp_send_json_error('Security check failed');
        }

        // Check permissions
        if (!current_user_can('edit_posts')) {
            wp_send_json_error('Insufficient permissions');
        }

        $url = sanitize_url($_POST['url']);
        if (empty($url)) {
            wp_send_json_error('Invalid URL');
        }

        // Try to find the entity by URL
        $detected_entity = $this->detect_entity_from_url($url);
        
        if ($detected_entity) {
            wp_send_json_success($detected_entity);
        } else {
            wp_send_json_error('Could not detect entity from URL');
        }
    }
    
    /**
     * Detect WordPress entity from URL
     */
    private function detect_entity_from_url($url) {
        // Remove domain and get path
        $parsed_url = wp_parse_url($url);
        $path = isset($parsed_url['path']) ? $parsed_url['path'] : '';
        $query = isset($parsed_url['query']) ? $parsed_url['query'] : '';
        
        // Parse query string
        parse_str($query, $query_params);
        
        // Check for direct post/page ID in query params
        if (isset($query_params['p'])) {
            $post_id = intval($query_params['p']);
            $post = get_post($post_id);
            if ($post && $post->post_status === 'publish') {
                return array(
                    'id' => $post->ID,
                    'type' => ucfirst($post->post_type),
                    'title' => $post->post_title,
                    'url' => get_permalink($post->ID)
                );
            }
        }
        
        if (isset($query_params['page_id'])) {
            $page_id = intval($query_params['page_id']);
            $page = get_post($page_id);
            if ($page && $page->post_type === 'page' && $page->post_status === 'publish') {
                return array(
                    'id' => $page->ID,
                    'type' => 'Page',
                    'title' => $page->post_title,
                    'url' => get_permalink($page->ID)
                );
            }
        }
        
        if (isset($query_params['cat'])) {
            $cat_id = intval($query_params['cat']);
            $category = get_category($cat_id);
            if ($category && !is_wp_error($category)) {
                return array(
                    'id' => $category->term_id,
                    'type' => 'Category',
                    'title' => $category->name,
                    'url' => get_category_link($category->term_id)
                );
            }
        }
        
        // Try to get post ID by URL
        $post_id = url_to_postid($url);
        if ($post_id > 0) {
            $post = get_post($post_id);
            if ($post && $post->post_status === 'publish') {
                $post_type = $post->post_type;
                $type_label = ucfirst($post_type);
                if ($post_type === 'product') {
                    $type_label = 'Product';
                } elseif ($post_type === 'page') {
                    $type_label = 'Page';
                } else {
                    $type_label = 'Post';
                }
                
                return array(
                    'id' => $post->ID,
                    'type' => $type_label,
                    'title' => $post->post_title,
                    'url' => get_permalink($post->ID)
                );
            }
        }
        
        // Try to detect category from URL path
        if (preg_match('/\/category\/([^\/]+)\/?/', $path, $matches)) {
            $category_slug = $matches[1];
            $category = get_category_by_slug($category_slug);
            if ($category) {
                return array(
                    'id' => $category->term_id,
                    'type' => 'Category',
                    'title' => $category->name,
                    'url' => get_category_link($category->term_id)
                );
            }
        }
        
        return null;
    }
}
