<?php

if (!defined('WPINC')) {
    die;
}

class Aysa_Scheduler {
    
    private $scheduled_tasks;
    
    public function __construct() {
        $this->scheduled_tasks = array();
    }
    
    public function init() {
        $this->register_scheduled_tasks();
        $this->init_hooks();
    }
    
    private function init_hooks() {
        add_action('wp_ajax_aysa_schedule_task', array($this, 'handle_schedule_task'));
        add_action('wp_ajax_aysa_unschedule_task', array($this, 'handle_unschedule_task'));
        add_action('wp_ajax_aysa_get_scheduled_tasks', array($this, 'handle_get_scheduled_tasks'));
        
        add_action('aysa_bulk_image_optimization', array($this, 'run_bulk_image_optimization'));
        add_action('aysa_bulk_meta_generation', array($this, 'run_bulk_meta_generation'));
        add_action('aysa_404_analysis', array($this, 'run_404_analysis'));
        add_action('aysa_keyword_analysis', array($this, 'run_keyword_analysis'));
        add_action('aysa_automated_seo_generation', array($this, 'run_automated_seo_generation'));
    }
    
    private function register_scheduled_tasks() {
        $this->scheduled_tasks = array(
            'bulk_image_optimization' => array(
                'name' => 'Bulk Image Optimization',
                'description' => 'Process all images without alt text',
                'hook' => 'aysa_bulk_image_optimization',
                'default_schedule' => 'weekly'
            ),
            'bulk_meta_generation' => array(
                'name' => 'Bulk Meta Generation',
                'description' => 'Generate meta tags for posts without them',
                'hook' => 'aysa_bulk_meta_generation',
                'default_schedule' => 'weekly'
            ),
            '404_analysis' => array(
                'name' => '404 Error Analysis',
                'description' => 'Analyze 404 errors and suggest redirects',
                'hook' => 'aysa_404_analysis',
                'default_schedule' => 'daily'
            ),
            'keyword_analysis' => array(
                'name' => 'Keyword Analysis',
                'description' => 'Analyze content for keyword opportunities',
                'hook' => 'aysa_keyword_analysis',
                'default_schedule' => 'weekly'
            ),
            'automated_seo_generation' => array(
                'name' => 'Automated SEO Generation',
                'description' => 'Generate SEO content for entities without SEO history',
                'hook' => 'aysa_automated_seo_generation',
                'default_schedule' => 'monthly'
            )
        );
    }
    
    public function schedule_task($task_id, $schedule = 'daily', $start_time = null) {
        if (!isset($this->scheduled_tasks[$task_id])) {
            return new WP_Error('invalid_task', 'Invalid task ID');
        }
        
        $hook = $this->scheduled_tasks[$task_id]['hook'];
        
        if (wp_next_scheduled($hook)) {
            wp_unschedule_event(wp_next_scheduled($hook), $hook);
        }
        
        $timestamp = $start_time ? strtotime($start_time) : time();
        
        $result = wp_schedule_event($timestamp, $schedule, $hook);
        
        if ($result === false) {
            return new WP_Error('schedule_failed', 'Failed to schedule task');
        }
        
        update_option('aysa_scheduled_task_' . $task_id, array(
            'schedule' => $schedule,
            'next_run' => wp_next_scheduled($hook),
            'enabled' => true
        ));
        
        return true;
    }
    
    public function unschedule_task($task_id) {
        if (!isset($this->scheduled_tasks[$task_id])) {
            return new WP_Error('invalid_task', 'Invalid task ID');
        }
        
        $hook = $this->scheduled_tasks[$task_id]['hook'];
        
        if (wp_next_scheduled($hook)) {
            wp_unschedule_event(wp_next_scheduled($hook), $hook);
        }
        
        update_option('aysa_scheduled_task_' . $task_id, array(
            'enabled' => false
        ));
        
        return true;
    }
    
    public function run_bulk_image_optimization() {
        global $wpdb;
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Reviewed release query uses WordPress or plugin-owned operational tables; current job, billing and idempotency state must not be cached because stale reads can duplicate or mis-order work.
        $images_without_alt = $wpdb->get_results(
            "SELECT p.ID 
             FROM {$wpdb->posts} p
             LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_wp_attachment_image_alt'
             WHERE p.post_type = 'attachment' 
             AND p.post_mime_type LIKE 'image/%'
             AND (pm.meta_value IS NULL OR pm.meta_value = '')
             LIMIT 50"
        );
        
        $queue_manager = new Aysa_Queue_Manager();
        $queued = 0;
        
        foreach ($images_without_alt as $image) {
            $job_data = array(
                'attachment_id' => $image->ID,
                'action_type' => 'bulk_image_optimization',
                'priority' => 7
            );
            
            $result = $queue_manager->add_job('image_processor', $job_data, 7);
            
            if (!is_wp_error($result)) {
                $queued++;
            }
        }
        
        aysa_debug_log("Aysa Automation: Queued {$queued} images for bulk optimization");
        
        return $queued;
    }
    
    public function run_bulk_meta_generation() {
        global $wpdb;
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Reviewed release query uses WordPress or plugin-owned operational tables; current job, billing and idempotency state must not be cached because stale reads can duplicate or mis-order work.
        $posts_without_meta = $wpdb->get_results(
            "SELECT p.ID, p.post_type, p.post_title, p.post_content
             FROM {$wpdb->posts} p
             LEFT JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_yoast_wpseo_title'
             WHERE p.post_type IN ('post', 'page', 'product')
             AND p.post_status = 'publish'
             AND (pm.meta_value IS NULL OR pm.meta_value = '')
             LIMIT 25"
        );
        
        $queue_manager = new Aysa_Queue_Manager();
        $queued = 0;
        
        foreach ($posts_without_meta as $post) {
            $job_data = array(
                'post_id' => $post->ID,
                'post_type' => $post->post_type,
                'action_type' => 'bulk_meta_generation',
                'priority' => 6,
                'content' => $post->post_content,
                'title' => $post->post_title
            );
            
            $result = $queue_manager->add_job('meta_processor', $job_data, 6);
            
            if (!is_wp_error($result)) {
                $queued++;
            }
        }
        
        aysa_debug_log("Aysa Automation: Queued {$queued} posts for bulk meta generation");
        
        return $queued;
    }
    
