<?php

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

/**
 * This file depends on WordPress core functionality.
 * The following functions are defined by WordPress and will be available at runtime:
 * - current_time: Function to get the current WordPress time
 * - wp_remote_post: Function to make HTTP POST requests
 * - is_wp_error: Function to check if a value is a WP_Error
 * - wp_remote_retrieve_body: Function to get body content from an HTTP response
 * - error_log: Function to log errors
 */

// Require the base controller
require_once dirname(__FILE__) . '/BaseController.php';

/**
 * Class ContentCraftAI_ScheduledArticleController
 * 
 * Handles the processing of scheduled articles for the Content Craft AI plugin.
 */
class ContentCraftAI_ScheduledArticleController extends ContentCraftAI_BaseController
{
    /**
     * Instance of this class.
     *
     * @var ContentCraftAI_ScheduledArticleController
     */
    private static $instance = null;

    /**
     * Get an instance of this class.
     *
     * @return ContentCraftAI_ScheduledArticleController
     */
    public static function get_instance()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct()
    {
        // Private constructor to prevent direct instantiation
    }

    /**
     * Process scheduled articles that are due for generation
     * 
     * @return array Statistics about processed articles
     */
    public function process_scheduled_articles()
    {
        // Get the scheduled article manager instance
        $scheduled_articles_manager = ContentCraftAI_ScheduledArticleManager::get_instance();
        $article_manager = ContentCraftAI_ArticleGenerationManager::get_instance();

        // Get scheduled articles that are due for generation
        $scheduled_articles = $scheduled_articles_manager->get_scheduled_generations_due();

        // Get current time using the base controller method
        $current_time = $this->format_datetime();

        // Simple log message as requested
        // error_log('Content Craft AI: Checking for scheduled articles at ' . $current_time);
        // error_log('Content Craft AI: Found ' . count($scheduled_articles) . ' articles ready to be generated');

        // Initialize counters for statistics
        $stats = [
            'total' => count($scheduled_articles),
            'processed' => 0,
            'success' => 0,
            'failed' => 0
        ];

        if (empty($scheduled_articles)) {
            return $stats;
        }

        // Process each scheduled article
        foreach ($scheduled_articles as $article) {
            try {
                // Get parameters
                $parameters = json_decode($article->parameters, true);

                if (!$parameters) {
                    // error_log('Content Craft AI: Invalid parameters for article ' . $article->queue_id);
                    $stats['failed']++;
                    continue;
                }

                // Update to pending status
                $article_manager->update_generation_status($article->queue_id, 'pending');
                // error_log('Content Craft AI: Starting generation for scheduled article: ' . $article->title);

                // Call API to generate article
                $api_response = content_craft_ai_api_generate_article($parameters);

                if ($api_response && isset($api_response['success']) && $api_response['success']) {
                    // Store API queue ID in parameters if available
                    if (isset($api_response['data']['queueId'])) {
                        $parameters['apiQueueId'] = $api_response['data']['queueId'];

                        // Update parameters in database
                        global $wpdb;
                        $wpdb->update(
                            $wpdb->prefix . 'content_craft_ai_generations',
                            ['parameters' => json_encode($parameters)],
                            ['queue_id' => $article->queue_id],
                            ['%s'], // parameters format
                            ['%s']  // queue_id format
                        );
                    }

                    // Update status to processing
                    $article_manager->update_generation_status($article->queue_id, 'processing');
                    // error_log('Content Craft AI: Successfully started generation for article: ' . $article->title);
                    $stats['success']++;
                } else {
                    // Failed to process
                    $article_manager->update_generation_status($article->queue_id, 'failed');
                    // error_log('Content Craft AI: Failed to start generation for article: ' . $article->title . ' - ' . ($api_response['message'] ?? 'Unknown error'));
                    $stats['failed']++;
                }
            } catch (Exception $e) {
                // Log the error and continue
                // error_log('Content Craft AI: Error processing scheduled article ' . $article->queue_id . ': ' . $e->getMessage());
                $article_manager->update_generation_status($article->queue_id, 'failed');
                $stats['failed']++;
            }

            $stats['processed']++;
        }

        return $stats;
    }

