<?php

namespace Template\Controller;

use League\Plates\Engine;
use Template\Entity\Brand;
use Template\Entity\Leads;
use Template\Entity\Statu;
use Template\Entity\Config;
use CoffeeCode\Router\Router;
use CoffeeCode\Paginator\Paginator;
use Template\Helper\FlashMessageTrait;
use Doctrine\ORM\EntityManagerInterface;

class Status 
{

    use FlashMessageTrait;

    private $view;
    private $repository;
    private $router;
    private $entityManager;
    private $repositoryStatus;
    private $repositoryBrand;
    private $repositoryConfig;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->view = new Engine(__DIR__ . '/../../views/admin/');
        $this->entityManager = $entityManager;
        $this->repository = $entityManager->getRepository(Leads::class);
        $this->repositoryStatus = $entityManager->getRepository(Statu::class);
        $this->repositoryBrand = $entityManager->getRepository(Brand::class);
        $this->repositoryConfig = $entityManager->getRepository(Config::class);
        $this->router = new Router(URL_BASE);
    }

    public function index($data)
    {

        $page = filter_var(
            $data['page'],
            FILTER_SANITIZE_STRIPPED
        );

        $paginator = new Paginator(URL_BASE . 'status' . "/", '', ["Primeira Página", "Primeira"], ["Última Página", "Última"]);

        $paginator->pager(count($this->repositoryStatus->findAll()), 10, $page, 2);

        $query_select = "SELECT s FROM Template\Entity\Statu s ORDER BY s.id DESC";

        $query = $this->entityManager
        ->createQuery($query_select)
        ->setFirstResult($paginator->offset())
        ->setMaxResults($paginator->limit());
  
        $status = $query->getResult();

        echo $this->view->render('status', [
            'status' => $status,
            'paginator' => $paginator,
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'setting' => $this->repositoryConfig->findOneBy(['id' => 1]),
        ]);
    }

    public function persist($data)
    {
        $descricao = filter_var($data['descricao'], FILTER_SANITIZE_STRING);

        $status = new Statu();
        $status->setName($descricao);

        try {
            $this->entityManager->persist($status);
            $this->entityManager->flush();
            $this->defineMensagem('success', "Status criado com sucesso");
            $this->router->redirect("$_SERVER[HTTP_REFERER]");
        } catch (\Throwable $th) {
            $this->defineMensagem('error', "Não foi possivel criar o status. Erro: {$th->getMessage()}");
            $this->router->redirect("$_SERVER[HTTP_REFERER]");
        }
    }
    
}
