<?php

namespace Amwdeveloper\plugins\webshop;

use Amwdeveloper\controller\connection;
use Amwdeveloper\core\session;
use Amwdeveloper\model\message;

class vault extends connection
{
    private $items;
    private $vaultverify = NULL;
    private $vault_slots = [];
    private $binary = null;
    private $line = null;
    private $slot = null;
    private $diviser;
    private $servertype;

    /**
     * __construct
     * SELECIONA O TAMANHO DO BAÚ DE ACORDO COM A VERSÃO
     * E ARMAZENA NAS VARIAVEIS OS DADOS
     * @return void
     */
    function __construct()
    {
        $account = (new session)->useraccount;
        $lenght = $this->db()->query("SELECT length FROM syscolumns WHERE OBJECT_NAME(id) = 'warehouse' AND name = 'Items'")->fetch();

        $this->binary = $lenght->length;
        $this->line = (($lenght->length * 2) / (web_shopping['db_version'] == 1 ? 20 : 32)) / 8;
        $this->slot = (($lenght->length * 2) / (web_shopping['db_version'] == 1 ? 20 : 32));

        $verifyvault = $this->db()->query("SELECT 1 FROM warehouse WHERE AccountID='{$account}'")->fetch();
        if (empty($verifyvault)) {
            $this->db()->query("INSERT INTO warehouse (AccountID, Items, Money, EndUseDate, DbVersion, pw) VALUES ('{$account}', 0x" . str_pad("", $this->binary * 2, "F") . ", 0, GETDATE(), " . web_shopping['db_version'] . ", 0);");
        }

        $query = $this->db()->query("SELECT Items FROM warehouse WHERE AccountID = '{$account}' ")->fetch();

        $this->items = bin2hex($query->Items);

        if (web_shopping['db_version'] == 1) {
            $this->diviser = 20;
            $this->servertype = 'OLD';
        } else {
            $this->diviser = 32;
            $this->servertype = 'NEW';
        }
    }


    /**
     * slotVault
     * RETONRA TODOS OS SLOTS DO BAÚ
     * @return void
     */
    public function slotVault()
    {
        $i = (int) 0;
        for ($line = 0; $line < $this->line; $line++) {
            for ($column = 0; $column < 8; $column++) {
                $this->vault_slots[$i / $this->diviser]['hex'] = substr($this->items, $i, $this->diviser);
                $this->vault_slots[$i / $this->diviser]['line'] = $line;
                $this->vault_slots[$i / $this->diviser]['column'] = $column;
                $i += $this->diviser;
            }
        }
        return $this->vault_slots;
    }

    /**
     * reversebit
     * RETORNA OS BITS DO ITEM ( 97D+99I )
     * @param  mixed $b
     * @return void
     */
    public function reversebit($b)
    {
        switch (strtoupper(substr($b, 0, 1))) {
            case "0":
                return "0000";
            case "1":
                return "0001";
            case "2":
                return "0010";
            case "3":
                return "0011";
            case "4":
                return "0100";
            case "5":
                return "0101";
            case "6":
                return "0110";
            case "7":
                return "0111";
            case "8":
                return "1000";
            case "9":
                return "1001";
            case "A":
                return "1010";
            case "B":
                return "1011";
            case "C":
                return "1100";
            case "D":
                return "1101";
            case "E":
                return "1110";
            case "F":
                return "1111";
        }
    }

    /**
     * reversebit3
     * RETORNA OS BITS3 DO ITEM ( 97D+99I )
     * @param  mixed $bits
     * @return void
     */
    public function reversebit3($bits)
    {
        switch ($bits) {
            case "000":
                return 0;
            case "001":
                return 1;
            case "010":
                return 2;
            case "011":
                return 3;
            case "100":
                return 4;
            case "101":
                return 5;
            case "110":
                return 6;
            case "111":
                return 7;
            case "000":
                return 8;
            case "001":
                return 9;
            case "010":
                return 10;
            case "011":
                return 11;
            case "100":
                return 12;
            case "101":
                return 13;
            case "110":
                return 14;
            case "111":
                return 15;
            case "000":
                return 16;
            case "001":
                return 17;
            case "010":
                return 18;
            case "011":
                return 19;
            case "100":
                return 20;
            case "101":
                return 21;
            case "110":
                return 22;
            case "111":
                return 23;
            case "000":
                return 24;
            case "001":
                return 25;
            case "010":
                return 26;
            case "011":
                return 27;
            case "100":
                return 28;
            case "101":
                return 29;
            case "110":
                return 30;
        }
    }

