<?php
  /*define("URLGETNET", "https://api-sandbox.getnet.com.br");
  define("clientId", "e753cf08-bd41-4355-a629-4ae4bf0167f0");
  define("clientSecret", "baa7029d-30a5-49ac-a44e-6742d64122d3");
  define("SELLERID", "726c5926-353e-43be-be8e-8156cb36e803");*/

define("URLGETNET", "https://api-homologacao.getnet.com.br");
define("clientId", "581040c4-817b-46e0-83d4-def14196c5cd");
define("clientSecret", "c5bbdc8f-56ce-40d3-a581-f645ce9434a2");
define("SELLERID", "f3f0ba64-c783-408b-89e6-6bf06d8bea49");

  include_once "controllers/AccessTokenGetCtl.php";

  function autenticacao(){
      $AccessToken = new AccessTokenGetCtl();
      $AccessToken->setClientId(clientId);
      $resAccess = $AccessToken->getAccessTokenDisponivelPorClientID();
      if($resAccess->rowCount() > 0){
          $item = $resAccess->fetch(PDO::FETCH_OBJ);
          $result = array(
              "access_token"=> $item->access_token,
                "token_type"=> "Bearer",
                "expires_in"=> 3600,
                "scope"=> "oob"
          );

          $retorno = array("dados" => $result, "httpCode" => 200);

      }else{
          $endPoint = "/auth/oauth/v2/token";
          $ch = curl_init();

          $dadosEnvio = json_encode(array("grant_type"=>"client_credentials",
              "scope"=>"oob"
          ));

          curl_setopt($ch, CURLOPT_URL, URLGETNET.$endPoint."?scope=oob&grant_type=client_credentials");
          curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
          curl_setopt($ch, CURLOPT_POST, true);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_POSTFIELDS, $dadosEnvio);
          curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . base64_encode( clientId . ':' . clientSecret ) ,
                  'Content-Type: application/x-www-form-urlencoded'
              )
          );

          $result = curl_exec($ch);
          $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

          curl_close($ch);
          $retorno = array("dados" => json_decode($result), "httpCode" => $httpCode);
          if($httpCode == 200){
              $dadosRetorno = json_decode($result);
              $AccessToken->setClientId(clientId);
              $AccessToken->setAccessToken($dadosRetorno->access_token);
              $AccessToken->setExpiresIn($dadosRetorno->expires_in);
              $AccessToken->inserir();
          }

      }

      return json_encode($retorno);
  }

