<?php

namespace Amwdeveloper\plugins\donate;

use Amwdeveloper\core\session;
use Amwdeveloper\model\layer;
use Amwdeveloper\model\message;
use MercadoPago\SDK;
use GuzzleHttp\Client;
use MercadoPago\Item;
use MercadoPago\Preference;

class mercadopago extends layer
{

    private $message;
    private $session;
    private $preference;

    public function __construct()
    {
        $this->message = new message();
        $this->session = new session();
        SDK::setAccessToken('' . payment_mp['token'] . '');
        $this->preference = new Preference();
    }

    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 < 1) {
            $this->message->class("error")->text("Valor mínimo da doação é de <strong>1 Real</strong>")->flash();
            return null;
        }

        $account = $this->table("MEMB_INFO")->columns("mail_addr,memb_name")->where("memb___id = :mi", "mi={$this->session->useraccount}")->get();

        if (empty($account)) {
            $this->message->class("error")->text("Sua conta não possuí E-mail<strong>, adicione pelo painel do usuário e tente novamente</strong>")->flash();
            return null;
        }

        $order_id = rand(1, 9999999999);

        $item = new Item();
        $item->title = "" . payment_mp['description'] . "";
        $item->quantity = 1;
        $item->unit_price = $value_donate;
        $this->preference->items = array($item);
        $this->preference->external_reference =  $order_id;
        // $this->preference->purpose = 'wallet_purchase';
        $this->preference->back_urls = array(
            "success" => base_url,
            "failure" => base_url,
            "pending" => base_url,
            "approved" => base_url,
        );
        $this->preference->auto_return = "approved";
        $this->preference->save();

        $pix_insert = [
            'price' => $value_donate,
            'order_id' => $order_id,
            'account' => $this->session->useraccount,
            'due_date' => date('Y-m-d', strtotime("now")),
            'status' => 0
        ];

        $this->table("amw_payment_mp")->created($pix_insert);
        echo json_encode(["message" => "<div class=\"success\"></div> <p>Você será redirecionado em instantes!</p> <a href=\"#\">Ok</a>", "redirect" => $this->preference->init_point]);
        return;
    }

    public function notification()
    {


        $gluzze = new Client();


        $payment = $gluzze->request('get', 'https://api.mercadopago.com/v1/payments/' . $_GET['data_id'], [
            'headers' => [
                'Authorization' => 'Bearer ' . payment_mp['token']
            ]
        ]);

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


        if ($response->status == "approved") {

            $info = $this->table("amw_payment_mp")
                ->columns("account,price,status")
                ->where("order_id = :oid", "oid={$response->external_reference}")
                ->get();

            $amount = $info->price;


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

            if (promotion['active']) {
                if ($amount >= 3 and $amount < 99) $coin_multiple = ($amount * promotion['multiple']['3-99']);
                if ($amount >= 100 and $amount < 149) $coin_multiple = ($amount * promotion['multiple']['100-149']);
                if ($amount >= 150) $coin_multiple = ($amount * promotion['multiple']['150']);
            } else {
                $coin_multiple = $amount;
            }

            $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_mp")
                ->where("order_id = :oid", "oid={$response->external_reference}")
                ->updated(['status' => 1]);
        }
    }
}
