<?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\Contact;

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

    public function persist($data)
    {

        if (isset($data['id'])) {
            $image = $this->repository->findOneBy(['id' => $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
        );

        if ($_FILES['image']['size'] != 0) {
            if ($_FILES['image']['type'] != mime_content_type($_FILES['image']['tmp_name']) || !preg_match('/^image\/(pjpeg|jpeg|png|gif|bmp|jpg)$/', $_FILES['image']['type'])) {
                $this->defineMensagem('error', "Essa não é uma imagem válida, tente novamente com outra imagem!");
                $this->router->redirect("//layout/contact");
            }
            try {
                if (isset($data['id']) && !empty($image->getImage())) {
                    unlink($image->getImage());
                }
                $upload = $this->upload->upload($_FILES['image'], $title);
            } catch (Exception $e) {
                $this->defineMensagem('error', "{$e->getMessage()}");
                $this->router->redirect("/layout/contact");
            }
        } elseif ($_FILES['image']['size'] == 0 && !isset($data['id'])) {
            $this->defineMensagem('error', "Por favor, para continuar insira uma imagem...");
            $this->router->redirect("/layout/contact");
        }
        
        $contact = new Contact();
        (isset($data['id'])) ? $contact->setId($id) : '';
        $contact->setTitle($title);
        $contact->setSubtitle($subtitle);
        $contact->setAction($action);
        (!isset($upload)) ? $contact->setImage($image->getImage()) : $contact->setImage($upload);

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

}
