<?php

class CurlRequest
{

  protected $curlOpts = false;

  public function callAPI($url, $method='GET', $dataSend = false, $header=array(), $file=false, &$httpcode=false){
    $curl = curl_init();

    switch ($method){

      case "POST":
          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);
          }
        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:
        curl_setopt($curl, CURLOPT_RETURNTRANSFER , true);
        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

    $content = curl_exec($curl);

    $dataSend = json_decode($content);

    curl_setopt($curl, CURLOPT_HEADER, true);
    $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    return $dataSend;
  }



}