    /**
     * reversebit5
     * RETORNA OS BITS5 DO ITEM ( 97D+99I )
     * @param  mixed $bits
     * @return void
     */
    public function reversebit5($bits)
    {
        switch ($bits) {
            case "00000":
                return 0;
            case "00001":
                return 1;
            case "00010":
                return 2;
            case "00011":
                return 3;
            case "00100":
                return 4;
            case "00101":
                return 5;
            case "00110":
                return 6;
            case "00111":
                return 7;
            case "01000":
                return 8;
            case "01001":
                return 9;
            case "01010":
                return 10;
            case "01011":
                return 11;
            case "01100":
                return 12;
            case "01101":
                return 13;
            case "01110":
                return 14;
            case "01111":
                return 15;
            case "10000":
                return 16;
            case "10001":
                return 17;
            case "10010":
                return 18;
            case "10011":
                return 19;
            case "10100":
                return 20;
            case "10101":
                return 21;
            case "10110":
                return 22;
            case "10111":
                return 23;
            case "11000":
                return 24;
            case "11001":
                return 25;
            case "11010":
                return 26;
            case "11011":
                return 27;
            case "11100":
                return 28;
            case "11101":
                return 29;
            case "11110":
                return 30;
            case "11111":
                return 31;
        }
    }
    /**
     * itemid
     * RETORNA O ID DO ITEM ( 97D+99I )
     * @param  mixed $id
     * @return void
     */
    public function itemid($id)
    {
        $bin1 = $this->reversebit(strtoupper(substr($id, 0, 1)));
        $bin2 = $this->reversebit(strtoupper(substr($id, 1, 1)));
        $bin = $bin1 . $bin2;
        return array('section' => $this->reversebit3(substr($bin, 0, 3)), 'index' => $this->reversebit5(substr($bin, 3, 5)));
    }

