<?php

namespace App\Services\Integrations;

use Exception;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class ZoomHardwareIntegration
{
    protected $baseUrl;
    protected $apiVersion;

    /**
     * Constructor for ZoomIntegration
     *
     */
    public function __construct()
    {
        $this->baseUrl = config('services.zoom_hardware.base_url');
        $this->apiVersion = config('services.zoom_hardware.api_version');
    }

    /**
     * Retrieves an access token using the provided credentials.
     *
     * @param object $credentials The credentials object containing the user name, password, and data.
     * @return mixed response is a JSON object containing the access token, the token type, and the number of seconds until the token expires.
     */
    public function generateAccessToken($credentials)
    {
        if (!$credentials) {
            return false;
        }

        try {
            $response = Http::withHeaders([
                'Authorization' => "Basic " . base64_encode($credentials->key . ':' . $credentials->password)
            ])
                ->post(config('services.zoom_hardware.token_url') . '?grant_type=account_credentials&account_id=' . $credentials->user_name)
                ->throw();

            if ($response->successful()) {
                return $response->json();
            }
        } catch (Exception $e) {
            Log::channel('daily')->error('Zoom token generation error: ' . $e->getMessage());
        }

        return false;
    }

    /**
     * It sends a POST request to the API endpoint with the data provided and returns the response in JSON format
     *
     * @param string $accessToken The access token for the API.
     * @param string $name The name of the API you are calling.
     * @param string $endpoint The url of the API endpoint you want to call.
     * @param array $queryParams The data to be sent to the API.
     *
     * @return mixed response from the API call.
     */
    public function getApiResponse($accessToken, $name, $endpoint, $queryParams = [])
    {
        if (!$accessToken) {
            return false;
        }

        $apiURL =  $this->baseUrl . '/' . $this->apiVersion . $endpoint;

        try {
            return Http::withToken($accessToken)
                ->retry(2, 2000)
                ->get($apiURL, $queryParams)
                ->throw()
                ->json();
        } catch (Exception $e) {
            Log::channel('daily')->info($name . " fetch error ---- " . $e->getMessage());

            return false;
        }
    }
}
