<?php

namespace App\Controller;

use App\Entity\Rodic;
use App\Entity\Zak;
use App\Form\RodicType;
use App\Repository\RodicRepository;
use App\Repository\UserRepository;
use App\Services\FileUploader;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/rodic", name="rodic.")
 */
class RodicController extends AbstractController
{
    /**
     * @Route("/", name="index")
     * @param RodicRepository $rodicRepository
     * @return Response
     */
    public function index(RodicRepository $rodicRepository)
    {
        $user = $this -> getUser();
        if($user -> getRoles()[0] != 'ROLE_TEACHER' && $user -> getRoles()[0] != 'ROLE_ADMIN') throw $this -> createAccessDeniedException("Přístup odepřen");

        $rodice = $rodicRepository -> findAll();
        return $this -> render('rodic/index.html.twig', ['rodice' => $rodice]);
    }

    /**
     * @Route("/create", name="create")
     * @param Request $request
     * @param FileUploader $fileUploader
     * @return RedirectResponse|Response
     */
    public function create(Request $request, FileUploader $fileUploader)
    {
        $this -> denyAccessUnlessGranted('ROLE_ADMIN', null, "Přístup odepřen");

        $rodic = new Rodic();
        $form = $this -> createForm(RodicType::class, $rodic);
        $form -> handleRequest($request);

        if($form -> isSubmitted())
        {
            $em = $this -> getDoctrine() -> getManager();
            /** @var UploadedFile $file */
            $file = $request -> files -> get('rodic')['image'];
            if ($file) {
                $filename = $fileUploader -> uploadFile($file);

                $rodic -> setImage($filename);
                $em -> persist($rodic);
                $em -> flush();
            } else {
                $em -> persist($rodic);
                $em -> flush();
            }
            $this -> addFlash('success', 'Rodič byl přidán');
            return $this->redirect($this->generateUrl('rodic.index'));
        }

        return $this->render('rodic/create.html.twig', ['form' => $form-> createView()]);
    }

    /**
     * @Route("/show/{rodic}", name="show")
     * @param Rodic $rodic
     * @param UserRepository $userRepository
     * @return Response
     */
    public function show(Rodic $rodic, UserRepository $userRepository)
    {
        $users = $userRepository -> findAll();
        $user = $this -> getUser();
        $vys = 0;
        if($user -> getRodic() != null && $user -> getRodic() -> getId() != $rodic -> getId() &&  $user -> getRoles()[0] != 'ROLE_TEACHER' &&
            $user -> getRoles()[0] != 'ROLE_ADMIN') throw $this -> createAccessDeniedException("Přístup odepřen");

        foreach ($users as $u) if($u -> getRodic() != null && $u -> getRodic() -> getId() == $rodic -> getId()) $vys = $u;

        return $this->render('rodic/show.html.twig', ['rodic' => $rodic, 'user' => $vys]);
    }

    /**
     * @Route("/delete/{rodic}", name="delete")
     * @param Rodic $rodic
     * @return RedirectResponse
     */
    public function remove(Rodic $rodic)
    {
        $this -> denyAccessUnlessGranted('ROLE_ADMIN', null, "Přístup odepřen");

        $em = $this->getDoctrine()->getManager();
        $em->remove($rodic);
        $em->flush();
        $this->addFlash('success', 'Rodič byl smazán');
        return $this->redirect($this -> generateUrl('rodic.index'));
    }

    /**
     * @Route("/edit{rodic}", name="edit")
     * @param Rodic $rodic
     * @param Request $request
     * @param FileUploader $fileUploader
     * @return Response
     */
    public function edit(Rodic $rodic, Request $request, FileUploader $fileUploader)
    {
        $this -> denyAccessUnlessGranted('ROLE_ADMIN', null, "Přístup odepřen");

        $form = $this->createForm(RodicType::class, $rodic);
        $form -> handleRequest($request);

        if ($form->isSubmitted()) {
            $em = $this -> getDoctrine() -> getManager();
            /** @var UploadedFile $file */
            $file = $request -> files -> get('rodic')['image'];
            if ($file) {
                $filename = $fileUploader -> uploadFile($file);

                $rodic -> setImage($filename);
                $em -> persist($rodic);
                $em -> flush();
            } else {
                $em -> persist($rodic);
                $em -> flush();
            }
            $this -> addFlash('success', 'Rodič byl upraven');
            return $this->render('rodic/show.html.twig', ['rodic' => $rodic]);
        }
        //return a response
        $this -> addFlash('danger', 'Někde nastala chyba');
        return $this->render('rodic/create.html.twig', ['form' => $form->createView(), 'rodic' => $rodic]);
    }

    /**
     * @Route("/add/{rodic}", name="add")
     * @param Request $request
     * @param Rodic $rodic
     * @return Response
     */
    public function addZak(Request $request, Rodic $rodic)
    {
        $this -> denyAccessUnlessGranted('ROLE_ADMIN', null, "Přístup odepřen");

        $form = $this -> createFormBuilder()
        ->add('zak', EntityType::class, ['class' => Zak::class, 'label' => 'Žák'])
        ->add('rodic', EntityType::class, ['class' => Rodic::class, 'label' => 'Rodič', 'data' => $rodic])
        ->add('ulozit', SubmitType::class, ['label' => 'Uožit', 'attr' => ['class' => 'btn btn-outline-success']])
        ->getForm();

        $form -> handleRequest($request);

        if($form -> isSubmitted())
        {
            $rodic -> addZak($form -> getData()['zak']);
            $em = $this -> getDoctrine() -> getManager();
            $em -> persist($rodic);
            $em -> flush();
            $this -> addFlash('success', 'Rodič byl upraven');
            return $this->render('rodic/show.html.twig', ['rodic' => $rodic]);
        }
        return $this->render('rodic/add.html.twig', ['form' => $form->createView(), 'rodic' => $rodic]);
    }
}
