<?php
defined('ABSPATH') || exit;

/* ---------------------------------------------------------
   REST API Endpoint Registration
--------------------------------------------------------- */
add_action('rest_api_init', function () {
    register_rest_route('ezhp/v1', '/numerology', [
        'methods'  => 'GET',
        'callback' => 'ezhp_rest_numerology',
        'permission_callback' => '__return_true',
    ]);
});

/* ---------------------------------------------------------
   REST Callback: Handle Numerology Request
--------------------------------------------------------- */
function ezhp_rest_numerology($request) {

    $full_name  = sanitize_text_field($request->get_param('fullName'));
    $birth_date = sanitize_text_field($request->get_param('birthDate'));
    $language   = sanitize_text_field($request->get_param('language') ?? 'en');
    $api_key    = sanitize_text_field(get_option('ezhp_horoscope_activation_guid', ''));

    if (empty($full_name) || empty($birth_date)) {
        wp_send_json([
            'html' => '<div>Please provide both your full name and birthdate.</div>'
        ]);
        return;
    }

    /* ---------------------------------------------------------
       Build Numerology API URL
    --------------------------------------------------------- */
    $api_url = sprintf(
        'https://api.ezhoroscope.com/api/horoscope/numerology?fullName=%s&birthDate=%s&apikey=%s&language=%s',
        rawurlencode($full_name),
        rawurlencode($birth_date),
        rawurlencode($api_key),
        rawurlencode($language)
    );

    /* ---------------------------------------------------------
       Perform Request
    --------------------------------------------------------- */
    $response = wp_remote_get($api_url, ['timeout' => 300]);

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

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

    if (empty($data) || empty($data['interpretation'])) {
        wp_send_json([
            'html' => '<div>Unable to generate numerology report.</div>'
        ]);
        return;
    }

    /* ---------------------------------------------------------
       Wrap Interpretation in <section> (block expects this)
    --------------------------------------------------------- */
    $wrapped_html = sprintf(
        '<section class="numerology-report">%s</section>',
        $data['interpretation']
    );

    wp_send_json([
        'html' => $wrapped_html
    ]);
    return;
}
