<?php

namespace Cobblestone\CcLogin\Service;

use Exception;

/**
 * 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
     */
    protected function callURMService(string $url, string $token): ?array
    {
       return $this->callApi($url, [
           "Authorization: Bearer ${token}",
       ]);
    }

    protected function callApi(string $url, array $headers): ?array
    {
        $curl = curl_init();

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

        $response = curl_exec($curl);

        curl_close($curl);

        $response = json_decode($response, true);

        return $this->validateAPIResponse($response);
    }

    /**
     * Throws exception if msg key exists in response AND response is not null
     *
     * @param array|null $response
     * @param string $endpoint Optionally provide the endpoint that was called for more informational error message
     * @return array|null
     * @throws Exception
     */
    protected function validateAPIResponse(?array $response, string $endpoint = ""): ?array
    {
        // If the API communication was successful, but no results were found, the API will return null
        // If msg key exists, it's likely that an API error happened
        if ($response !== null && array_key_exists('msg', $response)) {
            $apiMsg = $response['msg'];

            $msg = "Error calling API endpoint $endpoint $apiMsg";

            throw new Exception($msg);
        } else {
            return $response;
        }
    }
}
