<?php
/**
 * FajaedeSEO Pro AI Content Generator
 *
 * Handles AI-powered content generation, including text and SEO-optimized headers.
 */

defined('ABSPATH') or exit;

class FajaedeSEO_Pro_Generator {

    public static function init() {
        add_action('rest_api_init', [__CLASS__, 'register_routes']);
    }

    /**
     * Generates SEO-optimized H2 headers for a given content.
     *
     * @param string $content The content to analyze for header generation.
     * @param string $focus_keyword An optional focus keyword to guide generation.
     * @return array An array of suggested H2 headers.
     */
    public static function generate_h2_headers(string $content, string $focus_keyword = ''): array {
        // We leverage the existing SEO module for smart header suggestions.
        // This ensures consistency and utilizes the AI capabilities already in place.
        $prompt = "Generate 3-5 SEO-optimized H2 headers for the following content. Focus on clarity and relevance. Return as a comma-separated list. Content: " . wp_strip_all_tags($content);
        if (!empty($focus_keyword)) {
            $prompt .= " Focus keyword: " . sanitize_text_field($focus_keyword);
        }

        $result = \FajaedeSEO_AI_Service_Manager::call_openai($prompt, [
            'max_tokens' => 100, // Limit the length of the response
            'temperature' => 0.7, // Allow some creativity
        ]);

        if (is_wp_error($result)) {
            // Fallback to a simple rule-based approach or return empty
            return self::fallback_h2_generation($content, $focus_keyword);
        }

        $headers = explode(',', \FajaedeSEO_AI_Service_Manager::extract_text_from_response($result));
        return array_map('trim', $headers);
    }

    /**
     * Fallback for H2 header generation if AI service fails.
     *
     * @param string $content The content to analyze.
     * @param string $focus_keyword An optional focus keyword.
     * @return array An array of fallback H2 headers.
     */
    private static function fallback_h2_generation(string $content, string $focus_keyword = ''): array {
        // Simple fallback: use keywords or generic headers
        $keywords = \FajaedeSEO_Module_Keywords::extract_focus_keywords($content, 3);
        if (!empty($keywords)) {
            return array_map(fn($kw) => "H2: " . ucfirst($kw), $keywords);
        }
        return ['Belangrijke Informatie', 'Meer Details', 'Conclusie'];
    }

    /**
     * Generates a block of content based on a prompt and optional context.
     *
     * @param string $prompt The user's prompt for content generation.
     * @param string $focus_keyword An optional focus keyword to guide generation.
     * @param string $context_content Optional existing content for AI context.
     * @return string The AI-generated content.
     */
    public static function generate_content(string $prompt, string $focus_keyword = '', string $context_content = ''): string {
        $full_prompt = "Generate a compelling and SEO-friendly text block based on the following instructions:\n\n";
        $full_prompt .= "Prompt: " . sanitize_textarea_field($prompt) . "\n";
        
        if (!empty($focus_keyword)) {
            $full_prompt .= "Focus Keyword: " . sanitize_text_field($focus_keyword) . "\n";
        }
        if (!empty($context_content)) {
            $full_prompt .= "Existing Content Context: " . wp_strip_all_tags($context_content) . "\n";
        }
        $full_prompt .= "Ensure the output is well-structured, easy to read, and directly answers the prompt. Return only the generated text, formatted with paragraphs and basic HTML (like <strong> or <em>) if appropriate, but no H1/H2 tags.";

        $result = \FajaedeSEO_AI_Service_Manager::call_openai($full_prompt, [
            'max_tokens' => 500, // Allow for longer content blocks
            'temperature' => 0.8, // More creativity for content generation
        ]);

        if (is_wp_error($result)) {
            return self::fallback_content_generation($prompt, $focus_keyword);
        }

        return \FajaedeSEO_AI_Service_Manager::extract_text_from_response($result);
    }

    /**
     * Fallback for general content generation if AI service fails.
     */
    private static function fallback_content_generation(string $prompt, string $focus_keyword = ''): string {
        $fallback_text = "<p>We couldn't generate content based on your prompt at this time.</p>";
        if ( ! empty( $focus_keyword ) ) $fallback_text .= "<!-- Focus: {$focus_keyword} -->";
        return $fallback_text;
    }

    // NEW: Endpoint for general content generation
    public static function register_routes() {
        register_rest_route('fajaedeseo/v1', '/generate-h2-headers', [
            'methods' => 'POST',
            'callback' => function($request) {
                $params = $request->get_json_params();
                $content = isset($params['content']) ? wp_kses_post($params['content']) : '';
                $focus_keyword = isset($params['focus_keyword']) ? sanitize_text_field((string)$params['focus_keyword']) : '';

                if (!class_exists('FajaedeSEO_Pro_Generator')) {
                    return new \WP_Error('generator_not_found', 'FajaedeSEO_Pro_Generator class not found.', ['status' => 500]);
                }

                $headers = \FajaedeSEO_Pro_Generator::generate_h2_headers($content, $focus_keyword);
                return ['headers' => $headers];
            },
            'permission_callback' => fn() => current_user_can('edit_posts')
        ]);

        register_rest_route('fajaedeseo/v1', '/generate-content', [
            'methods' => 'POST',
            'callback' => function($request) {
                $params = $request->get_json_params();
                $prompt = isset($params['prompt']) ? sanitize_textarea_field($params['prompt']) : '';
                $focus_keyword = isset($params['focus_keyword']) ? sanitize_text_field((string)$params['focus_keyword']) : '';
                $context_content = isset($params['context_content']) ? wp_kses_post($params['context_content']) : '';

                if (!class_exists('FajaedeSEO_Pro_Generator')) {
                    return new \WP_Error('generator_not_found', 'FajaedeSEO_Pro_Generator class not found.', ['status' => 500]);
                }
                $content = \FajaedeSEO_Pro_Generator::generate_content($prompt, $focus_keyword, $context_content);
                return ['content' => $content];
            },
            'permission_callback' => fn() => current_user_can('edit_posts')
        ]);
    }
}