    public function hexvault($itemx, $itemy, $hexa, $id)
    {
        for ($i = 0; $i < 120; $i++) {
            if (
                strtoupper($this->slotVault()[$i]['hex']) != str_pad("", $this->diviser, "F")
                && $this->slotVault()[$i]['hex'] != str_pad("", $this->diviser, "0")
                && $this->slotVault()[$i]['hex'] != NULL
            ) {
                if ($this->servertype == "NEW") {
                    $ancient = hexdec(substr($this->vault_slots[$i]['hex'], 17, 1));
                    $category = hexdec(substr($this->vault_slots[$i]['hex'], 18, 1));
                    $index = hexdec(substr($this->vault_slots[$i]['hex'], 0, 2));
                    $excelent =  hexdec(substr($this->vault_slots[$i]['hex'], 14, 2));

                    $index = ($excelent >= 128) ? ($index + 256) : $index;

                    $details = $this->db()->query("SELECT  id,x, y,durability,name FROM amw_items WHERE id_item = {$index} AND section = '{$category}'")->fetch();
                } else {
                    $ancient = hexdec(substr($this->vault_slots[$i]['hex'], 17, 1));
                    $index = substr($this->vault_slots[$i]['hex'], 0, 2);
                    $unique = substr($this->vault_slots[$i]['hex'], 14, 2);
                    $uniquevault = (hexdec($unique) >= 128 ? 8 : 0);
                    $new = substr($this->vault_slots[$i]['hex'], 6, 2);
                    $id = $this->itemid($index);
                    if ($new == "F9") $id['index'] += 32;
                    $details = $this->db()->query("SELECT  id,x, y,durability,name FROM amw_items WHERE id_item = {$id['index']} AND section = " . (int)($id['section'] + $uniquevault) . "")->fetch();
                }

                $this->vault_slots[$i]['key'] = @$details->id;
                $this->vault_slots[$i]['width'] = @$details->x;
                $this->vault_slots[$i]['height'] = @$details->y;
                $this->vault_slots[$i]['name'] = @$details->name;
                $this->vault_slots[$i]['durability'] = @$details->durability;
                $this->vault_slots[$i]['free'] = false;
            } else {
                $this->vault_slots[$i]['key'] = NULL;
                $this->vault_slots[$i]['width'] = 0;
                $this->vault_slots[$i]['height'] = 0;
                $this->vault_slots[$i]['name'] = NULL;
                $this->vault_slots[$i]['free'] = true;
            }
        }

        for ($i = 0; $i < 120; $i++) {
            if (
                strtoupper($this->vault_slots[$i]['hex']) != str_pad("", $this->diviser, "F")
                && $this->vault_slots[$i]['hex'] != str_pad("", $this->diviser, "0")
                && $this->vault_slots[$i]['hex'] != NULL
            ) {
                for ($width = 0; $width < $this->vault_slots[$i]['width']; $width++) {
                    for ($height = 0; $height < $this->vault_slots[$i]['height']; $height++) {
                        $this->vault_slots[$i + $width]['free'] = false;
                        $this->vault_slots[$i + $width + (8 * $height)]['free'] = false;
                    }
                }
            }
        }

        for ($i = (int)0; $i < 120; $i++) {
            if (strtoupper($this->vault_slots[$i]['hex']) == str_pad("", $this->diviser, "F")) {
                $this->vault_slots[$i]['width'] = $itemx;
                $this->vault_slots[$i]['height'] = $itemy;
                $Full = false;
                for ($CTemp = 0; $CTemp < $this->vault_slots[$i]['width']; $CTemp++) {
                    for ($LTemp = 0; $LTemp < $this->vault_slots[$i]['height']; $LTemp++) {
                        if (!$Full) {
                            $tempI = $i + 1;
                            if (($tempI % 8) == 0 && $this->vault_slots[$i]['width'] > 1) $Full = true;
                            elseif (($tempI % 8) == 7 && $this->vault_slots[$i]['width'] > 2) $Full = true;
                            elseif (($tempI % 8) == 6 && $this->vault_slots[$i]['width'] > 3) $Full = true;
                            elseif (($tempI % 8) == 5 && $this->vault_slots[$i]['width'] > 4) $Full = true;
                            elseif (
                                @$this->vault_slots[$i + $CTemp]['free'] == false
                                || @$this->vault_slots[$i + $CTemp + (8 * $LTemp)]['free'] == false
                            ) $Full = true;
                            else continue (1);
                        }
                    }
                }
                if ($Full == false) {
                    $this->vaultverify = $i;
                    break;
                } elseif (!isset($this->vault_slots[$i])) $this->vaultverify = -1;
                else $this->vaultverify = -1;
            }
        }

        if ($this->vaultverify < 0) {
            $messages = new message();
            $messages->class("error")->text("Libere espaço em seu <em><strong>Baú</strong></em> para continuar")->flash();
            die();
        } elseif ($this->vaultverify < 0) return false;

        $this->vault_slots[$this->vaultverify]['free'] = false;
        $this->vault_slots[$this->vaultverify]['hex'] = $hexa;
        $this->vault_slots[$this->vaultverify]['key'] = $id;
        $this->vault_slots[$this->vaultverify]['width'] = $itemx;
        $this->vault_slots[$this->vaultverify]['height'] = $itemy;


        $x = '';
        for ($i = 0; $i < 120; $i++) {
            $x .= $this->vault_slots[$i]['hex'];
        }
        $account = (new session())->useraccount;
        $this->db()->query("UPDATE warehouse SET Items = 0x" . $x . " WHERE AccountID = '{$account}' ");
        $messages = new message();
        $messages->class("success")->text("Item compradoc com sucesso")->flash(true, true);
    }

