<?php

namespace Amwdeveloper\plugins\webshop;

use Amwdeveloper\core\session;
use Amwdeveloper\model\layer;
use Amwdeveloper\model\message;
use League\Plates\Engine;

class home extends layer
{

    public function __construct()
    {
        global $route;
        $this->view = new Engine(__DIR__ . "/../../../theme/" . config['path'] . "/pages", 'phtml');
        $this->route = $route;
        $this->title_web = config['web_title'];
        $this->session = new session();
        $this->messages = new message();
    }


    public function verifycategory($request)
    {
        global $route;
        $category = filter_var($request['category'], FILTER_SANITIZE_SPECIAL_CHARS);

        $verify = $this->table("amw_items")->columns("name")->where("category_group = :cg", "cg={$category}")->get();

        if (empty($verify)) $route->redirect('/shops');
    }


    public function verifycategorygroup($request)
    {
        $category = filter_var($request['category'], FILTER_SANITIZE_SPECIAL_CHARS);
        $item_group = filter_var($request['group'], FILTER_SANITIZE_SPECIAL_CHARS);

        $verify = $this->table("amw_items")->columns("name")->where("category_group = :cg AND item_group = :item_group", "cg={$category}&item_group={$item_group}")->get();

        if (empty($verify)) null;
    }


    public function shoppings()
    {
        echo $this->view->render("partials/shopping/all", [
            'title' => $this->title . ' Shopping'
        ]);
    }

    public function shoppingredirectcategory($request)
    {
        $this->verifycategory($request);

        echo $this->view->render("partials/shopping/view", [
            'title' => $this->title . ' Shopping ' . $request['category'],
            'title_shopping' => "Shopping {$request['category']}",
            'category' => $request['category'],
            'items' => null,
            'alert' => 'Selecione uma <em><strong>categoria</strong></em> de itens a lado'
        ]);
    }

    public function shoppingcategory($request)
    {
        $this->verifycategorygroup($request);
        echo $this->view->render("partials/shopping/view", [
            'title' => $this->title . ' Shopping ' . $request['category'],
            'title_shopping' => "Shopping {$request['category']} / <em><strong>{$request['group']}</strong></em>",
            'category' => $request['category'],
            'group_item' => $request['group'],
            'items' => $this->view($request),
            'coin' => web_shopping['shopping_category'][$request['category']],
            'alert' => 'Não há <strong>itens disponíveis</strong> nestá categoria'
        ]);
    }

    public function buyitemdetails($request)
    {

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

        if (!$id) return $this->route->redirect("/shops");

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

        if (!$verifyItem) return $this->route->redirect("/shops");

        echo $this->view->render("partials/shopping/details", [
            'title' => $this->title . ' Shopping ' . $request['category'],
            'title_shopping' => "Shopping {$request['category']} / Detalhes do item: <strong>{$verifyItem->name} </strong>",
            'category' => $request['category'],
            'items' => $this->view($request),
            'coin' => web_shopping['shopping_category'][$request['category']],
            'details' => $verifyItem,
            'group_item' => $request['group'],
            'alert' => 'Não há <strong>itens disponíveis</strong> nestá categoria'
        ]);
    }



    // SHOPPING KIT

    public function verifykitcategory($request)
    {
        global $route;
        $category = filter_var($request['category'], FILTER_SANITIZE_SPECIAL_CHARS);

        $verify = $this->table("amw_items_category")->columns("name")->where("category = :cg", "cg={$category}")->get();
        if (empty($verify)) $route->redirect('/shops');
    }

    public function shoppingkitlistcategories($request)
    {
        $this->verifykitcategory($request);
        $listCategories = $this->table("amw_items_category")->columns('name,slug')->where("category = :ct", "ct={$request['category']}")->all();
        return $listCategories;
    }

    public function verifykitcategorygroup($request)
    {
        $category = filter_var($request['category'], FILTER_SANITIZE_SPECIAL_CHARS);
        $item_group = filter_var($request['group'], FILTER_SANITIZE_SPECIAL_CHARS);

        $verify = $this->table("amw_items_category")->columns("name")->where("category = :cg AND slug = :group", "cg={$category}&group={$item_group}")->get();

        if (empty($verify)) null;
    }

    public function shoppingkitcategory($request)
    {
        $this->verifykitcategory($request);
        echo $this->view->render("partials/shopping/view_kit", [
            'title' => $this->title . ' Shopping ' . $request['category'],
            'title_shopping' => "Shopping {$request['category']} / " . isset($request['group']) ?? '',
            'category' => $request['category'],
            'items' => null,
            'categories' => $this->shoppingkitlistcategories($request),
            'alert' => 'Selecione uma <em><strong>categoria</strong></em> de itens a lado'
        ]);
    }

