<?php

namespace Template\Controller;

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

class Galery 
{
    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(Image::class);
        $this->repositoryBrand = $entityManager->getRepository(Brand::class);
        $this->repositoryConfig = $entityManager->getRepository(Config::class);
        $this->router = new Router(URL_BASE);
    }

    public function index()
    {
        $query_select = "SELECT i FROM Template\Entity\Image i ORDER BY i.position ASC";
        $query = $this->entityManager
        ->createQuery($query_select);

        echo $this->view->render('galery', [
            'galery' => $query->getResult(),
            '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 = filter_var($data['description'], FILTER_SANITIZE_STRING);

        $ext = pathinfo($_FILES['input-file']['name'], PATHINFO_EXTENSION);

        $this->upload = new Send("file", $ext, [$_FILES['input-file']['type']], [$ext]);

        if ($_FILES['input-file']['size'] > 0) {
            try {
                $upload = $this->upload->upload($_FILES['input-file'], $title);
            } catch (\Exception $e) {
                $this->defineMensagem('error', "{$e->getMessage()}");
                $this->router->redirect("/galery");
            }
        } else{
            $this->defineMensagem('error', "Por favor, insira um arquivo para continuar");
            $this->router->redirect("/galery");
        }
        
        $galery = new Image();
        $galery->setTitle($title);
        $galery->setDescription($description);
        $galery->setImage($upload);
        $galery->setPosition(count($this->repository->findAll()) + 1);

        try {
            $this->entityManager->persist($galery);
            $this->entityManager->flush();
            $this->defineMensagem('success', "Upload de Imagem com sucesso!");
            $this->router->redirect("/galery");
        } catch (\Throwable $th) {
            $this->defineMensagem('error', "Não foi possivel fazer o upload. Erro: {$th->getMessage()}");
            $this->router->redirect("/galery");
        }
    }

    public function steps($data)
    {
        $count = 1;
        foreach ($data['lista'] as $item) {
            $qb = $this->entityManager->createQueryBuilder();
            $q = $qb->update('Template\Entity\Image', 'i')
            ->set('i.position', $qb->expr()->literal($count))
            ->where('i.id = ?1')
            ->setParameter(1, $item)
            ->getQuery();
            $q->execute();
            $count++;
        }
    }

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

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

}
