<?php

namespace App\Controller;

use App\Entity\User;
use App\Form\User\Settings\ProfileType;
use App\Form\User\Settings\SecurityType;
use App\Service\UploaderService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

#[Route('/settings')]
final class SettingsController extends AbstractController
{
    #[Route('', name: 'app_settings')]
    public function index(): Response
    {
        return $this->redirectToRoute('app_settings_profile');
    }

    #[Route('/profile', name: 'app_settings_profile')]
    public function profile(Request $request, EntityManagerInterface $em,#[currentUser] User $user, UploaderService $uploaderService): Response
    {
        $form = $this->createForm(ProfileType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            /** @var UploadedFile $photo */
            $photo = $form->get('profile_picture_file')->getData();
            $nomPhoto = null;
            if ($photo) {
                $nomPhoto = $uploaderService->upload($photo, UploaderService::DIR_PP);
            }
            else if ($form->get('uri_pp')->getData()) {
                $nomPhoto = $form->get('uri_pp')->getData();
            }
            if ($nomPhoto) {
                if (!$user->hasURLpp() && $user->getUriPp()){
                    // Supprimer l'ancienne photo si elle existe et n'est pas une URL
                    $uploaderService->delete($user->getUriPp(), UploaderService::DIR_PP);
                }
                $user->setUriPp($nomPhoto);
            }
            $em->persist($user);
            $em->flush();
            $this->addFlash('success', 'Profil mis à jour avec succès.');
            return $this->redirectToRoute('app_settings_profile');
        }

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

    #[Route('/security', name: 'app_settings_security')]
    public function security(Request $request, EntityManagerInterface $em,#[currentUser] User $user,UserPasswordHasherInterface $passwordHasher): Response
    {
        $form = $this->createForm(SecurityType::class);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            if (!password_verify($form->get('current_password')->getData(), $user->getPassword())) {
                $this->addFlash('danger', 'Mot de passe actuel incorrect.');
                return $this->redirectToRoute('app_settings_security');
            }

            if ($form->get('new_password')->getData() !== $form->get('new_password_confirmation')->getData()) {
                $this->addFlash('danger', 'Les mots de passe ne correspondent pas.');
                return $this->redirectToRoute('app_settings_security');
            }

            if ($form->get('new_password')->getData() === $form->get('current_password')->getData()){
                $this->addFlash('danger', 'Le nouveau mot de passe doit être différent de l\'ancien.');
                return $this->redirectToRoute('app_settings_security');
            }

            $hash = $passwordHasher->hashPassword($user, $form->get('new_password')->getData());
            $user->setPassword($hash);
            $user->setDefaultPwd(false);
            $em->persist($user);
            $em->flush();
            $this->addFlash("success","Mot de passe mis à jour avec succès.");
             return $this->redirectToRoute('app_settings_security');


        }

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