    /**
     * Generate a scheduled article immediately
     * 
     * @param string $queue_id The queue ID of the article to generate
     * @return array Result of the operation with success/failure and data
     */
    public function generate_scheduled_article($queue_id)
    {
        try {
            // Get the scheduled article from database
            $scheduled_articles_manager = ContentCraftAI_ScheduledArticleManager::get_instance();
            $article_manager = ContentCraftAI_ArticleGenerationManager::get_instance();
            $scheduled_article = $scheduled_articles_manager->get_scheduled_generation_by_queue_id($queue_id);

            if (!$scheduled_article) {
                return [
                    'success' => false,
                    'message' => 'Scheduled article not found',
                    'code' => 404
                ];
            }

            // Check if article is actually scheduled
            if ($scheduled_article->status !== 'scheduled') {
                return [
                    'success' => false,
                    'message' => 'Article is not in scheduled status',
                    'code' => 400
                ];
            }

            // Get the stored parameters
            $parameters = json_decode($scheduled_article->parameters, true);
            if (!$parameters) {
                return [
                    'success' => false,
                    'message' => 'Invalid article parameters',
                    'code' => 500
                ];
            }

            // Update status to pending
            $article_manager->update_generation_status($queue_id, 'pending');

            // Get the post creation manager to prepare API data with internal links
            require_once CONTENT_CRAFT_AI_PLUGIN_PATH . 'app/controllers/article-generator/PostCreationManager.php';
            $post_creation_manager = ContentCraftAI_PostCreationManager::get_instance();

            // Prepare API data with internal links
            $parameters = $post_creation_manager->prepare_api_data($parameters);

            // Generate the article using the API
            $api_response = content_craft_ai_api_generate_article($parameters);

            // Update our database record with the API queue ID if available
            if ($api_response && isset($api_response['success']) && $api_response['success'] && isset($api_response['data']['queueId'])) {
                // Store the API queue ID in the parameters
                $parameters['apiQueueId'] = $api_response['data']['queueId'];

                // Update the record to "processing" status
                $article_manager->update_generation_status($queue_id, 'processing');

                // Update the parameters in the database
                global $wpdb;
                $wpdb->update(
                    $wpdb->prefix . 'content_craft_ai_generations',
                    ['parameters' => json_encode($parameters)],
                    ['queue_id' => $queue_id],
                    ['%s'], // parameters format
                    ['%s']  // queue_id format
                );

                return [
                    'success' => true,
                    'message' => 'Scheduled article generation started',
                    'data' => [
                        'queueId' => $queue_id,
                        'apiQueueId' => $api_response['data']['queueId']
                    ]
                ];
            } else {
                // If the API call failed, update the status back to scheduled
                $article_manager->update_generation_status($queue_id, 'scheduled');

                return [
                    'success' => false,
                    'message' => $api_response['message'] ?? 'Failed to start article generation',
                    'code' => 500
                ];
            }
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage(),
                'code' => 500
            ];
        }
    }

    /**
     * Reschedule an article for a different time
     * 
     * @param string $queue_id The queue ID of the article to reschedule
     * @param string $schedule_date The new schedule date in ISO format
     * @return array Result of the operation with success/failure and data
     */
    public function reschedule_article($queue_id, $schedule_date)
    {
        try {
            // Convert the ISO date from frontend to MySQL datetime
            $scheduled_time = gmdate('Y-m-d H:i:s', strtotime($schedule_date));

            if (!$scheduled_time || $scheduled_time === '1970-01-01 00:00:00') {
                return [
                    'success' => false,
                    'message' => 'Invalid schedule date format',
                    'code' => 400
                ];
            }

            // Get the article from database
            $article_manager = ContentCraftAI_ArticleGenerationManager::get_instance();
            $article = $article_manager->get_generation_by_queue_id($queue_id);

            if (!$article) {
                return [
                    'success' => false,
                    'message' => 'Article not found',
                    'code' => 404
                ];
            }

            // Update the scheduled time
            global $wpdb;
            $result = $wpdb->update(
                $wpdb->prefix . 'content_craft_ai_generations',
                [
                    'scheduled_time' => $scheduled_time,
                    'status' => 'scheduled',
                    'is_scheduled' => 1
                ],
                ['queue_id' => $queue_id],
                ['%s', '%s', '%d'], // formats
                ['%s']  // queue_id format
            );

            if (!$result) {
                return [
                    'success' => false,
                    'message' => 'Failed to update article schedule',
                    'code' => 500
                ];
            }

            // Also update parameters
            $parameters = json_decode($article->parameters, true) ?: [];
            $parameters['scheduleDateTime'] = $scheduled_time;

            $wpdb->update(
                $wpdb->prefix . 'content_craft_ai_generations',
                ['parameters' => json_encode($parameters)],
                ['queue_id' => $queue_id],
                ['%s'], // parameters format
                ['%s']  // queue_id format
            );

            return [
                'success' => true,
                'message' => 'Article rescheduled successfully',
                'data' => [
                    'queueId' => $queue_id,
                    'scheduledTime' => $scheduled_time
                ]
            ];
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage(),
                'code' => 500
            ];
        }
    }

    /**
     * Cancel an article generation
     * 
     * @param string $queue_id The queue ID of the article to cancel
     * @return array Result of the operation with success/failure and data
     */
    public function cancel_article($queue_id)
    {
        try {
            // Get the article from database
            $article_manager = ContentCraftAI_ArticleGenerationManager::get_instance();
            $article = $article_manager->get_generation_by_queue_id($queue_id);

            if (!$article) {
                return [
                    'success' => false,
                    'message' => 'Article not found',
                    'code' => 404
                ];
            }

            // Update status to cancelled
            $result = $article_manager->update_generation_status($queue_id, 'cancelled');

            if (!$result) {
                return [
                    'success' => false,
                    'message' => 'Failed to cancel article generation',
                    'code' => 500
                ];
            }

            return [
                'success' => true,
                'message' => 'Article generation cancelled',
                'data' => [
                    'queueId' => $queue_id,
                    'status' => 'cancelled'
                ]
            ];
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage(),
                'code' => 500
            ];
        }
    }
}
