<?php

namespace Cobblestone\CcLogin\Service;

use Exception;
use Symfony\Component\HttpFoundation\Response;

/**
 * Class AbstractCCService
 *
 * Abstract class for calling the API on CC User Rights Management
 * @package Cobblestone\CcLogin\Service
 */
abstract class AbstractCCService
{

    /**
     * @var string
     */
    protected $apiUrl;

    /**
     * UserService constructor.
     *
     * @param string $apiUrl
     */
    public function __construct(string $apiUrl)
    {
        $this->apiUrl = $apiUrl;
    }

    /**
     * @param string $url
     * @param string $token
     * @return array|null
     * @throws Exception
     */
    public function callURMService(string $url, string $token): ?array
    {
       return $this->callApi($url, [
           "Authorization: Bearer ${token}",
       ]);
    }

    /**
     * @param string $url
     * @param array $headers
     * @param array|string|null $payload
     * @return array|null
     * @throws Exception
     */
    public function callApi(string $url, array $headers, $payload = null): ?array
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $this->apiUrl . $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

        if (!empty($payload)) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
        }

        $response = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        curl_close($curl);

        $response = json_decode($response, true);

        if ($status >= Response::HTTP_BAD_REQUEST) {
            throw new Exception("Error calling API endpoint $response");
        }

        return $response;
    }
}
