<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;
use Doctrine\ORM\EntityManagerInterface;

class ProfileController extends AbstractController
{
    #[Route('/profile', name: 'app_profile')]
    public function index(): Response
    {
        return $this->render('profile/index.html.twig', [
            'controller_name' => 'ProfileController',
        ]);
    }

    #[Route('/changepasswd', name: 'app_change_passwd')]
    public function changePassword(Request $request, UserPasswordHasherInterface $hasher, EntityManagerInterface $entityManager): Response
    {
        $current = $request->getPayload()->get('_current_pass');
        $new = $request->getPayload()->get('_new_pass');
        $confirm = $request->getPayload()->get('_confirm_pass');
        $user = $this->getUser();

        if(! $hasher->isPasswordValid($user, $current)) {
            $this->addFlash('error', 'The current password is incorrect');
            return $this->redirectToRoute('app_profile');
        }

        if ($new !== $confirm) {
            $this->addFlash('error', 'The new password and the confirmation password don\'t match');
            return $this->redirectToRoute('app_profile');
        }

        $hashed = $hasher->hashPassword($user, $new);
        $user->setPassword($hashed);

        $entityManager->persist($user);
        $entityManager->flush();

        $this->addFlash('notice', 'Password updated successfully');

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