    public function run_404_analysis() {
        global $wpdb;
        
        $tracker_table = esc_sql($wpdb->prefix . 'aysa_404_tracker');
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Reviewed release query uses WordPress or plugin-owned operational tables; current job, billing and idempotency state must not be cached because stale reads can duplicate or mis-order work.
        if ($wpdb->get_var("SHOW TABLES LIKE '{$tracker_table}'") !== $tracker_table) {
            return 0;
        }
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Reviewed release query uses WordPress or plugin-owned operational tables; current job, billing and idempotency state must not be cached because stale reads can duplicate or mis-order work.
        $frequent_404s = $wpdb->get_results(
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Reviewed release SQL: interpolation is limited to escaped or allowlisted plugin-owned table identifiers and generated placeholder lists; all request-derived values are passed to prepare. Reviewed release SQL: interpolation is limited to escaped or allowlisted plugin-owned table identifiers and generated placeholder lists; all request-derived values are passed to prepare.
            "SELECT url, COUNT(*) as hit_count, user_agent
" .
            // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Reviewed release SQL: the interpolated identifier is an escaped or allowlisted plugin-owned table name; request-derived values remain prepared.
            "             FROM {$tracker_table}
             WHERE created_at > DATE_SUB(NOW(), INTERVAL 7 DAY)
             AND is_bot = 0
             GROUP BY url
             HAVING hit_count >= 3
             ORDER BY hit_count DESC
             LIMIT 20"
        );
        
        $queue_manager = new Aysa_Queue_Manager();
        $queued = 0;
        
        foreach ($frequent_404s as $error) {
            $job_data = array(
                'url' => $error->url,
                'hit_count' => $error->hit_count,
                'action_type' => 'scheduled_404_analysis',
                'priority' => 4,
                'user_agent' => $error->user_agent
            );
            
            $result = $queue_manager->add_job('redirect_processor', $job_data, 4);
            
            if (!is_wp_error($result)) {
                $queued++;
            }
        }
        
        aysa_debug_log("Aysa Automation: Queued {$queued} 404 errors for analysis");
        
        return $queued;
    }
    
    public function run_keyword_analysis() {
        // This would analyze content for keyword opportunities
        aysa_debug_log('AYSA Scheduler: Running keyword analysis');
        
        // Implementation would go here
        // For now, just log that it ran
    }
    
    /**
     * Run automated SEO generation
     */
    public function run_automated_seo_generation() {
        aysa_debug_log('AYSA Scheduler: Running automated SEO generation');
        
        // Get the automation manager instance
        global $aysa_automation_manager;
        
        if ($aysa_automation_manager) {
            $aysa_automation_manager->run_automated_seo_generation();
        } else {
            aysa_debug_log('AYSA Scheduler: Automation manager not available');
        }
    }
    
    public function handle_schedule_task() {
        check_ajax_referer('aysa_automation_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $task_id = sanitize_text_field(wp_unslash($_POST['task_id'] ?? ''));
        $schedule = sanitize_text_field(wp_unslash($_POST['schedule'] ?? ''));
        $start_time = sanitize_text_field(wp_unslash($_POST['start_time'] ?? ''));
        
        $result = $this->schedule_task($task_id, $schedule, $start_time);
        
        if (is_wp_error($result)) {
            wp_send_json_error($result->get_error_message());
        } else {
            wp_send_json_success(array(
                'message' => 'Task scheduled successfully',
                'task_id' => $task_id,
                'schedule' => $schedule
            ));
        }
    }
    
    public function handle_unschedule_task() {
        check_ajax_referer('aysa_automation_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $task_id = sanitize_text_field(wp_unslash($_POST['task_id'] ?? ''));
        
        $result = $this->unschedule_task($task_id);
        
        if (is_wp_error($result)) {
            wp_send_json_error($result->get_error_message());
        } else {
            wp_send_json_success(array(
                'message' => 'Task unscheduled successfully',
                'task_id' => $task_id
            ));
        }
    }
    
    public function handle_get_scheduled_tasks() {
        check_ajax_referer('aysa_automation_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $tasks_status = array();
        
        foreach ($this->scheduled_tasks as $task_id => $task_info) {
            $task_config = get_option('aysa_scheduled_task_' . $task_id, array());
            $next_run = wp_next_scheduled($task_info['hook']);
            
            $tasks_status[$task_id] = array(
                'name' => $task_info['name'],
                'description' => $task_info['description'],
                'enabled' => $task_config['enabled'] ?? false,
                'schedule' => $task_config['schedule'] ?? $task_info['default_schedule'],
                'next_run' => $next_run ? gmdate('Y-m-d H:i:s', $next_run) : null,
                'next_run_timestamp' => $next_run
            );
        }
        
        wp_send_json_success($tasks_status);
    }
    
    public function get_available_schedules() {
        return array(
            'hourly' => 'Every Hour',
            'twicedaily' => 'Twice Daily',
            'daily' => 'Daily',
            'weekly' => 'Weekly',
            'monthly' => 'Monthly',
            'every_5_minutes' => 'Every 5 Minutes'
        );
    }
    
    public function get_scheduled_tasks() {
        return $this->scheduled_tasks;
    }
}
