<?php

namespace Sibs\Sibs\Model\Api;

use Sibs\Sibs\Utils\SibsException;

class SibsApi
{
    private static function header($ch, $header)
    {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    }

    public static function get($url, $header = [])
    {
        $ch = curl_init();

        if (! empty($header)) {
            self::header($ch, $header);
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // this should be set to true in production
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        try {
            $resp = curl_exec($ch);

            if (curl_errno($ch)) {
                throw new SibsException(curl_error($ch));
            }

            $response = json_decode($resp, true);
        } catch(SibsException $e) {
            $response = false;
        } finally {
            curl_close($ch);
        }

        return $response;
    }

    public static function post($url, $data = [], $header = [])
    {
        $ch = curl_init();

        if (! empty($header)) {
            self::header($ch, $header);
        }

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // this should be set to true in production
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        try {
            $resp = curl_exec($ch);

            if (curl_errno($ch)) {
                throw new SibsException(curl_error($ch));
            }

            $response = json_decode($resp, true);
        } catch(SibsException $e) {
            $response = false;
        } finally {
            curl_close($ch);
        }

        return $response;
    }
}
