<?php

namespace Template\Controller;

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

class Services 
{
    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(Service::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-servico', [
            '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 (isset($data['youtube'])&&$data['youtube']!='') {

            $upload=$data['youtube'];

        }else{
            
            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("/service/create");
                }
                try {
                    $upload = $this->upload->upload($_FILES['input-file'], preg_replace('/\google/i', '', $title));
                } catch (Exception $e) {
                    $this->defineMensagem('error', "{$e->getMessage()}");
                    $this->router->redirect("/service/create");
                }
            } else {
                $this->defineMensagem('error', "Por favor, insira uma imagem para continuar...");
                $this->router->redirect("/service/create");
            }
        }

      
        
        $service = new Service();
        $service->setTitle($title);
        $service->setDescription($description);
        $service->setImage($upload);

        try {
            $this->entityManager->persist($service);
            $this->defineMensagem('success', "Serviço: {$title} .Inserido com sucesso!");
            $this->entityManager->flush();
            $this->router->redirect("/service/search");
        } catch (\Throwable $th) {
            $this->defineMensagem('error', "Não foi possivel inserir o serviço. Erro: {$th->getMessage()}");
            $this->router->redirect("/service/create");
        }
    }

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

    public function data()
    {
        $service = $this->repository->findAll();
        $json = array();
        foreach ($service as $value){
            array_push($json, array(
                "id" => $value->getId(),
                "title" => $value->getTitle(),
                "image" => $value->getImage()
            ));
        };
        print_r(json_encode($json));
    }

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

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

    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("/service/edit/{$id}");
            }
            try {
                unlink($image->getImage());
                $upload = $this->upload->upload($_FILES['input-file'], preg_replace('/\google/i', '', $title));
            } catch (Exception $e) {
                $this->defineMensagem('error', "{$e->getMessage()}");
                $this->router->redirect("/service/edit/{$id}");
            }
        } elseif ($_FILES['input-file']['size'] == 0 && !isset($data['id'])) {
            $this->defineMensagem('error', "Por favor, para continuar insira uma imagem...");
            $this->router->redirect("/service/edit/{$id}");
        }
        
        $service = new Service();
        $service->setId($id);
        $service->setTitle($title);
        $service->setDescription($description);
        ($_FILES['input-file']['size'] != 0) ? $service->setImage($upload) : $service->setImage($image->getImage());

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

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

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

}
