<?php

declare(strict_types=1);

namespace App\Controller\Admin\Properties;

use App\Entity\Properties\Bien;
use App\Entity\Properties\Demarcheur;
use App\Managers\ManagersInterface;
use App\Entity\Properties\Properties;
use App\Form\Properties\BienType;
use App\Form\Properties\DemarcheursType;
use App\Handlers\Forms\BiensHandle;
use App\Handlers\Forms\DemarcheursHandle;
use App\Interfaces\NotificationsInterface;
use App\Repository\Properties\BiensRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\Properties\DemarcheursRepository;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security as Security;

#[Route('/admin/biens')]
#[Security("is_granted('ROLE_SUPER_ADMIN') or is_granted('ROLE_ADMIN')")]
class AdminBienController extends AbstractController
{
    public function __construct(
        private NotificationsInterface $notifications,
        private ManagersInterface $managers,
        private BiensHandle $handle,
        private BiensRepository $bienRepository
    ) {}

    #[Route('/', name: "admin.biens.index", methods: ['GET'])]
    /**
     * @param BiensRepository $bienRepository
     * @return Response
     */
    public function index(BiensRepository $biensRepository): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');

        $user = $this->getUser();

        // if ($this->isGranted('ROLE_SUPER_ADMIN')) {
        //     $properties = $propertiesRepository->getAll();
        // } else {
        //     $properties = $propertiesRepository->findBy([
        //         'companyId' => $user->getCompanyId()
        //     ]);
        // }

        return $this->render('admin/properties/biens/index.html.twig', [
            'biens' => $biensRepository->findAllOrderByCreationDesc(),
            'title' => 'Liste des biens',
            'libelle_ajouter' => 'Nouveau bien',
            'current_page' => 'biens',
            'current_global' => 'biens'
        ]);
    }

    #[Route('/new', name: "admin.biens.new", methods: ["GET", "POST"])]
    /**
     * @param Request $request
     * @return Response
     */
    public function new(Request $request): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $bien = new Bien();

        $form = $this->createForm(BienType::class, $bien, ['bien' => $bien]);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $bien->setCompanyId($this->getUser()->getCompanyId());
            $this->handle->handleBienForm($form);
            $this->addFlash("success", 'Bien ajouté avec succès.');
            return $this->redirectToRoute('admin.biens.index');
        }

        return $this->render('admin/properties/biens/new.html.twig', [
            'bien' => $bien,
            'form' => $form->createView(),
            'title' => 'Nouveau bien',
            'libelle_liste' => 'Liste des biens',
            'current_page' => 'bien_new',
            'current_global' => 'biens'
        ]);
    }


    #[Route('/{id<\d+>}/edit', name: "admin.biens.edit", methods: ["GET", "POST"])]
    /**
     * @param Request $request
     * @return Response
     */

    public function edit(Request $request, Bien $bien): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $form = $this->createForm(BienType::class, $bien, ['bien' => $bien]);
        $form->handleRequest($request);

        if ($form->isSubmitted()) {

            $this->handle->handleBienForm($form);
            $this->addFlash("success", 'Bien modifié avec succès.');
            return $this->redirectToRoute('admin.biens.index');
        }

        return $this->render('admin/properties/biens/edit.html.twig', [
            'bien' => $bien,
            'form' => $form->createView(),
            'title' => 'Editer le bien',
            'libelle_ajouter' => 'Nouveau bien',
            'libelle_liste' => 'Liste des biens',
            'current_page' => 'biens',
            'current_global' => 'biens'
        ]);
    }

    #[Route('/{id<\d+>}', name: "admin.biens.delete", methods: ['DELETE'])]
    /**
     * @param Request $request
     * @param Properties $propertie
     * @return Response
     */
    public function delete(Request $request, Bien $bien): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');

        if ($this->isCsrfTokenValid('delete' . $bien->getId(), $request->request->get('_token'))) {
            // Enregistrement de la notification
            $this->notifications->save(
                "Suppression du bien #{$bien->getName()}",
                "Suppression",
                $bien,
                "trash",
                "red",
                $this->getUser()->getCompanyId()
            );

            // Soft delete : on met deletedAt à maintenant
            $bien->setDeletedAt(new \DateTime());

            // Sauvegarde
            $this->managers->setEntity($bien, 'edit'); // ou flush directement via l'EntityManager

            $this->addFlash("success", 'Bien supprimé avec succès.');
        }

        $referer = $request->headers->get('referer');
        return new RedirectResponse($referer ?? $this->generateUrl('admin.biens.index'));
    }



    #[Route('/{id<\d+>}', name: "admin.biens.export", methods: ['GET'])]
    /**
     * @param Request $request
     * @param Properties $propertie
     * @return Response
     */
    public function export(Request $request, Demarcheur $demarcheur): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');


        $referer = $request->headers->get('referer');
        return new RedirectResponse($referer ?? $this->generateUrl('admin.biens.index'));
    }
}
