<?php

namespace Amwdeveloper\controller;

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

class authadmin extends layer
{
    public $message;
    public $date;

    public function returnDate()
    {
        return date("d/m/Y H:i:s");
    }
    public function messages()
    {
        $this->message = new message();
        return $this->message;
    }

    /** Login account */
    public function postloginaccount($request)
    {
        $account = filter_var($request['account'], FILTER_SANITIZE_SPECIAL_CHARS);
        $password = filter_var($request['password'], FILTER_SANITIZE_SPECIAL_CHARS);

        if (requests_form("fail_admin", 5, 15)) {
            $this->messages()->class("error")->text("<em><strong>IP: {$_SERVER['REMOTE_ADDR']} </strong></em> bloqueado por 15 minutos")->flash();
            return null;
        }

        if (empty($account)) {
            $this->messages()->class("error")->text("Campo <em><strong> Usúario </strong></em> vázio")->flash();
            return null;
        }

        if (empty($password)) {
            $this->messages()->class("error")->text("Campo <em><strong> Password </strong></em> vázio")->flash();
            return null;
        }

        if ($account != admin_account['account'] or $password != admin_account['password']) {
            $this->messages()->class("error")->text("<em><strong> Usúario / Senha </strong></em> incorretos")->flash();
            return null;
        }

        $session = new session();
        $this->messages()->class("success")->text("<em><strong> Conta </strong></em> logada com sucesso")->flash(true, true);
        $session->set("adminlogged", true);
        $session->set("fail_admin", ['block' => null, 'request' => 1]);

    }

    /** Download */
    public function postnewdownload($request)
    {
        $title = filter_var($request['title'], FILTER_SANITIZE_SPECIAL_CHARS);
        $description = filter_var($request['description'], FILTER_SANITIZE_SPECIAL_CHARS);
        $size = filter_var($request['size'], FILTER_SANITIZE_SPECIAL_CHARS);
        $link = filter_var($request['link'], FILTER_SANITIZE_SPECIAL_CHARS);

        if (empty($title) or empty($description) or empty($size) or empty($link)) {
            $this->messages()->class("error")->text("<em><strong>Preecha</strong></em> todos os campos")->flash();
            return null;
        }

        $verifydownload = $this->table("amw_download")->columns("title")->where("title = :title", "title={$title}")->get();

        if (!empty($verifydownload)) {
            $this->messages()->class("error")->text("<em><strong>Download</strong></em> já cadastrado")->flash();
            return null;
        }

        $insert = array(
            'title' => $title,
            'description' => $description,
            'size' => $size,
            'link' => $link,
            'date' => date('Y-m-d H:i:s', strtotime('now'))
        );

        $this->table("amw_download")->created($insert);
        $this->messages()->class("success")->text("<em><strong>Download</strong></em> adicionado com sucesso")->flash(true, true);
    }

    public function posttoeditdownload($request)
    {
        $id = filter_var($request['id'], FILTER_VALIDATE_INT);
        $title = filter_var($request['title'], FILTER_SANITIZE_SPECIAL_CHARS);
        $description = filter_var($request['description'], FILTER_SANITIZE_SPECIAL_CHARS);
        $size = filter_var($request['size'], FILTER_SANITIZE_SPECIAL_CHARS);
        $link = filter_var($request['link'], FILTER_SANITIZE_SPECIAL_CHARS);

        if (empty($id) or empty($title) or empty($description) or empty($size) or empty($link)) {
            $this->messages()->class("error")->text("<em><strong>Preecha</strong></em> todos os campos")->flash();
            return null;
        }

        $verifydownload = $this->table("amw_download")->columns("title")->where("title = :title AND id != :id", "title={$title}&id={$id}")->get();

        if (!empty($verifydownload)) {
            $this->messages()->class("error")->text("<em><strong>Download</strong></em> já cadastrado")->flash();
            return null;
        }

        $insert = array(
            'title' => $title,
            'description' => $description,
            'size' => $size,
            'link' => $link,
            'date' => date('Y-m-d H:i:s', strtotime('now'))
        );

        $this->table("amw_download")->where("id = :id", "id={$id}")->updated($insert);
        $this->messages()->class("success")->text("<em><strong>Download</strong></em> editado com sucesso")->flash(true, true);
    }

    public function posttoremovedownload($request)
    {
        global $route;
        $id = filter_var($request['id'], FILTER_VALIDATE_INT);

        if (empty($id)) $route->redirect("/administration/manage/all/downloads");

        $verifydownload = $this->table("amw_download")->columns("title")->where("id = :id", "id={$id}")->get();

        if (empty($verifydownload)) $route->redirect("/administration/manage/all/downloads");

        $this->table("amw_download")->where("id = :id", "id={$id}")->destroy();
        $route->redirect("/administration/manage/all/downloads");
    }