    public function shoppingkitcategorygroup($request)
    {
        $this->verifykitcategorygroup($request);
        echo $this->view->render("partials/shopping/view_kit", [
            'title' => $this->title . ' Shopping ' . $request['category'] . ' ' . str_replace("-", " ", $request['group']),
            'title_shopping' => "Shopping {$request['category']} / <em><strong>" . str_replace("-", " ", $request['group']) . "</strong></em>",
            'category' => $request['category'],
            'items' => $this->viewKitCategory($request),
            'coin' => web_shopping['shopping_category'][$request['category']],
            'categories' => $this->shoppingkitlistcategories($request),
            'alert' => 'Está <em><strong>categoria</strong></em> não possuí itens no momento'
        ]);
    }

    public function viewKitCategory($request)
    {
        $category = filter_var($request['category'], FILTER_SANITIZE_SPECIAL_CHARS);
        $item_group = filter_var($request['group'], FILTER_SANITIZE_SPECIAL_CHARS);
        $verifyCategory = $this->table("amw_items_category")->columns("id")->where("category = :ct AND slug = :sl", "ct={$category}&sl={$item_group}")->get();

        if (!$verifyCategory) return null;

        $allitems = $this->table("amw_items_kit_category")->where("id_category = :id", "id={$verifyCategory->id}")->orderby("price")->all();

        foreach ($allitems as $items) {
            $item[] = [
                'name' => $items->name,
                'image' => $items->image,
                'price' => $items->price,
                'class' => $items->class,
                'id' => base64_encode($items->id)
            ];
        }
        return $item ?? null;
    }

    public function view($request)
    {
        $category = filter_var($request['category'], FILTER_SANITIZE_SPECIAL_CHARS);
        $item_group = filter_var($request['group'], FILTER_SANITIZE_SPECIAL_CHARS);
        $allitems = $this->table("amw_items")->columns("id,name,image,price,class")
            ->where("category_group = :cg AND active = :ac AND item_group = :ig", "cg={$category}&ac=1&ig={$item_group}")
            ->orderby("price")->all();
        foreach ($allitems as $items) {
            $item[] = [
                'name' => $items->name,
                'image' => $items->image,
                'price' => $items->price,
                'class' => $items->class,
                'id' => base64_encode($items->id)
            ];
        }
        return $item ?? null;
    }


    public function buyitem($request)
    {
        $id_item = filter_var(base64_decode($request['id_item']), FILTER_VALIDATE_INT);

        $account = $this->session->useraccount;
        if (empty($id_item)) {
            $this->messages->class("error")->text("<em><strong>Não foi possível continuar</strong></em>, atualize a página e tente novamente")->flash();
            return null;
        }

        $verifyexistitem = $this->table("amw_items")->columns("id_item,name,price,category_group,coin_name,item_group")->where("id = :id AND active = :ac", "id={$id_item}&ac=1")->get();

        if (empty($verifyexistitem)) {
            $this->messages->class("error")->text("<em><strong>Não foi possível continuar</strong></em>, atualize a página e tente novamente")->flash();
            return null;
        }

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

        if ($verifylogged->ConnectStat == 1) {
            $this->messages->class("error")->text("<em><strong>Deslogue de sua conta no jogo</strong></em>, para continuar com a compra")->flash();
            return null;
        }

        $excelentsSelect = [];

        if (isset($request['excelent_1'])) $excelentsSelect[] = 1;
        if (isset($request['excelent_2'])) $excelentsSelect[] = 1;
        if (isset($request['excelent_3'])) $excelentsSelect[] = 1;
        if (isset($request['excelent_4'])) $excelentsSelect[] = 1;
        if (isset($request['excelent_5'])) $excelentsSelect[] = 1;
        if (isset($request['excelent_6'])) $excelentsSelect[] = 1;

        $excelentsAllowed = web_shopping['shopping_category'][$verifyexistitem->category_group]['excelents'];
        $levelAllowed = web_shopping['shopping_category'][$verifyexistitem->category_group]['level'];


        $coininfo = web_shopping['shopping_category'][$verifyexistitem->category_group];
        $coinaccount = $this->table($coininfo['table'])->columns($verifyexistitem->coin_name)->where("{$coininfo['column_account']} = :mi", "mi={$account}")->get();

        if (empty($coinaccount)) {
            $this->messages->class("error")->text("<em><strong>Não foi possível continuar</strong></em>, atualize a página e tente novamente")->flash();
            return null;
        }

        if ($coinaccount->{$verifyexistitem->coin_name} < $verifyexistitem->price) {
            $this->messages->class("error")->text("Você não possuí o valor de <em><strong>{$verifyexistitem->price} {$coininfo['coin_name']}</strong></em>")->flash();
            return null;
        }

        if (count($excelentsSelect) > $excelentsAllowed) {
            $this->messages->class("error")->text("<em><strong>Não foi possível continuar</strong></em>, o limite de <strong>excelente é de {$excelentsAllowed}</strong>")->flash();
            return null;
        }

        if (!is_numeric($request['level']) or $request['level'] > $levelAllowed) {
            $this->messages->class("error")->text("<em><strong>Não foi possível continuar</strong></em>, o level permitido é até <strong>+{$levelAllowed}</strong>")->flash();
            return null;
        }

        if (web_shopping['shopping_category'][$verifyexistitem->category_group]['block']['ancient'] and isset($request['ancient'])) {
            $this->messages->class("error")->text("<em><strong>Não foi possível continuar</strong></em>, ancient não disponível")->flash();
            return null;
        }
        if (web_shopping['shopping_category'][$verifyexistitem->category_group]['block']['item380'] and isset($request['item380'])) {
            $this->messages->class("error")->text("<em><strong>Não foi possível continuar</strong></em>, item380 não disponível")->flash();
            return null;
        }
        if (web_shopping['shopping_category'][$verifyexistitem->category_group]['block']['harmony'] and isset($request['harmony'])) {
            $this->messages->class("error")->text("<em><strong>Não foi possível continuar</strong></em>, harmony não disponível")->flash();
            return null;
        }
        if (web_shopping['shopping_category'][$verifyexistitem->category_group]['block']['socket'] and isset($request['socket'])) {
            $this->messages->class("error")->text("<em><strong>Não foi possível continuar</strong></em>, socket não disponível")->flash();
            return null;
        }

        if (
            socket_unique
            and (isset($request['socket1']) and isset($request['socket2']) and isset($request['socket3']) and isset($request['socket4']) and isset($request['socket5']))
            and ($request['socket1'] != 255 and $request['socket1'] != 255 and $request['socket1'] != 255 and $request['socket1'] != 255)
        ) {
            if (
                ($request['socket1'] == $request['socket2']) or ($request['socket1'] == $request['socket3']) or ($request['socket1'] == $request['socket4']) or ($request['socket1'] == $request['socket5'])
                or ($request['socket2'] == $request['socket1']) or ($request['socket2'] == $request['socket3']) or ($request['socket2'] == $request['socket4']) or ($request['socket2'] == $request['socket5'])
                or ($request['socket3'] == $request['socket1']) or ($request['socket3'] == $request['socket2']) or ($request['socket3'] == $request['socket4']) or ($request['socket3'] == $request['socket5'])
                or ($request['socket4'] == $request['socket1']) or ($request['socket4'] == $request['socket2']) or ($request['socket4'] == $request['socket3']) or ($request['socket4'] == $request['socket5'])
                or ($request['socket5'] == $request['socket1']) or ($request['socket5'] == $request['socket2']) or ($request['socket5'] == $request['socket3']) or ($request['socket5'] == $request['socket4'])
            ) {
                $this->messages->class("error")->text("Não é possível, <em><strong>repetir sockets</strong></em>")->flash();
                return null;
            }
        }

        $newitem = new item();
        $newitem->setid($id_item);

        // Gera e envia o item
        $newitem->geratehex($coininfo['table'], $coininfo['column_account'], $verifyexistitem->coin_name, $verifyexistitem->price, $request);
    }


