<?php

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

class Aysa_Meta_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/';
        $this->confidence_scorer = new Aysa_Confidence_Scorer();
        $this->audit_logger = new Aysa_Audit_Logger();
    }
    
    public function process($job_data) {
        $post_id = $job_data['post_id'];
        
        $post = get_post($post_id);
        if (!$post) {
            return new WP_Error('post_not_found', 'Post not found');
        }
        
        $existing_title = get_post_meta($post_id, '_yoast_wpseo_title', true);
        $existing_description = get_post_meta($post_id, '_yoast_wpseo_metadesc', true);
        
        if (!empty($existing_title) && !empty($existing_description)) {
            return new WP_Error('meta_exists', 'Post already has meta tags');
        }
        
        $content_data = $this->prepare_content_data($post, $job_data);
        $generated_meta = $this->generate_meta_tags($content_data);
        
        if (is_wp_error($generated_meta)) {
            return $generated_meta;
        }
        
        $confidence_result = $this->confidence_scorer->calculate_meta_confidence($content_data, $generated_meta);
        
        $automation_config = get_option('aysa_automation_config', array());
        $threshold = $automation_config['confidence_threshold'] ?? 0.7;
        
        if ($confidence_result['score'] >= $threshold) {
            return $this->apply_meta_tags($post_id, $generated_meta, $confidence_result);
        } else {
            return $this->queue_meta_for_review($post_id, $generated_meta, $confidence_result);
        }
    }
    
    private function prepare_content_data($post, $job_data) {
        $content_data = array(
            'post_id' => $post->ID,
            'title' => $post->post_title,
            'content' => wp_strip_all_tags($post->post_content),
            'excerpt' => $post->post_excerpt,
            'post_type' => $post->post_type,
            'categories' => array(),
            'tags' => array(),
            'primary_keyword' => '',
            'secondary_keywords' => array()
        );
        
        if ($post->post_type === 'post') {
            $categories = get_the_category($post->ID);
            $content_data['categories'] = array_map(function($cat) { return $cat->name; }, $categories);
            
            $tags = get_the_tags($post->ID);
            if ($tags) {
                $content_data['tags'] = array_map(function($tag) { return $tag->name; }, $tags);
            }
        }
        
        if ($post->post_type === 'product' && class_exists('WooCommerce')) {
            $product_categories = get_the_terms($post->ID, 'product_cat');
            if ($product_categories) {
                $content_data['categories'] = array_map(function($cat) { return $cat->name; }, $product_categories);
            }
            
            $product_tags = get_the_terms($post->ID, 'product_tag');
            if ($product_tags) {
                $content_data['tags'] = array_map(function($tag) { return $tag->name; }, $product_tags);
            }
        }
        
        $primary_keyword = get_post_meta($post->ID, 'aysa_primary_keyword', true);
        if ($primary_keyword) {
            $content_data['primary_keyword'] = $primary_keyword;
        }
        
        $secondary_keywords = get_post_meta($post->ID, 'aysa_secondary_keywords', true);
        if ($secondary_keywords) {
            $content_data['secondary_keywords'] = explode(',', $secondary_keywords);
        }
        
        return $content_data;
    }
    
    private function generate_meta_tags($content_data) {
        $api_url = $this->api_base_url . 'ContentAnalysis/generateMetaTags';
        
        $request_data = array(
            'title' => $content_data['title'],
            'content' => substr($content_data['content'], 0, 2000),
            'postType' => $content_data['post_type'],
            'categories' => $content_data['categories'],
            'tags' => $content_data['tags'],
            'primaryKeyword' => $content_data['primary_keyword'],
            'secondaryKeywords' => $content_data['secondary_keywords']
        );
        
        $response = wp_remote_post($api_url, array(
            'timeout' => 30,
            'headers' => array(
                'Content-Type' => 'application/json',
                'Accept' => 'application/json'
            ),
            'body' => wp_json_encode($request_data)
        ));
        
        if (is_wp_error($response)) {
            return $this->generate_fallback_meta($content_data);
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            return $this->generate_fallback_meta($content_data);
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (!$data || !isset($data['title']) || !isset($data['description'])) {
            return $this->generate_fallback_meta($content_data);
        }
        
        return array(
            'title' => sanitize_text_field($data['title']),
            'description' => sanitize_textarea_field($data['description']),
            'keywords' => sanitize_text_field($data['keywords'] ?? ''),
            'api_confidence' => floatval($data['confidence'] ?? 0.5)
        );
    }
    
    private function generate_fallback_meta($content_data) {
        $title = $content_data['title'];
        
        if (!empty($content_data['primary_keyword'])) {
            $title = $content_data['primary_keyword'] . ' - ' . $title;
        }
        
        $title = substr($title, 0, 60);
        
        $description = '';
        if (!empty($content_data['excerpt'])) {
            $description = $content_data['excerpt'];
        } else {
            $description = substr($content_data['content'], 0, 160);
        }
        
        if (!empty($content_data['primary_keyword'])) {
            $description = $content_data['primary_keyword'] . '. ' . $description;
        }
        
        $description = substr($description, 0, 160);
        
        return array(
            'title' => $title,
            'description' => $description,
            'keywords' => implode(', ', array_merge(
                array($content_data['primary_keyword']),
                $content_data['secondary_keywords'],
                $content_data['categories']
            )),
            'api_confidence' => 0.3
        );
    }
    
    private function apply_meta_tags($post_id, $generated_meta, $confidence_result) {
        $old_data = array(
            'title' => get_post_meta($post_id, '_yoast_wpseo_title', true),
            'description' => get_post_meta($post_id, '_yoast_wpseo_metadesc', true),
            'keywords' => get_post_meta($post_id, '_yoast_wpseo_focuskw', true)
        );
        
        $applied_changes = array();
        
        if (!empty($generated_meta['title']) && empty($old_data['title'])) {
            update_post_meta($post_id, '_yoast_wpseo_title', $generated_meta['title']);
            $applied_changes['title'] = $generated_meta['title'];
        }
        
        if (!empty($generated_meta['description']) && empty($old_data['description'])) {
            update_post_meta($post_id, '_yoast_wpseo_metadesc', $generated_meta['description']);
            $applied_changes['description'] = $generated_meta['description'];
        }
        
        if (!empty($generated_meta['keywords']) && empty($old_data['keywords'])) {
            $primary_keyword = explode(',', $generated_meta['keywords'])[0];
            update_post_meta($post_id, '_yoast_wpseo_focuskw', trim($primary_keyword));
            $applied_changes['keywords'] = $generated_meta['keywords'];
        }
        
        $this->audit_logger->log_action(
            'meta_generation',
            $post_id,
            'post',
            $old_data,
            $applied_changes,
            $confidence_result['score'],
            true
        );
        
        return array(
            'success' => true,
            'applied_changes' => $applied_changes,
            'confidence_score' => $confidence_result['score'],
            'message' => 'Meta tags applied automatically'
        );
    }
    
    private function queue_meta_for_review($post_id, $generated_meta, $confidence_result) {
        $review_data = array(
            'post_id' => $post_id,
            'generated_meta' => $generated_meta,
            'confidence_score' => $confidence_result['score'],
            'confidence_factors' => $confidence_result['factors'],
            'recommendation' => $confidence_result['recommendation'],
            'created_at' => current_time('mysql')
        );
        
        $existing_reviews = get_option('aysa_pending_meta_reviews', array());
        $existing_reviews[$post_id] = $review_data;
        update_option('aysa_pending_meta_reviews', $existing_reviews);
        
        return array(
            'success' => true,
            'queued_for_review' => true,
            'confidence_score' => $confidence_result['score'],
            'message' => 'Meta tags queued for manual review due to low confidence'
        );
    }
    
    public function get_pending_reviews() {
        return get_option('aysa_pending_meta_reviews', array());
    }
    
    public function approve_meta_review($post_id) {
        $pending_reviews = get_option('aysa_pending_meta_reviews', array());
        
        if (!isset($pending_reviews[$post_id])) {
            return new WP_Error('review_not_found', 'Pending review not found');
        }
        
        $review_data = $pending_reviews[$post_id];
        $result = $this->apply_meta_tags(
            $post_id, 
            $review_data['generated_meta'], 
            array('score' => $review_data['confidence_score'])
        );
        
        unset($pending_reviews[$post_id]);
        update_option('aysa_pending_meta_reviews', $pending_reviews);
        
        return $result;
    }
    
    public function reject_meta_review($post_id) {
        $pending_reviews = get_option('aysa_pending_meta_reviews', array());
        
        if (!isset($pending_reviews[$post_id])) {
            return new WP_Error('review_not_found', 'Pending review not found');
        }
        
        unset($pending_reviews[$post_id]);
        update_option('aysa_pending_meta_reviews', $pending_reviews);
        
        return array(
            'success' => true,
            'message' => 'Meta tags review rejected'
        );
    }
}
