<?php

class EveAI_API {
    private $api_url;
    private $tenant_id;
    private $api_key;
    private $access_token;
    private $token_expiry;
    private $catalog_id;

    public function __construct() {
        $this->api_url = get_option('eveai_api_url');
        $this->tenant_id = get_option('eveai_tenant_id');
        $this->api_key = get_option('eveai_api_key');
        $this->access_token = get_option('eveai_access_token');
        $this->token_expiry = get_option('eveai_token_expiry', 0);
        $this->catalog_id = get_option('eveai_catalog_id');
    }

    private function ensure_valid_token() {
        if (empty($this->access_token) || time() > $this->token_expiry) {
            $this->get_new_token();
        }
    }

    private function get_new_token() {
        $response = wp_remote_post($this->api_url . '/api/v1/auth/token', [
            'body' => json_encode([
                'tenant_id' => $this->tenant_id,
                'api_key' => $this->api_key,
            ]),
            'headers' => [
                'Content-Type' => 'application/json',
            ],
        ]);

        if (is_wp_error($response)) {
            throw new Exception('Failed to get token: ' . $response->get_error_message());
        }

        $body = wp_remote_retrieve_body($response);

        // Check if the body is already an array (decoded JSON)
        if (!is_array($body)) {
            $body = json_decode($body, true);
        }

        if (empty($body['access_token'])) {
            throw new Exception('Invalid token response');
        }

        $this->access_token = $body['access_token'];
        // Use the expiration time from the API response, or default to 1 hour if not provided
        $expires_in = isset($body['expires_in']) ? $body['expires_in'] : 3600;
        $this->token_expiry = time() + $expires_in - 10; // Subtract 10 seconds to be safe

        update_option('eveai_access_token', $this->access_token);
        update_option('eveai_token_expiry', $this->token_expiry);
    }

    private function make_request($method, $endpoint, $data = null) {
        try {
            $this->ensure_valid_token();

            error_log('EveAI API Request: ' . $method . ' ' . $this->api_url . $endpoint);

            $url = $this->api_url . $endpoint;

            $args = array(
                'method'  => $method,
                'headers' => array(
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Bearer ' . $this->access_token,
                )
            );

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

            $response = wp_remote_request($url, $args);

            if (is_wp_error($response)) {
                $error_message = $response->get_error_message();
                error_log('EveAI API Error: ' . $error_message);
                throw new Exception('API request failed: ' . $error_message);
            }

            $body = wp_remote_retrieve_body($response);
            $status_code = wp_remote_retrieve_response_code($response);

            error_log('EveAI API Response: ' . print_r($body, true));
            error_log('EveAI API Status Code: ' . $status_code);

            // Check if the body is already an array (decoded JSON)
            if (!is_array($body)) {
                $body = json_decode($body, true);
            }

            if ($status_code == 401) {
                // Token might have expired, try to get a new one and retry the request
                error_log('Token expired, trying to get a new one...');
                $this->get_new_token();
                return $this->make_request($method, $endpoint, $data);
            }

            if ($status_code >= 400) {
                $error_type = isset($response_data['type']) ? $response_data['type'] : 'Unknown';
                $error_message = isset($response_data['message']) ? $response_data['message'] : 'Unknown error';
                $error_details = isset($response_data['debug']) ? json_encode($response_data['debug']) : '';

                error_log("EveAI API Error ({$error_type}): {$error_message}");
                if ($error_details) {
                    error_log("EveAI API Error Details: {$error_details}");
                }

                throw new Exception("API error ({$error_type}): {$error_message}");
            }

            return $body;
        } catch (Exception $e) {
            error_log("EveAI API Exception: " . $e->getMessage());
            throw $e;
        }
    }

    public function add_url($data) {
        $data['catalog_id'] = get_option('eveai_catalog_id');  // Include catalog_id
        return $this->make_request('POST', '/api/v1/documents/add_url', $data);
    }

    public function update_document($document_id, $data) {
        return $this->make_request('PUT', "/api/v1/documents/{$document_id}", $data);
    }

    public function invalidate_document($document_id) {
        error_log("EveAI API: Attempting to invalidate document {$document_id}");

        try {
            $result = $this->make_request('PUT', "/api/v1/documents/{$document_id}", [
                'valid_to' => gmdate('Y-m-d\TH:i:s\Z')  // Current UTC time in ISO 8601 format
            ]);

            error_log("EveAI API: Successfully invalidated document {$document_id}");
            return $result;
        } catch (Exception $e) {
            error_log("EveAI API: Error invalidating document {$document_id}: " . $e->getMessage());
            throw $e;
        }
    }

    public function refresh_document($document_id) {
        return $this->make_request('POST', "/api/v1/documents/{$document_id}/refresh");
    }

    public function refresh_document_with_info($document_id, $data) {
        return $this->make_request('POST', "/api/v1/documents/{$document_id}/refresh_with_info", $data);
    }
}
