<?php

class Yapay extends RestApi
{

  private $api;
  private $tokenapi;
  private $registry;
  private $load;
  private $config;
  private $session;
  private $db;
  private $log;

  public function __construct($registry)
  {
    $this->registry = $registry;
    $this->load = $registry->get('load');
    $this->config = $registry->get('config');
    $this->session = $registry->get('session');
    $this->db = $registry->get('db');
    $this->log = $registry->get('log');

    $this->curlOpts = array(
      CURLOPT_RETURNTRANSFER => 1,
      CURLOPT_SSL_VERIFYPEER => false,
      CURLOPT_SSL_VERIFYHOST => false
    );

    $this->tokenapi = $this->config->get('yapay_token');
    $this->setEnvironment();
  }

  public function __get($name) {
    return $this->registry->get($name);
  }

  public function setEnvironment()
  {
    if ($this->config->get('yapay_ambiente') == Type_Environment::Tp_Sandbox) {
        $this->api = 'https://api.intermediador.sandbox.yapay.com.br/';
    } else {
        $this->api = 'https://api.intermediador.yapay.com.br/';
    }
  }

  public function getEnvironment()
  {
    return $this->api;
  }

  public function sendPayment($dataSend, $order_id)
  {
    try {
      $header =  array('Content-Type: application/json');
      $url = $this->getEnvironment() . 'api/v3/transactions/payment';
      $data = parent::callAPI($url, 'POST', $dataSend, $header, false, $retorno,Type_DadosSend::TpDados_Json);

      if(property_exists($data, 'message_response')){
        switch ($data->message_response->message){
          case 'success':
              return $data->data_response;
            break;
          case 'error':
            $msgError = 'Error ao finalizar o pedido '.$order_id.' usando YAPAY';
            $this->setErrorLog($msgError, $data);
            throw new exception($msgError);
            break;
        }
      }

    } catch (Exception $e) {
      throw $e;
    }
  }

  public function getPaymentStatusByToken($order_id, $token_transaction){

    try {
      $header =  array('Content-Type: application/json');
      $url = $this->getEnvironment() . "api/v3/transactions/get_by_token?token_account=".$this->tokenapi."&token_transaction=".$token_transaction;
      $data = parent::callAPI($url, 'GET', false, $header, false, $retorno,Type_DadosSend::TpDados_Json);

      if(property_exists($data, 'message_response')){

        switch ($data->message_response->message){
          case 'success':
            return $data->data_response;
            break;
          case 'error':
            $msgError = 'Error no callback de pagamento do pedido '.$order_id.' usando YAPAY:';
            $this->setErrorLog($msgError, $data);
            throw new exception($msgError);
            break;
        }
      }
    } catch (Exception $e) {
      throw $e;
    }

  }

  protected function setErrorLog($msgError, $data){
    $log = new Log(Date('Y-m-d') . '_payment_error.txt');
    $error = false;

    if ($data instanceof Exception) {
      $error = true;
      $logData = [
        'tag'      => '[' . get_class($this) . ']',
        'event'    => 'yapay_error',
        'message'  => $msgError,
        'exception'=> [
          'type'    => get_class($data),
          'message' => $data->getMessage(),
          'code'    => $data->getCode(),
          'file'    => $data->getFile(),
          'line'    => $data->getLine(),
          'trace'   => $data->getTraceAsString()
        ],
        'datetime' => date('Y-m-d H:i:s'),
      ];
    }
    if (isset($data->error_response->general_errors)){
      $error = true;
      $logData = [
        'tag'      => '[' . get_class($this) . ']',
        'event'    => 'yapay_error',
        'message'  => 'Módulo Yapay erro: '.$msgError,
        'exception'=> [
          'type'    => get_class($data->error_response->general_errors),
          'errors' => $data->error_response->general_errors,
        ],
        'datetime' => date('Y-m-d H:i:s'),
      ];
      $log->write(json_encode($logData, JSON_UNESCAPED_UNICODE));
    }
    if (isset($data->error_response->validation_errors)){
      $error = true;
      $logData = [
        'tag'      => '[' . get_class($this) . ']',
        'event'    => 'yapay_error',
        'message'  => 'Validação Yapay erro: '.$msgError,
        'exception'=> [
          'type'    => get_class($data->error_response->validation_errors),
          'errors' => $data->error_response->validation_errors,
        ],
        'datetime' => date('Y-m-d H:i:s'),
      ];
    }
    if ($error) {
      $log->write(json_encode($logData, JSON_UNESCAPED_UNICODE));
    }

  }

  public function validateCredentials($token) {
    try {
        $dataSend = (object) ['token_account' => $token, 'price' => "100", 'type_response' => "J"];
        $header =  array('Content-Type: application/json');
        $url = $this->getEnvironment() . 'api/v1/transactions/simulate_splitting';
        $result = parent::callAPI($url, 'POST', $dataSend, $header, false, $retorno,Type_DadosSend::TpDados_Json);
    } catch (Exception $e) {
        $msgError = 'Erro em validateCredentials. Token: '.$token;
        $this->setErrorLog($msgError, $e);
        $result['error'] = $e;
    }

    return $result;
  }

}
