<?php

class Upgrader
{
  private $token = null;
  private $errors = null;
  //private $inst_url = 'http://localhost/projects/crmconhub/public_html/index.php';
  private $inst_url = 'https://hub.crmconnect.ro';

  public function apiRequest($endpoint, $jsonData = [],$type='GET'){
    $this->togen = getenv('HUB_TOKEN');
        $curl = curl_init($this->inst_url.'/'.$endpoint);
        //pre($this->inst_url.'/'.$endpoint);
        $jsonDataEncoded = json_encode($jsonData);

        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        curl_setopt($curl, CURLOPT_VERBOSE , true);
        curl_setopt($curl, CURLOPT_STDERR, $verbose = fopen('php://temp', 'rw+'));


        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($curl, CURLOPT_HTTPHEADER, [
          //'Content-Type: application/json',
          'authtoken: '.$this->token //sau Authorization
        ]);

        if($type == 'POST'){
          curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonData);
        }
        if($type == 'GET'){
          curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
          if(!empty($jsonData)){
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($jsonData));
          }
        }
        if($type == 'PUT'){
          curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
          curl_setopt($curl, CURLOPT_POSTFIELDS,http_build_query($jsonData));
        }

        $jsonResponse = curl_exec($curl);
        //echo "Verbose information:\n", !rewind($verbose), stream_get_contents($verbose), "\n";

        $header_info = curl_getinfo($curl,CURLINFO_HEADER_OUT);
        //echo '<hr>';
        //echo $header_info ;
        //echo '<hr>';
        if ( $jsonResponse === FALSE)
           { exit("cURL Error: ".curl_error($curl)); }

        $jsonResponse = json_decode($jsonResponse, true);
        curl_close($curl);
        return($jsonResponse);
   }

	public function set_error($error){
        $this->errors[] = $error;
    }
    public function get_errors(){
        return $this->errors;
    }

  public function post_install_data($data){
      return $this->apiRequest('updater/post_install_data/',$data,'POST');
  }


}
