<?php

class RestApi
{

  protected $curlOpts = false;

  public function setcurlOpts($curlOpts){
    $this->curlOpts = $curlOpts;
  }

  public function callAPI($url, $method, $dataSend, $header, $file, &$httpcode, $dataType = Type_DadosSend::TpDados_Identificar){
    $curl = curl_init();

    switch ($method){
      case "POST":
        if($dataType == Type_DadosSend::TpDados_Identificar){
          if (is_array($dataSend)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            if($file){
              curl_setopt($curl, CURLOPT_POSTFIELDS, $dataSend);
            }else{
              curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($dataSend));
            }
          }else{
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($curl, CURLOPT_POSTFIELDS, $dataSend);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER , true);
          }
        }else{
          if($dataType == Type_DadosSend::TpDados_Json){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($dataSend));
          }
        }
        break;
      case "PUT":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'PUT');
        if (is_array($dataSend)) {
          curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($dataSend));
        }else{
          curl_setopt($curl, CURLOPT_POSTFIELDS, $dataSend);
        }
        break;
      case "DELETE":
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'DELETE');
        break;
      default:
        if ($dataSend)
          $url = sprintf("%s?%s", $url, http_build_query($dataSend));
    }

    curl_setopt($curl, CURLOPT_URL, $url);
    if($this->curlOpts){
      foreach ($this->curlOpts as $key => $curlOpt){
        curl_setopt($curl, $key, $curlOpt);
      }
    }

    if(is_array($header) && !empty($header)){
      curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    }
//    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);/////Descomentar para teste local sem SSL
//    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);/////Descomentar para teste local sem SSL
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $content = curl_exec($curl);

    $dataSend = json_decode($content);

    curl_setopt($curl, CURLOPT_HEADER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT_MS, 5000);//time out em segundos
    $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    return $dataSend;
  }

}
