<?php

namespace App\Controller;
use App\Entity\User;
use App\Entity\Institution;
use App\Entity\PhotoInstitution;
use App\Repository\UserRepository;
use App\Form\UserType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\HttpFoundation\Response;

class RegistrationController extends AbstractController
{
    private $passwordEncoder;

    public function __construct(UserPasswordEncoderInterface $passwordEncoder)
    {
        $this->passwordEncoder = $passwordEncoder;
    }

    /**
     * @Route("/registration", name="registration")
     */
    public function index(Request $request,UserRepository $userRepository): Response
    {
        if ($request->isMethod('post')) {
            $data = $request->request->all();
             $user = new User();  
            $user->setPassword($this->passwordEncoder ->encodePassword($user, $data['password']));

            // Set their role
            $user->setRoles(json_encode(['ROLE_INSTITUTION']));
            //$user->setRoles(['ROLE_USER']);
           
            $user->setUsername($data['username']);
            $em = $this->getDoctrine();
            $username= $em->getRepository(User::class)->findOneBy(array("username" => $data['username']));
            $user->setEmail($data['email']);
            $email= $em->getRepository(User::class)->findOneBy(array("email" => $data['email']));
            $user->setPhoneNumber($data['phoneNumber']);
            $user->setFullAdress($data['fullAdress']);
           
            $institution = new Institution();
            $institution->setInstitutionName($data['institutionName']);
            $institutionName= $em->getRepository(Institution::class)->findOneBy(array("institutionName" => $data['institutionName']));
           
            if (!$username && !$email && !$institutionName) {
              
                $em = $this->getDoctrine()->getManager();
                $em->persist($user);
                $institution->setUser($user);
                $institution->setWallet(0);
                $em = $this->getDoctrine()->getManager();
                $em->persist($institution);
                $em->flush();                
            
            $fileThumbil = $request->files->get('thumbail');
            if ($fileThumbil) {
                $originalFilenameFile=$fileThumbil->getClientOriginalName();
                $originalFilename = pathinfo($fileThumbil->getClientOriginalName(), PATHINFO_FILENAME);
                // this is needed to safely include the file name as part of the URL

                $safeFilename=time();

                $newFilename = $safeFilename . '-' . uniqid() . '.' . $fileThumbil->guessExtension();

                // Move the file to the directory where brochures are stored
                try {
                    $fileThumbil->move(
                        $this->getParameter('files_directory'),
                        $newFilename
                    );
                } catch (FileException $e) {
                    // ... handle exception if something happens during file upload
                }
                $files= new PhotoInstitution() ;
                $files->setPath($newFilename);
                $files->setInstitution($institution);
                $files->setType('thumbelnail');
                $em = $this->getDoctrine()->getManager();
                $em->persist($files);
                $em->flush();
            } 
            $this->addFlash('success', 'Institution Created!');       
            return $this->redirectToRoute('login');
        } else {
            $this->get('session')->getFlashBag()->add('error', 'username or email Exist');
            //$this->addFlash('success', 'username or email exit!.');

        }
      
    }
    return $this->render('registration/index.html.twig');
}

}
