<?php

namespace Template\Controller;

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

class Materials 
{
    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(Material::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 create()
    {
        echo $this->view->render('criar-materia', [
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'setting' => $this->repositoryConfig->findOneBy(['id' => 1])
        ]);
    }

    public function persist($data)
    {
        $title = filter_var(
            $data['title'],
            FILTER_SANITIZE_STRING
        );
        
        $description = $data['description'];

        if ($_FILES['input-file']['size'] != 0) {
            if ($_FILES['input-file']['type'] != mime_content_type($_FILES['input-file']['tmp_name']) || !preg_match('/^image\/(pjpeg|jpeg|png|gif|bmp|jpg)$/', $_FILES['input-file']['type'])) {
                $this->defineMensagem('error', "Essa não é uma imagem válida, tente novamente com outra imagem!");
                $this->router->redirect("/material/create");
            }
            try {
                $upload = $this->upload->upload($_FILES['input-file'], $title);
            } catch (Exception $e) {
                $this->defineMensagem('error', "{$e->getMessage()}");
                $this->router->redirect("/material/create");
            }
        } elseif ($_FILES['input-file']['size'] == 0 && !isset($data['id'])) {
            $this->defineMensagem('error', "Por favor, para continuar insira uma imagem...");
            $this->router->redirect("/material/create");
        }
        
        $material = new Material();
        $material->setTitle($title);
        $material->setContent($description);
        $material->setImage($upload);
        $material->setDate(strftime('%d de %B de %Y', strtotime('today')));

        try {
            $this->entityManager->persist($material);
            $this->defineMensagem('success', "Matéria: {$title} .Inserida com sucesso!");
            $this->entityManager->flush();
            $this->router->redirect("/material/search");
        } catch (\Throwable $th) {
            $this->defineMensagem('error', "Não foi possivel inserir a matéria. Erro: {$th->getMessage()}");
            $this->router->redirect("/material/create");
        }
    }

    public function search()
    {
        echo $this->view->render('todas-as-materias', [
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'setting' => $this->repositoryConfig->findOneBy(['id' => 1])
        ]);
    }

    public function data()
    {
        $material = $this->repository->findAll();
        $json = [];
        foreach ($material as $value){
            $json[] = [
                "id" => $value->getId(),
                "title" => $value->getTitle(),
                "date" => $value->getDate(),
                "image" => $value->getImage()
            ];
        };
        $json = mb_convert_encoding($json,"UTF-8","auto");
        print_r(json_encode($json));
    }

    public function edit($data)
    {
        $id = filter_var(
            $data['id'],
            FILTER_VALIDATE_INT
        );

        echo $this->view->render('criar-materia', [
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'setting' => $this->repositoryConfig->findOneBy(['id' => 1]),
            'material' => $this->repository->findOneBy(['id' => $id])
        ]);
    }

    public function update($data)
    {
        $id = filter_var(
            $data['id'],
            FILTER_VALIDATE_INT
        );

        $image = $this->repository->findOneBy(['id' => $id]);

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

        if ($_FILES['input-file']['size'] > 0) {
            if ($_FILES['input-file']['type'] != mime_content_type($_FILES['input-file']['tmp_name']) || !preg_match('/^image\/(pjpeg|jpeg|png|gif|bmp|jpg)$/', $_FILES['input-file']['type'])) {
                $this->defineMensagem('error', "Essa não é uma imagem válida, tente novamente com outra imagem!");
                $this->router->redirect("/material/edit/{$id}");
            }
            try {
                unlink($image->getImage());
                $upload = $this->upload->upload($_FILES['input-file'], $title);
            } catch (Exception $e) {
                $this->defineMensagem('error', "{$e->getMessage()}");
                $this->router->redirect("/material/edit/{$id}");
            }
        }
        
        $material = new Material();
        $material->setId($id);
        $material->setTitle($title);
        $material->setContent($description);
        $material->setDate(strftime('%d de %B de %Y', strtotime('today')));
        ($_FILES['input-file']['size'] != 0) ? $material->setImage($upload) : $material->setImage($image->getImage());

        try {
            $this->entityManager->merge($material);
            $this->defineMensagem('success', "Matéria: {$title} .Atualizado com sucesso!");
            $this->entityManager->flush();
            $this->router->redirect("/material/edit/{$id}");
        } catch (\Throwable $th) {
            $this->defineMensagem('error', "Não foi possivel atualizar a matéria. Erro: {$th->getMessage()}");
            $this->router->redirect("/material/create");
        }
    }

    public function delete($data)
    {
        $id = filter_var(
            $data['id'],
            FILTER_VALIDATE_INT
        );

        $material = $this->repository->findOneBy(['id' => $id]);
        unlink($material->getImage());
        $this->entityManager->remove($material);
        $this->entityManager->flush();
    }

}
