<?php

namespace Amwdeveloper\plugins\ticket;

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

class geral extends layer
{
    private $msg;
    private $session;

    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->msg = new message();

        if (!$this->session->has("useraccount")) {
            return $this->route->redirect("/");
        }
    }

    public function index()
    {
        $ticketsopen = $this->table("amw_tickets")->where("account = :acc AND status = :s", "acc={$this->session->useraccount}&s=0")->all();
        $ticketsanswered = $this->table("amw_tickets")->where("account = :acc AND status = :s", "acc={$this->session->useraccount}&s=1")->all();
        $ticketsclosed = $this->table("amw_tickets")->where("account = :acc AND status = :s", "acc={$this->session->useraccount}&s=2")->all();

        echo $this->view->render('user/ticket/all', [
            'title' => $this->title_web . ' - Meus tickets',
            'ticket_open' => $ticketsopen ?? null,
            'ticket_answered' => $ticketsanswered ?? null,
            'ticket_closed' => $ticketsclosed ?? null,
        ]);
    }

    public function newticket()
    {
        echo $this->view->render('user/ticket/new', [
            'title' => $this->title_web . ' - Abrir novo ticket'
        ]);
    }

    public function viewticket($slug)
    {
        $slug = filter_var($slug['slug'], FILTER_SANITIZE_SPECIAL_CHARS);

        if (!$slug) return $this->route->redirect('/user/ticket');

        $ticket_info = $this->table("amw_tickets")->where("slug = :s", "s={$slug}")->get();

        if (!$ticket_info) return $this->route->redirect('/user/ticket');

        $tickets_answered = $this->table('amw_tickets_answered')->where("id_ticket = :id", "id={$ticket_info->id}")->orderby('date')->all();
        echo $this->view->render('user/ticket/view', [
            'title' => $this->title_web . ' - Ticket ' . $ticket_info->subject,
            'ticket_info' => $ticket_info,
            'tickets_answered' => $tickets_answered ?? null
        ]);
    }

    // POSTS

    public function authnewticket($request)
    {
        $subject = filter_var($request['subject'], FILTER_SANITIZE_SPECIAL_CHARS);
        $message = filter_var($request['message'], FILTER_SANITIZE_SPECIAL_CHARS);

        if (empty($message) or empty($subject)) {
            $this->msg->class('error')->text('Preecha o campo da <em><strong>Assunto e Menssagem</strong></em>')->flash();
            return null;
        }

        if (strlen($subject) < 10 or strlen($subject) > 80) {
            $this->msg->class('error')->text('Título não pode ser menor que <em><strong>10 caracteres</strong></em> ou maior que <em><strong>80 caracteres</strong></em>')->flash();
            return null;
        }

        if (strlen($message) < 10 or strlen($message) > 1000) {
            $this->msg->class('error')->text('Message não pode ser menor que <em><strong>10 caracteres</strong></em> ou maior que <em><strong>1000 caracteres</strong></em>')->flash();
            return null;
        }

        $file = $_FILES['image'];
        $name_image = null;

        if ($file['name']) {
            $extension = ['image/png', 'image/gif', 'image/jpg', 'image/jpeg'];

            if (in_array($file['type'], $extension)) {
                $newname = md5(uniqid()) . mb_strrchr($file['name'], ".");
                $temp = $file['tmp_name'];
                $resource = __DIR__ . '/../../../resource/ticket/';
                $temp = $file['tmp_name'];

                if (move_uploaded_file($temp, $resource . $newname)) {
                    $name_image = $newname;
                } else {
                    $this->msg->class('error')->text("Erro ao criar <em><strong>Ticket</strong></em>, tente novamente mais tarde")->flash();
                    return null;
                }
            } else {
                $this->msg->class('error')->text("formato da <em><strong>Imagem</strong></em> inválido")->flash();
                return null;
            }
        }

        $account_name = $this->table("MEMB_INFO")->columns('memb_name')->where("memb___id = :mi", "mi={$this->session->useraccount}")->get();

        if (requests_form("new_ticket", 2, 15)) {
            $this->message->class("error")->text("Você criou um ticket recentemente, aguarde <em><strong>15 minutos</strong></em>")->flash();
            return null;
        }

        $insert = [
            'subject' => $subject,
            'message' => $message,
            'image' => $name_image ?? NULL,
            'account' => $this->session->useraccount,
            'name' => $account_name->memb_name,
            'date' => date('Y-m-d H:i:s', strtotime('now')),
            'status' => 0,
            'slug' => (new Slugify())->slugify($subject)
        ];

        $this->table("amw_tickets")->created($insert);
        $this->msg->class('success')->text('<em><strong>Ticket</strong></em> criado com sucesso!')->flash(true, true);
    }

    public function authnewtickettorespond($request)
    {
        $id_ticket = filter_var($request['id_ticket'], FILTER_VALIDATE_INT);
        $message = filter_var($request['message'], FILTER_SANITIZE_SPECIAL_CHARS);
        $slug = filter_var($request['slug'], FILTER_SANITIZE_SPECIAL_CHARS);

        if (empty($id_ticket) or empty($message) or empty($slug)) {
            $this->msg->class('error')->text('<em><strong>Campos inválidos</strong></em>, atualize a página e tente novamente')->flash();
            return null;
        }

        if (strlen($message) < 10 or strlen($message) > 1000) {
            $this->msg->class('error')->text('Message não pode ser menor que <em><strong>10 caracteres</strong></em> ou maior que <em><strong>1000 caracteres</strong></em>')->flash();
            return null;
        }

        $ticketverifyexist = $this->table('amw_tickets')->where("id = :id AND slug = :s", "id={$id_ticket}&s={$slug}")->get();
        if (empty($ticketverifyexist)) {
            $this->msg->class('error')->text('Opss,<em><strong>algo deu errado</strong></em>, atualize a página e tente novamente')->flash();
            return null;
        }

        if ($ticketverifyexist->status == 2) {
            $this->msg->class('error')->text('Opss,<em><strong>Ticket já finalizado</strong></em>')->flash();
            return null;
        }

        $ticketverifyexistanswered = $this->table('amw_tickets_answered')->where("id_ticket = :id", "id={$id_ticket}")->orderby('date')->get();
        if ($ticketverifyexistanswered and $ticketverifyexistanswered->account == $this->session->useraccount) {
            $this->msg->class('error')->text('Opss,<em><strong>você precisa esperar</strong></em>, a resposta da administração')->flash();
            return null;
        }

        $account_name = $this->table("MEMB_INFO")->columns('memb_name')->where("memb___id = :mi", "mi={$this->session->useraccount}")->get();
        $insert = [
            'id_ticket' => $id_ticket,
            'message' => $message,
            'account' => $this->session->useraccount,
            'name' => $account_name->memb_name,
            'date' => date('Y-m-d H:i:s', strtotime('now'))
        ];

        $this->table("amw_tickets_answered")->created($insert);
        $this->msg->class('success')->text('<em><strong>Ticket</strong></em> respondido com sucesso!')->flash(true, true);
    }
}
