<?php

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

/**
 * Base class for all external API operations
 */
abstract class ContentCraftAI_ApiBase
{
    /**
     * API URL
     * @var string
     */
    protected $api_url;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->api_url = defined('CONTENT_CRAFT_AI_EXTERNAL_API') ? CONTENT_CRAFT_AI_EXTERNAL_API : '';
    }

    /**
     * Get common headers for API requests
     * 
     * @return array Headers array
     */
    protected function get_common_headers()
    {
        // Get the API key
        $api_key = get_option('content_craft_ai_api_key', '');

        // Get the site domain for the header
        $site_url = get_site_url();
        $domain = wp_parse_url($site_url, PHP_URL_HOST);

        return [
            'Content-Type' => 'application/json',
            'x-api-key' => $api_key,
            'x-wp-domain' => $domain
        ];
    }

    /**
     * Handle API response
     * 
     * @param mixed $response Response from wp_remote_request
     * @return array Processed response data
     */
    protected function handle_response($response)
    {
        if (is_wp_error($response)) {
            // error_log('Content Craft AI: External API error - ' . $response->get_error_message());
            return [
                'success' => false,
                'message' => $response->get_error_message()
            ];
        }

        $response_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);

        // Non-200 responses
        if ($response_code < 200 || $response_code >= 300) {
            // error_log('Content Craft AI: External API error - Response code ' . $response_code);

            // Return the error data from the API if available
            if ($data && isset($data['message'])) {
                return [
                    'success' => false,
                    'message' => $data['message'],
                    'code' => $response_code,
                    'errorCode' => $data['code'] ?? null
                ];
            }

            // Fallback error message
            return [
                'success' => false,
                'message' => 'API returned error code: ' . $response_code,
                'code' => $response_code
            ];
        }

        // Invalid JSON response
        if (json_last_error() !== JSON_ERROR_NONE) {
            // error_log('Content Craft AI: External API error - Invalid JSON response');
            return [
                'success' => false,
                'message' => 'Invalid JSON response from API'
            ];
        }

        return $data;
    }
}
