<?php
/**
 * Quality Checker
 *
 * @package AIContentGenerator
 */

namespace AICG;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Ensures content quality and SEO compliance
 */
class Quality_Checker
{

    /**
     * Run all quality checks on content
     */
    public function check_content($article)
    {
        $errors = array();
        $warnings = array();

        // Check title
        $title_check = $this->check_title($article['title'] ?? '');
        if ($title_check !== true) {
            // Title length is always a warning, never an error that blocks generation
            $warnings[] = $title_check;
        }

        // Check content
        $content_check = $this->check_content_quality($article['content'] ?? '');
        if (is_array($content_check)) {
            $errors = array_merge($errors, $content_check['errors'] ?? array());
            $warnings = array_merge($warnings, $content_check['warnings'] ?? array());
        }

        // Check meta description
        $meta_check = $this->check_meta_description($article['meta_description'] ?? '');
        if ($meta_check !== true) {
            $warnings[] = $meta_check;
        }

        // If there are critical errors, return WP_Error
        if (!empty($errors)) {
            return new \WP_Error('quality_check_failed', implode(' ', $errors));
        }

        return array(
            'passed' => true,
            'warnings' => $warnings,
            'score' => $this->calculate_seo_score($article),
        );
    }

    /**
     * Check title quality
     */
    private function check_title($title)
    {
        if (empty($title)) {
            return __('Title is required.', 'roidnet-ai-content-generator');
        }

        $length = strlen($title);

        if ($length < 20) {
            return __('Title is too short (minimum 20 characters).', 'roidnet-ai-content-generator');
        }

        if ($length > 70) {
            return __('Title is long (recommendation is 60-70 characters for SEO).', 'roidnet-ai-content-generator');
        }

        return true;
    }

    /**
     * Check content quality
     */
    private function check_content_quality($content)
    {
        $errors = array();
        $warnings = array();

        if (empty($content)) {
            $errors[] = __('Content is required.', 'roidnet-ai-content-generator');
            return array('errors' => $errors, 'warnings' => $warnings);
        }

        // Check word count
        $word_count = str_word_count(strip_tags($content));

        if ($word_count < 300) {
            $warnings[] = sprintf(
                __('Content is short (%d words). Aim for at least 300 words for better SEO.', 'roidnet-ai-content-generator'),
                $word_count
            );
        }

        // Check for headings
        if (!preg_match('/<h[2-6][^>]*>/i', $content)) {
            $warnings[] = __('Content should include subheadings (H2, H3) for better readability.', 'roidnet-ai-content-generator');
        }

        // Check for paragraphs
        if (substr_count($content, '<p>') < 2) {
            $warnings[] = __('Content should have multiple paragraphs for better readability.', 'roidnet-ai-content-generator');
        }

        // Check for images (optional)
        if (!preg_match('/<img[^>]+>/i', $content)) {
            // This is fine since we add featured image separately
        }

        return array('errors' => $errors, 'warnings' => $warnings);
    }

    /**
     * Check meta description
     */
    private function check_meta_description($meta_description)
    {
        if (empty($meta_description)) {
            return __('Meta description is recommended for SEO.', 'roidnet-ai-content-generator');
        }

        $length = strlen($meta_description);

        if ($length < 120) {
            return __('Meta description is short. Aim for 150-160 characters.', 'roidnet-ai-content-generator');
        }

        if ($length > 160) {
            return __('Meta description is too long (maximum 160 characters).', 'roidnet-ai-content-generator');
        }

        return true;
    }

