<?php

namespace App\Controller;

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



class UserController extends AbstractController
{
    private $passwordEncoder;

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


    /**
     * @Route("/profile", name="user_edit", methods={"GET","POST"})
     */
    public function edit(Request $request,UserPasswordEncoderInterface $encoder): Response
    {
        $user=$this->getUser();
        $em = $this->getDoctrine();
        $ins= $em->getRepository(Institution::class)->findOneBy(array("user" => $user));
        $Institution = $em->getRepository(Institution::class)->findOneBy(['user' => $user]);
       
        if ($request->isMethod('post')) {
          
            $data = $request->request->all();       
            $user->setEmail($data['email']);
            $email= $em->getRepository(User::class)->findOneBy(array("email" => $data['email']));
           

            $Institution->setInstitutionName($data['institutionName']);
            $institutionName= $em->getRepository(Institution::class)->findOneBy(array("institutionName" => $data['institutionName']));
         
            if ($data['password'] != "") {
                $user->setPassword($encoder->encodePassword($user,$data['password']));
            }
                $user->setPhoneNumber($data['phoneNumber']);
                $user->setCompany($data['company']);
                $user->setLicenceNumber($data['licenceNumber']);
                $user->setFirstOwnerName($data['firstOwnerName']);
                $user->setOtherOwnerName($data['otherOwnerName']);
                
                $user->setOfficeNumber($data['officeNumber']);
                $user->setCity($data['city']);
                $user->setProvince($data['province']);
                $user->setZipcode($data['zipcode']);
                $user->setFullAdress($data['fullAdress']);
                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->persist($user);
                $entityManager->flush();
                $Institution->setBankName($data['bankName']);
                $Institution->setFullName($data['fullName']);
                $Institution->setBankAdress($data['bankAdress']);
                $Institution->setBankAdress2($data['bankAdress2']);
                $Institution->setBankCity($data['bankCity']);
                $Institution->setBankProvince($data['bankProvince']);
                $Institution->setBankZip($data['bankZip']);
                $Institution->setBankCountry($data['bankCountry']);
                $Institution->setIban($data['iban']);
                $Institution->setSwift($data['swift']);
                $Institution->setTaxId($data['taxId']);
                $Institution->setTaxForm($data['taxForm']);
                $Institution->setDescription($data['description']);
                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->persist($Institution);
                $entityManager->flush();
            $files = $request->files->get('image');
                if(!empty($files))    {
                    $Photos = $this->getDoctrine()
                    ->getRepository(PhotoInstitution::class)
                    ->findBy(['institution' => $Institution,'Type'=>'optional']);
                foreach ($Photos as $index => $file) {
                    $entityManager = $this->getDoctrine()->getManager();
                    $entityManager->remove($file);
                    $entityManager->flush();
                }
            }
            foreach($files as $file)
            {
                if ($file) {
                    $originalFilenameFile=$file->getClientOriginalName();
                    $originalFilename = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
                    // this is needed to safely include the file name as part of the URL
                    $safeFilename=time();
                    $newFilename = $safeFilename . '-' . uniqid() . '.' . $file->guessExtension();

                    // Move the file to the directory where brochures are stored
                    try {
                        $file->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('optional');
                    $em = $this->getDoctrine()->getManager();
                    $em->persist($files);
                    $em->flush();
                }


            }
            $fileThumbil = $request->files->get('thumbail');
            if ($fileThumbil) {
                $Photo = $this->getDoctrine()
                ->getRepository(PhotoInstitution::class)
                ->findOneBy(['institution' => $Institution,'Type'=>'thumbelnail']);
                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->remove($Photo);
                $entityManager->flush();

                $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 updated!'); 

    }
        
    
        return $this->render('user/edit.html.twig', [
            'user' => $user,         
            'index' => $Institution,
            'institution' => $ins
        ]);
    }
    /**
     * @Route("/admin/profile", name="admin_edit", methods={"GET","POST"})
     */
    public function editadmin(Request $request, UserPasswordEncoderInterface $encoder): Response
    {
        $user = $this->getUser();
        $em = $this->getDoctrine();
        $ins= $em->getRepository(PhotoInstitution::class)->findOneBy(array("user" => $user));
        if ($request->isMethod('post')) {
            $data = $request->request->all();
            $user->setEmail($data['email']);
            $user->setUsername($data['username']);
            if ($data['password'] != "") {
                $user->setPassword($encoder->encodePassword($user,$data['password']));
            }
            $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
                }
                $user->setPhotoowner($newFilename);
            }
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();
        }
        return $this->render('user/editadmin.html.twig', [
            'user' => $user,
            'institution' => $ins

        ]);

    }
    /**
     * @Route("/sendemail", name="sendemail", methods={"GET","POST"})
     */
    public function sendemail(Request $request,\Swift_Mailer $mailer): Response
    {
        if ($request->isMethod('post')) {
            $data = $request->request->all();
            $user= $this->getDoctrine()
                ->getRepository(User::class)
                ->findOneBy(['email' =>$data['email']]);
            if (!empty($user)){
            if($user->getRoles()[0]=='ROLE_INSTITUTION'){
                $em = $this->getDoctrine()->getManager();
                $random = sha1(random_bytes(120));
                $user->setTokenPassword($random);
                $em->persist($user);
                $em->flush();
                $message = (new \Swift_Message('Reset password'))
                    ->setFrom("contact@drooob.net")
                    ->setTo($user->getEmail())
                    ->setBody(
                        $this->renderView(
                        // templates/emails/registration.html.twig
                            'email/password.html.twig',
                            ['token' => $random]
                        )

                        ,"text/html")
                ;
                $mailer->send($message);

            }
            return $this->render('login/email.html.twig', [
                'email'=>true
            ]);
            }
        }
        return $this->render('login/email.html.twig', [
        ]);

    }

    /**
     * @Route("/changepassword", name="changepassword", methods={"GET","POST"})
     */
    public function changepassword(Request $request, UserPasswordEncoderInterface $encoder): Response
    {

        $token= $request->get('token');
        if ($request->isMethod('post')) {
            $data = $request->request->all();

            $user = $this->getDoctrine()
                ->getRepository(User::class)
                ->findOneBy(['tokenPassword' => $token]);

            if ($data['password'] != "") {
                $user->setPassword($encoder->encodePassword($user, $data['password']));
            }
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($user);
            $entityManager->flush();
            return $this->redirectToRoute('login');

        }
        return $this->render('login/editpassword.html.twig', [

        ]);

    }


}
