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

// REST API endpoint for Chinese Horoscope
add_action('rest_api_init', function () {
    register_rest_route('ezhp/v1', '/chinese-horoscope', [
        'methods'  => 'GET',
        'callback' => 'ezhp_rest_chinese_horoscope',
        'permission_callback' => '__return_true',
    ]);
});

function ezhp_rest_chinese_horoscope(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 [
            'html' => '<div>Please enter a valid birthdate.</div>'
        ];
    }

    // Convert YYYY-MM-DD → MM-DD-YYYY
    if (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $ezhp_birthdate, $ezhp_m)) {
        $ezhp_birthdate = $ezhp_m[2] . '-' . $ezhp_m[3] . '-' . $ezhp_m[1];
    }

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

    $ezhp_api_url = sprintf(
        'https://api.ezhoroscope.com/api/Horoscope/chinese?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' => '*/*'],
    ]);

    if (is_wp_error($ezhp_response)) {
        return ['html' => '<div>Error contacting API.</div>'];
    }

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

    if (json_last_error() === JSON_ERROR_NONE && isset($ezhp_ch_data['horoscopeText'])) {
        return ['html' => $ezhp_ch_data['horoscopeText']];
    }

    return ['html' => '<div>Unable to load Chinese horoscope.</div>'];
}
