<?php

namespace Amwdeveloper\plugins\donate;

use Amwdeveloper\core\session;
use Amwdeveloper\model\layer;
use Amwdeveloper\model\message;
use GuzzleHttp\Client;

class pix extends layer
{
    private $message;
    private $session;
    private $api_key;
    private $token;
    public function __construct()
    {
        $this->message = new message();
        $this->session = new session();
        $this->api_key = payment['api_key'];
        $this->token  = payment['token'];
    }

    public function index($request)
    {
        $value_donate = filter_var($request['value'], FILTER_VALIDATE_INT);

        if (!$value_donate) {
            $this->message->class("error")->text("Preecha o campo de <strong>valor</strong>")->flash();
            return null;
        }

        if ($value_donate < 3) {
            $this->message->class("error")->text("Valor mínimo da doação é de <strong>3 Reais</strong>")->flash();
            return null;
        }

        $this->gerateqrcode($value_donate);
    }

    public function gerateqrcode($value)
    {
        $gluzze = new Client();
        $account = $this->table("MEMB_INFO")->columns("memb_name,mail_addr")->where("memb___id = :mi", "mi={$this->session->useraccount}")->get();
        $body = json_encode([
            'apiKey' => $this->api_key,
            'order_id' => rand(1, 99999999), // código interno do lojista para identificar a transacao.
            'payer_email' => $account->mail_addr, # email do pagador
            'payer_name' => $account->memb_name, // nome completo do pagador
            'payer_cpf_cnpj' => payment['cpf/cnpj'], // cpf ou cnpj
            'payer_phone' => payment['phone'], // Telefone do pagador
            'days_due_date' => '1', // dias para vencimento do Pix
            'items' => array(
                array(
                    'description' => 'Doação MuOnline',
                    'quantity' => '1',
                    'item_id' => '1',
                    'price_cents' => $value . '00'
                )
            )
        ]);

        $gerate = $gluzze->request("post", "https://pix.paghiper.com/invoice/create/", [
            'body' => $body,
            'headers' => [
                'Accept' => 'application/json',
                'Content-Type' => 'application/json'
            ]
        ]);

        $gerate = json_decode($gerate->getBody());
        
        if ($gerate->pix_create_request->http_code == 201) {

            $pix_insert = [
                'price' => $gerate->pix_create_request->value_cents,
                'order_id' => $gerate->pix_create_request->order_id,
                'transaction_id' => $gerate->pix_create_request->transaction_id,
                'account' => $this->session->useraccount,
                'due_date' => $gerate->pix_create_request->due_date,
                'status' => 0
            ];

            $this->table("amw_payment")->created($pix_insert);
            $image = "<img src='{$gerate->pix_create_request->pix_code->qrcode_image_url}' class='mt-5 mx-auto'>";
            $copy = $gerate->pix_create_request->pix_code->emv;
            $this->message->class("success")->text("
            <strong>QRCode gerado com sucesso</strong> 
            <br> {$image} 
            <br> 
            <p class='bg-neutral-200 text-xs p-1 rounded-md break-words text-left' id='emv'>{$copy}</p>
            <br>
            <button class='bg-blue-500 text-white text-xs rounded-md px-4 py-2 hover:bg-blue-600 mt-5' id='copy_code'>Copiar código </button>
            ")->flash();
            return;
        }

        $this->message->class("error")->text("Não foi <strong>possível concluir seu pedido</strong> teste novamente mais tarde")->flash(true, true);
    }

    public function notification($request)
    {


        $returnPayment = new Client();


        $body = [
            'notification_id' => $request['notification_id'],
            'transaction_id' => $request['transaction_id'],
            'token' => $this->token,
            'apiKey' => $this->api_key
        ];

        $payment = $returnPayment->request(
            'post',
            'https://pix.paghiper.com/invoice/notification/',
            [
                'body' => json_encode($body),
                'headers' => [
                    'accept' => 'application/json',
                    'content-type' => 'application/json'
                ]
            ]
        );


        $result = json_decode($payment->getBody());
        

        if ($result->status_request->result == 'success') {
            if ($result->status_request->status == "paid") {
                $info = $this->table("amw_payment")
                    ->columns("account,price,status")
                    ->where("order_id = :oid AND transaction_id = :tid", "oid={$result->status_request->order_id}&tid={$result->status_request->transaction_id}")
                    ->get();



                if ($info->status == 1) return null;


                $value_donate = substr($info->price, 0, -2);
                if (promotion['active']) {
                    if ($value_donate >= 3 and $value_donate < 100) $coin_multiple = ($value_donate * promotion['multiple']['3-99']);
                    if ($value_donate >= 100 and $value_donate < 150) $coin_multiple = ($value_donate * promotion['multiple']['100-149']);
                    if ($value_donate >= 150) $coin_multiple = ($value_donate * promotion['multiple']['150']);
                } else {
                    $coin_multiple = $value_donate;
                }

                $coin = coins[payment['coin']];
                $accountuser = $this->table($coin['table'])->columns("{$coin['column_coin']} as coin")->where("{$coin['column_account']} = :mi", "mi={$info->account}")->get();

                $updated = array($coin['column_coin'] => ($accountuser->coin + $coin_multiple));

                $this->table($coin['table'])->where("{$coin['column_account']} = :mi", "mi={$info->account}")->updated($updated);

                $this->table("amw_payment")
                    ->where("order_id = :oid AND transaction_id = :tid", "oid={$result->status_request->order_id}&tid={$result->status_request->transaction_id}")
                    ->updated(['status' => 1]);
            }
        }

        return null;
    }
}
