<?php

namespace Template\Controller;

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

class Socials 
{
    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(Social::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('midias', [
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'setting' => $this->repositoryConfig->findOneBy(['id' => 1]),
            'social' => $this->repository->findOneBy(['id' => 1])
        ]);
    }

    public function persist($data)
    {

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

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

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

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

        $youtube = filter_var(
            $data['youtube'],
            FILTER_SANITIZE_STRING
        );
        
        $social = new Social();
        (isset($data['id'])) ? $social->setId($id) : '';
        $social->setFacebook($facebook);
        $social->setInstagram($instagram);
        $social->setLinkedin($linkedin);
        $social->setYoutube($youtube);
        (isset($data['plugin'])) ? $social->setPlugin(1) : '';

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

}
