<?php
// Functions for API calls
if (! defined('ABSPATH')) exit;
// Include configuration file dynamically
include_once TAROTXHOROSCOPE_PLUGIN_DIR . 'api/config.php';

// Tarot Games and Chat Token API Handler Class
class TarotxHoroscope_API_Handler
{
    public function tarotxhoroscope_card_api_call()
    {
        // Check if action is provided
        if (!isset($_POST['action'])) {
            wp_send_json_error('Missing action');
            wp_die();
        }

        // Sanitize and unslash the action name
        $action_name = sanitize_text_field(wp_unslash($_POST['action']));

        // Verify nonce based on action
        if ($action_name === 'onecard_api_call') {
            check_ajax_referer('onecard_nonce', 'security');
        } elseif ($action_name === 'dailytarot_api_call') {
            check_ajax_referer('dailycard_nonce', 'security');
        } elseif ($action_name === 'threecard_api_call') {
            check_ajax_referer('threecard_nonce', 'security');
        } else {
            wp_send_json_error('Invalid action name');
            wp_die();
        }

        // Ensure API URLs are defined
        if (!isset($GLOBALS['tarotxhoroscope_oneCardUrl']) || !isset($GLOBALS['tarotxhoroscope_dailyTarotUrl']) || !isset($GLOBALS['tarotxhoroscope_threeCardUrl'])) {
            wp_send_json_error('API configuration error');
            wp_die();
        }

        // Map action names to URLs
        $action_urls = array(
            'onecard_api_call' => $GLOBALS['tarotxhoroscope_oneCardUrl'],
            'dailytarot_api_call' => $GLOBALS['tarotxhoroscope_dailyTarotUrl'],
            'threecard_api_call' => $GLOBALS['tarotxhoroscope_threeCardUrl'],
        );

        // Validate URL for the action
        $url = isset($action_urls[$action_name]) ? $action_urls[$action_name] : '';
        if (!$url) {
            wp_send_json_error('Invalid action name');
            wp_die();
        }

        // Fetch API key and make HTTP GET request
        $apiKey = get_option('tarotxhoroscope_api_key');
        $response = wp_remote_get($url, array(
            'headers' => array(
                'Authorization' => 'Api-Key ' . $apiKey
            )
        ));

        // Handle request errors
        if (is_wp_error($response)) {
            wp_send_json_error('HTTP request error: ' . $response->get_error_message());
            wp_die();
        }

        // Check HTTP status code
        $http_code = wp_remote_retrieve_response_code($response);
        if ($http_code != 200) {
            wp_send_json_error('HTTP error: ' . $http_code);
            wp_die();
        }

        // Decode response body
        $body = wp_remote_retrieve_body($response);
        $cards = json_decode($body, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            wp_send_json_error('JSON decode error: ' . json_last_error_msg());
            wp_die();
        }

        // Echo the response directly
        header('Content-Type: application/json');
        echo wp_json_encode($cards);
        wp_die();
    }
}

// Instantiate and add WordPress AJAX handlers
$api_handler = new TarotxHoroscope_API_Handler();
add_action('wp_ajax_onecard_api_call', array($api_handler, 'tarotxhoroscope_card_api_call'));
add_action('wp_ajax_nopriv_onecard_api_call', array($api_handler, 'tarotxhoroscope_card_api_call'));
add_action('wp_ajax_dailytarot_api_call', array($api_handler, 'tarotxhoroscope_card_api_call'));
add_action('wp_ajax_nopriv_dailytarot_api_call', array($api_handler, 'tarotxhoroscope_card_api_call'));
add_action('wp_ajax_threecard_api_call', array($api_handler, 'tarotxhoroscope_card_api_call'));
add_action('wp_ajax_nopriv_threecard_api_call', array($api_handler, 'tarotxhoroscope_card_api_call'));

