<?php

namespace Amwdeveloper\plugins\market;

use Amwdeveloper\core\details;
use Amwdeveloper\core\session;
use Amwdeveloper\model\layer;
use Amwdeveloper\model\message;
use Amwdeveloper\plugins\webshop\vaultmarket;

class item extends layer
{

    protected function loadvault()
    {
        $session = (new session())->useraccount;
        $vault = $this->table("warehouse")->columns("Items")->where("AccountID = :acc", "acc={$session}")->get();
        return strtoupper(bin2hex($vault->Items));
    }

    protected function vaultitems(bool $uniqueItem = false, string $hexa = '')
    {
        $data = [];
        if ($uniqueItem and $hexa) {
            $section = hexdec(substr($hexa, 18, 1));
            $index = hexdec(substr($hexa, 0, 2));
            $level = hexdec(substr($hexa, 2, 2));
            $excelents = hexdec(substr($hexa, 14, 2));
            $durabillity = hexdec(substr($hexa, 4, 2));
            $ancient = hexdec(substr($hexa, 16, 2));
            $harmony = hexdec(substr($hexa, 20, 2));
            $item360 = hexdec(substr($hexa, 18, 2));
            $socket1 = hexdec(substr($hexa, 22, 2));
            $socket2 = hexdec(substr($hexa, 24, 2));
            $socket3 = hexdec(substr($hexa, 26, 2));
            $socket4 = hexdec(substr($hexa, 28, 2));
            $socket5 = hexdec(substr($hexa, 30, 2));

            $detailsitem = $this->table("amw_items")->where("id_item = :id AND section = :sc", "id={$index}&sc={$section}")->get();

            $data = [
                'hex' => $hexa,
                'name' => $detailsitem->name,
                'x' => $detailsitem->x,
                'y' => $detailsitem->y,
                'image' => "{$section}-{$index}.gif",
                'description' => details::descriptionitem($detailsitem, $section, $index, $level, $excelents, $durabillity, $ancient, $harmony, $item360, $socket1, $socket2, $socket3, $socket4, $socket5)
            ];
        } else {
            for ($i = 0; $i < 120; $i++)
                $items[] = substr($this->loadvault(), (web_shopping['db_slotcount'] * $i), web_shopping['db_slotcount']);
            foreach ($items as $item) {
                if (str_pad("", web_shopping['db_slotcount'], "F") != $item) {
                    $section = hexdec(substr($item, 18, 1));
                    $index = hexdec(substr($item, 0, 2));
                    $level = hexdec(substr($item, 2, 2));
                    $excelents = hexdec(substr($item, 14, 2));
                    $durabillity = hexdec(substr($item, 4, 2));
                    $ancient = hexdec(substr($item, 16, 2));
                    $harmony = hexdec(substr($item, 20, 2));
                    $item360 = hexdec(substr($item, 18, 2));
                    $socket1 = hexdec(substr($item, 22, 2));
                    $socket2 = hexdec(substr($item, 24, 2));
                    $socket3 = hexdec(substr($item, 26, 2));
                    $socket4 = hexdec(substr($item, 28, 2));
                    $socket5 = hexdec(substr($item, 30, 2));
                    $detailsitem = $this->table("amw_items")->where("id_item = :id AND section = :sc", "id={$index}&sc={$section}")->get();

                    $data[] = [
                        'hex' => $item,
                        'name' => $detailsitem->name,
                        'x' => $detailsitem->x,
                        'y' => $detailsitem->y,
                        'width' => ($detailsitem->x * web_shopping['db_slotcount']),
                        'height' => ($detailsitem->y * web_shopping['db_slotcount']),
                        'image' => "{$section}-{$index}.gif",
                        'description' => details::descriptionitem(
                            $detailsitem,
                            $section,
                            $index,
                            $level,
                            $excelents,
                            $durabillity,
                            $ancient,
                            $harmony,
                            $item360,
                            $socket1,
                            $socket2,
                            $socket3,
                            $socket4,
                            $socket5
                        )
                    ];
                } else {
                    $data[] = [
                        'name' => null,
                        'width' => 32,
                        'height' => 32,
                        'description' => null
                    ];
                }
            }
        }




        return $data;
    }

    public function getVaultItems(bool $uniqueItem = false, string $hexa = '')
    {
        return $this->vaultitems($uniqueItem, $hexa);
    }

    // POST

