<?php
require_once("../../config.php");
/**
 * 
 */
class Paghiper  
{
  
  private $classe; 

  private $email; //= "contato@iptvcs.eu";
  // private $token_sandbox = "88C4985520D746F1B690F90888FC8E76";
  private $apiKey;
  //URL OFICIAL
  //COMENTE AS 4 LINHAS ABAIXO E DESCOMENTE AS URLS DA SANDBOX PARA REALIZAR TESTES
  private $url;              
  //private $url_notificacao  = "https://iptvcs.eu/vendor/paghiper/notification.php";

  //private $email_token = "";//NÃO MODIFICAR
  private $statusCode = [ 
                0=>"pending",
                1=>"reserved",
                2=>"canceled",
                3=>"completed",
                4=>"paid",
                5=>"processing",
                6=>"refunded" ];
    
  public function __construct(){
    $this->classe = new cs;
    $this->email = 'contato@iptvcs.eu';
    $this->apiKey = "apk_48779473-rrovjCfjkkmDLwjmSmCuTPpsmvKtmjne";
    $this->url = "http://api.paghiper.com/transaction/create/";
    $this->url_retorno = SITE_URL."/vendor/paghiper/notificacao.php"; 
  }  

  public function setData($data) { 
    $data = [ 
      'apiKey'           => $this->apiKey,
      'email'            => $this->email,
      'order_id'         => $data['order_id'], // código interno do lojista para identificar a transacao.
      'payer_email'      => $data['payer_email'],
      'payer_name'       => $data['payer_name'],  
      'payer_cpf_cnpj'   => '02261719060', // cpf ou cnpj 
      'notification_url' => $this->url_retorno,
      'type_bank_slip'   => 'boletoA4', // formato do boleto
      'days_due_date'    => '5', // dias para vencimento do boleto

      'items' => [
        [
          'description' => $data['description'],
          'quantity'    => 1,
          'item_id'     => (string) $data['order_id'],
          'price_cents' => intval(str_replace('.', "", $data['amount']))
        ]
        
      ]
    ]; 
    return json_encode($data); 
  } 

  public function executeCheckout($data){
    
    $data = $this->setData($data);

    $curl = curl_init($this->url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=UTF-8'));
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    $result = curl_exec($curl);
    
    $json = json_decode($result, true);
    // captura o http code
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    
    if($httpCode == 201):
      
      curl_close($curl);
      
      
      
      $res = [
      // Exemplo de como capturar a resposta json
        'order_id'       => $json['create_request']['order_id'],
        'transaction_id' => $json['create_request']['transaction_id'],
        'url_slip'       => $json['create_request']['bank_slip']['url_slip'],
        'digitable_line' => $json['create_request']['bank_slip']['digitable_line']
      ]; 
      
      $this->updateStatus($res);
      // CÓDIGO 201 SIGNIFICA QUE O BOLETO FOI GERADO COM SUCESSO
      echo $result;
    
    else:
      echo $result;
    endif;

    //echo $url_code;
    
    //echo "<a title=\"URL do pagamento\" href=\"$url_code\"target=\_blank\"><button type=\"button\" class=\"btn btn-success\">Efetuar Pagamento!</button></a>";
    
    //header('Location: '.$this->url_redirect.$xml_obj->code);
  } 

  private function updateStatus($res) {
    //Atualizar code e link da cobrança
    $this->classe->executeQuery("
      UPDATE pagamentos_boleto 
      SET 
        date_update = '".date('Y-m-d H:i:s')."', 
        transaction_id = '".$res['transaction_id']."', 
        url = '".$res['url_slip']."', 
        bar_code = '".$res['digitable_line']."' 
      WHERE id = '".$res['order_id']."' 
    ");
  }

    
  
}