    /** Account */
    public function postaccountaddcoin($request)
    {
        $type = filter_var($request['type'], FILTER_SANITIZE_SPECIAL_CHARS);
        $account = filter_var($request['account'], FILTER_SANITIZE_SPECIAL_CHARS);
        $coin = $request['coin'];
        $amount = filter_var($request['amount'], FILTER_VALIDATE_INT);

        if (empty($account) or empty($type)) {
            $this->messages()->class("error")->text("<em><strong>Login</strong></em> vázio")->flash();
            return null;
        }

        if (empty($amount)) {
            $this->messages()->class("error")->text("<em><strong>Quantidade</strong></em>, tem que ser >= 1")->flash();
            return null;
        }

        if ($coin < 0) {
            $this->messages()->class("error")->text("<em><strong>Moeda informada</strong></em> é inválida")->flash();
            return null;
        }

        $coininfo = coins[$coin];
        if ($type == 'account') {
            $verifyaccount = $this->table($coininfo['table'])->columns($coininfo['column_coin'] . " as coin, " . $coininfo['column_account'] . " as login")->where("{$coininfo['column_account']} = :mi", "mi={$account}")->get();

            if (empty($verifyaccount)) {
                $this->messages()->class("error")->text("<em><strong>Login</strong></em> inválido")->flash();
                return null;
            }
        } else {
            $character = $this->table("Character")->columns("AccountID")->where("Name = :mi", "mi={$account}")->get();
            if (empty($character)) {
                $this->messages()->class("error")->text("<em><strong>Character</strong></em> inválido")->flash();
                return null;
            }

            $verifyaccount = $this->table($coininfo['table'])->columns($coininfo['column_coin'] . " as coin , " . $coininfo['column_account'] . " as login")->where("{$coininfo['column_account']} = :mi", "mi={$character->AccountID}")->get();

            if (empty($verifyaccount)) {
                $this->messages()->class("error")->text("<em><strong>Login</strong></em> inválido")->flash();
                return null;
            }
        }

        $update = [
            "{$coininfo['column_coin']}" => ($verifyaccount->coin + $amount)
        ];

        $this->table($coininfo['table'])->where("{$coininfo['column_account']} = :mi", "mi={$verifyaccount->login}")->updated($update);
        $this->messages()->class("success")->text("<em><strong>{$amount} {$coininfo['name_coin']}</strong></em> adicionado com sucesso")->flash(true, true);
    }

