<?php

namespace Template\Controller;

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

class ServiceAds 
{
    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(ServiceAd::class);
        $this->repositoryBrand = $entityManager->getRepository(Brand::class);
        $this->repositoryConfig = $entityManager->getRepository(Config::class);
        $path = 'public/admin/images';
        $this->upload = new Image($path, "images", 600);
        $this->router = new Router(URL_BASE);
    }

    public function index()
    {
        echo $this->view->render('service', [
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'service' => $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
            );
        }

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

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

        $action = filter_var(
            $data['action'],
            FILTER_SANITIZE_STRING
        );
        
        $service = new ServiceAd();
        (isset($data['id'])) ? $service->setId($id) : '';
        $service->setTitle($title);
        $service->setSubtitle($subtitle);
        $service->setAction($action);

        try {
            if(isset($data['id'])){
                $this->entityManager->merge($service);
            } else {
                $this->entityManager->persist($service);
            }
            $this->defineMensagem('success', "Chamada de Serviços Alterada com sucesso!");
            $this->entityManager->flush();
            $this->router->redirect("/layout/service");
        } catch (\Throwable $th) {
            $this->defineMensagem('error', "Não foi possivel alterar a chamada de serviços. Erro: {$th->getMessage()}");
            $this->router->redirect("/layout/service");
        }
    }

}
