<?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 Exception;
use Template\Entity\Company;

class Companys 
{
    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(Company::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('company', [
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'company' => $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 = $data['title'];

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

        $description = $data['description'];

        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/company");
            }
            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/company");
            }
        } elseif ($_FILES['input-file']['size'] == 0 && !isset($data['id'])) {
            $upload = 'public/site/images/empresa.png';
        }
        
        $company = new Company();
        (isset($data['id'])) ? $company->setId($id) : '';
        $company->setTitle($title);
        $company->setAction($action);
        $company->setDescription($description);
        (!isset($upload) && isset($data['id'])) ? $company->setImage($image->getImage()) : $company->setImage($upload);

        try {
            if(isset($data['id'])){
                $this->entityManager->merge($company);
            } else {
                $this->entityManager->persist($company);
            }
            if ($_FILES['input-file']['size'] == 0 && !isset($data['id'])):
                $this->defineMensagem('error', "Por favor, para continuar insira uma imagem... Será inserido uma padrão no momento.");
            else:
                $this->defineMensagem('success', "Sobre a Empresa Alterado com sucesso!");
            endif;

            $this->entityManager->flush();
            $this->router->redirect("/layout/company");
        } catch (\Throwable $th) {
            $this->defineMensagem('error', "Não foi possivel alterar sobre a empresa. Erro: {$th->getMessage()}");
            $this->router->redirect("/layout/company");
        }
    }

}
