<?php

namespace Template\Controller;

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

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

    public function create()
    {
        echo $this->view->render('criar-pergunta', [
            'brand' => $this->repositoryBrand->findOneBy(['id' => 1]),
            'setting' => $this->repositoryConfig->findOneBy(['id' => 1])
        ]);
    }

    public function persist($data)
    {

        if (isset($data['id'])) {
            $id = filter_var(
                $data['id'],
                FILTER_VALIDATE_INT
            );
        }

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

        $answer = $data['answer'];

        $testimonys = filter_var(
            $data['testimony'],
            FILTER_SANITIZE_STRING
        );
        
        $questions = new Questions();
        (isset($data['id'])) ? $questions->setId($id) : '';
        $questions->setQuestion($question);
        $questions->setAnswer($answer);

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

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

    public function data()
    {
        $questions = $this->repository->findAll();
        $json = array();
        foreach ($questions as $value){
            array_push($json, array(
                "id" => $value->getId(),
                "question" => $value->getQuestion(),
            ));
        };
        print_r(json_encode($json));
    }

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

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

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

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

}
