<?php

namespace Amwdeveloper\plugins\auction;

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

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

    public function __construct()
    {
        global $route;
        $this->view = new Engine(__DIR__ . "/../../../theme/admin/pages", 'phtml');
        $this->route = $route;
        $this->message = new message();
    }

    public function checklogin()
    {
        $session = new session();
        if (!$session->has("adminlogged")) {
            return $this->route->redirect("/administration/account/login");
        }
    }

    public function index()
    {
        $this->checklogin();
        echo $this->view->render('auctions/add', [
            'title' =>  'Novo leilão',
            'coins' => coins
        ]);
    }

    public function manage()
    {
        $this->checklogin();
        $auctions = $this->table("amw_auctions")->orderby('date')->all();
        foreach ($auctions as $auction) {
            $auctions_info[] = [
                'id' => $auction->id,
                'title' => $auction->title,
                'image' => $auction->image,
                'price' => $auction->price,
                'coin_name' => $auction->coin_name,
                'date' => $auction->date,
                'player_winner' => $this->table("amw_auctions_lance")->where("id_auction = :id", "id={$auction->id}")->orderby('price')->get() ?? null
            ];
        }

        echo $this->view->render('auctions/manage', [
            'title' =>  'Todos os leilões',
            'auctions' => $auctions_info ?? null
        ]);
    }

    public function toedit($id)
    {
        $this->checklogin();
        $id = filter_var($id['id'], FILTER_VALIDATE_INT);

        if (empty($id)) $this->route->redirect("/administration/auction/manage");

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

        if (empty($auction)) $this->route->redirect("/administration/auction/manage");

        echo $this->view->render('auctions/toedit', [
            'title' =>  'Editando leilão',
            'auction' => $auction ?? null,
            'coins' => coins
        ]);
    }

    public function toremove($id)
    {
        $this->checklogin();
        $id = filter_var($id['id'], FILTER_VALIDATE_INT);

        if (empty($id)) $this->route->redirect("/administration/auction/manage");

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

        if (empty($auction)) $this->route->redirect("/administration/auction/manage");

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

        $this->route->redirect("/administration/auction/manage");
    }

    //POSTS

    public function authaddnewauction($request)
    {
        $title = filter_var($request['title'], FILTER_SANITIZE_SPECIAL_CHARS);
        $price = filter_var($request['price'], FILTER_VALIDATE_INT);
        $coin = filter_var($request['coin'], FILTER_SANITIZE_SPECIAL_CHARS);
        $date = filter_var($request['date'], FILTER_SANITIZE_SPECIAL_CHARS);


        if (empty($title) or empty($price) or !is_numeric($coin) or empty($date)) {
            $this->message->class('error')->text("Preecha os <em><strong>campos obrigatórios</strong></em> para prosseguir.")->flash();
            return null;
        }

        $file = $_FILES['image'];
        $extension = ['image/png', 'image/gif', 'image/jpg', 'image/jpeg'];

        if ($file) {
            if (in_array($file['type'], $extension)) {
                $newname = md5(uniqid()) . mb_strrchr($file['name'], ".");
                $temp = $file['tmp_name'];
                $resource = __DIR__ . '/../../../resource/auctions/';
                $temp = $file['tmp_name'];
                if (move_uploaded_file($temp, $resource . $newname)) {
                    $coin = coins[$coin];

                    $insert = [
                        'title' => $title,
                        'image' => $newname,
                        'price' => $price,
                        'table_coin' => $coin['table'],
                        'column_account' => $coin['column_account'],
                        'coin' => $coin['column_coin'],
                        'coin_name' => $coin['name_coin'],
                        'date' => date('Y-m-d H:i', strtotime($date)),
                        'slug' => (new Slugify())->slugify($title)
                    ];

                    $this->table('amw_auctions')->created($insert);
                    $this->message->class('success')->text("<em><strong>Leilão</strong></em> criado com sucesso")->flash(true, true);
                } else {
                    $this->message->class('error')->text("Erro ao adicionar <em><strong>Leilão</strong></em>, tente novamente mais tarde")->flash();
                    return null;
                }
            } else {
                $this->message->class('error')->text("formato da <em><strong>Imagem</strong></em> inválido")->flash();
                return null;
            }
        } else {
            $this->message->class('error')->text("<em><strong>Imagem</strong></em> não selecionada")->flash();
            return null;
        }
    }

    public function authupdateauction($request)
    {
        $id = filter_var($request['id'], FILTER_VALIDATE_INT);
        $title = filter_var($request['title'], FILTER_SANITIZE_SPECIAL_CHARS);
        $price = filter_var($request['price'], FILTER_VALIDATE_INT);
        $coin = filter_var($request['coin'], FILTER_SANITIZE_SPECIAL_CHARS);
        $date = filter_var($request['date'], FILTER_SANITIZE_SPECIAL_CHARS);


        if (empty($title) or empty($price) or !is_numeric($coin) or empty($date) or empty($id)) {
            $this->message->class('error')->text("Preecha os <em><strong>Campos obrigatórios</strong></em> para prosseguir.")->flash();
            return null;
        }

        $file = $_FILES['image'];
        $extension = ['image/png', 'image/gif', 'image/jpg', 'image/jpeg'];


        if (!empty($file['name'])) {
            if (in_array($file['type'], $extension)) {
                $newname = md5(uniqid()) . mb_strrchr($file['name'], ".");
                $temp = $file['tmp_name'];
                $resource = __DIR__ . '/../../../resource/auctions/';
                $temp = $file['tmp_name'];

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

                if ($imageauction) {
                    unlink($resource . $imageauction->image);
                }

                if (move_uploaded_file($temp, $resource . $newname)) {
                    $update = ['image' => $newname];

                    $this->table('amw_auctions')->where("id = :id", "id={$id}")->updated($update);
                } else {
                    $this->message->class('error')->text("Erro ao adicionar <em><strong>Leilão</strong></em>, tente novamente mais tarde")->flash();
                    return null;
                }
            } else {
                $this->message->class('error')->text("formato da <em><strong>Imagem</strong></em> inválido")->flash();
                return null;
            }
        }

        $coin = coins[$coin];


        $update = [
            'title' => $title,
            'price' => $price,
            'table_coin' => $coin['table'],
            'column_account' => $coin['column_account'],
            'coin' => $coin['column_coin'],
            'coin_name' => $coin['name_coin'],
            'date' => date('Y-m-d H:i', strtotime($date)),
            'slug' => (new Slugify())->slugify($title)
        ];

        $this->table('amw_auctions')->where("id = :id", "id={$id}")->updated($update);
        $this->message->class('success')->text("<em><strong>Leilão</strong></em> editado com sucesso")->flash(true, true);
    }
}
