<?php

namespace Amwdeveloper\plugins\market\character;

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

class geral extends layer
{

    private $message;
    private $session;

    public function __construct()
    {
        $this->message = (new message());
        $this->session = (new session());
    }

    public function myCharacters()
    {
        $characters = $this->table("Character")
            ->columns("Name as name, Imagem as image, " . columns_score_perfil['hero'] . " as hero, " . columns_score_perfil['killer'] . " as killer, " . columns_score_perfil['mresets'] . " as mresets, " . columns_score_perfil['resets'] . " as resets, Strength as strength,Dexterity as dexterity, Vitality as vitality, Energy as energy")
            ->where("AccountID = :acc AND CtlCode = :c", "acc=" . (new session())->useraccount . "&c=0")
            ->all();
        return $characters;
    }

    public function myCharacter($char)
    {
        $character = $this->table("Character")
            ->columns("Name as name, Imagem as image, " . columns_score_perfil['hero'] . " as hero, " . columns_score_perfil['killer'] . " as killer, " . columns_score_perfil['mresets'] . " as mresets, " . columns_score_perfil['resets'] . " as resets, Strength as strength,Dexterity as dexterity, Vitality as vitality, Energy as energy")
            ->where("AccountID = :acc AND CtlCode = :c AND Name = :name", "acc=" . (new session())->useraccount . "&c=0&name={$char}")
            ->get();
        return $character;
    }

    public function inventoryCharacter($char)
    {
        $inventory = (new inventory($char))->CutHexSlotsInventory();

        return $inventory;
    }

    public function authAdvertiseChar($request)
    {
        $char = filter_var($request['char'], FILTER_SANITIZE_SPECIAL_CHARS);
        $price = filter_var($request['price'], FILTER_VALIDATE_INT);

        if (!$char) {
            (new message())->class("error")->text("Campos inválidos,<em><strong>atualize a página</strong></em>")->flash();
        }

        if (!$price or $price > 4000000) {
            (new message())->class("error")->text("Campos preço,<em><strong>inválido</strong></em>")->flash();
        }


        $virifychar = $this->table("Character")
            ->where("Name = :name AND AccountID = :acc AND CtlCode = :c", "name={$char}&acc=" . (new session)->useraccount . "&c=0")
            ->get();

        if (!$virifychar) {
            (new message())->class("error")->text("Personagem,<em><strong>não existe em sua conta</strong></em>")->flash();
            return;
        }

        $data = [
            'name' => $char,
            'account' => (new session)->useraccount,
            'description' => json_encode([
                'avatar' => $virifychar->Imagem,
                'resets' => $virifychar->{columns_score_perfil['resets']},
                'mresets' => $virifychar->{columns_score_perfil['mresets']},
                'hero' => $virifychar->{columns_score_perfil['hero']},
                'killer' => $virifychar->{columns_score_perfil['killer']},
                'strength' => $virifychar->Strength,
                'dexterity' => $virifychar->Dexterity,
                'vitality' => $virifychar->Vitality,
                'energy' => $virifychar->Energy,
            ]),
            'class' => characters['classes'][$virifychar->Class]['short_name'],
            'n_class' => $virifychar->Class,
            'price' => $price
        ];

        $this->table("Character")->where("Name = :name AND AccountID = :acc", "name={$char}&acc=" . (new session)->useraccount . "")->updated(['CtlCode' => 1]);

        $this->table("amw_market_character")->created($data);

        (new message())->class("success")->text("Personagem,<em><strong>foi anunciado com sucesso</strong></em>")->flash(true, true);
    }

    public function removeCharacter($id)
    {
        $verifyChar = $this->table("amw_market_character")->where("account = :acc AND id = :id", "acc=" . (new session)->useraccount . "&id={$id}")->get();

        if (!$verifyChar) return false;

        $this->table("Character")->where("Name = :name", "name={$verifyChar->name}")->updated(["CtlCode" => 0]);
        $this->table("amw_market_character")->where("id = :id", "id={$id}")->destroy();

        return true;
    }

