<?php

namespace App\Controller\Admin;

use App\Entity\User;
use App\Service\KeycloakAdminService;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
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\IsGranted;

#[Route('/admin/profil', name: 'app_admin_profil')]
#[IsGranted('ROLE_EMPLOYE')]
class ProfilController extends AbstractController
{
    public function __construct(
        private LoggerInterface $logger,
    ) {
    }

    #[Route('', name: '')]
    public function index(): Response
    {
        return $this->render('admin/profil/index.html.twig');
    }

    #[Route('/password', name: '_password', methods: ['POST'])]
    public function password(
        Request $request,
        UserPasswordHasherInterface $passwordHasher,
        EntityManagerInterface $em,
        KeycloakAdminService $keycloak,
    ): Response {
        /** @var User $user */
        $user = $this->getUser();

        $currentPassword = $request->request->getString('current_password');
        $newPassword = $request->request->getString('new_password');
        $confirmPassword = $request->request->getString('confirm_password');

        if (!$passwordHasher->isPasswordValid($user, $currentPassword)) {
            $this->addFlash('error', 'Le mot de passe actuel est incorrect.');
        } elseif (\strlen($newPassword) < 8) {
            $this->addFlash('error', 'Le nouveau mot de passe doit contenir au moins 8 caracteres.');
        } elseif ($newPassword !== $confirmPassword) {
            $this->addFlash('error', 'Les mots de passe ne correspondent pas.');
        } else {
            // Mettre à jour en BDD
            $user->setPassword($passwordHasher->hashPassword($user, $newPassword));
            $user->clearTempPassword();
            $em->flush();

            // Mettre à jour dans Keycloak si compte lié
            if (null !== $user->getKeycloakId()) {
                try {
                    $keycloak->resetPassword($user->getKeycloakId(), $newPassword);
                } catch (\Throwable $e) {
                    $this->logger->error('Keycloak: Failed to reset password for user '.$user->getUserIdentifier().': '.$e->getMessage());
                }
            }

            $this->addFlash('success', 'Mot de passe modifie avec succes.');
        }

        return $this->redirectToRoute('app_admin_profil');
    }

    #[Route('/update', name: '_update', methods: ['POST'])]
    #[IsGranted('ROLE_ROOT')]
    public function update(Request $request, EntityManagerInterface $em, KeycloakAdminService $keycloak): Response
    {
        /** @var User $user */
        $user = $this->getUser();

        $firstName = trim($request->request->getString('firstName'));
        $lastName = trim($request->request->getString('lastName'));
        $email = trim($request->request->getString('email'));

        if ('' === $firstName || '' === $lastName || '' === $email) {
            $this->addFlash('error', 'Tous les champs sont requis.');
        } else {
            $user->setFirstName($firstName);
            $user->setLastName($lastName);
            $user->setEmail($email);
            $em->flush();

            // Sync Keycloak
            if (null !== $user->getKeycloakId()) {
                try {
                    $keycloak->updateUser($user->getKeycloakId(), $firstName, $lastName, $email);
                } catch (\Throwable $e) {
                    $this->logger->error('Keycloak: Failed to update user '.$email.': '.$e->getMessage());
                }
            }

            $this->addFlash('success', 'Informations mises a jour.');
        }

        return $this->redirectToRoute('app_admin_profil');
    }

    #[Route('/avatar', name: '_avatar', methods: ['POST'])]
    public function avatar(Request $request, EntityManagerInterface $em): Response
    {
        /** @var User $user */
        $user = $this->getUser();

        $file = $request->files->get('avatar');

        if (null === $file) {
            $this->addFlash('error', 'Aucun fichier selectionne.');

            return $this->redirectToRoute('app_admin_profil');
        }

        $user->setAvatarFile($file);
        $em->flush();

        $this->addFlash('success', 'Avatar mis a jour.');

        return $this->redirectToRoute('app_admin_profil');
    }

    #[Route('/avatar/delete', name: '_avatar_delete', methods: ['POST'])]
    public function avatarDelete(EntityManagerInterface $em): Response
    {
        /** @var User $user */
        $user = $this->getUser();

        $user->setAvatarFile(null);
        $user->setAvatar(null);
        $em->flush();

        $this->addFlash('success', 'Avatar supprime.');

        return $this->redirectToRoute('app_admin_profil');
    }
}
