<?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 Template\Entity\Qualidade;
use Template\Helper\FlashMessageTrait;
use Doctrine\ORM\EntityManagerInterface;

class Qualidades 
{

    use FlashMessageTrait;

    private $view;
    private $repository;
    private $router;
    private $entityManager;
    private $repositoryStatus;
    private $repositoryQ;
    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->repositoryQ = $entityManager->getRepository(Qualidade::class);
        $this->repositoryBrand = $entityManager->getRepository(Brand::class);
        $this->repositoryConfig = $entityManager->getRepository(Config::class);
        $this->router = new Router(URL_BASE);
    }

    public function index($data)
    {

        echo $this->view->render('qualidade', [
            'status1' => $this->repositoryQ->findBy(['type' => 0]),
            'status2' => $this->repositoryQ->findBy(['type' => 1]),
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'setting' => $this->repositoryConfig->findOneBy(['id' => 1]),
        ]);
    }

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

        $qualidade = new Qualidade();
        $qualidade->setName($descricao);
        $qualidade->setType($type);

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