    public function advertiseitem($request)
    {
        $hexa = filter_var($request['hex'], FILTER_SANITIZE_SPECIAL_CHARS);
        $zen = filter_var($request['zen'], FILTER_VALIDATE_INT);
        $hcoin = filter_var($request['hcoin'], FILTER_VALIDATE_INT);
        $bless = filter_var($request['bless'], FILTER_VALIDATE_INT);
        $soul = filter_var($request['soul'], FILTER_VALIDATE_INT);
        $life = filter_var($request['life'], FILTER_VALIDATE_INT);
        $guardian = filter_var($request['guardian'], FILTER_VALIDATE_INT);
        $harmony_coin = filter_var($request['harmony'], FILTER_VALIDATE_INT);
        $chaos = filter_var($request['chaos'], FILTER_VALIDATE_INT);
        $creation = filter_var($request['creation'], FILTER_VALIDATE_INT);
        $name_item = filter_var($request['name_item'], FILTER_SANITIZE_SPECIAL_CHARS);



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

        for ($i = 0; $i < 120; $i++)
        $items[] = substr($this->loadvault(), (web_shopping['db_slotcount'] * $i), web_shopping['db_slotcount']);
        
        if(!in_array($hexa, $items)){
            (new message)->class('error')->text('<em><strong>Ops</strong></em> item não foi encontrado no seu baú')->flash();
            return null;
        }

        if ($hcoin >= 1 or $zen >= 1) {
            if ($bless >= 1 or $soul >= 1 or $life >= 1 or $chaos >= 1 or $creation >= 1 or $guardian >= 1 or $harmony_coin >= 1) {
                (new message)->class('error')->text('<em><strong>Atenção</strong></em>, Você pode vender seu item somente por <em><strong>Coins</strong></em> ou <em><strong>Jewels</strong></em> ')->flash();
                return null;
            }
        }

        if ($hcoin <= 0 and $zen <= 0) {
            if ($bless <= 0 and $soul <= 0 and $life <= 0 and $chaos <= 0 and $creation <= 0 and $guardian <= 0  and $harmony_coin <= 0) {
                (new message)->class('error')->text('<em><strong>Atenção</strong></em>, adicione um valor ao seu item para vende-lo')->flash();
                return null;
            }
        }

        $section = hexdec(substr($hexa, 18, 1));
        $index = hexdec(substr($hexa, 0, 2));
        $ancient = hexdec(substr($hexa, 16, 2));
        $harmony = hexdec(substr($hexa, 20, 2));
        $item380 = hexdec(substr($hexa, 19, 1));
        $socket = hexdec(substr($hexa, 22, 2));
        $excelents = hexdec(substr($hexa, 14, 2));
        $hp = 0;
        $reduce = 0;
        $reflect = 0;

        for ($options = 0; $options <= 6; $options++) {
            if (($excelents & (1 << $options)) != 0) {
                $opt[$options] = true;
            } else {
                $opt[$options] = false;
            }
        }

        if ($section < 6) {
            if ($opt[5] == true) $hp = 1; #HP
            if ($opt[3] == true) $reduce = 1; # reduce
            if ($opt[2] == true) $reflect = 1; #reflect
        } elseif ($section < 12) {
            if ($opt[5] == true) $hp = 1; #HP
            if ($opt[3] == true) $reduce = 1; # reduce
            if ($opt[2] == true) $reflect = 1; #reflect
        }

        if ($section == 13 and ($index >= 8 and $index <= 13)) {
            if ($opt[5] == true) $hp = 1; #HP
            if ($opt[3] == true) $reduce = 1; # reduce
            if ($opt[2] == true) $reflect = 1; #reflect
        } elseif ($section == 13 and ($index >= 20 and $index <= 28)) {
            if ($opt[5] == true) $hp = 1; #HP
            if ($opt[3] == true) $reduce = 1; # reduce
            if ($opt[2] == true) $reflect = 1; #reflect
        }

        if (
            $section == 14
            or $section == 15
            // or  ($section == 13 and ( $section == 13 or $index >= 5 and $index <= 7) or ($section == 13 or $index >= 14 and $index <= 19) or $index == 29 or $index > 31)
            // or  ($section == 12 and $index > 6)
        ) {
            (new message)->class('error')->text('<em><strong>Item bloqueado</strong></em>, não é possível vender o mesmo no mercado')->flash();
            return null;
        }


        if (market['block']['item380'] and $item380 > 0) {
            (new message)->class('error')->text('<em><strong>Item 380 bloqueado</strong></em>, não é possível vender o mesmo no mercado')->flash();
            return null;
        }

        if (market['block']['ancient'] and $ancient > 0) {
            (new message)->class('error')->text('<em><strong>Item ancient bloqueado</strong></em>, não é possível vender o mesmo no mercado')->flash();
            return null;
        }

        if (market['block']['harmony'] and $harmony > 0) {
            (new message)->class('error')->text('<em><strong>Item Harmony bloqueado</strong></em>, não é possível vender o mesmo no mercado')->flash();
            return null;
        }


        if (market['block']['socket'] and $socket > 0 and $socket != 255) {
            (new message)->class('error')->text('<em><strong>Item Socket bloqueado</strong></em>, não é possível vender o mesmo no mercado')->flash();
            return null;
        }



        $account = (new session())->useraccount;

        $accountLogged = $this->table("MEMB_STAT")->columns("ConnectStat as online")->where("memb___id = :mi", "mi={$account}")->get();

        if ($accountLogged) {
            if ($accountLogged->online == 1) {
                (new message)->class('error')->text('<em><strong>Deslogue sua conta no jogo</strong></em>, para anunciar o item')->flash();
                return null;
            }
        } else {
            (new message)->class('error')->text('<em><strong>Você precisa abrir sua conta no jogo pelo menos 1 vez</strong></em>, para anunciar o item')->flash();
            return null;
        }

        $infoItem = $this->table("amw_items")->where("section = :sc AND id_item = :in", "sc={$section}&in={$index}")->get();

        if (!$infoItem) {
            (new message)->class('error')->text('<em><strong>Item não encontrado</strong></em>, não foi possível usar o mercado.')->flash();
            return null;
        }


        $itemX = $infoItem->x;
        $itemY = $infoItem->y;
        $nameDivisionOne = explode("[", $infoItem->name);

        if (isset($nameDivisionOne[1])) {
            $exp = explode("]", $nameDivisionOne[1]);
            $nameDivision = $exp[0];
        } else $nameDivision = "Comum";

        $this->table("amw_market_items")->created([
            'name' => $name_item,
            'section' => $section,
            'hexa' => $hexa,
            'zen' => $zen,
            'price' => $hcoin,
            'bless' => $bless,
            'soul' => $soul,
            'life' => $life,
            'chaos' => $chaos,
            'creation' => $creation,
            'guardian' => $guardian,
            'harmony' => $harmony_coin,
            'account' => $account,
            'x' => $itemX,
            'y' => $itemY,
            'status' => 1,
            'dw' => $infoItem->dw,
            'dk' => $infoItem->dk,
            'fe' => $infoItem->fe,
            'mg' => $infoItem->mg,
            'dl' => $infoItem->dl,
            'su' => $infoItem->su,
            'rf' => $infoItem->rf,
            'tier' => $nameDivision,
            'hp' => $hp,
            'reduce' => $reduce,
            'reflect' => $reflect
        ]);

        $newhexa = str_replace($hexa, str_pad('', web_shopping['db_slotcount'], 'F'), $this->loadvault());

        $this->db()->query("UPDATE warehouse SET Items = 0x{$newhexa} WHERE AccountID = '{$account}'");

        (new message)->class('success')->text('<em><strong>Item adicionado ao mercado</strong></em> com sucesso')->flash(true, true);
    }

