<?php

namespace Template\Controller;

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

class Simulators 
{
    use FlashMessageTrait;

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

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->view = new Engine(__DIR__ . '/../../views/admin/');
        $this->entityManager = $entityManager;
        $this->repository = $entityManager->getRepository(Simulator::class);
        $this->repositoryBrand = $entityManager->getRepository(Brand::class);
        $this->repositoryConfig = $entityManager->getRepository(Config::class);
        $this->repositoryBanner = $entityManager->getRepository(Banner::class);
        $this->router = new Router(URL_BASE);
    }

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

        echo $this->view->render('simulator', [
            'simulator' => $query->getResult(),
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'setting' => $this->repositoryConfig->findOneBy(['id' => 1]),
            'banner' => $this->repositoryBanner->findOneBy(['id' => 1])
        ]);
    }

    public function persist($data)
    {

        $type = filter_var($data['type'], FILTER_SANITIZE_STRING);
        $name = filter_var($data['name'], FILTER_SANITIZE_STRING);
        $required = (isset($data['required'])) ? 1 : 0;
        $options = (isset($data['options'])) ? implode(',', $data['options']) : '';
        $minQ = (isset($data['minQ'])) ? filter_var($data['minQ'], FILTER_VALIDATE_INT) : '';
        $maxQ = (isset($data['maxQ'])) ? filter_var($data['maxQ'], FILTER_VALIDATE_INT) : '';
        $maxLength = (isset($data['maxLength'])) ? filter_var($data['maxLength'], FILTER_VALIDATE_INT) : '';
        
        $simulator = new Simulator();
        $simulator->setType($type);
        $simulator->setName($name);
        $simulator->setRequired($required);
        (!empty($options)) ? $simulator->setOptions($options) : '';
        (!empty($minQ)) ? $simulator->setMinQ($minQ) : '';
        (!empty($maxQ)) ? $simulator->setMaxQ($maxQ) : '';
        (!empty($maxLength)) ? $simulator->setMaxLength($maxLength) : '';
        $simulator->setPosition(count($this->repository->findAll()) + 1);

        try {
            $this->entityManager->persist($simulator);
            $this->defineMensagem('success', "Campo adicionado com sucesso");
            $this->entityManager->flush();
            $this->router->redirect("/simulator");
        } catch (\Throwable $th) {
            $this->defineMensagem('error', "Não foi possivel adicionar campo. Erro: {$th->getMessage()}");
            $this->router->redirect("/simulator");
        }
    }

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

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

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

}
