<?php

namespace Amwdeveloper\plugins\packages;

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

class admin extends layer
{

    private $route;
    private $view;
    private $message;

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

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

    public function index()
    {
        $this->checklogin();
        echo $this->view->render('packages/add', [
            'title' =>  'Novo pacote',
            'vips' => vip,
            'coins' => coins,
            'coins_deman' => coins
        ]);
    }

    public function managepackages()
    {
        $this->checklogin();
        $packages = $this->table("amw_packages")->all();
        echo $this->view->render('packages/managepackages', [
            'title' =>  'Gerenciar pacotes',
            'packages' => $packages ?? null
        ]);
    }

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

        if (!$id) $this->route->redirect('/administration/manage/packages');

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

        if (!$packageinfo) $this->route->redirect('/administration/manage/packages');

        $package = array(
            'id' => $packageinfo->id,
            'title' => $packageinfo->title,
            'description' => $packageinfo->description,
            'price' => $packageinfo->price,
            'coin_demand_name' => $packageinfo->coin_demand_name,
            'coin_name' => $packageinfo->coin_name,
            'quantity' => $packageinfo->quantity,
            'vip_type' =>  $packageinfo->vip_type,
            'vip_time' => $packageinfo->vip_time
        );

        echo $this->view->render('packages/editpackage', [
            'title' =>  'Editar pacote ' . $package['title'],
            'package' => $package,
            'vips' => vip,
            'coins' => coins,
            'coins_deman' => coins
        ]);
    }

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

        if (!$id) $this->route->redirect('/administration/manage/packages');

        $this->table("amw_packages")->where("id = :id", "id={$id}")->destroy();
        $this->route->redirect('/administration/manage/packages');
    }
    // POST
    public function newpackage($request)
    {
        $title = filter_var($request['title'], FILTER_SANITIZE_SPECIAL_CHARS);
        $description = filter_var($request['description'], FILTER_SANITIZE_SPECIAL_CHARS);
        $coin_demand = $request['coin_demand'];
        $price = filter_var($request['price'], FILTER_VALIDATE_INT);

        $coin =  $request['coin'];
        $quantity = filter_var($request['quantity'], FILTER_VALIDATE_INT);
        $vip_type = filter_var($request['vip_type'], FILTER_VALIDATE_INT);
        $vip_time = filter_var($request['vip_time'], FILTER_VALIDATE_INT);

        if (empty($title) or empty($description) or !is_numeric($coin_demand) or empty($price)) {
            $this->message->class("error")->text("Campos obrigatórios vázios")->flash();
            return;
        }
        if (!is_numeric($coin) and empty($vip_type)) {
            $this->message->class("error")->text("O Pacote deve conter Moedas ou Vip")->flash();
            return;
        }

        $verifyPackageExist = $this->table("amw_packages")->where("title = :title", "title={$title}")->get();

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

        $demand = coins[$coin_demand];

        $insert = array();

        if ($demand >= 0) {
            $insertDemand = array(
                'price' => $price,
                'title' => $title,
                'description' => $description,
                'table_coin_demand' => $demand['table'],
                'column_account_demand' => $demand['column_account'],
                'coin_demand' => $demand['column_coin'],
                'coin_demand_name' => $demand['name_coin'],
            );
            $insert = array_merge($insert, $insertDemand);
        }

        if ($coin >= 0) {

            $coin = coins[$coin];

            if ($demand['column_coin'] == $coin['column_coin']) {
                $this->message->class("error")->text("moedas de <strong>cobrança e a receber</strong> não pode ser iguais")->flash();
                return;
            }

            $insertCoin = array(
                'coin' => $coin['column_coin'],
                'table_coin' => $coin['table'],
                'quantity' => $quantity,
                'column_account' => $coin['column_account'],
                'coin_name' => $coin['name_coin'],
            );

            $insert = array_merge($insert, $insertCoin);
        }

        if ($vip_type >= 1) {
            $insertVip = array(
                'vip_type' => $vip_type,
                'vip_time' => $vip_time
            );

            $insert = array_merge($insert, $insertVip);
        }

        $this->message->class("success")->text("<strong>{$title}</strong> Adicionado com sucesso")->flash(true, true);
        $this->table("amw_packages")->created($insert);
    }

    public function updatepackage($request)
    {
        $id = filter_var($request['id'], FILTER_VALIDATE_INT);
        $title = filter_var($request['title'], FILTER_SANITIZE_SPECIAL_CHARS);
        $description = filter_var($request['description'], FILTER_SANITIZE_SPECIAL_CHARS);
        $coin_demand = $request['coin_demand'];
        $price = filter_var($request['price'], FILTER_VALIDATE_INT);

        $coin =  $request['coin'];
        $quantity = filter_var($request['quantity'], FILTER_VALIDATE_INT);
        $vip_type = filter_var($request['vip_type'], FILTER_VALIDATE_INT);
        $vip_time = filter_var($request['vip_time'], FILTER_VALIDATE_INT);

        if (empty($title) or empty($description) or !is_numeric($coin_demand) or empty($price) or empty($id)) {
            $this->message->class("error")->text("Campos obrigatórios vázios")->flash();
            return;
        }
        if (!is_numeric($coin) and empty($vip_type)) {
            $this->message->class("error")->text("O Pacote deve conter Moedas ou Vip")->flash();
            return;
        }

        $verifyPackageExist = $this->table("amw_packages")->columns('title')->where("title = :title AND id != :id", "title={$title}&id={$id}")->get();

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

        $demand = coins[$coin_demand];

        $insert = array();

        if ($demand >= 0) {
            $insertDemand = array(
                'price' => $price,
                'title' => $title,
                'description' => $description,
                'table_coin_demand' => $demand['table'],
                'column_account_demand' => $demand['column_account'],
                'coin_demand' => $demand['column_coin'],
                'coin_demand_name' => $demand['name_coin'],
            );
            $insert = array_merge($insert, $insertDemand);
        }

        if ($coin >= 0) {

            $coin = coins[$coin];

            if ($demand['column_coin'] == $coin['column_coin']) {
                $this->message->class("error")->text("moedas de <strong>cobrança e a receber</strong> não pode ser iguais")->flash();
                return;
            }

            $insertCoin = array(
                'coin' => $coin['column_coin'],
                'table_coin' => $coin['table'],
                'quantity' => $quantity,
                'column_account' => $coin['column_account'],
                'coin_name' => $coin['name_coin'],
            );

            $insert = array_merge($insert, $insertCoin);
        }

        if ($vip_type >= 1) {
            $insertVip = array(
                'vip_type' => $vip_type,
                'vip_time' => $vip_time
            );

            $insert = array_merge($insert, $insertVip);
        }

        $this->message->class("success")->text("<strong>{$title}</strong> editado com sucesso")->flash(true, true);
        $this->table("amw_packages")->where("id = :id", "id={$id}")->updated($insert);
    }
}
