<?php
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped,WordPress.Security.EscapeOutput.ExceptionNotEscaped,WordPress.DB.PreparedSQL.NotPrepared,WordPress.DB.PreparedSQLPlaceholders.LikeWildcardsInQuery,PluginCheck.Security.DirectDB.UnescapedDBParameter,WordPress.WP.AlternativeFunctions.file_system_operations_fopen,WordPress.WP.AlternativeFunctions.file_system_operations_fclose,WordPress.WP.AlternativeFunctions.file_system_operations_is_writable,WordPress.WP.AlternativeFunctions.file_system_operations_chmod,WordPress.WP.AlternativeFunctions.file_system_operations_rmdir,WordPress.DateTime.RestrictedFunctions.date_date,WordPress.WP.I18n.NonSingularStringLiteralDomain,WordPress.WP.I18n.MissingTranslatorsComment,WordPress.WP.I18n.MissingArgDomain,WordPressVIPMinimum.Performance.WPQueryParams.SuppressFilters_suppress_filters,WordPress.WP.EnqueuedResources.NonEnqueuedScript,WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- WordPress.org PCP audit pass: legacy controlled-beta surfaces require targeted follow-up hardening.

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

class Aysa_Seo_Entity_Processor {
    
    private $confidence_scorer;
    private $audit_logger;
    
    public function __construct() {
        $this->confidence_scorer = new Aysa_Confidence_Scorer();
        $this->audit_logger = new Aysa_Audit_Logger();
    }
    
    public function process($job_data) {
        $action_type = $job_data['action_type'] ?? 'find_entities_without_history';
        
        switch ($action_type) {
            case 'find_entities_without_history':
                return $this->find_and_process_entities_without_history();
            case 'generate_seo_for_entity':
                return $this->generate_seo_for_entity($job_data);
            default:
                return new WP_Error('invalid_action', 'Invalid action type specified');
        }
    }
    
    private function find_and_process_entities_without_history() {
        global $wpdb;
        
        // Find entities (posts/pages/products) without SEO history
        $entities_without_history = $this->get_entities_without_history();
        
        if (empty($entities_without_history)) {
            return array(
                'message' => 'No entities without SEO history found',
                'processed' => 0
            );
        }
        
        // Process only one entity per job run
        $entity = $entities_without_history[0];
        
        // Generate SEO content for this entity
        $seo_result = $this->generate_seo_content_for_entity($entity);
        
        if (is_wp_error($seo_result)) {
            return $seo_result;
        }
        
        // Add to pending reviews (not auto-approved)
        $this->add_to_pending_reviews($entity, $seo_result);
        
        return array(
            'message' => 'SEO content generated for entity: ' . $entity['title'],
            'entity_id' => $entity['ID'],
            'entity_type' => $entity['post_type'],
            'processed' => 1
        );
    }
    
    private function get_entities_without_history() {
        global $wpdb;
        
        // Get posts/pages/products that don't have SEO history entries and are not already in pending reviews
        $query = "
            SELECT p.ID, p.post_title as title, p.post_type, p.post_content, p.post_excerpt
            FROM {$wpdb->posts} p
            LEFT JOIN {$wpdb->prefix}aysa_seo_history h ON p.ID = h.entity_id AND h.entity_type = p.post_type
            LEFT JOIN {$wpdb->prefix}aysa_automated_pending_reviews apr ON p.ID = apr.entity_id AND apr.entity_type = p.post_type AND apr.status = 'pending'
            WHERE p.post_status = 'publish'
            AND p.post_type IN ('post', 'page', 'product')
            AND h.id IS NULL
            AND apr.id IS NULL
            ORDER BY p.post_date DESC
            LIMIT 10
        ";
        
        return $wpdb->get_results($query, ARRAY_A);
    }
    
    private function generate_seo_content_for_entity($entity) {
        // Extract primary keyword from content or title
        $primary_keyword = $this->extract_primary_keyword($entity);
        
        if (empty($primary_keyword)) {
            return new WP_Error('no_keyword', 'Could not extract primary keyword for entity');
        }
        
        // Generate SEO suggestions using the same logic as the manual process
        $seo_suggestions = $this->generate_seo_suggestions($entity, $primary_keyword);
        
        if (is_wp_error($seo_suggestions)) {
            return $seo_suggestions;
        }
        
        // Log the generation in SEO history
        $this->log_seo_generation($entity, $primary_keyword, $seo_suggestions);
        
        return array(
            'keyword' => $primary_keyword,
            'suggestions' => $seo_suggestions,
            'entity' => $entity
        );
    }
    
