<?php

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Controller for Title-to-Article feature
 * Handles the business logic layer between WordPress routes and external API
 */
class TitleArticleController
{
    /**
     * API handler instance
     * @var ContentCraftAI_TitleArticleAPI
     */
    protected $api_handler;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->api_handler = new ContentCraftAI_TitleArticleAPI();
    }

    /**
     * Generate titles based on keywords
     * 
     * @param array $data Data for title generation
     * @return array Result with generated titles
     */
    public function generate_titles($data)
    {
        // Enhance data with category name if needed
        if (!empty($data['category'])) {
            $category_id = intval($data['category']);
            $category_obj = get_category($category_id);
            if ($category_obj) {
                $data['categoryName'] = $category_obj->name;
            }
        }

        // Call the API handler
        return $this->api_handler->generate_titles($data);
    }

    /**
     * Generate articles from selected titles
     * 
     * @param array $articles Array of article data
     * @return array Result of the operation
     */
    public function generate_articles($articles)
    {
        try {
            // Validate articles array
            if (empty($articles) || !is_array($articles)) {
                return [
                    'success' => false,
                    'message' => 'Articles data is required',
                    'code' => 400
                ];
            }

            // Limit to 10 articles
            if (count($articles) > 10) {
                return [
                    'success' => false,
                    'message' => 'Maximum of 10 articles allowed per request',
                    'code' => 400
                ];
            }

            // Format articles for validation
            $articles_to_validate = [];
            foreach ($articles as $article) {
                if (empty($article['articleTitle']) || empty($article['focusKeyword'])) {
                    continue;
                }

                $articles_to_validate[] = [
                    'title' => $article['articleTitle'],
                    'focusKeyword' => $article['focusKeyword'],
                    'wordCount' => $article['wordCount'] ?? 1000,
                    'tagCount' => $article['tagCount'] ?? 5,
                    'language' => $article['language'] ?? 'en',
                    'aiModel' => $article['aiModel'] ?? 'gpt-4o-mini',
                    'imageService' => $article['imageService'] ?? 'pexels',
                    'includeImages' => isset($article['includeImages']) ? $article['includeImages'] : true,
                    'setFeaturedImage' => isset($article['setFeaturedImage']) ? $article['setFeaturedImage'] : true,
                    'imageKeywords' => $article['imageKeywords'] ?? '',
                    'postStatus' => $article['postStatus'] ?? 'draft',
                ];
            }

            // Validate all articles in bulk
            require_once CONTENT_CRAFT_AI_PLUGIN_PATH . 'app/api/article-generator/single-article.php';
            $validation_result = content_craft_ai_api_validate_article($articles_to_validate, true);

            if (!$validation_result['success']) {
                // Format validation errors for the response
                $failed_articles = [];

                // Check if we have results for individual articles
                if (isset($validation_result['results']) && is_array($validation_result['results'])) {
                    foreach ($validation_result['results'] as $index => $result) {
                        if (!$result['valid']) {
                            $title = isset($result['article']) ? $result['article'] : "Article #" . ($index + 1);
                            $error_message = $this->format_error_message($result['errors'] ?? []);

                            $failed_articles[] = [
                                'title' => $title,
                                'error' => $error_message,
                                'code' => 403
                            ];
                        }
                    }
                }
                // If we have general errors
                else if (isset($validation_result['errors']) && is_array($validation_result['errors'])) {
                    $failed_articles[] = [
                        'title' => 'Article validation',
                        'error' => $this->format_error_message($validation_result['errors']),
                        'code' => 403
                    ];
                }
                // Fallback for unknown error format
                else {
                    $failed_articles[] = [
                        'title' => 'Article validation',
                        'error' => 'Unknown validation error',
                        'code' => 403
                    ];
                }

                $response = [
                    'success' => false,
                    'message' => $validation_result['message'],
                    'data' => [
                        'articles' => [],
                        'failedArticles' => $failed_articles,
                        'hasFailedArticles' => true,
                        'hasScheduledArticles' => false
                    ],
                    'code' => $validation_result['code'] ?? 403
                ];

                // Forward the 'results' array if present for frontend debugging
                if (isset($validation_result['results'])) {
                    $response['results'] = $validation_result['results'];
                }

                return $response;
            }

            // Get article generator controller
            require_once CONTENT_CRAFT_AI_PLUGIN_PATH . 'app/controllers/article-generator/ArticleGenerationController.php';
            $article_generator = ContentCraftAI_ArticleGenerationController::get_instance();

            $generated_articles = [];
            $failed_articles = [];
            $has_scheduled_articles = false;

            // Process each article
            foreach ($articles as $article) {
                // Skip articles without title or focus keyword
                if (empty($article['articleTitle']) || empty($article['focusKeyword'])) {
                    continue;
                }

                // Generate the article
                $result = $article_generator->generate_single_article($article);

                if ($result['success']) {
                    $generated_articles[] = $result['data'];

                    if (isset($result['data']['scheduled']) && $result['data']['scheduled']) {
                        $has_scheduled_articles = true;
                    }
                } else {
                    $failed_articles[] = [
                        'title' => $article['articleTitle'],
                        'error' => $result['message'],
                        'code' => $result['code'] ?? 400
                    ];
                }
            }

            return [
                'success' => true,
                'message' => count($generated_articles) . ' articles submitted for generation',
                'data' => [
                    'articles' => $generated_articles,
                    'failedArticles' => $failed_articles,
                    'hasFailedArticles' => !empty($failed_articles),
                    'hasScheduledArticles' => $has_scheduled_articles
                ]
            ];
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => 'Error generating articles: ' . $e->getMessage(),
                'code' => 500
            ];
        }
    }

    /**
     * Format error messages from validation errors
     * 
     * @param array $errors Array of error objects
     * @return string Formatted error message
     */
    private function format_error_message($errors)
    {
        if (empty($errors)) {
            return 'Unknown validation error';
        }

        $messages = [];
        foreach ($errors as $error) {
            if (isset($error['param']) && isset($error['message'])) {
                $messages[] = $error['message'];
            }
        }

        return implode('. ', $messages);
    }

    /**
     * Get instance (singleton pattern)
     * 
     * @return TitleArticleController
     */
    public static function get_instance()
    {
        static $instance = null;

        if ($instance === null) {
            $instance = new self();
        }

        return $instance;
    }
}
