<?php

namespace limble\classes;
require_once WD . '/modules/limble/interfaces/limble_request_i.php';

use limble_request_i;

class limble_request implements limble_request_i
{

    /**
     * @inheritDoc
     */
    public function sendRequest(string $url, string $method = 'GET', array $data = [], array $headers = []): array
    {
        // Initialize cURL
        $ch = curl_init();
        $method = strtoupper($method);
        // Set the URL
        curl_setopt($ch, CURLOPT_URL, $url . ($method === 'GET' && !empty($data) ? '?' . http_build_query($data) : ''));
        // Set the HTTP method
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        // Set the data to send with the request
        if ($method !== 'GET') {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
            $headers[] = 'Content-Type: application/json';
        };
        // Set the headers
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        // Set options to return the response and handle SSL
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        // Execute the request
        $response = curl_exec($ch);
        // Check for errors
        if (curl_errno($ch)) {
            throw new \Exception('cURL error: ' . curl_error($ch));
        }
        // Get the HTTP status code
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // Close the cURL session
        curl_close($ch);
        // Check if the response is successful
        if ($httpCode < 200 || $httpCode >= 300) {
            $slack = new \classes\slack();
            echo 'Attempting credentials: ' . $url . ' with method: ' . $method . ' and data: ' . json_encode($data) . "\n";
            echo 'Response: ' . $response . "\n";
            echo 'HTTP Code: ' . $httpCode . "\n";
            echo 'Headers: ' . json_encode($headers) . "\n";
            $slack->send_message('Limble Request Failed: ' . $response, 'Limble Request Error');
            throw new \Exception('Request failed with status code ' . $httpCode);
        }
        // Check if the response is valid JSON
        $responseData = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new \Exception('Invalid JSON response: ' . json_last_error_msg());
        }
        // Return the response data
        return $responseData;
    }

    /**
     * @inheritDoc
     */
    public function generateBasicAuthHeader(string $client_id, string $client_secret): string
    {
        // Generate the Basic Auth header using the client ID and secret
        return 'Authorization: Basic ' . base64_encode($client_id . ':' . $client_secret);
    }
}