function autenticacaoNovaChave(){

    sleep(5);

        $endPoint = "/auth/oauth/v2/token";
        $ch = curl_init();

        $dadosEnvio = json_encode(array("grant_type"=>"client_credentials",
            "scope"=>"oob"
        ));

        curl_setopt($ch, CURLOPT_URL, URLGETNET.$endPoint."?scope=oob&grant_type=client_credentials");
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $dadosEnvio);
        curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Authorization: Basic ' . base64_encode( clientId . ':' . clientSecret ) ,
                'Content-Type: application/x-www-form-urlencoded'
            )
        );

        $result = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);
        $retorno = array("dados" => json_decode($result), "httpCode" => $httpCode);

    return json_encode($retorno);
}

  function gerarTokenCartao($accessToken, $cardNumber, $customerId){
      $endPoint = "/v1/tokens/card";

      $dadosEnvio = json_encode(array("card_number"=>$cardNumber,
          "customer_id"=>$customerId
      ));

      $ch = curl_init();

      curl_setopt($ch, CURLOPT_URL, URLGETNET.$endPoint);
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
      curl_setopt($ch, CURLOPT_POST, true);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $dadosEnvio);
      curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $accessToken ,
              'Content-Type: application/json; charset=utf-8',
              'api_mode: mocked',
              'seller_id: '.SELLERID,
              'Content-Length: ' . strlen($dadosEnvio)
          )
      );

      $resultToken = curl_exec($ch);
      $httpCodeToken = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      $dados = json_decode(($resultToken));

      curl_close($ch);

      if($httpCodeToken == 201){
          $retornoToken = array("status"=>true, "number_token"=>$dados->number_token);
      }else{
              $retornoToken = array("status" => false, "mensagem" => $dados->message, "name" => $dados->name, "status_code" => $dados->status_code, "details" => $dados->details, "httpCode" => $httpCodeToken);

      }
      return json_encode($retornoToken);
  }

  function armazenaCofre($accessTokenC, $number_token, $cardholder_name, $expiration_month, $expiration_year, $customer_id,
                         $cardholder_identification, $verify_card, $security_code){
    $endPoint = "/v1/cards";

    $dadosEnvio = json_encode(array("number_token"=>$number_token,
        //"brand"=>"",
        "cardholder_name"=>$cardholder_name,
        "expiration_month"=>$expiration_month,
        "expiration_year"=>$expiration_year,
        "customer_id"=>$customer_id,
        "cardholder_identification"=>$cardholder_identification,
        "verify_card"=>$verify_card,
        "security_code"=>$security_code
    ));

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, URLGETNET.$endPoint);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dadosEnvio);
    curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $accessTokenC ,
            'Content-Type: application/json; charset=utf-8',
            'seller_id: '.SELLERID,
            //'api_mode: mocked',
            'Content-Length: ' . strlen($dadosEnvio)
        )
    );

    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $dados = json_decode(($result));

    curl_close($ch);

    if($httpCode == 201){
        $retorno = array("status"=>true,"card_id" => $dados->card_id, "number_token"=>$dados->number_token);
    }else{

            $retorno = array("status" => false, "mensagem" => $dados->message, "name" => $dados->name, "status_code" => $dados->status_code, "details" => $dados->details, "httpCode" => $httpCode);

    }

      return json_encode($retorno);
  }

function recuperarCartaoCofre($accessToken, $cardId){
    $endPoint = "/v1/cards/".$cardId;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, URLGETNET.$endPoint);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
    //curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $accessToken ,
            'Content-Type: application/json; charset=utf-8',
            'api_mode: mocked',
            'seller_id: '.SELLERID
        )
    );

    $resultSaved = curl_exec($ch);
    $httpCodeSaved = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $dadosSaved = json_decode(($resultSaved));

    curl_close($ch);

    if($httpCodeSaved == 200){
        $retornoToken = array("status"=>true,"data" =>$dadosSaved);
    }else{
        $retornoToken = array("status"=>false,"mensagem" => "Erro ao buscar cartao salvo", "httpCode"=>$httpCodeSaved);
    }
    return json_encode($retornoToken);
}

function deletaCartaoCofre($accessToken, $cardId){
    $endPoint = "/v1/cards/".$cardId;

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, URLGETNET.$endPoint);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    //curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $accessToken ,
            'Content-Type: application/json; charset=utf-8',
            'api_mode: mocked',
            'seller_id: '.SELLERID
        )
    );

    $resultDelete = curl_exec($ch);
    $httpCodeDelete = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $dadosDelete = json_decode(($resultDelete));

    curl_close($ch);

    if($httpCodeDelete == 204){
        $retornoToken = array("status"=>true,"data" =>$dadosDelete);
    }else{
        sleep(5);
        //Efetua nova autenticacao
        $retAutenticacao = json_decode( autenticacaoNovaChave());

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, URLGETNET.$endPoint);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
        //curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt( $ch, CURLOPT_HTTPHEADER, array('Authorization: Bearer ' . $retAutenticacao->dados->access_token ,
                'Content-Type: application/json; charset=utf-8',
                'api_mode: mocked',
                'seller_id: '.SELLERID
            )
        );

        $resultDelete = curl_exec($ch);
        $httpCodeDelete = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $dadosDelete = json_decode(($resultDelete));

        curl_close($ch);
        if($httpCodeDelete == 204) {
            $retornoToken = array("status" => true, "data" => $dadosDelete);
        }else {
            $retornoToken = array("status" => false, "mensagem" => "Erro ao deletar cartao salvo", "httpCode" => $httpCodeDelete);
        }
    }
    return json_encode($retornoToken);
}

