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

class Suit extends CI_Controller {

    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 criarQrCode($valor) {

        $transacao_id = 'SP'. rand(0, 999) .'-'.date('YMDHms');

        // Pega a data de hoje
        $dataDeHoje = new DateTime();

        // Adiciona um dia
        $dataDeAmanha = $dataDeHoje->modify('+1 day');

        // Formata a data para exibição
        $dataFormatada = $dataDeAmanha->format('Y-m-d');

        $this->db->where('id',0);	
        $suitpayData = $this->db->get('suitpay')->result();


        $url = $suitpayData[0]->url.'/api/v1/gateway/request-qrcode';

        $data = array(
            "requestNumber" => $transacao_id,
            "dueDate" => $dataFormatada,
            'amount' => $valor,
            "callbackUrl" => base_url().'suit/webhook',
            'client' => array(
                'name' => $this->session->nome,
                'document' => $this->engine->cpf($this->session->cpf),
                "email" => $this->session->email
            )
        );


        $header = array(
            'ci: '.$suitpayData[0]->client_id,
            'cs: '.$suitpayData[0]->client_secret,
            'Content-Type: application/json',
        );

        $response = $this->enviarRequest($url, $header, $data);

        
        $dados = json_decode($response, true);

        if($dados['response'] == 'PIX_ERROR'){

            $msg = array("mensagem" => "Erro ao gerar o QR para deposito, tente novamente mais tarde ou entre em contato com o suporte!",
                         "status" => "Error");

            echo $this->engine->output('500', $msg);

        }else{

            if($dados['idTransaction']){

                if($this->session->bonus == true){
                    $insert = array(
                        'transacao_id' =>  $dados['idTransaction'],
                        'usuario' => $this->session->id,
                        'valor' => $valor,
                        'tipo' => 'deposito',
                        'data_hora' => date('Y-m-d H:i:s'),
                        'qrcode' => $this->generateQRCode($dados['paymentCode']),
                        'status' => 'processamento',
                        'bonus' => 1,
                        'code' =>  $dados['paymentCode']
                    );
                }else{
                    $insert = array(
                        'transacao_id' =>  $dados['idTransaction'],
                        'usuario' => $this->session->id,
                        'valor' => $valor,
                        'tipo' => 'deposito',
                        'data_hora' => date('Y-m-d H:i:s'),
                        'qrcode' => $this->generateQRCode($dados['paymentCode']),
                        'status' => 'processamento',
                        'bonus' => 0,
                        'code' =>  $dados['paymentCode']
                    );
                };

                $this->session->set_userdata('bonus', false);
                $this->db->insert('transacoes', $insert);
                $this->session->set_userdata('transacao_id', $dados['idTransaction']);
                echo $this->engine->output('200', $insert);
    
            }else{
                echo "Erro: ". $dados['message'];
            }

        }

       
    }
    public function generateQRCode($data) {
        require_once(APPPATH . 'libraries/phpqrcode/qrlib.php');
        $file = FCPATH . '/public/uploads/qrcode.png';
        QRcode::png($data, $file);
        $qrCodeImage = file_get_contents($file);
        $base64QRCode = base64_encode($qrCodeImage);
        return $base64QRCode;
    } 
    
    public function status($uID,$transactionId){

        $this->db->where('id',0);	
        $suitpayData = $this->db->get('suitpay')->result();
        $url = $suitpayData[0]->url.'/api/v1/gateway/consult-status-transaction';
        $data = array(
            'typeTransaction' => "PIX",
            'idTransaction' => $transactionId
        );

        $header = array(
            'ci: '.$suitpayData[0]->client_id,
            'cs: '.$suitpayData[0]->client_secret,
            'Content-Type: application/json',
        );

        $response = $this->enviarRequest($url, $header, $data);

        $this->db->where('transacao_id', $transactionId);
        $valorData = $this->db->get('transacoes')->row();
        
        $dados = json_decode($response, true);
        $insert = array(
            'status' => $dados,
            'usuario' => $uID,
            'transactionId' => $transactionId
        );

        echo $this->engine->output('200', $insert);
    }


    public function webhook() {

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            show_404();
        }
        $json_data = file_get_contents('php://input');

        $data = json_decode($json_data, true);

        if (!isset($data['idTransaction']) || !isset($data['typeTransaction']) || !isset($data['statusTransaction'])) {
            echo json_encode(['status' => 'error', 'message' => 'Dados incompletos']);
            return;
        }

        // Processa os dados conforme necessário
        $idTransaction = $data['idTransaction'];
        $typeTransaction = $data['typeTransaction'];
        $statusTransaction = $data['statusTransaction'];


        if ($statusTransaction === 'PAID_OUT') {

            $this->db->where('transacao_id', $idTransaction);
            $this->db->update('transacoes', ['status' => 'pago']);

            $this->db->where('transacao_id', $idTransaction);
            $trans = $this->db->get('transacoes')->result();

            $usuario = $trans[0]->usuario;

            $dados = array(
                "historico_id" => $trans[0]->transacao_id,
                "credito" => 'R$ ' . number_format($trans[0]->valor, 2),
                "usuario" => $trans[0]->usuario,
                "pagina" => 'Depósito',
                'ip' => $this->input->ip_address(),
                'data_hora' => date('d/m/Y H:i:s'),
            );

            $this->app->insertHist($dados);

            if($trans[0]->bonus == 1){
                $novoValor = (2 * $trans[0]->valor);
            }else{
                $novoValor = $trans[0]->valor;
            };

            $setSaldo = $this->fiverscans->enviarSaldo($usuario, $novoValor);
            $this->cpa->checaCPA($usuario, $idTransaction);

        }

        echo json_encode(['status' => 'success']);
    }
}
