<?php

namespace Amwdeveloper\plugins\webshop;

use Amwdeveloper\controller\admin as controllerdmin;
use Amwdeveloper\core\session;
use Amwdeveloper\model\layer;
use Amwdeveloper\model\message;
use Amwdeveloper\plugins\market\item as Market;

use Cocur\Slugify\Slugify;
use League\Plates\Engine;

class admin extends controllerdmin
{
    public $message;
    public $view;
    public $route;
    public function __construct()
    {
        global $route;
        $this->view = new Engine(__DIR__ . "/../../../theme/admin/pages", 'phtml');
        $this->message = new message();
        $this->route = $route;
    }

    public function returnDate()
    {
        return date("d/m/Y H:i:s");
    }

    public function checklogin()
    {
        $session = new session();
        if (!$session->has("adminlogged")) {
            return $this->route->redirect("/administration/account/login");
        }
    }

    public function accountlogin()
    {
        $session = new session();
        if ($session->has("adminlogged")) {
            return $this->route->redirect("/administration/home");
        }
        echo $this->view->render('login');
    }


    public function shoppingaddnewitem()
    {
        $this->checklogin();
        echo $this->view->render('shopping/newitem', [
            'title' =>  'Adicionar novo item'
        ]);
    }

    public function shoppingitemtxt()
    {
        $this->checklogin();
        echo $this->view->render('shopping/itemtxt', [
            'title' =>  'Adicionar item.txt'
        ]);
    }

    public function shoppingallitem()
    {
        $this->checklogin();
        echo $this->view->render('shopping/allitem', [
            'title' =>  'Todos os itens',
            'items' => $this->allitemshopping()
        ]);
    }

    public function shoppingtoedit($request)
    {
        $this->checklogin();
        echo $this->view->render('shopping/toedit', [
            'title' =>  'Editar item / id:' . $request['id'],
            'item' => $this->infoitemedit($request)
        ]);
    }

    public function shoppingtoeditkit($request)
    {
        $this->checklogin();
        $id = filter_var($request['id'], FILTER_VALIDATE_INT);

        if (!$id) return $this->route->redirect("/administration/shopping/kit/manage/category");
        $info = $this->table("amw_items_kit_category")->where("id = :id", "id={$id}")->get();

        echo $this->view->render('shopping/toeditkit', [
            'title' =>  'Editar kit / id:' . $request['id'],
            'item' =>  $info
        ]);
    }



    public function shoppingtoremove($request)
    {
        $this->checklogin();
        $this->shoppingremoveitem($request);
    }

    public function shoppinglogs()
    {
        $market = new Market();
        $itemlogs = $this->table('amw_shopping_logs')->columns('id,shopping,account,item_name,item_category,hexa,created_at')->orderby('id', 'DESC')->all();
        $dataItems = [];
        foreach ($itemlogs as $item) $dataItems[] = [
            'id' => $item->id,
            'shopping' => $item->shopping,
            'account' => $item->account,
            'item_name' => $item->item_name,
            'item_category' => $item->item_category,
            'details' => $market->getVaultItems(true, $item->hexa),
            'created_at' => $item->created_at
        ];

        echo $this->view->render('shopping/logs', [
            'title' => ' Shopping Logs',
            'items' => $dataItems
        ]);
    }

    // Kits ----------------------------------------------------------------

    public function shoppingkitaddcategory()
    {
        $this->checklogin();
        echo $this->view->render('shopping/addkitcategory', [
            'title' =>  'Adicionar nova categoria'
        ]);
    }

    public function shoppingkitmanagecategory()
    {
        $this->checklogin();
        $keys = array_keys(web_shopping['shopping_category']);
        $categories = [];
        foreach ($keys as $key) {
            $categories[] = [
                'name' => $key,
                'category' => $this->table("amw_items_category")->where("category = :c", "c={$key}")->all()
            ];
        }

        echo $this->view->render('shopping/managekitcategory', [
            'title' =>  'Gerenciar todas as categorias',
            'categories' => $categories ?? null
        ]);
    }

    public function shoppingaddnewkitcategory($request)
    {
        $this->checklogin();
        $category = filter_var($request['id'], FILTER_VALIDATE_INT);

        if (!$category) return $this->route->redirect("/administration/shopping/kit/manage/category");

        $listkit = $this->table("amw_items_kit_category")->where("id_category = :id", "id={$category}")->all();
        echo $this->view->render('shopping/addnewkitcategory', [
            'title' =>  'Gerenciar todas as categorias',
            'category' => $category,
            'listkit' => $listkit
        ]);
    }

