<?php

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

class Aysa_Association_Processor {
    
    private $api_base_url;
    private $confidence_scorer;
    private $audit_logger;
    
    public function __construct() {
        $this->api_base_url = defined('AYSA_API_BASE_URL') ? AYSA_API_BASE_URL : 'https://api.aysa.ai/api/';
        
        if (class_exists('Aysa_Confidence_Scorer')) {
            $this->confidence_scorer = new Aysa_Confidence_Scorer();
        } else {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Aysa_Confidence_Scorer class not found');
        }
        
        if (class_exists('Aysa_Audit_Logger')) {
            $this->audit_logger = new Aysa_Audit_Logger();
        } else {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Aysa_Audit_Logger class not found');
        }
    }
    
    public function process($job_data) {
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Starting association task processing for project: ' . $job_data['project_id']);
        $project_id = $job_data['project_id'];
        $task_data = $job_data['task_data'];
        
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Association task data: ' . json_encode($task_data));
        
        if (!$this->confidence_scorer) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Confidence scorer not available, cannot process association task');
            return new WP_Error('confidence_scorer_unavailable', 'Confidence scorer not available');
        }
        
        $confidence_result = $this->confidence_scorer->calculate_association_confidence($task_data);
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Association confidence calculation result: ' . json_encode($confidence_result));
        
        $automation_config = get_option('aysa_automation_config', array());
        $threshold = $automation_config['confidence_threshold'] ?? 0.7;
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Using confidence threshold: ' . $threshold);
        
