<?php

namespace Template\Controller;

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

class Colors 
{
    use FlashMessageTrait;

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

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

    public function index()
    {
        echo $this->view->render('cor', [
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'color' => $this->repository->findOneBy(['id' => 1]),
            'setting' => $this->repositoryConfig->findOneBy(['id' => 1]),
        ]);
    }

    public function persist($data)
    {

        if (isset($data['id'])) {
            $id = filter_var(
                $data['id'],
                FILTER_VALIDATE_INT
            );
        }

        $primary = filter_var(
            $data['primary'],
            FILTER_SANITIZE_STRING
        );

        $secondary = filter_var(
            $data['secondary'],
            FILTER_SANITIZE_STRING
        );
        
        $color = new Color();
        (isset($data['id'])) ? $color->setId($id) : '';
        $color->setColorFirst($primary);
        $color->setColorSecond($secondary);

        try {
            if(isset($data['id'])){
                $this->entityManager->merge($color);
            } else {
                $this->entityManager->persist($color);
            }
            $this->defineMensagem('success', "Cor Padrão Alterada com sucesso!");
            $this->entityManager->flush();
            $this->router->redirect("/color");
        } catch (\Throwable $th) {
            $this->defineMensagem('error', "Não foi possivel alterar a cor. Erro: {$th->getMessage()}");
            $this->router->redirect("/color");
        }
    }

    public function delete()
    {
        $color = new Color();
        $color->setId(1);
        $color->setColorFirst('');
        $color->setColorSecond('');
        $this->entityManager->merge($color);
        $this->defineMensagem('success', "Cor Padrão Resetada com sucesso!");
        $this->entityManager->flush();
        $this->router->redirect("/color");
    }

}