    public function hexvaultkit($itemx, $itemy, $hexa, $id)
    {
        for ($i = 0; $i < 120; $i++) {
            if (
                strtoupper($this->slotVault()[$i]['hex']) != str_pad("", $this->diviser, "F")
                && $this->slotVault()[$i]['hex'] != str_pad("", $this->diviser, "0")
                && $this->slotVault()[$i]['hex'] != NULL
            ) {
                if ($this->servertype == "NEW") {
                    $ancient = hexdec(substr($this->vault_slots[$i]['hex'], 17, 1));
                    $category = hexdec(substr($this->vault_slots[$i]['hex'], 18, 1));
                    $index = hexdec(substr($this->vault_slots[$i]['hex'], 0, 2));
                    $excelent =  hexdec(substr($this->vault_slots[$i]['hex'], 14, 2));

                    $index = ($excelent >= 128) ? ($index + 256) : $index;

                    $details = $this->db()->query("SELECT  id,x, y,durability,name FROM amw_items WHERE id_item = {$index} AND section = '{$category}'")->fetch();
                } else {
                    $ancient = hexdec(substr($this->vault_slots[$i]['hex'], 17, 1));
                    $index = substr($this->vault_slots[$i]['hex'], 0, 2);
                    $unique = substr($this->vault_slots[$i]['hex'], 14, 2);
                    $uniquevault = (hexdec($unique) >= 128 ? 8 : 0);
                    $new = substr($this->vault_slots[$i]['hex'], 6, 2);
                    $id = $this->itemid($index);
                    if ($new == "F9") $id['index'] += 32;
                    $details = $this->db()->query("SELECT  id,x, y,durability,name FROM amw_items WHERE id_item = {$id['index']} AND section = " . (int)($id['section'] + $uniquevault) . "")->fetch();
                }

                $this->vault_slots[$i]['key'] = @$details->id;
                $this->vault_slots[$i]['width'] = @$details->x;
                $this->vault_slots[$i]['height'] = @$details->y;
                $this->vault_slots[$i]['name'] = @$details->name;
                $this->vault_slots[$i]['durability'] = @$details->durability;
                $this->vault_slots[$i]['free'] = false;
            } else {
                $this->vault_slots[$i]['key'] = NULL;
                $this->vault_slots[$i]['width'] = 0;
                $this->vault_slots[$i]['height'] = 0;
                $this->vault_slots[$i]['name'] = NULL;
                $this->vault_slots[$i]['free'] = true;
            }
        }

        for ($i = 0; $i < 120; $i++) {
            if (
                strtoupper($this->vault_slots[$i]['hex']) != str_pad("", $this->diviser, "F")
                && $this->vault_slots[$i]['hex'] != str_pad("", $this->diviser, "0")
                && $this->vault_slots[$i]['hex'] != NULL
            ) {
                for ($width = 0; $width < $this->vault_slots[$i]['width']; $width++) {
                    for ($height = 0; $height < $this->vault_slots[$i]['height']; $height++) {
                        $this->vault_slots[$i + $width]['free'] = false;
                        $this->vault_slots[$i + $width + (8 * $height)]['free'] = false;
                    }
                }
            }
        }

        for ($i = (int)0; $i < 120; $i++) {
            if (strtoupper($this->vault_slots[$i]['hex']) == str_pad("", $this->diviser, "F")) {
                $this->vault_slots[$i]['width'] = $itemx;
                $this->vault_slots[$i]['height'] = $itemy;
                $Full = false;
                for ($CTemp = 0; $CTemp < $this->vault_slots[$i]['width']; $CTemp++) {
                    for ($LTemp = 0; $LTemp < $this->vault_slots[$i]['height']; $LTemp++) {
                        if (!$Full) {
                            $tempI = $i + 1;
                            if (($tempI % 8) == 0 && $this->vault_slots[$i]['width'] > 1) $Full = true;
                            elseif (($tempI % 8) == 7 && $this->vault_slots[$i]['width'] > 2) $Full = true;
                            elseif (($tempI % 8) == 6 && $this->vault_slots[$i]['width'] > 3) $Full = true;
                            elseif (($tempI % 8) == 5 && $this->vault_slots[$i]['width'] > 4) $Full = true;
                            elseif (
                                @$this->vault_slots[$i + $CTemp]['free'] == false
                                || @$this->vault_slots[$i + $CTemp + (8 * $LTemp)]['free'] == false
                            ) $Full = true;
                            else continue (1);
                        }
                    }
                }
                if ($Full == false) {
                    $this->vaultverify = $i;
                    break;
                } elseif (!isset($this->vault_slots[$i])) $this->vaultverify = -1;
                else $this->vaultverify = -1;
            }
        }

        if ($this->vaultverify < 0) {
            $messages = new message();
            $messages->class("error")->text("Libere espaço em seu <em><strong>Baú</strong></em> para continuar")->flash();
            die();
        } elseif ($this->vaultverify < 0) return false;

        $this->vault_slots[$this->vaultverify]['free'] = false;
        $this->vault_slots[$this->vaultverify]['hex'] = $hexa;
        $this->vault_slots[$this->vaultverify]['key'] = $id;
        $this->vault_slots[$this->vaultverify]['width'] = $itemx;
        $this->vault_slots[$this->vaultverify]['height'] = $itemy;


        $x = '';
        for ($i = 0; $i < 120; $i++) {
            $x .= $this->vault_slots[$i]['hex'];
        }
        $account = (new session())->useraccount;
        $this->db()->query("UPDATE warehouse SET Items = 0x" . $x . " WHERE AccountID = '{$account}' ");
    }
}
