<?php
if (!defined('ABSPATH'))
    exit;

class Dori_Chatbot_API_Client
{
    public static function get_timeout_short()
    {
        return 60;
    }

    public static function get_timeout_long()
    {
        return 90;
    }

    public static function call_api($api_url, $data, $timeout = 30, $bypass_cache = false)
    {
        if ($bypass_cache) {
            $client_id = get_option('dori-chatbot-client-id', '');
            $client_secret = get_option('dori-chatbot-client-secret', '');
        } else {
            $credentials = Dori_Chatbot_Cache_Manager::get_api_credentials();
            $client_id = $credentials['client_id'];
            $client_secret = $credentials['client_secret'];
        }

        if (empty($client_id) || empty($client_secret)) {
            throw new Exception('شناسه کلاینت یا رمز کلاینت پیکربندی نشده است');
        }

        $body = wp_json_encode($data);
        $timestamp = time();
        $to_sign = "POST\n{$body}\n{$timestamp}";
        $signature = hash_hmac('sha256', $to_sign, $client_secret);

        $args = array(
            'headers' => array(
                'X-Client-Id' => $client_id,
                'X-Signature' => $signature,
                'X-Timestamp' => $timestamp,
                'Content-Type' => 'application/json',
            ),
            'body' => $body,
            'timeout' => $timeout,
        );

        $response = wp_remote_post($api_url, $args);

        return $response;
    }

    public static function call_api_simple($api_url, $data, $timeout = 30)
    {
        $args = array(
            'method' => 'POST',
            'timeout' => $timeout,
            'headers' => array(
                'Content-Type' => 'application/json'
            ),
            'body' => wp_json_encode($data),
        );

        $response = wp_remote_post($api_url, $args);

        return $response;
    }

    public static function call_api_get($api_url, $timeout = 15)
    {
        $args = array(
            'method' => 'GET',
            'timeout' => $timeout,
            'headers' => array(
                'Content-Type' => 'application/json'
            ),
        );

        $response = wp_remote_get($api_url, $args);

        return $response;
    }

    private static function should_retry_fast_response($response)
    {
        if (is_wp_error($response)) {
            return true;
        }

        $response_code = wp_remote_retrieve_response_code($response);
        return $response_code >= 500 && $response_code < 600;
    }

    private static function log_fast_retry($method, $api_url, $attempt, $response)
    {
        $status = 'transport_error';
        if (!is_wp_error($response)) {
            $status_code = wp_remote_retrieve_response_code($response);
            $status = 'http_' . $status_code;
        }

        Dori_Chatbot_Logger::debug("Retrying {$method} {$api_url} attempt {$attempt} ({$status})");
    }

    public static function call_api_post_fast($api_url, $data = null, $headers = array(), $timeout = 30, $max_retries = 0, $retry_delay_ms = 300)
    {
        $request_headers = array_merge(
            array(
                'Content-Type' => 'application/json',
            ),
            is_array($headers) ? $headers : array()
        );

        $args = array(
            'method' => 'POST',
            'timeout' => $timeout,
            'headers' => $request_headers,
        );

        if (null !== $data) {
            $args['body'] = wp_json_encode($data);
        }

        $attempt = 0;
        while (true) {
            $response = wp_remote_post($api_url, $args);
            if (!self::should_retry_fast_response($response) || $attempt >= $max_retries) {
                return $response;
            }

            $attempt++;
            self::log_fast_retry('POST', $api_url, $attempt, $response);

            $delay = (int) $retry_delay_ms * $attempt;
            if ($delay > 0) {
                usleep($delay * 1000);
            }
        }
    }

    public static function call_api_get_fast($api_url, $headers = array(), $timeout = 15, $max_retries = 0, $retry_delay_ms = 300)
    {
        $request_headers = array_merge(
            array(
                'Content-Type' => 'application/json',
            ),
            is_array($headers) ? $headers : array()
        );

        $args = array(
            'method' => 'GET',
            'timeout' => $timeout,
            'headers' => $request_headers,
        );

        $attempt = 0;
        while (true) {
            $response = wp_remote_get($api_url, $args);
            if (!self::should_retry_fast_response($response) || $attempt >= $max_retries) {
                return $response;
            }

            $attempt++;
            self::log_fast_retry('GET', $api_url, $attempt, $response);

            $delay = (int) $retry_delay_ms * $attempt;
            if ($delay > 0) {
                usleep($delay * 1000);
            }
        }
    }

    public static function get_user_id()
    {
        $credentials = Dori_Chatbot_Cache_Manager::get_api_credentials();
        $client_id = $credentials['client_id'];
        $client_secret = $credentials['client_secret'];

        if (empty($client_id) || empty($client_secret)) {
            throw new Exception('اعتبارات کلاینت پیکربندی نشده است');
        }

        $api_url = Dori_Chatbot_API_Constants::get_server_base_url() . Dori_Chatbot_API_Constants::ENDPOINT_WOOCOMMERCE_LOOKUP_USER;
        $data = array(
            'client_id' => $client_id,
            'client_secret' => $client_secret
        );

        $response = self::call_api_simple($api_url, $data);

        if (is_wp_error($response)) {
            throw new Exception('جستجوی کاربر ناموفق بود: ' . esc_html($response->get_error_message()));
        }

        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            $response_body = wp_remote_retrieve_body($response);
            throw new Exception('خطای سرور: ' . esc_html($response_body));
        }

        $response_body = wp_remote_retrieve_body($response);
        $response_data = json_decode($response_body, true);

        if (!is_array($response_data) || !isset($response_data['success']) || !$response_data['success']) {
            throw new Exception('جستجوی کاربر ناموفق بود: پاسخ نامعتبر');
        }

        if (!isset($response_data['user_id'])) {
            throw new Exception('شناسه کاربر در پاسخ یافت نشد');
        }

        return $response_data['user_id'];
    }

    public static function handle_api_response($response, $error_message = 'خطای API')
    {
        if (is_wp_error($response)) {
            throw new Exception($error_message . ': ' . esc_html($response->get_error_message()));
        }

        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            $response_body = wp_remote_retrieve_body($response);

            $decoded_body = json_decode($response_body, true);

            if (is_array($decoded_body) && isset($decoded_body['error'])) {
                $actual_error = sanitize_text_field($decoded_body['error']);
                throw new Exception($actual_error);
            } elseif (is_array($decoded_body) && isset($decoded_body['message'])) {
                $actual_error = sanitize_text_field($decoded_body['message']);
                throw new Exception($actual_error);
            }

            $trimmed_body = trim($response_body);
            if (!empty($trimmed_body)) {
                throw new Exception(sanitize_text_field($trimmed_body));
            }

            throw new Exception($error_message . ' - کد خطا ' . esc_html($response_code));
        }

        $response_body = wp_remote_retrieve_body($response);
        return json_decode($response_body, true);
    }
}