    public function shoppingaddeditkitcategory($request)
    {
        $this->checklogin();

        $id = filter_var($request['id'], FILTER_VALIDATE_INT);

        if (!$id) return $this->route->redirect("/administration/shopping/kit/manage/category");

        $category = $this->table("amw_items_category")->where("id = :id", "id={$id}")->get();
        echo $this->view->render('shopping/editkitcategory', [
            'title' =>  'Gerenciar todas as categorias',
            'category' => $category,
            'id' => $id
        ]);
    }

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

        if (!$id) return $this->route->redirect("/administration/shopping/kit/manage/category");

        $category = $this->table("amw_items_category")->where("id = :id", "id={$id}")->get();

        if (!$category) return $this->route->redirect("/administration/shopping/kit/manage/category");

        $subcategory = $this->table("amw_items_kit_category")->columns("id")->where("id_category = :id", "id={$id}")->get();

        $this->table("amw_items_kit")->columns("id")->where("id_package = :id", "id={$subcategory->id}")->destroy();
        $this->table("amw_items_kit_category")->columns("id")->where("id_category = :id", "id={$id}")->destroy();
        $this->table("amw_items_category")->where("id = :id", "id={$id}")->destroy();

        return $this->route->redirect("/administration/shopping/kit/manage/category");
    }

    public function shoppingremovekitall($request)
    {
        $id = filter_var($request['id'], FILTER_VALIDATE_INT);
        $category_id = filter_var($request['category'], FILTER_VALIDATE_INT);

        if (!$id) return $this->route->redirect("/administration/shopping/add/new/kit/category/{$category_id}");
        $category = $this->table("amw_items_kit_category")->columns("id")->where("id = :id", "id={$id}")->get();

        if (!$category) return $this->route->redirect("/administration/shopping/add/new/kit/category/{$category_id}");

        $this->table("amw_items_kit")->where("id_package = :id", "id={$id}")->destroy();
        $this->table("amw_items_kit_category")->columns("id")->where("id = :id", "id={$id}")->destroy();

        return $this->route->redirect("/administration/shopping/add/new/kit/category/{$category_id}");
    }

    public function shoppingadditemskit($request)
    {
        $this->checklogin();
        $id = filter_var($request['id'], FILTER_VALIDATE_INT);

        if (!$id) return $this->route->redirect("/administration/shopping/kit/manage/category");

        $listkit = $this->table("amw_items_kit")->where("id_package = :id", "id={$id}")->all();
        echo $this->view->render('shopping/addnewitemkit', [
            'title' =>  'Adicionar novo item ao kit',
            'category' => $id,
            'listkit' => $listkit
        ]);
    }

    public function shoppingremoveitemskit($request)
    {
        $this->checklogin();
        $id = filter_var($request['id'], FILTER_VALIDATE_INT);
        $category = filter_var($request['category'], FILTER_VALIDATE_INT);
        if (!$id and !$category) return $this->route->redirect("/administration/shopping/to/add/items/kit/{$category}");

        $this->table("amw_items_kit")->where("id = :id AND id_package = :idp", "id={$id}&idp={$category}")->destroy();
        return $this->route->redirect("/administration/shopping/to/add/items/kit/{$category}");
    }




    // posts

    public function authaddnewitem($request)
    {
        $name = filter_var($request['name'], FILTER_SANITIZE_SPECIAL_CHARS);
        $class = filter_var($request['class'], FILTER_SANITIZE_SPECIAL_CHARS);
        $section = $request['section'];
        $id_item = $request['id_item'];
        $ancient = $request['ancient'];
        $x = $request['x'];
        $y = $request['y'];
        $price = $request['price'];
        $category = filter_var($request['category'], FILTER_SANITIZE_SPECIAL_CHARS);
        $item_group = filter_var($request['item_group'], FILTER_SANITIZE_SPECIAL_CHARS);
        $active = $request['active'];


        if (empty($name) or empty($name) or !is_numeric($section) or !is_numeric($id_item)  or !is_numeric($x) or !is_numeric($y) or !is_numeric($price) or empty($category) or empty($item_group) or !is_numeric($active)) {
            $this->message->class("error")->text("Algum <em><strong>campo</strong></em> está inválido")->flash();
            return null;
        }

        if ($request['x'] < 1 or $request['y'] < 1) {
            $this->message->class("error")->text("<em><strong>Largura & Algura</strong></em> incorreto")->flash();
            return null;
        }

        $fileimage = $_FILES['image'];
        if (!empty($fileimage['name'])) {
            $extension = array('image/png', 'image/jpg', 'image/jpeg');
            if (in_array($fileimage['type'], $extension)) {
                $resource = __DIR__ . '/../../../resource/items/';
                $newname = md5(uniqid()) . mb_strrchr($fileimage['name'], ".");
                $temp = $fileimage['tmp_name'];

                $coinitem = web_shopping['shopping_category'][$category]['column_coin'];

                $ancient_1 = 0;
                $ancient_2 = 0;
                if ($ancient == "type_1") $ancient_1 = 1;
                elseif ($ancient == "type_2") $ancient_2 = 1;

                if (move_uploaded_file($temp, $resource . $newname)) {
                    $insert = [
                        'name' => $name,
                        'section' => $section,
                        'id_item' => $id_item,
                        'aditional' => 28,
                        'x' => $x,
                        'y' => $y,
                        'price' => $price,
                        'category_group' => $category,
                        'item_group' => $item_group,
                        'active' => $active,
                        'image' => $newname,
                        'coin_name' => $coinitem,
                        'class' => $class,
                        'ancient_1' => $ancient_1,
                        'ancient_2' => $ancient_2,
                    ];



                    $this->table("amw_items")->created($insert);
                    $this->message->class("success")->text("<em><strong>Item adicionado</strong></em>, com sucesso")->flash();
                } else {
                    $this->message->class("error")->text("<em><strong>Erro ao enviar imagem</strong></em>, atualize a página e tente novamente")->flash();
                    return null;
                }
            } else {
                $this->message->class("error")->text("<em><strong>Extensão da imagem</strong></em> não permitida")->flash();
                return null;
            }
        } else {
            $this->message->class("error")->text("<em><strong>Selecione uma image</strong></em> para continuar")->flash();
            return null;
        }
    }

    public function authtoeditoitem($request)
    {

        $id = filter_var($request['id'], FILTER_VALIDATE_INT);
        $name = filter_var($request['name'], FILTER_SANITIZE_SPECIAL_CHARS);
        $class = filter_var($request['class'], FILTER_SANITIZE_SPECIAL_CHARS);
        $section = $request['section'];
        $id_item = $request['id_item'];
        $ancient = $request['ancient'];
        $x = $request['x'];
        $y = $request['y'];
        $price = $request['price'];
        $category = filter_var($request['category'], FILTER_SANITIZE_SPECIAL_CHARS);
        $item_group = isset($request['item_group']) ? filter_var($request['item_group'], FILTER_SANITIZE_SPECIAL_CHARS) : null;
        $active = $request['active'];

        if (empty($name) or empty($class) or !is_numeric($section) or !is_numeric($id_item)  or !is_numeric($x) or !is_numeric($y) or !is_numeric($price) or empty($category) or !is_numeric($active)) {
            $this->message->class("error")->text("Algum <em><strong>campo</strong></em> está inválido")->flash();
            return null;
        }

        if (empty($item_group)) {
            $this->message->class("error")->text("Selecione um <em><strong>grupo de item</strong></em> válido")->flash();
            return null;
        }

        if ($request['x'] < 1 or $request['y'] < 1) {
            $this->message->class("error")->text("<em><strong>Largura & Algura</strong></em> incorreto")->flash();
            return null;
        }



        $fileimage = $_FILES['image'];
        if (!empty($fileimage['name'])) {
            $extension = array('image/png', 'image/jpg', 'image/jpeg');
            if (in_array($fileimage['type'], $extension)) {
                $resource = __DIR__ . '/../../../resource/items/';
                $newname = md5(uniqid()) . mb_strrchr($fileimage['name'], ".");
                $temp = $fileimage['tmp_name'];

                if (move_uploaded_file($temp, $resource . $newname)) {
                    $update = [
                        'image' => $newname
                    ];
                    $this->table("amw_items")->where("id = :id", "id={$id}")->updated($update);
                } else {
                    $this->message->class("error")->text("<em><strong>Erro ao enviar imagem</strong></em>, item não foi atualizado")->flash();
                    return null;
                }
            } else {
                $this->message->class("error")->text("<em><strong>Extensão da imagem</strong></em> não permitida")->flash();
                return null;
            }
        }
        $coinitem = web_shopping['shopping_category'][$category]['column_coin'];

        $ancient_1 = 0;
        $ancient_2 = 0;
        if ($ancient == "type_1") $ancient_1 = 1;
        elseif ($ancient == "type_2") $ancient_2 = 1;

        $update = [
            'name' => $name,
            'section' => $section,
            'id_item' => $id_item,
            'aditional' => 28,
            'x' => $x,
            'y' => $y,
            'price' => $price,
            'category_group' => $category,
            'item_group' => $item_group,
            'active' => $active,
            'coin_name' => $coinitem,
            'class' => $class,
            'ancient_1' => $ancient_1,
            'ancient_2' => $ancient_2,
        ];


        $this->table("amw_items")->where("id = :id", "id={$id}")->updated($update);
        $this->message->class("success")->text("<em><strong>Item editado</strong></em> com sucesso")->flash(false, true);
    }

    public function authadditemtxt($request)
    {
        $category_item = filter_var($request['category'], FILTER_SANITIZE_SPECIAL_CHARS);
        $type_option = filter_var($request['option'], FILTER_SANITIZE_SPECIAL_CHARS);

        if (empty($category_item) or empty($type_option)) {
            $this->message->class("error")->text("Algum <em><strong>campos</strong></em> inválido, atualize a página")->flash();
            return null;
        }

        if ($type_option == 'clear') {
            $this->table("amw_items")->where("category_group = :cg", "cg={$category_item}")->destroy();
        }

        if ($type_option == 'clearall') {
            $this->table("amw_items")->destroy();
        }

        if (!($file = fopen(__DIR__ . "/../../../item.txt", "rb+"))) {
            $this->message->class("error")->text("Adicione o <em><strong>item.txt </strong></em> na sua hospedagem")->flash();
            return null;
        }

        $coin = web_shopping['shopping_category'][$category_item]['column_coin'];

        $section = -1;
        $key = null;
        $count_column = null;
        $number = 0;
        while (!feof($file)) {
            $line = fgets($file);
            $line = trim($line, " \t\r\n");
            if (substr($line, 0, 2) == "//" || substr($line, 0, 2) == "#" || $line == "") {
                continue;
            }
            if (($pos = strpos($line, "//")) !== false) {
                $line = substr($line, 0, $pos);
            }
            $line = trim($line, " \t\r\n");
            if ($section == -1) {
                if (is_numeric($line)) {
                    $section = $line;
                }
            } else {
                if (strtolower($line) == "end") {
                    $section = -1;
                    continue;
                }
                $columns = preg_split("/[\\s,]*\\\"([^\\\"]+)\\\"[\\s,]*|[\\s,]*'([^']+)'[\\s,]*|[\\s,]+/", $line, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);

                $old = array("index" => 0, "x" => 1, "y" => 2, "name" => 6, "attackspeed" => 10, "damagemin" => 8, "damagemax" => 9, "durability" => 11, "reqstrenth" => 13, "reqdexterity" => 14, "dw" => 15, "dk" => 16, "fe" => 17, "mg" => 18);
                $new = "";

                if ($section == 6) {
                    $new = [
                        "index" => 0,
                        "slot" => 1,
                        "skill" => 2,
                        "x" => 3,
                        "y" => 4,
                        "name" => 8,
                        "uselevel" => 9,
                        "defense" => 10,
                        "defenserate" => 11,
                        "durability" => 12,
                        "reqlevel" => 13,
                        "reqstrength" => 14,
                        "reqdexterity" => 15,
                        "reqdenergy" => 16,
                        "reqvitality" => 17,
                        "dw" => 20,
                        "dk" => 21,
                        "fe" => 22,
                        "mg" => 23,
                        "dl" => 24,
                        "su" => 25,
                        "rf" => 26,
                    ];
                } elseif ($section >= 7 and $section <= 9) {
                    $new = [
                        "index" => 0,
                        "slot" => 1,
                        "skill" => 2,
                        "x" => 3,
                        "y" => 4,
                        "name" => 8,
                        "uselevel" => 9,
                        "defense" => 10,
                        "magicdefense" => 11,
                        "durability" => 12,
                        "reqlevel" => 13,
                        "reqstrength" => 14,
                        "reqdexterity" => 15,
                        "reqenergy" => 16,
                        "reqvitality" => 17,
                        "dw" => 20,
                        "dk" => 21,
                        "fe" => 22,
                        "mg" => 23,
                        "dl" => 24,
                        "su" => 25,
                        "rf" => 26,
                    ];
                } elseif ($section == 10) {
                    $new = [
                        "index" => 0,
                        "slot" => 1,
                        "skill" => 2,
                        "x" => 3,
                        "y" => 4,
                        "name" => 8,
                        "uselevel" => 9,
                        "defense" => 10,
                        "attackspeed" => 11,
                        "durability" => 12,
                        "reqlevel" => 13,
                        "reqstrength" => 14,
                        "reqdexterity" => 15,
                        "reqenergy" => 16,
                        "reqvitality" => 17,
                        "dw" => 20,
                        "dk" => 21,
                        "fe" => 22,
                        "mg" => 23,
                        "dl" => 24,
                        "su" => 25,
                        "rf" => 26,
                    ];
                } elseif ($section == 11) {
                    $new = [
                        "index" => 0,
                        "slot" => 1,
                        "skill" => 2,
                        "x" => 3,
                        "y" => 4,
                        "name" => 8,
                        "uselevel" => 9,
                        "defense" => 10,
                        "walkspeed" => 11,
                        "durability" => 12,
                        "reqlevel" => 13,
                        "reqstrength" => 14,
                        "reqdexterity" => 15,
                        "reqenergy" => 16,
                        "reqvitality" => 17,
                        "dw" => 20,
                        "dk" => 21,
                        "fe" => 22,
                        "mg" => 23,
                        "dl" => 24,
                        "su" => 25,
                        "rf" => 26,
                    ];
                } elseif ($section == 12) {
                    $new = [
                        "index" => 0,
                        "slot" => 1,
                        "skill" => 2,
                        "x" => 3,
                        "y" => 4,
                        "name" => 8,
                        "uselevel" => 9,
                        "defense" => 10,
                        "durability" => 11,
                        "reqlevel" => 12,
                        "reqstrength" => 13,
                        "reqdexterity" => 14,
                        "reqenergy" => 15,
                        "dw" => 18,
                        "dk" => 19,
                        "fe" => 20,
                        "mg" => 21,
                        "dl" => 22,
                        "su" => 23,
                        "rf" => 24,
                    ];
                } elseif ($section == 13) {
                    $new = [
                        "index" => 0,
                        "slot" => 1,
                        "skill" => 2,
                        "x" => 3,
                        "y" => 4,
                        "name" => 8,
                        "uselevel" => 9,
                        "durability" => 10,
                        "reqlevel" => 12,
                        "reqstrength" => 13,
                        "reqdexterity" => 14,
                        "reqenergy" => 15,
                        "dw" => 17,
                        "dk" => 18,
                        "fe" => 19,
                        "mg" => 30,
                        "dl" => 21,
                        "su" => 22,
                        "rf" => 23,
                    ];
                } else {
                    $new = [
                        "index" => 0,
                        "slot" => 1,
                        "skill" => 2,
                        "x" => 3,
                        "y" => 4,
                        "name" => 8,
                        "attackspeed" => 12,
                        "uselevel" => 9,
                        "damagemin" => 10,
                        "damagemax" => 11,
                        "durability" => 13,
                        "magicdurability" => 14,
                        "magicrate" => 15,
                        "reqlevel" => 16,
                        "reqstrength" => 17,
                        "reqdexterity" => 18,
                        "reqenergy" => 19,
                        "reqvitality" => 20,
                        "dw" => 23,
                        "dk" => 24,
                        "fe" => 25,
                        "mg" => 26,
                        "dl" => 27,
                        "su" => 28,
                        "rf" => 29,
                        "defense" => null,
                        "defenserate" => null,
                        "magicdefense" => null,
                        "walkspeed" => null,
                        "reqleadership" => null,
                    ];
                }

                if ($count_column === null) {
                    if (count($columns) <= 19) {
                        $count_column = 1;
                    } else {
                        $count_column = 3;
                    }
                }

                $key = null;
                if ($key === null) {
                    if (count($columns) <= 19) {
                        $key = $old;
                    } else {
                        $key = $new;
                    }
                }

                switch ($section) {
                    case 0:
                        $shopname = "swords";
                        break;
                    case 1:
                        $shopname = "axes";
                        break;
                    case 2:
                        $shopname = "maces";
                        break;
                    case 3:
                        $shopname = "spears";
                        break;
                    case 4:
                        $shopname = "bows";
                        break;
                    case 5:
                        $shopname = "staffs";
                        break;
                    case 6:
                        $shopname = "shields";
                        break;
                    case 7:
                        $shopname = "helms";
                        break;
                    case 8:
                        $shopname = "armors";
                        break;
                    case 9:
                        $shopname = "pants";
                        break;
                    case 10:
                        $shopname = "gloves";
                        break;
                    case 11:
                        $shopname = "boots";
                        break;
                    case 12:
                        $shopname = "wings";
                        break;
                    case 13:
                        $shopname = "outros";
                        break;
                    case 14:
                        $shopname = "outros";
                        break;
                    case 15:
                        $shopname = "outros";
                        break;
                    default:
                        $shopname = "";
                        break;
                        return $shopname;
                }
                if ($section <= 13) {
                    $data = array(
                        "category" => $section,
                        "name" => @isset($columns[$key["name"]]) ? $columns[$key["name"]] : "",
                        "width" => @isset($columns[$key["x"]]) ? $columns[$key["x"]] : 1,
                        "height" => @isset($columns[$key["y"]]) ? $columns[$key["y"]] : 1,
                        "id" => $columns[0],
                        "durability" => @isset($columns[$key['durability']]) ? $columns[$key['durability']] : "",
                        "attackspeed" => @isset($columns[$key['attackspeed']]) ? $columns[$key['attackspeed']] : "",
                        "damagemin" => @isset($columns[$key['damagemin']]) ? $columns[$key['damagemin']] : "",
                        "damagemax" => @isset($columns[$key['damagemax']]) ? $columns[$key['damagemax']] : "",
                        "reqstrength" => @isset($columns[$key['reqstrength']]) ? $columns[$key['reqstrength']] : "",
                        "reqdexterity" =>  @isset($columns[$key['reqdexterity']]) ? $columns[$key['reqdexterity']] : "",
                        "reqenergy" =>  @isset($columns[$key['reqenergy']]) ? $columns[$key['reqenergy']] : "",
                        "reqvitality" =>  @isset($columns[$key['reqvitality']]) ? $columns[$key['reqvitality']] : "",
                        "dw" => @isset($columns[$key['dw']]) ? $columns[$key['dw']] : 0,
                        "dk" => @isset($columns[$key['dk']]) ? $columns[$key['dk']] : 0,
                        "fe" => @isset($columns[$key['fe']]) ? $columns[$key['fe']] : 0,
                        "mg" => @isset($columns[$key['mg']]) ? $columns[$key['mg']] : 0,
                        "dl" => @isset($columns[$key['dl']]) ? $columns[$key['dl']] : 0,
                        "su" => @isset($columns[$key['su']]) ? $columns[$key['su']] : 0,
                        "rf" => @isset($columns[$key['rf']]) ? $columns[$key['rf']] : 0,
                        "defense" => @isset($columns[$key['defense']]) ? $columns[$key['defense']] : 0,
                        "uselevel" => @isset($columns[$key['uselevel']]) ? $columns[$key['uselevel']] : 0,
                        "reqlevel" => @isset($columns[$key['reqlevel']]) ? $columns[$key['reqlevel']] : 0,
                        "walkspeed" => @isset($columns[$key['walkspeed']]) ? $columns[$key['walkspeed']] : 0,
                        "magicdurability" => @isset($columns[$key['magicdurability']]) ? $columns[$key['magicdurability']] : 0,
                        "magicrate" => @isset($columns[$key['magicrate']]) ? $columns[$key['magicrate']] : 0,
                        "imagem" => $section . '-' . $columns[0] . '.gif'
                    );

                    $insert = [
                        'name' => $data['name'],
                        'image' => $data['imagem'],
                        'section' => $data['category'],
                        'id_item' => $data['id'],
                        'level' => 15,
                        'aditional' => 28,
                        'luck' => 1,
                        'skill' => 1,
                        'durability' => $data['durability'],
                        'excelent_1' => 1,
                        'excelent_2' => 1,
                        'excelent_3' => 1,
                        'excelent_4' => 1,
                        'excelent_5' => 1,
                        'excelent_6' => 1,
                        'ancient_1' => 0,
                        'ancient_2' => 0,
                        'x' => $data['width'],
                        'y' => $data['height'],
                        'coin_name' => $coin,
                        'price' => 10,
                        'category_group' => $category_item,
                        'item_group' => $shopname,
                        'attackspeed' => $data['attackspeed'],
                        'damagemin' => $data['damagemin'],
                        'damagemax' => $data['damagemax'],
                        'reqstrength' => $data['reqstrength'],
                        'reqdexterity' => $data['reqdexterity'],
                        'reqenergy' => $data['reqenergy'],
                        'reqvitality' => $data['reqvitality'],
                        'dw' => $data['dw'],
                        'dk' => $data['dk'],
                        'fe' => $data['fe'],
                        'mg' => $data['mg'],
                        'dl' => $data['dl'],
                        'su' => $data['su'],
                        'rf' => $data['rf'],
                        'defense' => $data['defense'],
                        'uselevel' => $data['uselevel'],
                        'reqlevel' => $data['reqlevel'],
                        'walkspeed' => $data['walkspeed'],
                        'magicdurability' => $data['magicdurability'],
                        'magicrate' => $data['magicrate'],
                    ];
                } else {
                    if ($count_column != 3) {
                        $data = array(
                            "category" => $section,
                            "name" => isset($columns[$key["name"]]) ? $columns[$key["name"]] : "",
                            "width" => isset($columns[$key["x"]]) ? $columns[$key["x"]] : 1,
                            "height" => isset($columns[$key["y"]]) ? $columns[$key["y"]] : 1,
                            "id" => $columns[0],
                            "imagem" => $section . '-' . $columns[0] . '.gif'
                        );
                    } else {
                        $data = array(
                            "category" => $section,
                            "name" => isset($columns[8]) ? $columns[8] : "",
                            "width" => isset($columns[3]) ? $columns[3] : 1,
                            "height" => isset($columns[4]) ? $columns[4] : 1,
                            "id" => $columns[0],
                            "imagem" => $section . '-' . $columns[0] . '.gif'
                        );
                    }

                    $insert = [
                        'name' => $data['name'],
                        'image' => $data['imagem'],
                        'section' => $data['category'],
                        'id_item' => $data['id'],
                        'level' => 15,
                        'aditional' => 28,
                        'luck' => 1,
                        'skill' => 1,
                        'durability' => 255,
                        'excelent_1' => 1,
                        'excelent_2' => 1,
                        'excelent_3' => 1,
                        'excelent_4' => 1,
                        'excelent_5' => 1,
                        'excelent_6' => 1,
                        'ancient_1' => 0,
                        'ancient_2' => 0,
                        'x' => $data['width'],
                        'y' => $data['height'],
                        'coin_name' => $coin,
                        'price' => 10,
                        'category_group' => $category_item,
                        'item_group' => $shopname
                    ];
                }

                $this->table("amw_items")->created($insert);
            }
        }
        $this->message->class("success")->text("<em><strong>Item.txt</strong></em> adicionado com sucesso")->flash();
    }

    // posts kits

    public function authaddnewkitcategory($request)
    {
        $name = filter_var($request['name'], FILTER_SANITIZE_SPECIAL_CHARS);
        $category = filter_var($request['category'], FILTER_SANITIZE_SPECIAL_CHARS);

        if (empty($name) or empty($category)) {
            $this->message->class("error")->text("Algum <em><strong>campos</strong></em> inválido, atualize a página")->flash();
            return null;
        }

        $verify = $this->table("amw_items_category")->where("name = :name AND category = :category", "name={$name}&category={$category}")->get();
        if ($verify) {
            $this->message->class("error")->text("<em><strong>Nome do kit</strong></em> já está sendo usado nesta categoria")->flash();
            return null;
        }

        $insert = array('category' => $category, 'name' => $name, 'slug' => (new Slugify())->slugify($name));
        $this->table("amw_items_category")->created($insert);
        $this->message->class("success")->text("<em><strong>Categoria </strong></em> adicionada com sucesso")->flash(true, true);
    }

    public function authaddnewkitcategoryall($request)
    {
        $name = filter_var($request['name'], FILTER_SANITIZE_SPECIAL_CHARS);
        $price = filter_var($request['price'], FILTER_VALIDATE_INT);
        $id = filter_var($request['id'], FILTER_VALIDATE_INT);
        $class = filter_var($request['class'], FILTER_SANITIZE_SPECIAL_CHARS);

        if (empty($name) or empty($price) or empty($id) or empty($class)) {
            $this->message->class("error")->text("Algum <em><strong>campos</strong></em> inválido, atualize a página")->flash();
            return null;
        }

        $verifyname = $this->table("amw_items_kit_category")->where("name = :name AND id_category = :id", "name={$name}&id={$id}")->get();
        if ($verifyname) {
            $this->message->class("error")->text("<em><strong>Nome do kit</strong></em> já está em uso")->flash();
            return null;
        }

        $files = $_FILES['image'];
        $resource = __DIR__ . '/../../../resource/kits/';

        if ($files) {
            $extensions = array('image/png', 'image/jpg', 'image/jpeg');
            if (in_array($files['type'], $extensions)) {
                $newname = uniqid() . mb_strrchr($files['name'], ".");
                $temp = $files['tmp_name'];
                if (move_uploaded_file($temp, $resource . $newname)) {
                    $category = $this->table("amw_items_category")->where("id = :id", "id={$id}")->get();
                    $insert = array(
                        'name' => $name,
                        'price' => $price,
                        'image' => $newname,
                        'id_category' => $id,
                        'class' => $class,
                        'coin' => web_shopping['shopping_category'][$category->category]['column_coin']
                    );



                    $this->table("amw_items_kit_category")->created($insert);
                    $this->message->class("success")->text("<em><strong>Kit </strong></em> adicionado com sucesso")->flash(true, true);
                } else {
                    $this->message->class("error")->text("<em><strong>Não foi possível</strong></em> adicionar a categoria no momento.")->flash();
                }
            } else {
                $this->message->class("error")->text("<em><strong>Extensão</strong></em> não permitida")->flash();
            }
        } else {
            $this->message->class("error")->text("Selecione uma <em><strong>imagem</strong></em> para continuar")->flash(true, true);
        }
    }

    public function autheditkitcategoryall($request)
    {
        $name = filter_var($request['name'], FILTER_SANITIZE_SPECIAL_CHARS);
        $price = filter_var($request['price'], FILTER_VALIDATE_INT);
        $id = filter_var($request['id'], FILTER_VALIDATE_INT);
        $class = filter_var($request['class'], FILTER_SANITIZE_SPECIAL_CHARS);

        if (empty($name) or empty($price) or empty($id) or empty($class)) {
            $this->message->class("error")->text("Algum <em><strong>campos</strong></em> inválido, atualize a página")->flash();
            return null;
        }

        $verifyname = $this->table("amw_items_kit_category")->where("name = :name AND id != :id", "name={$name}&id={$id}")->get();

        if ($verifyname) {
            $this->message->class("error")->text("<em><strong>Nome do kit</strong></em> já está em uso")->flash();
            return null;
        }

        $files = $_FILES['image'];
        $resource = __DIR__ . '/../../../resource/kits/';
        if ($files) {
            $extensions = array('image/png', 'image/jpg', 'image/jpeg');
            if (in_array($files['type'], $extensions)) {
                $newname = uniqid() . mb_strrchr($files['name'], ".");
                $temp = $files['tmp_name'];
                if (move_uploaded_file($temp, $resource . $newname)) {

                    if (file_exists($resource . $verifyname->image))  unlink($resource . $verifyname->image);

                    $update = array('image' => $newname);
                    $this->table("amw_items_kit_category")->where("id = :id", "id={$id}")->updated($update);
                }
            }
        }

        $update = array(
            'name' => $name,
            'price' => $price,
            'class' => $class
        );

        $this->table("amw_items_kit_category")->where("id = :id", "id={$id}")->updated($update);



        $this->message->class("success")->text("<em><strong>Kit </strong></em> editado com sucesso")->flash(true, true);
    }

    public function autheditkitcategory($request)
    {
        $name = filter_var($request['name'], FILTER_SANITIZE_SPECIAL_CHARS);
        $category = filter_var($request['category'], FILTER_SANITIZE_SPECIAL_CHARS);
        $id = filter_var($request['id'], FILTER_VALIDATE_INT);
        if (empty($name) or empty($category) or empty($id)) {
            $this->message->class("error")->text("Algum <em><strong>campos</strong></em> inválido, atualize a página")->flash();
            return null;
        }

        $verify = $this->table("amw_items_category")->where("name = :name AND category = :category AND id != :id", "name={$name}&category={$category}&id={$id}")->get();
        if ($verify) {
            $this->message->class("error")->text("<em><strong>Nome do kit</strong></em> já está sendo usado nesta categoria")->flash();
            return null;
        }

        $update = array('category' => $category, 'name' => $name, 'slug' => (new Slugify())->slugify($name));
        $this->table("amw_items_category")->where("id = :id", "id={$id}")->updated($update);

        $updatecoin = array('coin' => web_shopping['shopping_category'][$category]['column_coin']);
        $this->table("amw_items_kit_category")->where("id_category = :id", "id={$id}")->updated($updatecoin);



        $this->message->class("success")->text("<em><strong>Categoria </strong></em> editada com sucesso")->flash(true, true);
    }

    public function authaddnewitemkit($request)
    {
        $name = filter_var($request['name'], FILTER_SANITIZE_SPECIAL_CHARS);
        $section = $request['section'];
        $id_item = $request['id_item'];
        $level = $request['level'];
        $luck = $request['luck'];
        $skill = $request['skill'];
        $excelent = $request['excelent'];
        $ancient = $request['ancient'];
        $harmony = $request['harmony'];
        $id_package = filter_var($request['id_package'], FILTER_VALIDATE_INT);

        $socket1 = $request['socket1'];
        $socket2 = $request['socket2'];
        $socket3 = $request['socket3'];
        $socket4 = $request['socket4'];
        $socket5 = $request['socket5'];

        if (empty($name) or !is_numeric($section) or !is_numeric($id_item) or !is_numeric($level) or !is_numeric($luck) or !is_numeric($skill) or !is_numeric($excelent) or !is_numeric($ancient) or empty($id_package) or !is_numeric($harmony)) {
            $this->message->class("error")->text("Algum <em><strong>campo</strong></em> está inválido")->flash();
            return null;
        }

        if ($request['level'] < 0 or $request['level'] > 15) {
            $this->message->class("error")->text("<em><strong>Level do item</strong></em> incorreto")->flash();
            return null;
        }

        if (($socket2 != 255 && $socket2 == $socket1)
            or ($socket3 != 255 && ($socket3 == $socket2 or $socket3 == $socket1))
            or ($socket4 != 255 && ($socket4 == $socket2 or $socket4 == $socket1 or $socket4 == $socket3))
            or ($socket5 != 255 && ($socket5 == $socket2 or $socket5 == $socket1 or $socket5 == $socket3 or $socket5 == $socket4))
        ) {
            $this->message->class("error")->text("Não é possível repetir<em><strong>Sockets</strong></em>")->flash();
            return null;
        }

        $namekit = $this->table("amw_items_kit_category")->where("id", $id_package)->get();

        $insert = array(
            'name' => $name,
            'section' => $section,
            'id_item' => $id_item,
            'level' => $level,
            'luck' => $luck,
            'skill' => $skill,
            'excelent' => $excelent,
            'ancient' => $ancient,
            'id_package' => $id_package,
            'harmony' => $harmony,
            'socket1' => $socket1,
            'socket2' => $socket2,
            'socket3' => $socket3,
            'socket4' => $socket4,
            'socket5' => $socket5
        );



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