<?php
require_once "tlog.php";

class TCall {

    static function makeRequest($json, $token) {
        global $config;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $config['Server'] . "message");
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $token
        ]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json));

        // informa que irá aguardar a resposta do servidor
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $retorno = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // verifica se o servidor da telic recebeu as informações com sucesso.
        if (curl_errno($ch)) {
            $error_msg = curl_error($ch);
            TLog::log("[ERRO CURL] Durante envio para o servidor ".$config['Server'].", houve o seguinte erro: ".$error_msg);
        } else {
            $retorno = json_decode($retorno);

            if($retorno) {
                if(!$retorno->ok)
                    TLog::log("[ERRO Webhook] Durante envio para o servidor ".$config['Server'].", o servidor recusou a mensagem (".json_encode($retorno).")");
                else {
                    curl_close($ch);
                    return true;
                }
            } else {
                TLog::log("[ERRO cURL] No envio para ".$config['Server'].", opções usadas: TOKEN=$token | Mensagem:".$json);
            }
        }
        curl_close($ch);
        return false;
    }

}