    public function postaccountremovecoin($request)
    {
        $type = filter_var($request['type'], FILTER_SANITIZE_SPECIAL_CHARS);
        $account = filter_var($request['account'], FILTER_SANITIZE_SPECIAL_CHARS);
        $coin = $request['coin'];
        $amount = filter_var($request['amount'], FILTER_VALIDATE_INT);

        if (empty($account)) {
            $this->messages()->class("error")->text("<em><strong>Login</strong></em> vázio")->flash();
            return null;
        }

        if (empty($amount)) {
            $this->messages()->class("error")->text("<em><strong>Quantidade</strong></em>, tem que ser >= 1")->flash();
            return null;
        }

        if ($coin < 0) {
            $this->messages()->class("error")->text("<em><strong>Moeda informada</strong></em> é inválida")->flash();
            return null;
        }

        $coininfo = coins[$coin];
        if ($type == 'account') {
            $verifyaccount = $this->table($coininfo['table'])->columns($coininfo['column_coin'] . " as coin," . $coininfo['column_account'] . " as login")->where("{$coininfo['column_account']} = :mi", "mi={$account}")->get();

            if (empty($verifyaccount)) {
                $this->messages()->class("error")->text("<em><strong>Login</strong></em> inválido")->flash();
                return null;
            }
        } else {
            $character = $this->table("Character")->columns("AccountID, Name")->where("Name = :mi", "mi={$account}")->get();

            if (empty($character)) {
                $this->messages()->class("error")->text("<em><strong>Character</strong></em> inválido")->flash();
                return null;
            }

            $verifyaccount = $this->table($coininfo['table'])->columns($coininfo['column_coin'] . " as coin," . $coininfo['column_account'] . " as login")->where("{$coininfo['column_account']} = :mi", "mi={$character->AccountID}")->get();

            if (empty($verifyaccount)) {
                $this->messages()->class("error")->text("<em><strong>Login</strong></em> inválido")->flash();
                return null;
            }
        }

        if ($amount > $verifyaccount->coin) {
            $this->messages()->class("error")->text("Conta não possuí o valor <em><strong>{$amount} {$coininfo['name_coin']}</strong></em>
            <br><br><em><strong>{$coininfo['name_coin']}: {$verifyaccount->coin}</strong></em>")->flash();
            return null;
        }

        $update = [
            "{$coininfo['column_coin']}" => ($verifyaccount->coin - $amount)
        ];


        $this->table($coininfo['table'])->where("{$coininfo['column_account']} = :mi", "mi={$verifyaccount->login}")->updated($update);
        $this->messages()->class("success")->text("<em><strong>{$amount} {$coininfo['name_coin']}</strong></em> removido com sucesso")->flash(true, true);
    }

    public function postaccountaddvip($request)
    {
        $account = filter_var($request['account'], FILTER_SANITIZE_SPECIAL_CHARS);
        $vip = filter_var($request['vip'], FILTER_VALIDATE_INT);
        $days = filter_var($request['amount'], FILTER_VALIDATE_INT);
        $alter_vip = filter_var($request['alter_vip'], FILTER_VALIDATE_INT);

        if (empty($account)) {
            $this->messages()->class("error")->text("<em><strong>Login</strong></em> vázio")->flash();
            return null;
        }

        if (empty($days)) {
            $this->messages()->class("error")->text("<em><strong>Dias</strong></em>, tem que ser >= 1")->flash();
            return null;
        }

        if ($vip < 0) {
            $this->messages()->class("error")->text("<em><strong>Vip informado</strong></em> é inválido")->flash();
            return null;
        }

        if ($alter_vip < 0 or $alter_vip > 1) {
            $this->messages()->class("error")->text("<em><strong>Alterar vip</strong></em> é inválido")->flash();
            return null;
        }

        $verifyaccount = $this->table("MEMB_INFO")->columns("" . config['column_vip'] . ",AccountExpireDate")->where("memb___id = :mi", "mi={$account}")->get();

        if (empty($verifyaccount)) {
            $this->messages()->class("error")->text("<em><strong>Login</strong></em> inválido")->flash();
            return null;
        }

        $vipname = vip[($alter_vip == 1 or $verifyaccount->{config['column_vip']} == 0) ? $vip : $verifyaccount->{config['column_vip']}];
        if ($verifyaccount->AccountExpireDate < date('Y-m-d H:i:s')) {
            $addvip = [
                '' . config['column_vip'] . '' => $vip,
                'AccountExpireDate' => date('Y-m-d H:i:s', strtotime("+{$days} days"))
            ];
        } else {
            $addvip = [
                '' . config['column_vip'] . '' => ($alter_vip == 1) ? $vip : $verifyaccount->{config['column_vip']},
                'AccountExpireDate' => date('Y-m-d H:i:s', strtotime("+{$days} days", strtotime($verifyaccount->AccountExpireDate)))
            ];
        }


        $this->table("MEMB_INFO")->where("memb___id = :mi", "mi={$account}")->updated($addvip);
        $this->messages()->class("success")->text("<em><strong>{$days} dias de {$vipname}</strong></em> adicionado com sucesso")->flash(true, true);
    }

    public function postaccountremovevip($request)
    {
        $account = filter_var($request['account'], FILTER_SANITIZE_SPECIAL_CHARS);
        $days = filter_var($request['amount'], FILTER_VALIDATE_INT);

        if (empty($account)) {
            $this->messages()->class("error")->text("<em><strong>Login</strong></em> vázio")->flash();
            return null;
        }

        if (empty($days)) {
            $this->messages()->class("error")->text("<em><strong>Dias</strong></em>, tem que ser >= 1")->flash();
            return null;
        }

        $verifyaccount = $this->table("MEMB_INFO")->columns("" . config['column_vip'] . ",AccountExpireDate")->where("memb___id = :mi", "mi={$account}")->get();

        if (empty($verifyaccount)) {
            $this->messages()->class("error")->text("<em><strong>Login</strong></em> inválido")->flash();
            return null;
        }

        if ($verifyaccount->AccountExpireDate < date('Y-m-d H:i:s')) {
            $this->messages()->class("error")->text("<em><strong>Conta</strong></em> não possuí dias de vip")->flash();
            $addvip = ['' . config['column_vip'] . '' => 0];
            $this->table("MEMB_INFO")->where("memb___id = :mi", "mi={$account}")->updated($addvip);
            return;
        }
        $addvip = [
            'AccountExpireDate' => date('Y-m-d H:i:s', strtotime("-{$days} days", strtotime($verifyaccount->AccountExpireDate)))
        ];

        $this->table("MEMB_INFO")->where("memb___id = :mi", "mi={$account}")->updated($addvip);


        $verifynewdate = $this->table("MEMB_INFO")->columns("AccountExpireDate")->where("memb___id = :mi", "mi={$account}")->get();
        if ($verifynewdate->AccountExpireDate < date('Y-m-d H:i:s')) {
            $addvip = ['' . config['column_vip'] . '' => 0];
            $this->table("MEMB_INFO")->where("memb___id = :mi", "mi={$account}")->updated($addvip);
        }

        $this->messages()->class("success")->text("<em><strong>{$days} dias de vip</strong></em> removido com sucesso")->flash(true, true);
    }

    public function postaccountbanunban($request)
    {
        $account = filter_var($request['account'], FILTER_SANITIZE_SPECIAL_CHARS);
        $typeSelect = filter_var($request['type_select'], FILTER_SANITIZE_SPECIAL_CHARS);
        $option = $request['option'];

        if (empty($account) or empty($typeSelect)) {
            $this->messages()->class("error")->text("<em><strong>Login</strong></em> vázio")->flash();
            return null;
        }

        if ($option < 0 or $option > 1) {
            $this->messages()->class("error")->text("<em><strong>Opção</strong></em>, inválida")->flash();
            return null;
        }

        if ($typeSelect == 'character') {
            $account = $this->table("Character")->columns('AccountID as account')->where("Name = :n", "n={$account}")->get()->account;
        }

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

        if (empty($verifyaccount)) {
            $this->messages()->class("error")->text("<em><strong>Login</strong></em> inválido")->flash();
            return null;
        }

        $type = $option == 1 ? 'Banida' : 'Desbanida';

        $this->table("MEMB_INFO")->where("memb___id = :mi", "mi={$account}")->updated(['bloc_code' => $option]);



        $this->messages()->class("success")->text("<em><strong>Conta {$type}</strong></em> com sucesso")->flash(true, true);
    }

    public function postsearchaccount($request)
    {
        $account = filter_var($request['account'], FILTER_SANITIZE_SPECIAL_CHARS);

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

        if ($serachaccount) {
            echo json_encode([
                'message' => $serachaccount->memb___id,
                'status' => 201
            ]);


            return;
        }

        $serachcharacter = $this->table("Character")->columns("AccountID")->where("Name = :name", "name={$account}")->get();

        if ($serachcharacter) {
            echo json_encode([
                'message' => $serachcharacter->AccountID,
                'status' => 201
            ]);


            return;
        }
        return null;
    }

    /** Character */
    public function postcharacteraddstaff($request)
    {
        $name = filter_var($request['character'], FILTER_SANITIZE_SPECIAL_CHARS);
        $option = $request['add_staff'];

        if (empty($name)) {
            $this->messages()->class("error")->text("<em><strong>Character</strong></em> vázio")->flash();
            return null;
        }

        if ($option < 0 or $option > 1) {
            $this->messages()->class("error")->text("<em><strong>Opção</strong></em>, inválida")->flash();
            return null;
        }

        $verifychar = $this->table("Character")->columns("AccountID")->where("Name = :name", "name={$name}")->get();

        if (empty($verifychar)) {
            $this->messages()->class("error")->text("<em><strong>Character</strong></em> inválido")->flash();
            return null;
        }
        $optionname = $option == 1 ? 'Adicionado à' : 'Removido da';


        $this->table("Character")->where("Name = :name", "name={$name}")->updated(["CtlCode" => ($option == 1) ? config['number_staff'] : 0]);
        $this->messages()->class("success")->text("Personagem, <em><strong>{$optionname} equipe</strong></em> com sucesso")->flash(true, true);
    }

    public function postcharacterbanunban($request)
    {
        $name = filter_var($request['character'], FILTER_SANITIZE_SPECIAL_CHARS);
        $option = $request['add_staff'];

        if (empty($name)) {
            $this->messages()->class("error")->text("<em><strong>Character</strong></em> vázio")->flash();
            return null;
        }

        if ($option < 0 or $option > 1) {
            $this->messages()->class("error")->text("<em><strong>Opção</strong></em>, inválida")->flash();
            return null;
        }

        $verifychar = $this->table("Character")->columns("AccountID")->where("Name = :name", "name={$name}")->get();

        if (empty($verifychar)) {
            $this->messages()->class("error")->text("<em><strong>Character</strong></em> inválido")->flash();
            return null;
        }
        $optionname = $option == 1 ? 'Banido' : 'Desbanido';

        $this->table("Character")->where("Name = :name", "name={$name}")->updated(["CtlCode" => $option]);
        $this->messages()->class("success")->text("Personagem, <em><strong>{$optionname}</strong></em> com sucesso")->flash(true, true);
    }

    public function postcharacteredit($request)
    {
        $name = filter_var($request['name'], FILTER_SANITIZE_SPECIAL_CHARS);
        $level = $request['level'];
        $strength = $request['strength'];
        $dexterity = $request['dexterity'];
        $vitality = $request['vitality'];
        $energy = $request['energy'];
        $command = $request['command'] ?? 0;
        $class = $request['class'];
        $resets = $request['resets'];
        $mresets = $request['mresets'];
        $kills = $request['kills'];
        $hero = $request['hero'];
        $reipvp = $request['reipvp'];

        if (empty($name) or !is_numeric($strength) or !is_numeric($dexterity) or !is_numeric($vitality) or !is_numeric($energy) or !is_numeric($command) or !is_numeric($class) or !is_numeric($resets) or !is_numeric($mresets)  or !is_numeric($kills)  or !is_numeric($hero) or !is_numeric($level)) {
            $this->messages()->class('error')->text("Preecha todos os <em><strong>campos corretamente</strong></em> para continuar")->flash();
            return null;
        }

        if ($level > server['max_level'] or $level < 1) {
            $this->messages()->class('error')->text("Level não pode ser maior que <em><strong>" . server['max_level'] . "</strong></em> e menor que <em><strong>1</strong></em>")->flash();
            return null;
        }

        if ($strength > server['max_points'] or $strength < 0) {
            $this->messages()->class('error')->text("Força não pode ser maior que <em><strong>32767</strong></em> e menor que <em><strong>0</strong></em>")->flash();
            return null;
        }

        if ($dexterity > server['max_points'] or $dexterity < 0) {
            $this->messages()->class('error')->text("Agilidade não pode ser maior que <em><strong>" . server['max_level'] . "</strong></em> e menor que <em><strong>0</strong></em>")->flash();
            return null;
        }

        if ($vitality > server['max_points'] or $vitality < 0) {
            $this->messages()->class('error')->text("Vitalidade não pode ser maior que <em><strong>" . server['max_level'] . "</strong></em> e menor que <em><strong>0</strong></em>")->flash();
            return null;
        }

        if ($energy > server['max_points'] or $energy < 0) {
            $this->messages()->class('error')->text("Energia não pode ser maior que <em><strong>" . server['max_level'] . "</strong></em> e menor que <em><strong>0</strong></em>")->flash();
            return null;
        }

        if ($command > server['max_points'] or $command < 0) {
            $this->messages()->class('error')->text("Comando não pode ser maior que <em><strong>" . server['max_level'] . "</strong></em> e menor que <em><strong>0</strong></em>")->flash();
            return null;
        }

        if (empty(characters['classes'][$class])) {
            $this->messages()->class('error')->text("Classe informada <em><strong>está incorreta</strong></em>")->flash();
            return null;
        }

        if ($resets < 0) {
            $this->messages()->class('error')->text("Resets não pode ser menor que <em><strong>0</strong></em>")->flash();
            return null;
        }

        if ($mresets < 0) {
            $this->messages()->class('error')->text("MResets não pode ser menor que <em><strong>0</strong></em>")->flash();
            return null;
        }

        if ($kills < 0) {
            $this->messages()->class('error')->text("Kills não pode ser menor que <em><strong>0</strong></em>")->flash();
            return null;
        }

        if ($hero < 0) {
            $this->messages()->class('error')->text("Heros não pode ser menor que <em><strong>0</strong></em>")->flash();
            return null;
        }
        if ($reipvp == 1) {
            $this->table("Character")->where("reipvp = :r", "r=1")->updated(['reipvp' => 0]);
        }

        $update = [
            'cLevel' => $level,
            'Strength' => $strength,
            'Dexterity' => $dexterity,
            'Vitality' => $vitality,
            'Energy' => $energy,
            'Leadership' => $command,
            'Class' => $class,
            '' . columns_score_perfil['resets'] . '' => $resets,
            '' . columns_score_perfil['mresets'] . '' => $mresets,
            '' . columns_score_perfil['killer'] . '' => $kills,
            '' . columns_score_perfil['hero'] . '' => $hero,
            'reipvp' => $reipvp
        ];

        $this->table("Character")->where("Name = :name", "name={$name}")->updated($update);
        $this->messages()->class('success')->text("Personagem, <em><strong>{$name}</strong></em> com sucesso")->flash(true, true);
    }
}
