<?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\Entity\Testimony;
use Template\Helper\FlashMessageTrait;
use Doctrine\ORM\EntityManagerInterface;

class Testimonys 
{
    use FlashMessageTrait;

    private $view;
    private $router;
    private $repository;
    private $repositoryBrand;
    private $repositoryConfig;
    private $upload;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->view = new Engine(__DIR__ . '/../../views/admin/');
        $this->entityManager = $entityManager;
        $this->repository = $entityManager->getRepository(Testimony::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-depoimento', [
            'brand' => $this->repositoryBrand->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
            );
        }

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

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

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

        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("/testimony/create");
            }
            try {
                if (isset($data['id']) && !empty($image->getImage())) {
                    unlink($image->getImage());
                }
                $upload = $this->upload->upload($_FILES['input-file'], $name);
            } catch (Exception $e) {
                $this->defineMensagem('error', "{$e->getMessage()}");
                $this->router->redirect("/testimony/create");
            }
        } else if($_FILES['input-file']['size'] == 0 && !isset($data['id'])){
            $this->defineMensagem('error', "Por favor, insira uma imagem para continuar!");
            $this->router->redirect("/testimony/create");
        }
        
        $testimony = new Testimony();
        (isset($data['id'])) ? $testimony->setId($id) : '';
        $testimony->setName($name);
        $testimony->setCity($city);
        $testimony->setTestimony($testimonys);
        (!isset($upload)) ? $testimony->setImage($image->getImage()) : $testimony->setImage($upload);

        try {
            if(isset($data['id'])){
                $this->entityManager->merge($testimony);
                $this->defineMensagem('success', "Depoimento Alterado com sucesso!");
            } else {
                $this->entityManager->persist($testimony);
                $this->defineMensagem('success', "Depoimento Inserido com sucesso!");
            }
            $this->entityManager->flush();
            if(isset($data['id'])){
                $this->router->redirect("/testimony/edit/$id");
                return false;
            }
            $this->router->redirect("/testimony/search");
        } catch (\Throwable $th) {
            $this->defineMensagem('error', "Não foi possivel. Erro: {$th->getMessage()}");
            $this->router->redirect("/testimony/create");
        }
    }

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

    public function data()
    {
        $testimony = $this->repository->findAll();
        $json = array();
        foreach ($testimony as $value){
            array_push($json, array(
                "id" => $value->getId(),
                "image" => $value->getImage(),
                "name" => $value->getName(),
                "city" => $value->getCity()
            ));
        };
        print_r(json_encode($json));
    }

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

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

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

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

}
