<?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/StatusCheckController.php';

/**
 * Handle article status check request
 * 
 * @param WP_REST_Request $request The request object
 * @return WP_REST_Response The response object
 */
function content_craft_ai_handle_article_status($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 controller instance
        $controller = ContentCraftAI_StatusCheckController::get_instance();

        // Check article status using controller
        $result = $controller->check_article_status($queue_id);

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

/**
 * Handle article generation history request
 * 
 * @param WP_REST_Request $request The request object
 * @return WP_REST_Response The response object
 */
function content_craft_ai_handle_article_history($request)
{
    try {
        // Get query parameters for pagination and filtering
        $page = $request->get_param('page') ? (int)$request->get_param('page') : 1;
        $per_page = $request->get_param('per_page') ? (int)$request->get_param('per_page') : 10;

        // Get filters
        $filters = [
            'status' => $request->get_param('status'),
            'postStatus' => $request->get_param('postStatus'),
            'category' => $request->get_param('category'),
            'dateFrom' => $request->get_param('dateFrom'),
            'dateTo' => $request->get_param('dateTo'),
            'search' => $request->get_param('search'),
        ];

        // Remove empty filters
        $filters = array_filter($filters);

        // Get generations from database using the controller
        $controller = ContentCraftAI_StatusCheckController::get_instance();
        $history = $controller->get_generation_history($page, $per_page, $filters);

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

/**
 * Make a direct call to the external API to check article generation status
 * 
 * @param string $queue_id API queue ID to check
 * @return array Status response from API
 */
function content_craft_ai_api_check_status($queue_id)
{
    // Build API URL from constant or fallback to default
    $api_url = defined('CONTENT_CRAFT_AI_EXTERNAL_API')
        ? CONTENT_CRAFT_AI_EXTERNAL_API
        : '';

    if (empty($api_url)) {
        return [
            'success' => false,
            'message' => 'API URL not configured'
        ];
    }

    // Get API key
    $api_key = get_option('content_craft_ai_api_key', '');

    // Prepare headers
    $headers = [
        'Content-Type' => 'application/json',
        'x-api-key' => $api_key,
    ];

    // Prepare request args
    $request_args = [
        'headers' => $headers,
        'timeout' => 120
    ];

    // Add domain header - sanitize and unslash HTTP_HOST
    $domain = isset($_SERVER['HTTP_HOST']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_HOST'])) : site_url();
    $request_args['headers']['x-wp-domain'] = $domain;

    // Make API request
    $response = wp_remote_get($api_url . '/articles/status/' . $queue_id, $request_args);

    if (is_wp_error($response)) {
        // error_log('Content Craft AI: API status check failed - ' . $response->get_error_message());
        return [
            'success' => false,
            'message' => $response->get_error_message()
        ];
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);

    if (!$body) {
        // error_log('Content Craft AI: Invalid API status response');
        return [
            'success' => false,
            'message' => 'Invalid API status response'
        ];
    }

    return $body;
}