function gravarCDX($documento,$paymentId,$razaoRecusa,$codigoRetorno,$totalDebitos,$codigoAdquirente,$autorizacao,$terminal_nsu,
                   $cardHolder,$brand, $total, $parcelas, $status,
                   $geraNota, $dadosDocumento, $dadosNome,$dadosTelefone,$dadosCep,$dadosRua,$dadosNumero,$dadosComplemento,$dadosBairro,
                   $dadosCidade,$dadosEstado, $dadosEmail, $debitos, $proprietario, $proprietrioDocumento, $placa, $renavam,$estado, $urlNotification){
    //insere informacoes para CDX
    $endPoint = "https://appws.feelbank.com.br/cdxpos/ws/cadastrarTransacao.php";
    $token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VySWQiOiIxMTI4IiwibG9naW4iOiJ0aUBmaXJzdHBhZy5jb20uYnIiLCJlbWFpbCI6InRpQGZpcnN0cGFnLmNvbS5iciJ9.CVb4rWw9Jofht8fFcRtG3hIKYW6_hP7ja3-4toaRQp8";

    $valorSelecionado = number_format( $total,2,'.','');
    $valorOriginal = number_format( $totalDebitos,2,'.','');

    $emiteNota = 0;
    if($geraNota == true){
        $emiteNota = 1;
    }

    $dadosEnvio = json_encode(array(
        "origem"=>"Externo - Master",
        "servico"=>"Debito Veicular",
        "documento"=>$documento,
        "referenciaExterna"=>$paymentId,
        "situacao"=>$status,
        "refuse_reason"=>$razaoRecusa,
        "codigoRetorno"=>$codigoRetorno,
        "codigoAdquirente"=>$codigoAdquirente,
        "codigoMCC"=>4900,
        "autorizacao"=>$autorizacao,
        "moeda"=>"957",
        "tefNsu"=>$terminal_nsu,
        "nsu"=>$terminal_nsu,
        "valor"=> $valorSelecionado,
        "valorOriginal"=> $valorOriginal,
        "parcelas"=>$parcelas,
        "cartao_portador"=>$cardHolder,
        "cartao_primeiros_digitos"=>"",
        "cartao_ultimos_digitos"=>"",
        "bandeira"=>$brand,
        "forma_pagamento"=>"",
        "forma_captura"=>"GETNET - Web",
        "numero_serie"=>"",
        "emiteNota"=>$emiteNota,
        "novosDados"=>true,
        "notaNome"=>$dadosNome,
        "notaDocumento"=>$dadosDocumento,
        "notaEmail"=>$dadosEmail,
        "notaTelefone"=>$dadosTelefone,
        "notaCep"=>$dadosCep,
        "notaRua"=>$dadosRua,
        "notaNumero"=>$dadosNumero,
        "notaComplemento"=>$dadosComplemento,
        "notaBairro"=>$dadosBairro,
        "notaCidade"=>$dadosCidade,
        "notaEstado"=>$dadosEstado,
        "urlNotification"=>$urlNotification
    ));

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $endPoint);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dadosEnvio);
    curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
            'AdgToken: '.$token,
            'Content-Type: application/json',
            'Content-Length: ' . strlen($dadosEnvio)
        )
    );

    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if($httpCode == 200){
        $retornoCadastro = json_decode($result);
        $idTransacao = $retornoCadastro->id;

        $endPoint = "https://appws.feelbank.com.br/cdxpos/ws/cadastrarDebitoVeicular.php";

        $debitos =  json_encode($debitos);

        $dadosEnvio = json_encode(array(
            "idMovimentacao"=>$idTransacao,
            "estado"=>$estado,
            "placa"=>$placa,
            "renavam"=>$renavam,
            "proprietario"=>$proprietario,
            "proprietarioDocumento"=>$proprietrioDocumento,
            "debitos"=>$debitos
        ));

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $endPoint);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $dadosEnvio);
        curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
                'AdgToken: '.$token,
                'Content-Type: application/json',
                'Content-Length: ' . strlen($dadosEnvio)
            )
        );

        $result2 = curl_exec($ch);
        $httpCode2 = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $error2 = curl_error($ch);
        curl_close($ch);

    }
}