    public function authBuyChar($request)
    {
        $char = filter_var($request['char'], FILTER_SANITIZE_SPECIAL_CHARS);
        $id_char = filter_var($request['id_char'], FILTER_VALIDATE_INT);

        if (!$char or !$id_char) {
            $this->message->class('error')->text('<em><strong>Algo deu errado</strong></em>, não é possível continuar com a compra!')->flash();
            return null;
        }

        $verifyCharMarket = $this->table("amw_market_character")->where("name = :n AND id = :id", "n={$char}&id={$id_char}")->get();
        if (!$verifyCharMarket) {
            $this->message->class('error')->text('<em><strong>Algo deu errado</strong></em>, não é possível continuar com a compra!')->flash();
            return null;
        }

        if ($verifyCharMarket->account == $this->session->useraccount) {
            $this->message->class('error')->text('<em><strong>Você não pode</strong></em>, comprar seu próprio personagem!')->flash();
            return null;
        }

        $myAccount = $this->table("" . market['coin_table'] . "")->columns("" . market['coin_column'] . " as coin")->where("" . market['coin_account'] . " = :acc", "acc={$this->session->useraccount}")->get();

        if ($myAccount->coin < $verifyCharMarket->price) {
            $this->message->class('error')->text('Você não possuí o valor de, <em><strong>' . $verifyCharMarket->price . ' ' . market['coin_name'] . '</strong></em>')->flash();
            return null;
        }

        $slotsAccountCharacter = $this->table("AccountCharacter")->where("Id = :acc", "acc={$this->session->useraccount}")->get();

        $game = "";
        if (empty($slotsAccountCharacter->GameID1)) $game = "GameID1";
        elseif (empty($slotsAccountCharacter->GameID2)) $game = "GameID2";
        elseif (empty($slotsAccountCharacter->GameID3)) $game = "GameID3";
        elseif (empty($slotsAccountCharacter->GameID4)) $game = "GameID4";
        elseif (empty($slotsAccountCharacter->GameID5)) $game = "GameID5";
        else {
            $this->message->class('error')->text('<em><strong>Você não possuí</strong></em>, slots vázios!')->flash();
            return null;
        }

        $filterChars = $this->table("AccountCharacter")->where("Id = :acc", "acc={$verifyCharMarket->account}")->get();

        $search = "";
        if ($filterChars->GameID1 == $verifyCharMarket->name) $search = "GameID1";
        elseif ($filterChars->GameID2 == $verifyCharMarket->name) $search = "GameID2";
        elseif ($filterChars->GameID3 == $verifyCharMarket->name) $search = "GameID3";
        elseif ($filterChars->GameID4 == $verifyCharMarket->name) $search = "GameID4";
        elseif ($filterChars->GameID5 == $verifyCharMarket->name) $search = "GameID5";
        else {
            $this->message->class('error')->text('<em><strong>O Vendedor não possuí</strong></em>, mais o personagem!')->flash();
            return null;
        }

        $this->table("AccountCharacter")->where("Id = :acc", "acc={$this->session->useraccount}")->updated([$game => $verifyCharMarket->name]);
        $this->table("Character")->where("Name = :name", "name={$verifyCharMarket->name}")->updated(['AccountID' => $this->session->useraccount,'CtlCode' => 0]);
        $this->db()->query("UPDATE " . market['coin_table'] . " SET " . market['coin_column'] . " = " . market['coin_column'] . " - {$verifyCharMarket->price} WHERE " . market['coin_account'] . " = '{$this->session->useraccount}' ");


        $this->table("AccountCharacter")->where("Id = :acc", "acc={$verifyCharMarket->account}")->updated([$search => NULL]);
        $this->db()->query("UPDATE " . market['coin_table'] . " SET " . market['coin_column'] . " = " . market['coin_column'] . " + {$verifyCharMarket->price} WHERE " . market['coin_account'] . " = '{$verifyCharMarket->account}' ");

        $this->table("amw_market_character")->where("name = :n AND id = :id", "n={$char}&id={$id_char}")->destroy();

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