        if ($confidence_result['score'] >= $threshold) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Association confidence score ' . $confidence_result['score'] . ' meets threshold, applying task automatically');
            return $this->apply_association_task($project_id, $task_data, $confidence_result);
        } else {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Association confidence score ' . $confidence_result['score'] . ' below threshold, queuing for review');
            return $this->queue_for_review($project_id, $task_data, $confidence_result);
        }
    }
    
    private function apply_association_task($project_id, $task_data, $confidence_result) {
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Applying association task automatically for project: ' . $project_id);
        
        if ($this->audit_logger) {
            $this->audit_logger->log_action('association_task_applied', array(
                'project_id' => $project_id,
                'task_data' => $task_data,
                'confidence_score' => $confidence_result['score'],
                'auto_applied' => true
            ));
        }
        
        $association_count = $task_data['association_count'] ?? 0;
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Processing ' . $association_count . ' keyword associations');
        
        $result = array(
            'status' => 'completed',
            'message' => "Successfully processed {$association_count} keyword associations",
            'project_id' => $project_id,
            'confidence_score' => $confidence_result['score'],
            'auto_applied' => true,
            'processed_at' => current_time('mysql')
        );
        
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Association task applied successfully: ' . json_encode($result));
        return $result;
    }
    
    private function queue_for_review($project_id, $task_data, $confidence_result) {
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Queuing association task for manual review');
        
        global $wpdb;
        $table_name = esc_sql($wpdb->prefix . 'aysa_pending_reviews');
        
        $review_data = array(
            'task_type' => 'association',
            'project_id' => $project_id,
            'task_data' => json_encode($task_data),
            'confidence_score' => $confidence_result['score'],
            'confidence_factors' => json_encode($confidence_result['factors']),
            'recommendation' => $confidence_result['recommendation'],
            'status' => 'pending',
            'created_at' => current_time('mysql')
        );
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- 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.
        $inserted = $wpdb->insert($table_name, $review_data);
        
        if ($inserted === false) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Failed to insert association task into pending reviews: ' . $wpdb->last_error);
            return new WP_Error('database_error', 'Failed to queue task for review');
        }
        
        $review_id = $wpdb->insert_id;
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Association task queued for review with ID: ' . $review_id);
        
        if ($this->audit_logger) {
            $this->audit_logger->log_action('association_task_queued_for_review', array(
                'review_id' => $review_id,
                'project_id' => $project_id,
                'task_data' => $task_data,
                'confidence_score' => $confidence_result['score']
            ));
        }
        
        return array(
            'status' => 'queued_for_review',
            'review_id' => $review_id,
            'message' => 'Association task queued for manual review',
            'confidence_score' => $confidence_result['score'],
            'recommendation' => $confidence_result['recommendation']
        );
    }
    
    public function get_pending_reviews($project_id = null) {
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Retrieving pending association reviews' . ($project_id ? ' for project: ' . $project_id : ''));
        
        global $wpdb;
        $table_name = esc_sql($wpdb->prefix . 'aysa_pending_reviews');
        
        $where_clause = "task_type = 'association' AND status = 'pending'";
        $params = array();
        
        if ($project_id) {
            $where_clause .= " AND project_id = %d";
            $params[] = $project_id;
        }
        
        $query = "SELECT * FROM {$table_name} WHERE {$where_clause} ORDER BY created_at DESC";
        
        if (!empty($params)) {
            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Reviewed release query: table identifiers and structure are internal, and request-derived values are prepared before execution. 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.
            $results = $wpdb->get_results($wpdb->prepare($query, $params));
        } else {
            // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Reviewed release query: table identifiers and structure are internal, and request-derived values are prepared before execution. 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.
            $results = $wpdb->get_results($query);
        }
        
        if ($results === false) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Database error retrieving association reviews: ' . $wpdb->last_error);
            return array();
        }
        
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Retrieved ' . count($results) . ' pending association reviews');
        return $results;
    }
    
    public function approve_review($review_id) {
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Approving association review: ' . $review_id);
        
        global $wpdb;
        $table_name = esc_sql($wpdb->prefix . 'aysa_pending_reviews');
        
        // 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.
        $review = $wpdb->get_row($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 * FROM {$table_name} WHERE id = %d AND task_type = 'association'",
            $review_id
        ));
        
        if (!$review) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Association review not found: ' . $review_id);
            return new WP_Error('review_not_found', 'Review not found');
        }
        
        $task_data = json_decode($review->task_data, true);
        $confidence_result = array(
            'score' => $review->confidence_score,
            'factors' => json_decode($review->confidence_factors, true),
            'recommendation' => $review->recommendation
        );
        
        $result = $this->apply_association_task($review->project_id, $task_data, $confidence_result);
        
        if (!is_wp_error($result)) {
            // 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.
            $wpdb->update(
                $table_name,
                array(
                    'status' => 'approved',
                    'processed_at' => current_time('mysql')
                ),
                array('id' => $review_id)
            );
            
            // Update association statuses to "processed" for this project
            $this->update_association_statuses_on_approval($review->project_id, $task_data);
            
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Association review approved and processed: ' . $review_id);
        }
        
        return $result;
    }
    
    /**
     * Update association statuses to "processed" when a review is approved
     */
    private function update_association_statuses_on_approval($project_id, $task_data) {
        aysa_debug_log('[AYSA ASSOCIATION STATUS] Updating association statuses for approved review - Project: ' . $project_id);
        
        // Check if the Aysa_Association_Status class exists
        if (!class_exists('Aysa_Association_Status')) {
            aysa_debug_log('[AYSA ASSOCIATION STATUS] Aysa_Association_Status class not available');
            return;
        }
        
        try {
            $status_manager = new Aysa_Association_Status();
            
            // If specific association IDs are provided in task_data, update those
            if (isset($task_data['association_ids']) && is_array($task_data['association_ids'])) {
                foreach ($task_data['association_ids'] as $association_id) {
                    $status_manager->update_status($association_id, 'processed');
                    aysa_debug_log('[AYSA ASSOCIATION STATUS] Updated association ' . $association_id . ' status to processed');
                }
            } else {
                // If no specific IDs, get all associations for this project that need work
                $this->update_project_associations_status($project_id, $status_manager);
            }
            
        } catch (Exception $e) {
            aysa_debug_log('[AYSA ASSOCIATION STATUS] Error updating association statuses: ' . $e->getMessage());
        }
    }
    
    /**
     * Update all associations for a project that currently need work
     */
    private function update_project_associations_status($project_id, $status_manager) {
        aysa_debug_log('[AYSA ASSOCIATION STATUS] Updating all project associations for project: ' . $project_id);
        
        // Get all current statuses
        $all_statuses = $status_manager->get_all_statuses();
        
        if (is_wp_error($all_statuses)) {
            aysa_debug_log('[AYSA ASSOCIATION STATUS] Error getting all statuses: ' . $all_statuses->get_error_message());
            return;
        }
        
        $updated_count = 0;
        
        // Update associations that currently have "needs-work" status
        foreach ($all_statuses as $association_id => $current_status) {
            if ($current_status === 'needs-work') {
                $result = $status_manager->update_status($association_id, 'processed');
                if (!is_wp_error($result)) {
                    $updated_count++;
                    aysa_debug_log('[AYSA ASSOCIATION STATUS] Updated association ' . $association_id . ' from needs-work to processed');
                }
            }
        }
        
        aysa_debug_log('[AYSA ASSOCIATION STATUS] Updated ' . $updated_count . ' associations to processed status');
    }
    
    public function reject_review($review_id) {
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Rejecting association review: ' . $review_id);
        
        global $wpdb;
        $table_name = esc_sql($wpdb->prefix . 'aysa_pending_reviews');
        
        // 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.
        $updated = $wpdb->update(
            $table_name,
            array(
                'status' => 'rejected',
                'processed_at' => current_time('mysql')
            ),
            array(
                'id' => $review_id,
                'task_type' => 'association'
            )
        );
        
        if ($updated === false) {
            aysa_debug_log('[AYSA DOMAIN AUTHORITY] Failed to reject association review: ' . $wpdb->last_error);
            return new WP_Error('database_error', 'Failed to reject review');
        }
        
        if ($this->audit_logger) {
            $this->audit_logger->log_action('association_review_rejected', array(
                'review_id' => $review_id
            ));
        }
        
        aysa_debug_log('[AYSA DOMAIN AUTHORITY] Association review rejected: ' . $review_id);
        return array(
            'status' => 'rejected',
            'message' => 'Association review rejected successfully'
        );
    }
}
