<?php

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

class Aysa_Domain_Authority_Scheduler {
    
    private $api_base_url;
    private $queue_manager;
    
    public function __construct() {
        $this->api_base_url = defined('AYSA_API_BASE_URL') ? AYSA_API_BASE_URL : 'https://api.aysa.ai/api/';
        $this->queue_manager = new Aysa_Queue_Manager();
    }
    
    public function schedule_domain_authority_tasks() {
        $automation_config = get_option('aysa_automation_config', array());
        
        if (!isset($automation_config['domain_authority_automation']) || !$automation_config['domain_authority_automation']) {
            return;
        }
        
        $project_id = $this->get_current_project_id();
        if (!$project_id) {
            return;
        }
        
        $domain_authority_data = $this->fetch_domain_authority_data($project_id);
        if (!$domain_authority_data) {
            return;
        }
        
        $this->create_domain_authority_jobs($project_id, $domain_authority_data);
    }
    
    private function get_current_project_id() {
        $domain = isset($_SERVER['HTTP_HOST']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])) : '';
        if (empty($domain)) {
            return null;
        }
        
        $response = wp_remote_get($this->api_base_url . 'Project/getbydomain/' . $domain);
        
        if (is_wp_error($response)) {
            return null;
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        return isset($data['projectId']) ? $data['projectId'] : null;
    }
    
    private function fetch_domain_authority_data($project_id) {
        $response = wp_remote_get($this->api_base_url . 'aysa-plugin/datasks/domain-authority-avg/' . $project_id);
        
        if (is_wp_error($response)) {
            return null;
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!is_array($data)) {
            return null;
        }
        
        return array_filter($data, function($item) {
            return isset($item['backlinksCount']) && $item['backlinksCount'] > 0 
                && isset($item['averageDomainAuthority']) && $item['averageDomainAuthority'] > 0;
        });
    }
    
    private function create_domain_authority_jobs($project_id, $domain_authority_data) {
        if (empty($domain_authority_data)) {
            return;
        }
        
        $mean_backlinks = round(array_sum(array_column($domain_authority_data, 'backlinksCount')) / count($domain_authority_data));
        $mean_authority = round(array_sum(array_column($domain_authority_data, 'averageDomainAuthority')) / count($domain_authority_data));
        
        $task_data = array(
            'title' => "Get {$mean_backlinks} links with {$mean_authority}+ authority",
            'description' => 'Domain authority optimization task based on competitor analysis',
            'target_backlinks' => $mean_backlinks,
            'target_authority' => $mean_authority,
            'competitor_data' => $domain_authority_data,
            'created_at' => current_time('mysql')
        );
        
        $job_data = array(
            'project_id' => $project_id,
            'task_data' => $task_data,
            'priority' => 5
        );
        
        $existing_jobs = $this->check_existing_domain_authority_jobs($project_id);
        if ($existing_jobs > 0) {
            return;
        }
        
        $result = $this->queue_manager->add_job('domain_authority_processor', $job_data, 5);
        
        if (!is_wp_error($result)) {
            do_action('aysa_domain_authority_task_scheduled', $project_id, $task_data);
        }
    }
    
    private function check_existing_domain_authority_jobs($project_id) {
        global $wpdb;
        
        $table_name = esc_sql($wpdb->prefix . 'aysa_automation_queue');
        
        // 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.
        return $wpdb->get_var($wpdb->prepare(
            // 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.
            "SELECT COUNT(*) FROM {$table_name} 
             WHERE processor = 'domain_authority_processor' 
             AND JSON_EXTRACT(job_data, '$.project_id') = %d
             AND status IN ('pending', 'processing')
             AND created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)",
            $project_id
        ));
    }
    
    public function handle_schedule_domain_authority_tasks() {
        check_ajax_referer('aysa_automation_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error('Insufficient permissions');
        }
        
        $this->schedule_domain_authority_tasks();
        
        wp_send_json_success(array(
            'message' => 'Domain Authority tasks scheduled successfully'
        ));
    }
}