    public function buyitem($data)
    {
        $item = $this->table('amw_market_items')->where("id = :id", "id={$data['id']}")->get();
        if (!$item) {
            (new message)->class('error')->text('<em><strong>Não foi possível continuar com sua compra</strong></em>, atualiza a página e tente novamente')->flash();
            return null;
        }

        $account = (new session())->useraccount;
        if ($item->account == $account) {
            (new message)->class('error')->text('<em><strong>Não foi possível continuar</strong></em>, você não pode comprar seu próprio item')->flash();
            return null;
        }

        $accountCoin = $this->table("" . market['coin_table'] . "")->columns("" . market['coin_column'] . " as coin")
            ->where("" . market['coin_account'] . " = :mi", "mi={$account}")->get();

        $accountJewels = $this->table("MEMB_INFO")->columns("soul,life,chaos,bless,creation,harmony,guardian,zen")
            ->where("memb___id = :mi", "mi={$account}")->get();

        if ($item->price >= 1) {
            if ($accountCoin->coin < $item->price) {
                (new message)->class('error')->text("You don't have the value of <em><strong>{$item->price} " . market['coin_name'] . "</strong></em>")->flash();
                return null;
            }
        }

        if ($item->zen >= 1) {
            if ($accountJewels->zen < $item->zen) {
                (new message)->class('error')->text("You don't have the value of <em><strong>{$item->zen} zen</strong></em>")->flash();
                return null;
            }
        }

        if ($item->soul >= 1) {
            if ($accountJewels->soul < $item->soul) {
                (new message)->class('error')->text("You don't have the value of <em><strong>{$item->soul} soul</strong></em>")->flash();
                return null;
            }
        }

        if ($item->bless >= 1) {
            if ($accountJewels->bless < $item->bless) {
                (new message)->class('error')->text("You don't have the value of <em><strong>{$item->bless} bless</strong></em>")->flash();
                return null;
            }
        }

        if ($item->chaos >= 1) {
            if ($accountJewels->chaos < $item->chaos) {
                (new message)->class('error')->text("You don't have the value of <em><strong>{$item->chaos} chaos</strong></em>")->flash();
                return null;
            }
        }

        if ($item->life >= 1) {
            if ($accountJewels->life < $item->life) {
                (new message)->class('error')->text("You don't have the value of <em><strong>{$item->life} life</strong></em>")->flash();
                return null;
            }
        }

        if ($item->creation >= 1) {
            if ($accountJewels->creation < $item->creation) {
                (new message)->class('error')->text("You don't have the value of <em><strong>{$item->creation} creation</strong></em>")->flash();
                return null;
            }
        }

        if ($item->guardian >= 1) {
            if ($accountJewels->guardian < $item->guardian) {
                (new message)->class('error')->text("You don't have the value of <em><strong>{$item->guardian} guardian</strong></em>")->flash();
                return null;
            }
        }

        if ($item->harmony >= 1) {
            if ($accountJewels->harmony < $item->harmony) {
                (new message)->class('error')->text("You don't have the value of <em><strong>{$item->harmony} harmony</strong></em>")->flash();
                return null;
            }
        }

        if ($item->status != 1) {
            (new message)->class('error')->text('<em><strong>Não foi possível continuar</strong></em>, o item não está disponível para compra')->flash();
            return null;
        }

        $account = (new session())->useraccount;

        $accountLogged = $this->table("MEMB_STAT")->columns("ConnectStat as online")->where("memb___id = :mi", "mi={$account}")->get();
        if ($accountLogged->online == 1) {
            (new message)->class('error')->text('<em><strong>Deslogue sua conta no jogo</strong></em>, para anunciar o item')->flash();
            return null;
        }

        (new vaultmarket())->hexvault(
            $item->x,
            $item->y,
            $item->hexa,
            market['coin_table'],
            market['coin_account'],
            market['coin_column'],
            $item->price,
            $item->zen,
            $item->soul,
            $item->bless,
            $item->chaos,
            $item->life,
            $item->creation,
            $item->harmony,
            $item->guardian,
            $item->account,
        );
    }

