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

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

function ezhp_rest_zodiac_compatibility(WP_REST_Request $ezhp_request)
{
    $ezhp_yourSign  = sanitize_text_field($ezhp_request->get_param('yourSign'));
    $ezhp_theirSign = sanitize_text_field($ezhp_request->get_param('theirSign'));
    $ezhp_language  = sanitize_text_field($ezhp_request->get_param('language') ?: 'en');

    if (empty($ezhp_yourSign) || empty($ezhp_theirSign)) {
        return [
            'html' => '<div>Please select both zodiac signs.</div>'
        ];
    }

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

    $ezhp_apiUrl = sprintf(
        'https://api.ezhoroscope.com/api/Horoscope/zodiac-compatibility?yourSign=%s&theirSign=%s&apikey=%s&language=%s',
        rawurlencode($ezhp_yourSign),
        rawurlencode($ezhp_theirSign),
        rawurlencode($ezhp_apiKey),
        rawurlencode($ezhp_language)
    );

    $ezhp_response = wp_remote_get($ezhp_apiUrl, [
        'timeout' => 300,
        'headers' => ['Accept' => '*/*'],
    ]);

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

    $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['compatibilityReport'])) {
        return ['html' => $ezhp_data['compatibilityReport']];
    }

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