<?php

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

/**
 * This file depends on WordPress core functionality.
 * The following constants and types are defined by WordPress and will be available at runtime:
 * - CONTENT_CRAFT_AI_PLUGIN_PATH: Plugin path constant defined in the main plugin file
 * - WP_REST_Response: WordPress REST API response class
 */

// Include our new controller
require_once CONTENT_CRAFT_AI_PLUGIN_PATH . 'app/controllers/article-generator/ScheduledArticleController.php';
require_once __DIR__ . '/single-article.php'; // Include single-article.php for the API function

/**
 * Handle request to generate a scheduled article immediately
 * 
 * @param WP_REST_Request $request The request object
 * @return WP_REST_Response The response object
 */
function content_craft_ai_handle_generate_scheduled_article($request)
{
    try {
        $queue_id = $request['queue_id'];

        if (empty($queue_id)) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Queue ID is required'
            ], 400);
        }

        // Get the controller instance
        $controller = ContentCraftAI_ScheduledArticleController::get_instance();

        // Use the controller to generate the article
        $result = $controller->generate_scheduled_article($queue_id);

        if ($result['success']) {
            return new WP_REST_Response([
                'success' => true,
                'message' => 'Scheduled article generation started',
                'data' => $result['data']
            ]);
        } else {
            return new WP_REST_Response([
                'success' => false,
                'message' => $result['message']
            ], 500);
        }
    } catch (Exception $e) {
        return new WP_REST_Response([
            'success' => false,
            'message' => $e->getMessage()
        ], 500);
    }
}

/**
 * Handle request to reschedule an article
 * 
 * @param WP_REST_Request $request The request object
 * @return WP_REST_Response The response object
 */
function content_craft_ai_handle_reschedule_article($request)
{
    try {
        $queue_id = $request['queue_id'];
        $params = $request->get_json_params();

        if (empty($queue_id) || empty($params['scheduleDate'])) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Queue ID and new schedule date are required'
            ], 400);
        }

        // Get the controller instance
        $controller = ContentCraftAI_ScheduledArticleController::get_instance();

        // Use the controller to reschedule the article
        $result = $controller->reschedule_article($queue_id, $params['scheduleDate']);

        if ($result['success']) {
            return new WP_REST_Response([
                'success' => true,
                'message' => 'Article rescheduled successfully',
                'data' => $result['data']
            ]);
        } else {
            return new WP_REST_Response([
                'success' => false,
                'message' => $result['message']
            ], $result['code'] ?? 500);
        }
    } catch (Exception $e) {
        return new WP_REST_Response([
            'success' => false,
            'message' => $e->getMessage()
        ], 500);
    }
}

/**
 * Force check for scheduled articles
 * 
 * @param WP_REST_Request $request The request object
 * @return WP_REST_Response The response object
 */
function content_craft_ai_handle_check_scheduled_articles($request)
{
    try {
        // Get the controller instance
        $controller = ContentCraftAI_ScheduledArticleController::get_instance();

        // Use the controller to check for scheduled articles
        $stats = $controller->process_scheduled_articles();

        return new WP_REST_Response([
            'success' => true,
            'message' => $stats['processed'] > 0
                ? "Generated {$stats['success']} articles successfully. Failed: {$stats['failed']}"
                : "No scheduled articles due for generation",
            'data' => [
                'articlesCount' => $stats['total'],
                'processed' => $stats['processed'],
                'success' => $stats['success'],
                'failed' => $stats['failed']
            ]
        ]);
    } catch (Exception $e) {
        return new WP_REST_Response([
            'success' => false,
            'message' => $e->getMessage()
        ], 500);
    }
}

/**
 * Handle request to cancel an article generation
 * 
 * @param WP_REST_Request $request The request object
 * @return WP_REST_Response The response object
 */
function content_craft_ai_handle_cancel_article($request)
{
    try {
        $queue_id = $request['queue_id'];

        if (empty($queue_id)) {
            return new WP_REST_Response([
                'success' => false,
                'message' => 'Queue ID is required'
            ], 400);
        }

        // Get the controller instance
        $controller = ContentCraftAI_ScheduledArticleController::get_instance();

        // Use the controller to cancel the article
        $result = $controller->cancel_article($queue_id);

        if ($result['success']) {
            return new WP_REST_Response([
                'success' => true,
                'message' => 'Article generation cancelled successfully',
                'data' => $result['data']
            ]);
        } else {
            return new WP_REST_Response([
                'success' => false,
                'message' => $result['message']
            ], $result['code'] ?? 500);
        }
    } catch (Exception $e) {
        return new WP_REST_Response([
            'success' => false,
            'message' => $e->getMessage()
        ], 500);
    }
}
