<?php

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

/**
 * Controller that handles REST API requests for Title-to-Article functionality
 */
class TitleArticleHandlersController
{
    /**
     * TitleArticleController instance
     * @var TitleArticleController
     */
    protected $controller;

    /**
     * Constructor
     */
    public function __construct()
    {
        require_once dirname(__FILE__) . '/TitleArticleController.php';
        $this->controller = TitleArticleController::get_instance();
    }

    /**
     * Handle title generation from keywords
     * 
     * @param WP_REST_Request $request The request object
     * @return WP_REST_Response The response object
     */
    public function handle_generate_titles($request)
    {
        try {
            $params = $request->get_json_params();

            // Validate required fields
            if (empty($params['keywords'])) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Keywords are required'
                ], 400);
            }

            // Validate maximum number of keywords
            $keywords = $params['keywords'];
            if (is_array($keywords)) {
                $keyword_count = count($keywords);
            } else {
                // Handle newlines and commas
                $keywords = str_replace(["\r\n", "\r", "\n"], ',', $keywords);
                $keywords_array = array_map('trim', explode(',', $keywords));
                $keywords_array = array_filter($keywords_array); // Remove empty entries
                $keyword_count = count($keywords_array);
            }

            if ($keyword_count > 10) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Maximum 10 keywords allowed. Please reduce the number of keywords.'
                ], 400);
            }

            // Get or default other parameters
            $count = isset($params['count']) ? intval($params['count']) : 5;

            // Validate maximum title count
            if ($count > 10) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Maximum 10 titles can be generated at once'
                ], 400);
            }

            $language = isset($params['language']) ? sanitize_text_field($params['language']) : 'en';
            $category = isset($params['category']) ? intval($params['category']) : 0;
            $aiModel = isset($params['aiModel']) ? sanitize_text_field($params['aiModel']) : '';

            // Process the request through the controller
            $result = $this->controller->generate_titles([
                'keywords' => $params['keywords'],
                'titleCount' => $count,
                'language' => $language,
                'category' => $category,
                'aiModel' => $aiModel
            ]);

            if ($result['success']) {
                return new WP_REST_Response([
                    'success' => true,
                    'data' => $result['data']
                ], 200);
            } else {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => $result['message'] ?? 'Failed to generate titles'
                ], 500);
            }
        } catch (Exception $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Handle article generation from selected titles
     * 
     * @param WP_REST_Request $request The request object
     * @return WP_REST_Response The response object
     */
    public function handle_generate_articles($request)
    {
        try {
            $params = $request->get_json_params();

            // Validate required fields
            if (empty($params['articles']) || !is_array($params['articles'])) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => 'Articles data is required'
                ], 400);
            }

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

            // Process articles through the controller
            $result = $this->controller->generate_articles($params['articles']);

            // Check if the generation process succeeded at all
            if (!$result['success']) {
                return new WP_REST_Response([
                    'success' => false,
                    'message' => $result['message'],
                    'data' => $result['data'] ?? null
                ], $result['code'] ?? 400);
            }

            // Determine the appropriate message based on results
            $message = 'Article generation started';

            if ($result['data']['hasScheduledArticles']) {
                $message = 'Articles scheduled successfully';
            }

            // Check if there were partial failures
            if (!empty($result['data']['failedArticles'])) {
                $successCount = count($result['data']['articles']);
                $failCount = count($result['data']['failedArticles']);

                if ($successCount > 0) {
                    $message = "$successCount article(s) submitted for generation. $failCount article(s) failed validation.";
                }
            }

            return new WP_REST_Response([
                'success' => true,
                'message' => $message,
                'data' => $result['data']
            ], 200);
        } catch (Exception $e) {
            return new WP_REST_Response([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

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

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

        return $instance;
    }
}
