<?php 
defined('BASEPATH') OR exit('No direct script access allowed');

class Ezze{
        
            public function __construct()
            {
                $this->CI = &get_instance();
                $this->CI->load->helper('url');
                $this->CI->config->item('base_url');
                $this->CI->load->database();
            }
          
            private function enviarRequest($url, $header, $data=null) {
                $ch = curl_init();
        
            
                $data_json = json_encode($data);
        
                // Configurando as opções do cURL
                curl_setopt($ch, CURLOPT_URL, $url);
                if(!$data == null){
                    curl_setopt($ch, CURLOPT_POST, 1);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_json);
                }
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        
                // Executando a requisição e obtendo a resposta
                $response = curl_exec($ch);
        
                // Fechando a conexão cURL
                curl_close($ch);
        
                return $response;
            }
            private function requestToken($url, $header, $data) {
                $ch = curl_init();
        
                // Configurando as opções do cURL
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        
                // Executando a requisição e obtendo a resposta
                $response = curl_exec($ch);
        
                // Fechando a conexão cURL
                curl_close($ch);
        
                return $response;
            }
        
            public function obterToken() {
                $this->CI->db->where('id',0);	
                $ezzeData = $this->CI->db->get('ezzebank')->result();
        
                $url = $ezzeData[0]->url.'/oauth/token';
                $client_id = $ezzeData[0]->client_id;
                $client_secret = $ezzeData[0]->client_secret;
        
                $b64token = base64_encode($client_id.':'.$client_secret);
        
                $data = array(
                    'grant_type' => 'client_credentials'
                );
                $authorization = 'Basic '.$b64token;
        
                $header = array(
                    'Authorization: ' . $authorization
                );
                $response = $this->requestToken($url, $header, $data);
        
                $dados = json_decode($response, true);
        
                if($dados['access_token']){
                    $access_token = $dados['access_token'];
                    return $access_token;

                }else{
                    echo "Erro: ". $dados['message'];
                }
            }

            public function criarSaque($id, $valor,$tipo,$key){
         
                $this->CI->db->where('id',0);	
                $ezzeData = $this->CI->db->get('ezzebank')->result();

                $this->CI->db->where('id',$id);	
                $userData = $this->CI->db->get('usuarios')->result();
        
                $url = $ezzeData[0]->url.'/pix/payment';
        
                $data = array(
                    'amount' => $valor,
                    'description' => 'Saque de saldo da plataforma de jogos',
                    'creditParty' => array(
                        'name' => $userData[0]->nome,
                        'keyType' =>  $tipo,
                        'key' => $key,
                        'taxId' =>  $this->engine->cpf($userData[0]->cpf)
                    )
                );
        
                $header = array(
                    'Authorization: Bearer ' .  $this->obterToken()
                );
        
                $response = $this->enviarRequest($url, $header, $data);
        
                
                $dados = json_decode($response, true);
        
                if($dados['transactionId']){
        
                    $insert = array(
                        'transacao_id' => $dados['transactionId'],
                        'usuario' => $id,
                        'valor' => $valor,
                        'tipo' => 'saque',
                        'data_hora' => date('Y-m-d H:i:s'),
                        'status' => 'pago'
                    );
        
                    $this->CI->db->insert('transacoes', $insert);
        
                    $this->session->set_userdata('transacao_id', $dados['transactionId']);
        
                }else{
                    echo "Falha na api";
                }
            }
}