<?php

namespace App\Controller;

use App\Entity\User;
use App\Entity\Zprava;
use App\Form\ZpravaType;
use App\Repository\ZpravaRepository;
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("/zprava", name="zprava.")
 */
class ZpravaController extends AbstractController
{
    /**
     * @Route("/", name="index")
     * @param ZpravaRepository $zpravaRepository
     * @return Response
     */
    public function index(ZpravaRepository $zpravaRepository)
    {
        $zpravy = $zpravaRepository -> findAll();
        $user = $this -> getUser();
        $vysledek = array();

        foreach ($zpravy as $zprava)
        {
            if($zprava -> getPrijemce() -> getId() == $user -> getId())
            {
                array_push($vysledek, $zprava);
            }
        }

        $em = $this -> getDoctrine() -> getManager();

        foreach ($vysledek as $zprava)
        {
            $zprava -> setPrecteno(true);
            $em -> persist($zprava);
            $em -> flush();
        }

        return $this->render('zprava/index.html.twig', [
            'zpravy' => $vysledek,
        ]);
    }

    /**
     * @Route("/odesl", name="odeslane")
     * @param ZpravaRepository $zpravaRepository
     * @return Response
     */
    public function odeslane(ZpravaRepository $zpravaRepository)
    {
        $zpravy = $zpravaRepository -> findAll();
        $user = $this -> getUser();
        $vysledek = array();

        foreach ($zpravy as $zprava)
        {
            if($zprava -> getOdesilatel() -> getId() == $user -> getId())
            {
                array_push($vysledek, $zprava);
            }
        }

        return $this->render('zprava/odesl.html.twig', [
            'zpravy' => $vysledek,
        ]);
    }

    /**
     * @Route("/create/{prijemce}", name="create")
     * @param User $prijemce
     * @param Request $request
     * @return Response
     */
    public function create(User $prijemce, Request $request)
    {
        $zprava = new Zprava();
        $user = $this -> getUser();
        $datum = new \DateTime('now');
        $zprava -> setPrijemce($prijemce) -> setOdesilatel($user) -> setDatOdesl($datum) -> setPrecteno(false);

        $form = $this -> createForm(ZpravaType::class, $zprava);

        $form -> handleRequest($request);

        if($form -> isSubmitted())
        {
            $em = $this -> getDoctrine() -> getManager();
            $em -> persist($zprava);
            $em -> flush();

            $this -> addFlash('success', 'Zpráva byla odeslána');
            return $this -> redirect($this -> generateUrl('zprava.odeslane'));
        }

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