<?php

namespace App\Controller;

use App\Entity\User;
use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;

/**
 * Class UserController
 * @package App\Controller
 */
class UserController extends AbstractController
{
	/**
	 * @param \App\Repository\UserRepository $userRepository
	 * @param string                         $userName
	 *
	 * @return \Symfony\Component\HttpFoundation\Response
	 */
	#[Route(path: '/profile/edit/{username}', name: 'app_profile_edit')]
	public function editProfile(UserRepository $userRepository, string $username = ''): Response
	{
		/** var User $user */
		if ($username === '') {
			if ($this->isGranted(attribute: 'ROLE_USER')) {
				$user = $this->getUser();
			} else {
				throw new AccessDeniedException(message: 'You need to be logged in.');
			}
		} else {
			if ($this->isGranted(attribute: 'ROLE_ADMIN')) {
				$user = $userRepository->findOneBy([
					"username" => $username
				]);
			}
		}
		
		if (isset($user)) {
			return $this->render(view: 'user/edit_profile.html.twig', parameters: [
				'user' => $user,
			]);
		} else {
			throw new UserNotFoundException();
		}
	}
	
	/**
	 * @param \App\Repository\UserRepository $userRepository
	 * @param string                         $username
	 *
	 * @return \Symfony\Component\HttpFoundation\Response
	 */
	#[Route(path: '/profile/{username}', name: 'app_profile')]
	public function showProfile(UserRepository $userRepository, string $username = ''): Response
	{
		/** var User $user */
		if ($username === '') {
			$user = $this->getUser();
		} else {
			$user = $userRepository->findOneBy([
				"username" => $username
			]);
		}
		
		return $this->render(view: 'user/show_profile.html.twig', parameters: [
			'user' => $user,
		]);
	}
	
}