    /**
     * Calculate SEO score (0-100)
     */
    public function calculate_seo_score($article)
    {
        $score = 0;
        $max_score = 100;
        $checks = 0;
        $passed = 0;

        // Title checks (20 points)
        $checks++;
        $title = $article['title'] ?? '';
        if (!empty($title) && strlen($title) >= 20 && strlen($title) <= 70) {
            $passed++;
            $score += 20;
        }

        // Content length (20 points)
        $checks++;
        $content = strip_tags($article['content'] ?? '');
        $word_count = str_word_count($content);
        if ($word_count >= 300) {
            $passed++;
            $score += min(20, ($word_count / 500) * 20);
        }

        // Meta description (15 points)
        $checks++;
        $meta = $article['meta_description'] ?? '';
        if (!empty($meta) && strlen($meta) >= 120 && strlen($meta) <= 160) {
            $passed++;
            $score += 15;
        } elseif (!empty($meta)) {
            $score += 10;
        }

        // Focus keyword presence (15 points)
        $checks++;
        $focus_keyword = $article['focus_keyword'] ?? '';
        if (!empty($focus_keyword)) {
            $keyword_in_title = stripos($title, $focus_keyword) !== false;
            $keyword_in_content = stripos($content, $focus_keyword) !== false;

            if ($keyword_in_title && $keyword_in_content) {
                $passed++;
                $score += 15;
            } elseif ($keyword_in_content) {
                $score += 10;
            }
        }

        // Headings structure (15 points)
        $checks++;
        $raw_content = $article['content'] ?? '';
        if (preg_match('/<h2[^>]*>/i', $raw_content)) {
            $score += 10;
            if (preg_match('/<h3[^>]*>/i', $raw_content)) {
                $passed++;
                $score += 5;
            }
        }

        // Paragraph structure (10 points)
        $checks++;
        $paragraph_count = substr_count($raw_content, '<p>');
        if ($paragraph_count >= 3) {
            $passed++;
            $score += 10;
        } elseif ($paragraph_count >= 2) {
            $score += 5;
        }

        // Excerpt/intro (5 points)
        $checks++;
        if (!empty($article['excerpt'])) {
            $passed++;
            $score += 5;
        }

        return min(100, round($score));
    }

    /**
     * Check if keyword is unique (not already used)
     */
    public function is_keyword_unique($keyword)
    {
        $keyword_manager = new Keyword_Manager();
        return !$keyword_manager->is_duplicate($keyword);
    }

    /**
     * Validate content before publishing
     */
    public function validate_for_publish($post_id)
    {
        $post = get_post($post_id);

        if (!$post) {
            return new \WP_Error('post_not_found', __('Post not found.', 'roidnet-ai-content-generator'));
        }

        $article = array(
            'title' => $post->post_title,
            'content' => $post->post_content,
            'excerpt' => $post->post_excerpt,
            'meta_description' => get_post_meta($post_id, '_roidaico_meta_description', true),
            'focus_keyword' => get_post_meta($post_id, '_roidaico_focus_keyword', true),
        );

        return $this->check_content($article);
    }

    /**
     * Get quality report for a post
     */
    public function get_report($post_id)
    {
        $post = get_post($post_id);

        if (!$post) {
            return null;
        }

        $article = array(
            'title' => $post->post_title,
            'content' => $post->post_content,
            'excerpt' => $post->post_excerpt,
            'meta_description' => get_post_meta($post_id, '_roidaico_meta_description', true)
                ?: get_post_meta($post_id, '_yoast_wpseo_metadesc', true)
                ?: get_post_meta($post_id, 'rank_math_description', true),
            'focus_keyword' => get_post_meta($post_id, '_roidaico_focus_keyword', true)
                ?: get_post_meta($post_id, '_yoast_wpseo_focuskw', true)
                ?: get_post_meta($post_id, 'rank_math_focus_keyword', true),
        );

        $content_stripped = strip_tags($article['content']);

        return array(
            'seo_score' => $this->calculate_seo_score($article),
            'word_count' => str_word_count($content_stripped),
            'title_length' => strlen($article['title']),
            'meta_length' => strlen($article['meta_description']),
            'has_headings' => (bool) preg_match('/<h[2-6][^>]*>/i', $article['content']),
            'has_image' => has_post_thumbnail($post_id),
            'focus_keyword' => $article['focus_keyword'],
            'keyword_in_title' => !empty($article['focus_keyword'])
                && stripos($article['title'], $article['focus_keyword']) !== false,
        );
    }
}
