<?php

namespace Amwdeveloper\plugins\auction;

use Amwdeveloper\core\session;
use Amwdeveloper\model\layer;
use Amwdeveloper\model\message;
use League\Plates\Engine;

class geral extends layer
{
    private $message;
    private $session;

    public function __construct()
    {
        global $route;
        $this->view = new Engine(__DIR__ . "/../../../theme/" . config['path'] . "/pages", 'phtml');
        $this->route = $route;
        $this->title_web = config['web_title'];
        $this->session = new session();
        $this->message = new message();
    }

    public function index()
    {
        $auctions = $this->table("amw_auctions")->orderby('date')->all();
        echo $this->view->render('partials/auction/all', [
            'title' => $this->title_web . ' - Leilões',
            'auctions' => $auctions ?? null
        ]);
    }

    public function view($slug)
    {

        $slug = filter_var($slug['slug'], FILTER_SANITIZE_SPECIAL_CHARS);

        if (!$slug) return $this->route->redirect('/auction');

        $auction = $this->table("amw_auctions")->where('slug = :slug', "slug={$slug}")->get();

        if (!$auction) return $this->route->redirect('/auction');

        $lances = $this->table("amw_auctions_lance")->where("id_auction = :id", "id={$auction->id}")->orderby('price')->all();

        echo $this->view->render('partials/auction/view', [
            'title' => $this->title_web . ' - Leilão ' . $auction->title,
            'auction' => $auction,
            'lances' => $lances ?? null
        ]);
    }

    public function authnewlance($request)
    {
        $id = filter_var($request['id_lance'], FILTER_VALIDATE_INT);
        $price = filter_var($request['price'], FILTER_VALIDATE_INT);

        if (empty($id) or empty($price)) {
            $this->message->class('error')->text("Campo <em><strong>Lance</strong></em> está vázio")->flash();
            return null;
        }

        $auction = $this->table("amw_auctions")->where("id = :id", "id={$id}")->get();

        if (empty($auction)) {
            $this->message->class('error')->text("opps, <em><strong>algo deu errado</strong></em> atualize a página e tente novamente")->flash();
            return null;
        }

        if ($auction->date < date('Y-m-d H:i:s', strtotime('now'))) {
            $this->message->class('error')->text("<em><strong>Leilão já finalizado</strong></em>")->flash();
            return null;
        }

        if (requests_form("auction_lance", 2, 15)) {
            $this->message->class("error")->text("Você deu um lance recentemente, aguarde <em><strong>15 minutos</strong></em>")->flash();
            return null;
        }

        $auction_lance = $this->table("amw_auctions_lance")->where("id_auction = :id", "id={$id}")->orderby('price')->get();

        $myaccount = $this->session->useraccount;

        $coinaccount = $this->table("{$auction->table_coin}")->columns("{$auction->coin} as coin")->where("{$auction->column_account} = :acc", "acc={$myaccount}")->get();

        if (isset($auction_lance->price)) {
            if ($auction_lance->price >= $coinaccount->coin) {
                $this->message->class('error')->text("Ops sua conta possui:<em><strong>{$coinaccount->coin} {$auction->coin_name}</strong></em>, sendo impossível de você estar efetuando um novo lance")->flash();
                return null;
            }
        }


        $auction_lance_account = $this->table("amw_auctions_lance")->where("id_auction = :id AND account = :acc", "id={$id}&acc={$myaccount}")->get();

        if ($auction_lance_account &&  $coinaccount->coin < ($auction_lance_account->price + $price)) {
            $this->message->class('error')->text("Ops sua conta possui:<em><strong>{$coinaccount->coin} {$auction->coin_name}</strong></em>, sendo impossível de você estar efetuando um novo lance")->flash();
            return null;
        }


        if ($auction_lance_account && $auction_lance && $auction_lance->price >= ($auction_lance_account->price + $price)) {
            $this->message->class('error')->text("Seu lance não pode ser menor ou igual que <em><strong>{$auction_lance->price} {$auction->coin_name}</strong></em>")->flash();
            return null;
        }

        $nameaccount = $this->table('MEMB_INFO')->columns("memb_name")->where('memb___id = :mi', "mi={$myaccount}")->get();

        if (!$auction_lance_account && !$auction_lance && $price < $auction->price) {
            $this->message->class('error')->text("Seu lance não pode ser menor que <em><strong>{$auction->price} {$auction->coin_name}</strong></em>")->flash();
            return null;
        }

        if (!$auction_lance_account && $auction_lance && $price < $auction_lance->price) {
            $this->message->class('error')->text("Seu lance não pode ser menor que <em><strong>{$auction_lance->price} {$auction->coin_name}</strong></em>")->flash();
            return null;
        }

        if ($auction_lance_account) {
            $udpate = [
                'price' => ($auction_lance_account->price + $price)
            ];
            $this->table('amw_auctions_lance')->where('account = :acc AND id_auction = :ida', "acc={$myaccount}&ida={$id}")->updated($udpate);
        } else {
            $insert = [
                'id_auction' => $id,
                'account' => $myaccount,
                'price' => $price,
                'name' => $nameaccount->memb_name
            ];
            $this->table('amw_auctions_lance')->created($insert);
        }

        $this->message->class('success')->text("<em><strong>Lance efetuado</strong></em> com sucesso")->flash(true, true);
    }
}