    public function removeitem($data)
    {
        global $route;
        $item = $this->table('amw_market_items')->where("id = :id", "id={$data['id']}")->get();

        if (!$item) $route->redirect('/market/my/ads');

        $account = (new session())->useraccount;

        $accountLogged = $this->table("MEMB_STAT")->columns("ConnectStat as online")->where("memb___id = :mi", "mi={$account}")->get();
        if ($accountLogged->online == 1) $route->redirect('/market/my/ads');


        (new vaultmarket())->hexvault($item->x, $item->y, $item->hexa, '', '', '', '', '', '', '', '', '', '', '', '', true);
        $route->redirect('/market/my/ads');
    }

    public function searchitem($data)
    {
        $item = filter_var($data['search'], FILTER_SANITIZE_SPECIAL_CHARS);

        $itensmarket = (new layer())->db()->query("SELECT id,hexa,tier,price,zen,bless,soul,life,chaos,creation,harmony,guardian FROM amw_market_items WHERE name LIKE '%{$item}%'")->fetchAll();

        $items = [];

        foreach ($itensmarket as $item) $items[] = [
            'id' => $item->id,
            'tier' => $item->tier,
            'price' => $item->price,
            'zen' => $item->zen,
            'bless' => $item->bless,
            'soul' => $item->soul,
            'life' => $item->life,
            'chaos' => $item->chaos,
            'creation' => $item->creation,
            'harmony' => $item->harmony,
            'guardian' => $item->guardian,
            'details' => $this->vaultitems(true, $item->hexa),
            'coin_name' => market['coin_name']
        ];

        require __DIR__ . '/../../../theme/' . config['path'] . '/pages/user/market/search.phtml';
    }
}
