<?php

namespace Amwdeveloper\plugins\jewels;

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

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()
    {
        $data = [];

        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();

                $name = explode(" ", strtolower($detailsitem->name));
                if ($section >= 12) {
                    if (in_array('jewel', $name)) {
                        if ($level == 0) {
                            $image = "{$section}-{$index}.gif";
                        } else {
                            if ($level == 8) $image = "{$section}-{$index}-1.gif";
                            else $image = "{$section}-{$index}-2.gif";
                        }
                    } else {
                        $image = "{$section}-{$index}.gif";
                    }
                } else {
                    $image = "{$section}-{$index}.gif";
                }
                if (in_array('jewel', $name)) {
                    foreach (jewels_trade as $jewel) {
                        if (in_array($jewel, $name)) {
                            $block = "active";
                        }
                    }
                } else {
                    $block = "block";
                }

                $data[] = [
                    'hex' => $item,
                    'name' => $detailsitem->name,
                    'x' => $detailsitem->x,
                    'y' => $detailsitem->y,
                    'width' => ($detailsitem->x * 32),
                    'height' => ($detailsitem->y * 32),
                    'image' => $image,
                    'block' => $block,
                    '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 converteJewelToCoin($item)
    {
        for ($i = 0; $i < 120; $i++)
            $items[] = substr($this->loadvault(), (web_shopping['db_slotcount'] * $i), web_shopping['db_slotcount']);
        $item = $item['hex'];
        if (!in_array($item, $items)) {
            (new message)->class("error")->text("Item não foi encontrado em seu baú!")->flash();
            return;
        }

        $section = hexdec(substr($item, 18, 1));
        $index = hexdec(substr($item, 0, 2));
        $level = hexdec(substr($item, 2, 2));

        if (!in_array($index, jewels[$section])) {
            (new message)->class("error")->text("Este item não pode ser trocado!")->flash();
            return;
        }

        $jewelName = $this->table("amw_items")->columns("name")->where("section = :sc AND id_item = :i", "sc={$section}&i={$index}")->get();
 

        if (!$jewelName) {
            (new message)->class("error")->text("Item não encontrado, atualize a página e tente novamente!")->flash();
            return;
        }

        $verifyName = explode(" ", strtolower($jewelName->name));
        if (in_array("bless", $verifyName)) $columnCoin = 'bless';
        elseif (in_array("creation", $verifyName)) $columnCoin = 'creation';
        elseif (in_array("chaos", $verifyName)) $columnCoin = 'chaos';
        elseif (in_array("life", $verifyName)) $columnCoin = 'life';
        elseif (in_array("soul", $verifyName)) $columnCoin = 'soul';
        elseif (in_array("harmony", $verifyName)) $columnCoin = 'harmony';
        elseif (in_array("guardian", $verifyName)) $columnCoin = 'guardian';
        else {
            (new message)->class("error")->text("Item não encontrado, atualize a página e tente novamente!")->flash();
            return;
        }



        $coin = jewels['multi_coin'];
        if (in_array($index, jewels['jewel_multi']) and $section == 12) {
            if ($level == 0) $coin *= 10;
            elseif ($level == 8) $coin *= 20;
            elseif ($level == 16) $coin *= 30;
            else $coin = $coin;
        } else {
            $coin = $coin;
        }

        $account = (new session())->useraccount;
        $hexa = str_replace($item, str_pad('', web_shopping['db_slotcount'], 'F'), $this->loadvault());
        $this->db()->query("UPDATE warehouse SET Items = 0x{$hexa} WHERE AccountID = '{$account}'");
        $this->db()->query("UPDATE MEMB_INFO SET " . $columnCoin . " = " . $columnCoin . " + " . $coin . " WHERE memb___id = '{$account}'");

        (new message)->class("success")->text("Você trocou sua jóia com sucesso")->flash(true, true);
    }

    public function infokit(int $quantity, string $coin)
    {

        if (!$detailsCoin = info_jewels[$coin]) {
            (new message)->class("error")->text("Não está liberado a troca de moedas por essa jóia!")->flash();
            return null;
        }

        $listitem = array();
        for ($i = 1; $i <= $quantity; $i++) {

            $itemverify = $this->table("amw_items")
                ->where("section = :s AND id_item = :id", "s={$detailsCoin['section']}&id={$detailsCoin['index']}")
                ->get();
            if (empty($itemverify)) return null;

            if (web_shopping['db_version'] == 1) {
                $item_convert = $itemverify->id_item + ($itemverify->section  * 32);
                $item = (int)($item_convert % 256);
                $group = (int)($item_convert / 256);

                if ($group == 1) $this->excelents = 128;
            } else {
                $item = $itemverify->id_item;
            }

            $serial = str_pad(dechex(substr(rand(0, 9999999999), 0, 8)), 8, 0, STR_PAD_LEFT);

            $listitem[] = array(
                'item' => $item,
                'group' => $group ?? null,
                'serial' => $serial,
                'infoitem' => $itemverify,
                'id_items' => $itemverify->id,
                'x' => $itemverify->x,
                'y' => $itemverify->y

            );
        }
        return $listitem ?? null;
    }

    public function converteCoinToJewel($data)
    {
        $quantity = filter_var($data['quantity'], FILTER_VALIDATE_INT);
        $coin = filter_var($data['coin'], FILTER_SANITIZE_SPECIAL_CHARS);

        if (empty($quantity) or empty($coin)) {
            (new message)->class("error")->text("Preecha os campos corretamente!")->flash();
        }

        if (!in_array($coin, jewels_trade)) {
            (new message)->class("error")->text("Moeda não permitida para a troca!")->flash();
        }

        if ($quantity > 120) {
            (new message)->class("error")->text("Você só pode converter até 120 jóias!")->flash();
        }

        $account = (new session())->useraccount;
        $verifyCoin = $this->table("MEMB_INFO")->columns("" . $coin . " as coin")->where("memb___id = :mi", "mi={$account}")->get();

        $multi_coin = ($quantity * jewels['multi_coin']);
        if ($verifyCoin->coin < $multi_coin) {
            (new message)->class("error")->text("Você não possuí a quantidade de {$multi_coin} {$coin}!")->flash();
            return null;
        }

        if ($quantity > 1) {
            $items = $this->db()->query("SELECT Items FROM warehouse WHERE AccountID = '{$account}' ")->fetch();
            if (preg_match("/[abcdeghijklmnopqrstuwxyzABCDEGHIJKLMNOPQRSTUWXYZ]/", strtoupper(bin2hex($items->Items)))) {
                (new message)->class("error")->text("Você está tentando <strong>converter mais de 1 jóia</strong>, para sua segurança <strong>limpe seu baú</strong> para continuar")->flash();
                return;
            }
        }
        if ($this->infokit($quantity, $coin)) {
            $session = new session();
            $messages = new message();

            foreach ($this->infokit($quantity, $coin) as $item) {

                if (isset($item['group']) and $item['group'] == 1) $this->excelents = 128;
                $category = dechex($item['infoitem']->section);

                /** [Ancients do item] */
                if ($item['infoitem']->ancient == 1) $this->ancient = 5;
                elseif ($item['infoitem']->ancient == 2) $this->ancient = 10;
                else $this->ancient = 0;

                $hexaitem = ($item['item'] >= 256)
                    ? substr(dechex($item['item'] + 256), 1, 2)
                    : str_pad(dechex($item['item']), 2, 0, STR_PAD_LEFT);


                $durability = str_pad(dechex(0), 2, 0, STR_PAD_LEFT);

                $excelents  = str_pad(dechex(0), 2, 0, STR_PAD_LEFT);

                $levelitem  = str_pad(dechex(0), 2, 0, STR_PAD_LEFT);

                $ancient    = str_pad(dechex(0), 2, 0, STR_PAD_LEFT);

                $harmony = str_pad(dechex(0), 2, 0, STR_PAD_LEFT);

                $socket1    = str_pad(dechex(255), 2, 0, STR_PAD_LEFT);
                $socket2    = str_pad(dechex(255), 2, 0, STR_PAD_LEFT);
                $socket3    = str_pad(dechex(255), 2, 0, STR_PAD_LEFT);
                $socket4    = str_pad(dechex(255), 2, 0, STR_PAD_LEFT);
                $socket5    = str_pad(dechex(255), 2, 0, STR_PAD_LEFT);

                $hexa = (web_shopping['db_slotcount'] == 32 and web_shopping['db_version'] >= 2)
                    ? strtoupper($hexaitem . $levelitem . $durability . $item['serial'] . $excelents . $ancient . $category . '0' . $harmony . $socket1 . $socket2 . $socket3 . $socket4 . $socket5)
                    : strtoupper($hexaitem . $levelitem . $durability . $item['serial'] . $excelents . '00' . $ancient);

                (new vault())->hexvaultkit($item['x'], $item['y'], $hexa, $item['id_items']);
            }

            $this->db()->query("UPDATE MEMB_INFO SET {$coin} = {$coin} - {$multi_coin} WHERE memb___id = '{$session->useraccount}'");
            $messages->class("success")->text("<em><strong>Troca realiazada</strong></em> com sucesso")->flash(true, true);
        }
    }
}
