<?php

namespace xlvask\classes;
require_once WD . '/modules/xlvask/interfaces/xlvask_request_i.php';

use classes\slack;
use xlvask\interfaces\xlvask_request_i;

class xlvask_request implements xlvask_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 slack();
            $slack->send_message(
                'XLVask API Request Failed',
                "URL: $url\nMethod: $method\nData: " . json_encode($data) . "\nHeaders: " . implode(', ', $headers) . "\nHTTP Code: $httpCode\nResponse: $response"
            );
            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) {
            // Check if the response is empty (which is valid)
            if ($response === '') {
                return [];
            }
            throw new \Exception('Invalid JSON response: ' . json_last_error_msg());
        }
        // Return the response data
        return $responseData;
    }

    /**
     * @inheritDoc
     */
    public function generateBasicAuthHeader(string $username, string $password): string
    {
        return 'Authorization: Basic ' . base64_encode($username . ':' . $password);
    }
}