<?php

namespace Template\Controller;

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

class Banners 
{
    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(Banner::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('banner', [
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'banner' => $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
        );

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

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

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

}
