<?php

namespace App\Controller;

use App\Entity\Offering;
use App\Form\OfferingFormType;

use App\Repository\OfferingRepository;
use App\Repository\WishRepository;


use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\Routing\Annotation\Route;
use Twig\Environment;

class OfferController extends AbstractController
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    #[Route('/offers', name: 'offers')]
    public function index(Environment $twig, OfferingRepository $offerRepository): Response
    {
        return new Response($twig->render('offer/index.html.twig', [
            'offers' => $offerRepository->findAll(),
        ]));
    }

    #[Route('/new', name: 'new_offer')]
    public function newOffer(Request $request, string $photoDir): Response
    {
        $offer = new Offering();
        $form = $this->createForm(OfferingFormType::class, $offer);
        $user = $this->getUser(); 

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $offer->setByUser($user);
            $offer->setCreatedAt(new \DateTime());

            if ($photo = $form['photo']->getData()) {
                $filename = bin2hex(random_bytes(6)).'.'.$photo->guessExtension();
                try {
                    $photo->move($photoDir, $filename);
                } catch (FileException $e) {
                    // unable to upload the photo, give up
                    $this->addFlash("error", "There was an error uploading the photo: ".$e);
                    return $this->redirectToRoute('new_offer');
                }
                $offer->setPhotoFilename($filename);
            }

            $this->entityManager->persist($offer);
            $this->entityManager->flush();

            $this->addFlash("success", "Successfully added the new offer!");
            return $this->redirectToRoute('offers');
        }

        return $this->render('app/new_offer.html.twig', [
            'user' => $this->getUser(),
            'offer_form' => $form->createView(),
        ]);
    }

    #[Route('/offer/{id}', name: 'show_offer')]
    public function show_offer(Offering $offer, WishRepository $wishRepository): Response
    {
        return $this->render('app/offer.html.twig', [
            'user' => $this->getUser(),
            'offer' => $offer,
            'wishes' => $wishRepository->findByUser($offer->getByUser()),
        ]);
    }

    #[Route('/offer/edit/{id}', name: 'edit_offer')]
    public function editOffer(Offering $offer, OfferingRepository $offerRepository, Request $request, string $photoDir): Response
    {
        $form = $this->createForm(OfferingFormType::class, $offer);
        $user = $this->getUser(); 
        if ($offer->getByUser() === $user)
        {
            $form->handleRequest($request);

            if ($form->isSubmitted() && $form->isValid()) {
                $offer->setByUser($user);
                $offer->setCreatedAt(new \DateTime());

                if ($photo = $form['photo']->getData()) {
                    $filename = bin2hex(random_bytes(6)).'.'.$photo->guessExtension();
                    try {
                        $photo->move($photoDir, $filename);
                    } catch (FileException $e) {
                        // unable to upload the photo, give up
                        $this->addFlash("error", "There was an error uploading the photo: ".$e);
                        return $this->redirectToRoute('new_offer');
                    }
                    $offer->setPhotoFilename($filename);
                }

                $this->entityManager->persist($offer);
                $this->entityManager->flush();
            } 

            return $this->render('offer/edit.html.twig', [
                'user' => $this->getUser(),
                'offer' => $offer,
                'offer_form' => $form->createView(),
            ]);
        }
        
        throw new HttpException(403, "No permission");
    }

    #[Route('/offer/delete/{id}', name: 'delete_offer')]
    public function deleteOffer(Offering $offer): Response
    {
        $user = $this->getUser(); 

        if ($offer->getByUser() === $user)
        {
                $this->entityManager->remove($offer);
                $this->entityManager->flush();
                $this->addFlash(
                    'success','Successfully removed offer!'
                );
    
                return $this->redirectToRoute('own_offers');    
        } 

        throw new HttpException(403, "No permission");
    }

    #[Route('/myoffers', name: 'own_offers')]
    public function ownOffers(OfferingRepository $offeringRepository): Response
    {
        $user = $this->getUser();

        return $this->render('user/offers.html.twig', [
            'user' => $user,
            'offers' => $offeringRepository->findByUser($user),
        ]);
    }
}