<?php
class Asaas{

  public $account;
  public $api_key;

  public function __construct(){}

  // API KEY
  // **************************************

  private function set_api_key($api_key=false){
    $this->api_key = false;
    // CONTA MASTER
    if($api_key=="master"){$this->api_key = GLOBAL_ASAAS_GID_API_KEY;}
    // APIKEY FORNECIDA POR PARAMETRO
    elseif($api_key){$this->api_key = $api_key;}
    // APIKEY DA SUBCONTA (SE SETADO)
    elseif(isset($this->account->EXT_api_key) && $this->account->EXT_api_key!=""){
      $this->api_key = $this->account->EXT_api_key;
    }
  }

  // SUBCONTA
  // **************************************

  // Criar nova conta
  public function account_new($dds){
    $this->set_api_key('master');
    $response = $this->requestPOST('accounts', $dds);
    return $response;
  }

  // Dados da subconta (bd fncr)
  public function account_dds($dds){
    require_once('Crypto.php');
    $crypto = new Crypto();
    $this->account = (object)[
	    "EXT_api_key" => $crypto->decode($dds['EXT_api_key'])
    ];
var_dump($this->account);
    $this->set_api_key();
  }

  // Dados da subconta (externo)
  public function account_status(){
    $dds = [];

    /*
    // Dados Comerciais
    $response = $this->requestGET('myAccount', []);
    if($response){$dds['teste']=$response;}

    // Dados Comerciais
    $response = $this->requestGET('myAccount/commercialInfo', []);
    if($response){$dds['comercial']=$response;}

    // Configurações de personalização
    $response = $this->requestGET('myAccount/paymentCheckoutConfig', [], $this->account->EXT_api_key);
    if($response){$dds['config']=$response;}

    // Taxas da Conta
    $response = $this->requestGET('myAccount/fees', [], $this->account->EXT_api_key);
    if($response){$dds['taxas']=$response;}
    */

    // Status da Conta
    $response = $this->requestGET('myAccount/status', []);
    if($response){$dds['status']=$response;}

    return $dds;
  }

  // SUBCONTA - DOCUMENTOS
  // **************************************

  // Documentos
  public function account_docs(){
    if($this->account){
      $response = $this->requestGET('myAccount/documents', []);
      return $response;
    }
    return false;
  }

  // Enviar documento
  public function account_doc_send($id_doc, $dds){
    if($this->account){
      $response = $this->requestPOST('myAccount/documents/'.$id_doc, $dds, ['content-type'=>'multipart/form-data']);
      return $response;
    }
    return false;
  }

  // Enviar documento
  public function account_doc_get($id_doc){
    if($this->account){
      $response = $this->requestGET('myAccount/documents/files/'.$id_doc, []);
      echoPre($response);
      return $response;
    }
    return false;
  }

  // SUBCONTA - WEBHOOKS
  // **************************************

  // Lista de webhooks
  public function account_webhooks(){
    if($this->account){
      $response = $this->requestGET('webhooks', []);
      return $response;
    }
    return false;
  }

  // Lista de webhooks
  public function account_webhooks_criar($dds){
    if($this->account){
      $response = $this->requestPOST('webhooks', $dds);
      return $response;
    }
    return false;
  }

  // Lista de webhooks
  public function account_webhooks_deletar($id){
    if($this->account){
      $response = $this->requestDELETE('webhooks/'.$id, []);
      return $response;
    }
    return false;
  }

  // SUBCONTA - CHAVES PIX
  // **************************************

  // Criar chave pix
  public function account_pix_chave_criar(){
    if($this->account){
      $response = $this->requestPOST('pix/addressKeys', ["type"=>"EVP"]);
      return $response;
    }
    return false;
  }

  // Lista de chaves
  public function account_pix_chaves_get(){
    if($this->account){
      $response = $this->requestGET('pix/addressKeys', []);
      return $response;
    }
    return false;
  }

  // COBRANÇA
  // **************************************

  // Pega dados do cobrança
  public function paymentData($id){
    if($this->account){
      $response = (array) $this->requestGET('payments/'.$id, []);
      return (isset($response['object']) && $response['object']=="payment") ? $response : false;
    }
    return false;
  }

  // Confirma o pagamento em pix de forma manual
  // Utilizado em sandbox (produção não possui função)
  public function paymentConfirm($id){
    if($this->account){
      $response = $this->requestPOST('sandbox/payment/'.$id.'/confirm', []);
      return $response;
    }
    return false;
  }

  // SALDO
  // **************************************

  // Pega o saldo atual da conta
  public function saldo($api_key=false){
    $this->set_api_key($api_key);
    $response = $this->requestPOST('finance/balance',[]);
    return isset($response->balance) ? $response->balance : 0;
  }


  // REPASSE
  // **************************************
  public function transfer($dds, $api_key=false){
    $this->set_api_key($api_key);
    $response = $this->requestPOST('transfers',[
      "value"=> $dds->valor,
      "pixAddressKeyType"=> $dds->chave_tipo, // CPF, CNPJ, EMAIL, PHONE, EVP
      "pixAddressKey"=> $dds->chave_pix,
      "description"=> "Pix PokerWeb",
      "operationType"=> "PIX"
    ]);
    return isset($response->id) ? $response : $response;
  }


  // REALIZA A REQUISIÇÃO
  // **************************************
  private function request($endpoint, $data, $metodo, $opts=[]){
    if($this->api_key){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, GLOBAL_ASAAS_URL.$endpoint);
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $metodo);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_HTTPHEADER, [
        "access_token: ".$this->api_key,
        "User-Agent: pokerweb",
        "accept: application/json",
        "content-type: ".(isset($opts['content-type']) ? $opts['content-type'] : 'application/json'),
      ]);
      $response = curl_exec($ch);
      $err = curl_error($ch);
      curl_close($ch);
      var_dump($response, $err);
      if(!$err){ return json_decode($response); }
      return $response;
    }
    return false;
  }
  // POST
  private function requestPOST($endpoint, $data, $opts=[]){
    if(!(isset($opts['content-type']) && $opts['content-type']=='multipart/form-data')){
      $data = json_encode($data);
    }
    return $this->request($endpoint, $data, 'POST', $opts);
  }
  // GET
  private function requestGET($endpoint, $data=null, $opts=[]){
    return $this->request($endpoint, null, 'GET', $opts);
  }
  // DELETE
  private function requestDELETE($endpoint, $data=null, $opts=[]){
    return $this->request($endpoint, null, 'DELETE', $opts);
  }

}
