<?php
// Exit if accessed directly
defined('ABSPATH') || exit;

// REST API endpoint for Zodiac Profile
add_action('rest_api_init', function () {
    register_rest_route('ezhp/v1', '/zodiac-profile', [
        'methods'             => 'GET',
        'callback'            => 'ezhp_rest_zodiac_profile',
        'permission_callback' => '__return_true',
    ]);
});

function ezhp_rest_zodiac_profile(WP_REST_Request $ezhp_request)
{
    $ezhp_birthdate = sanitize_text_field($ezhp_request->get_param('birthdate'));
    $ezhp_language  = sanitize_text_field($ezhp_request->get_param('language') ?: 'en');

    if (empty($ezhp_birthdate)) {
        return new WP_REST_Response([
            'error' => 'Please enter a valid birthdate.',
        ], 400);
    }

    $ezhp_api_key = sanitize_text_field(get_option('ezhp_horoscope_activation_guid', ''));

    $ezhp_api_url = sprintf(
        'https://api.ezhoroscope.com/api/ZodiacProfile/by-birthdate?birthdate=%s&apikey=%s&language=%s',
        rawurlencode($ezhp_birthdate),
        rawurlencode($ezhp_api_key),
        rawurlencode($ezhp_language)
    );

    $ezhp_response = wp_remote_get($ezhp_api_url, [
        'timeout' => 20,
        'headers' => ['Accept' => 'application/json'],
    ]);

    if (is_wp_error($ezhp_response)) {
        return new WP_REST_Response([
            'error' => 'Error contacting API.',
        ], 502);
    }

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

    if (json_last_error() !== JSON_ERROR_NONE || ! isset($ezhp_data['profileData'])) {
        return new WP_REST_Response([
            'error' => 'Unable to load zodiac profile.',
        ], 502);
    }

    // Return the full profile JSON to the frontend
    return new WP_REST_Response($ezhp_data, 200);
}