<?php

namespace Template\Controller;

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

class Googles 
{
    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(Google::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('google', [
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'google' => $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
            );
        }

        $manager = filter_var($data['manager'], FILTER_SANITIZE_STRING);
        $analitycs = filter_var($data['analitycs'], FILTER_SANITIZE_STRING);
        $facebook = filter_var($data['facebook'], FILTER_SANITIZE_STRING);
        $pixel = filter_var($data['pixel'], FILTER_SANITIZE_STRING);
        
        $google = new Google();
        (isset($data['id'])) ? $google->setId($id) : '';
        $google->setManager($manager);
        $google->setFacebook($facebook);
        $google->setAnalitycs($analitycs);
        $google->setPixel($pixel);

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

}