    public function buykititem($request)
    {
        $id_item = filter_var(base64_decode($request['item']), FILTER_VALIDATE_INT);
        $name_item = filter_var($request['name'], FILTER_SANITIZE_SPECIAL_CHARS);


        $account = $this->session->useraccount;
        if (empty($id_item) or empty($name_item)) {
            $this->messages->class("error")->text("<em><strong>Não foi possível continuar</strong></em>, atualize a página e tente novamente")->flash();
            return null;
        }

        $verifyexistitem = $this->table("amw_items_kit")->columns("id_item")->where("id_package = :id", "id={$id_item}")->all();

        if (empty($verifyexistitem)) {
            $this->messages->class("error")->text("<em><strong>Não foi possível continuar</strong></em>, atualize a página e tente novamente")->flash();
            return null;
        }

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

        if ($verifylogged->ConnectStat == 1) {
            $this->messages->class("error")->text("<em><strong>Deslogue de sua conta no jogo</strong></em>, para continuar com a compra")->flash();
            return null;
        }

        $item_category = $this->table("amw_items_kit_category")->columns("id_category,coin,price")->where("id = :id", "id={$id_item}")->get();
        $category = $this->table("amw_items_category")->columns("category")->where("id = :id", "id={$item_category->id_category}")->get();

        $coininfo = web_shopping['shopping_category'][$category->category];
        $coinaccount = $this->table($coininfo['table'])->columns("{$item_category->coin} as coin")->where("{$coininfo['column_account']} = :mi", "mi={$account}")->get();

        if (empty($coinaccount)) {
            $this->messages->class("error")->text("<em><strong>Não foi possível continuar</strong></em>, atualize a página e tente novamente")->flash();
            return null;
        }

        if ($coinaccount->coin < $item_category->price) {
            $this->messages->class("error")->text("Você não possuí o valor de <em><strong>{$item_category->price} {$coininfo['coin_name']}</strong></em>")->flash();
            return null;
        }

        $newitem = new kit();
        $newitem->setidkit($id_item);
        $newitem->geratehexkit($name_item, $coininfo['table'], $coininfo['column_account'], $item_category->coin, $item_category->price);
    }
}