    private function extract_primary_keyword($entity) {
        // Check if there's already a primary keyword set
        $existing_keyword = get_post_meta($entity['ID'], 'aysa_primary_keyword', true);
        if (!empty($existing_keyword)) {
            return $existing_keyword;
        }
        
        // Extract from title - take first 2-3 meaningful words
        $title_words = explode(' ', strtolower($entity['title']));
        $stop_words = array('the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'is', 'are', 'was', 'were');
        
        $meaningful_words = array();
        foreach ($title_words as $word) {
            $word = trim($word, '.,!?;:');
            if (strlen($word) > 2 && !in_array($word, $stop_words)) {
                $meaningful_words[] = $word;
                if (count($meaningful_words) >= 2) {
                    break;
                }
            }
        }
        
        return implode(' ', $meaningful_words);
    }
    
    private function generate_seo_suggestions($entity, $keyword) {
        // Simulate SEO generation similar to the manual process
        $current_title = get_post_meta($entity['ID'], '_yoast_wpseo_title', true) ?: $entity['title'];
        $current_description = get_post_meta($entity['ID'], '_yoast_wpseo_metadesc', true) ?: substr(wp_strip_all_tags($entity['post_content']), 0, 160);
        $current_keywords = get_post_meta($entity['ID'], '_yoast_wpseo_focuskw', true) ?: '';
        
        // Generate improved versions
        $suggested_title = $this->improve_title($current_title, $keyword);
        $suggested_description = $this->improve_description($current_description, $keyword, $entity);
        $suggested_keywords = $this->improve_keywords($current_keywords, $keyword);
        
        return array(
            'current' => array(
                'title' => $current_title,
                'description' => $current_description,
                'keywords' => $current_keywords
            ),
            'suggested' => array(
                'title' => $suggested_title,
                'description' => $suggested_description,
                'keywords' => $suggested_keywords
            )
        );
    }
    
    private function improve_title($current_title, $keyword) {
        // If keyword is not in title, add it
        if (stripos($current_title, $keyword) === false) {
            return $keyword . ' - ' . $current_title;
        }
        return $current_title;
    }
    
    private function improve_description($current_description, $keyword, $entity) {
        // Ensure keyword is in description
        if (stripos($current_description, $keyword) === false) {
            $description = $keyword . '. ' . $current_description;
        } else {
            $description = $current_description;
        }
        
        // Ensure proper length
        return substr($description, 0, 160);
    }
    
    private function improve_keywords($current_keywords, $keyword) {
        $keywords_array = array_filter(array_map('trim', explode(',', $current_keywords)));
        
        if (!in_array($keyword, $keywords_array)) {
            array_unshift($keywords_array, $keyword);
        }
        
        return implode(', ', array_slice($keywords_array, 0, 5));
    }
    
    private function log_seo_generation($entity, $keyword, $suggestions) {
        global $wpdb;
        
        $history_table = $wpdb->prefix . 'aysa_seo_history';
        
        $wpdb->insert(
            $history_table,
            array(
                'entity_id' => $entity['ID'],
                'entity_type' => $entity['post_type'],
                'keyword' => $keyword,
                'generated_data' => wp_json_encode($suggestions),
                'generation_method' => 'automated',
                'created_at' => current_time('mysql'),
                'status' => 'pending_review'
            ),
            array('%d', '%s', '%s', '%s', '%s', '%s', '%s')
        );
    }
    
    private function add_to_pending_reviews($entity, $seo_result) {
        // Store in the correct option that the automation manager expects
        $pending_reviews = get_option('aysa_pending_automated_seo_reviews', array());
        
        $review_id = uniqid('seo_');
        $review_item = array(
            'post_id' => $entity['ID'],
            'entity_id' => $entity['ID'],
            'entity_type' => $entity['post_type'],
            'title' => $entity['title'],
            'keyword' => $seo_result['keyword'],
            'meta_title' => $seo_result['suggestions']['suggested']['title'],
            'meta_description' => $seo_result['suggestions']['suggested']['description'],
            'keywords' => $seo_result['suggestions']['suggested']['keywords'],
            'current_title' => $seo_result['suggestions']['current']['title'],
            'current_description' => $seo_result['suggestions']['current']['description'],
            'current_keywords' => $seo_result['suggestions']['current']['keywords'],
            'generated_at' => current_time('mysql'),
            'status' => 'pending'
        );
        
        $pending_reviews[$review_id] = $review_item;
        update_option('aysa_pending_automated_seo_reviews', $pending_reviews);
        
        aysa_debug_log("AYSA DUPLICATE DEBUG: Added to option-based pending reviews - Entity ID: {$entity['ID']}, Type: {$entity['post_type']}, Review ID: {$review_id}");
        
        // Also trigger an action for other systems to hook into
        do_action('aysa_seo_content_generated', $review_item);
    }
    
    public function generate_seo_for_entity($job_data) {
        $entity_id = $job_data['entity_id'];
        $entity_type = $job_data['entity_type'];
        
        $entity = get_post($entity_id);
        if (!$entity || $entity->post_type !== $entity_type) {
            return new WP_Error('entity_not_found', 'Entity not found');
        }
        
        $entity_array = array(
            'ID' => $entity->ID,
            'title' => $entity->post_title,
            'post_type' => $entity->post_type,
            'post_content' => $entity->post_content,
            'post_excerpt' => $entity->post_excerpt
        );
        
        return $this->generate_seo_content_for_entity($entity_array);
    }
}