<?php
/**
 * Moon Phase REST API
 *
 * @package EZ_Horoscope
 */

defined('ABSPATH') || exit;

/**
 * Register moon phase REST API routes
 */
add_action('rest_api_init', function () {
    register_rest_route('ezhp/v1', '/moon-content', array(
        'methods'             => 'GET',
        'callback'            => 'ezhp_get_moon_content',
        'permission_callback' => '__return_true',
        'args'                => array(
            'zodiacSign' => array(
                'required'          => true,
                'type'              => 'string',
                'sanitize_callback' => 'sanitize_text_field',
            ),
            'language'   => array(
                'required'          => false,
                'type'              => 'string',
                'default'           => 'en',
                'sanitize_callback' => 'sanitize_text_field',
            ),
        ),
    ));
});

/**
 * Get moon content from external API
 *
 * @param WP_REST_Request $request The request object.
 * @return WP_REST_Response|WP_Error
 */
function ezhp_get_moon_content($request) {
    $ezhp_zodiac_sign = $request->get_param('zodiacSign');
    $ezhp_language    = $request->get_param('language');
    $ezhp_api_key     = get_option('ezhp_horoscope_activation_guid', '');

    // Build external API URL
    $ezhp_api_url = add_query_arg(
        array(
            'zodiacSign' => $ezhp_zodiac_sign,
            'language'   => $ezhp_language,
            'apikey'     => $ezhp_api_key,
        ),
        'https://api.ezhoroscope.com/api/Astrology/moon-content'
    );

    // Make the request
    $ezhp_response = wp_remote_get($ezhp_api_url, array(
        'timeout' => 20,
        'headers' => array('Accept' => 'application/json'),
    ));

    if (is_wp_error($ezhp_response)) {
        return new WP_Error(
            'api_error',
            __('Unable to fetch moon content.', 'ez-horoscope'),
            array('status' => 500)
        );
    }

    $ezhp_body = wp_remote_retrieve_body($ezhp_response);
    $ezhp_data = json_decode($ezhp_body, true);

    if (empty($ezhp_data)) {
        return new WP_Error(
            'no_content',
            __('No moon content available.', 'ez-horoscope'),
            array('status' => 404)
        );
    }

    return rest_ensure_response($ezhp_data);
}