// Function to get chat token for WebSocket connection
function tarotxhoroscope_chat_token_api_call()
{
    // Get raw input and decode JSON
    $raw_input = file_get_contents('php://input');
    if (empty($raw_input)) {
        wp_send_json_error('Empty input data');
        wp_die();
    }
    $input_data = json_decode($raw_input, true);
    if (!is_array($input_data)) {
        wp_send_json_error('Invalid JSON data');
        wp_die();
    }

    // Validate security nonce
    if (!isset($input_data['security']) || !is_string($input_data['security'])) {
        wp_send_json_error('Missing or invalid security nonce');
        wp_die();
    }

    $nonce = sanitize_text_field(wp_unslash($input_data['security']));
    if (!wp_verify_nonce($nonce, 'chat_token_nonce')) {
        wp_send_json_error('Invalid nonce');
        wp_die();
    }

    // Fetch API key and URL
    global $tarotxhoroscope_chatTokenUrl;
    $apiKey = get_option('tarotxhoroscope_api_key');

    // Make POST request
    $response = wp_remote_post($tarotxhoroscope_chatTokenUrl, array(
        'body' => array('api_key' => $apiKey)
    ));

    // Handle request errors
    if (is_wp_error($response)) {
        wp_send_json_error('HTTP request error: ' . $response->get_error_message());
        wp_die();
    }

    // Decode response
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body);
    if (json_last_error() !== JSON_ERROR_NONE || !isset($data->token)) {
        wp_send_json_error('Invalid API response');
        wp_die();
    }

    // Echo the token directly
    header('Content-Type: application/json');
    echo wp_json_encode(array('token' => $data->token));
    wp_die();
}

// Function to call Monthly Horoscope API
function tarotxhoroscope_horoscopemonthly_api_call()
{
    // Verify nonce
    check_ajax_referer('horoscope_nonce', 'security');

    // Validate and sanitize star sign
    if (!isset($_POST['starsign'])) {
        wp_send_json_error('Missing star sign');
        wp_die();
    }
    $starsign = sanitize_text_field(wp_unslash($_POST['starsign']));
    $valid_signs = ['aries', 'taurus', 'gemini', 'cancer', 'leo', 'virgo', 'libra', 'scorpio', 'sagittarius', 'capricorn', 'aquarius', 'pisces'];
    if (!in_array($starsign, $valid_signs)) {
        wp_send_json_error('Invalid star sign');
        wp_die();
    }

    // Use gmdate for consistent month value
    $month = gmdate('m');
    $url = $GLOBALS['tarotxhoroscope_monthlyhoroscopeCardUrl'] . "?starsign=" . $starsign . "&month=" . $month;
    $apiKey = get_option('tarotxhoroscope_api_key');

    // Make GET request
    $response = wp_remote_get($url, array(
        'headers' => array(
            'Authorization' => 'Api-Key ' . $apiKey,
            'Content-Type' => 'application/json'
        )
    ));

    // Handle request errors
    if (is_wp_error($response)) {
        wp_send_json_error('HTTP request error: ' . $response->get_error_message());
        wp_die();
    }

    // Check HTTP status code
    $http_code = wp_remote_retrieve_response_code($response);
    if ($http_code != 200) {
        wp_send_json_error('HTTP error: ' . $http_code);
        wp_die();
    }

    // Decode response
    $body = wp_remote_retrieve_body($response);
    $data = json_decode($body, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        wp_send_json_error('JSON decode error: ' . json_last_error_msg());
        wp_die();
    }

    // Send success response
    wp_send_json_success(array('monthly' => $data['monthly'] ?? 'No message available'));
}

// Add WordPress AJAX actions
add_action('wp_ajax_tarotxhoroscope_chat_token_api_call', 'tarotxhoroscope_chat_token_api_call');
add_action('wp_ajax_nopriv_tarotxhoroscope_chat_token_api_call', 'tarotxhoroscope_chat_token_api_call');
add_action('wp_ajax_tarotxhoroscope_horoscopemonthly_api_call', 'tarotxhoroscope_horoscopemonthly_api_call');
add_action('wp_ajax_nopriv_tarotxhoroscope_horoscopemonthly_api_call', 'tarotxhoroscope_horoscopemonthly_api_call');
