<?php
/**
 * Created by PhpStorm.
 * User: hicham benkachoud
 * Date: 06/01/2020
 * Time: 20:39
 */

namespace App\Controller;


use App\Entity\Buy;
use App\Entity\Cource;
use App\Entity\User;
use App\Entity\Panier;
use App\Entity\Institution;
use App\Entity\Participant;
use App\Entity\Withdraw;
use App\Entity\Amount;
use App\Entity\PhotoCource;
use App\Form\CourceType;
use App\Entity\PhotoInstitution;
use App\Repository\BuyRepository;
use App\Repository\CourceRepository;
use App\Repository\InstitutionRepository;
use App\Repository\ParticipantRepository;
use App\Repository\WithdrawRepository;
use Lexik\Bundle\JWTAuthenticationBundle\Services\JWTTokenManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\User\UserInterface;

class StudentController extends ApiController
{
    /**
     * @Route("/verifystudent", name="student")
     */
    public function student()
    {
        $em = $this->getDoctrine();
        $institution= $em->getRepository(Institution::class)->findOneBy(array("user" =>  $this->getUser()));
        return $this->render('student/index.html.twig',[
            'institution' => $institution
        ]);
    }
    /**
     * @Route("/cleverif/{cle}", name="cleverif")
     */
    public function cleverif($cle)
    {
        $buy= $this->getDoctrine()
            ->getRepository(Buy::class)
            ->findOneBy(['cle' =>$cle]);
        if (!empty($buy) ){
            if( $buy->getStatut()==1)
                    return new JsonResponse(array("resultat"=>'true','date'=>$buy->getDate()->format('d/m/yy')));
            else{
                    $buy->setStatut(1);
                    $em = $this->getDoctrine()->getManager();
                    $em->persist($buy);
                    $em->flush();
                    return new JsonResponse(array("resultat"=>'update','date'=>$buy->getDate()->format('d/m/yy')));
            }
        }
        else
            return new JsonResponse(array("resultat"=>'false'));
//        return $this->render('student/buy.html.twig',array("buy"=>$buy));
    }
    /**
     * @Route("/cleverifcontent/{cle}", name="cleverifcontent")
     */
    public function cleverifcontent($cle)
    {
        $buy= $this->getDoctrine()
            ->getRepository(Buy::class)
            ->findOneBy(['cle' =>$cle]);
        return $this->render('student/buy.html.twig',array("buy"=>$buy));
    }
    /**
     * @Route("/home", name="app_home")
     */
    public function home(CourceRepository $courceRepository)
    {
        $user=$this->getUser();
        $em = $this->getDoctrine();
        $institution= $em->getRepository(Institution::class)->findOneBy(array("user" => $user));
        $courses = $this->getDoctrine()
            ->getRepository(Cource::class)
            ->findBy(['Institution' => $institution]);        $total=0;
        foreach ($courses as $index => $cours) {
            $total+=($cours->getBuy()->count()*$cours->getPrice());
        }
        return $this->render('home.html.twig', [
            'total' =>$total,
            'cources' =>$courses,
            'institution' => $institution
        ]);
    }
    /**
     * @Route("/admin/home", name="admin_home")
     */
    public function homeadmin(CourceRepository $courceRepository , WithdrawRepository $withdrawRepository,InstitutionRepository $institutionRepository)
    {
        $user=$this->getUser();
        $em = $this->getDoctrine();
        $institution= $em->getRepository(Institution::class)->findOneBy(array("user" => $user));
        $ins= $em->getRepository(PhotoInstitution::class)->findOneBy(array("user" => $user));
        $amount= $em->getRepository(Amount::class)->findOneBy(array("id" => 1));
        $user= $em->getRepository(Institution::class)->findAll();
        $withdraw= $em->getRepository(Withdraw::class)->findAll();
        $courses = $this->getDoctrine()
            ->getRepository(Cource::class)
            ->findBy(['Institution' => $institution]);        $total=0;
        foreach ($courses as $index => $cours) {
          
            $total+=($cours->getBuy()->count()*$cours->getPrice());
        }
        return $this->render('homeadmin.html.twig', [
            'total' =>$total,
            'cources' =>$courses,
            'withdraw' => $withdraw,
            'data' => $amount,
            'institution' => $ins,
            'notActive' =>$institutionRepository->findBy(['islogin' => '0'])
        ]);
    }
    /**
     * @Route("/admin/courses", name="admin_courses")
     */
    public function indexCourses(CourceRepository $courceRepository,BuyRepository $institutionRepository,ParticipantRepository $participantRepository): Response
    {
        $user=$this->getUser();
        $em = $this->getDoctrine();
        $institution= $em->getRepository(Institution::class)->findOneBy(array("user" => $user));
            $cources = $this->getDoctrine()
            ->getRepository(Cource::class)
            ->findAll(); 
        foreach($cources as $index => $cource)
            {
                 $date = new \DateTime('now');
                 $dateEnd = $cource->getCourseEnd();
                 $interval =  date_diff($dateEnd, $date);
                 if($interval->format('%R%a') > +3){
                    $photos = $this->getDoctrine()
                    ->getRepository(PhotoCource::class)
                    ->findBy(['Cource' => $cource]);
                foreach ($photos as $index => $photo) {
                    $entityManager = $this->getDoctrine()->getManager();
                    $entityManager->remove($photo);
                    $entityManager->flush();
                }
                $paniers= $this->getDoctrine()
                    ->getRepository(Panier::class)
                    ->findBy(['Cource' => $cource]);
                foreach ($paniers as $index => $panier) {
                    $entityManager = $this->getDoctrine()->getManager();
                    $entityManager->remove($panier);
                    $entityManager->flush();
                }

                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->remove($cource);
                $entityManager->flush();
            }
        }
        $cources = $this->getDoctrine()
            ->getRepository(Cource::class)
            ->findAll();

        return $this->render('admin/courses.html.twig', [
            'cources' => $cources,
            'institution' => $institution
        ]);

    }
    /**
     * @Route("/{id}", name="cource_delete_admin", methods={"DELETE"})
     */
    public function deleteCource(Request $request, Cource $cource): Response
    {
        if ($this->isCsrfTokenValid('delete'.$cource->getId(), $request->request->get('_token'))) {
            $photos = $this->getDoctrine()
                ->getRepository(PhotoCource::class)
                ->findBy(['Cource' => $cource]);
            foreach ($photos as $index => $photo) {
                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->remove($photo);
                $entityManager->flush();
            }
            $paniers= $this->getDoctrine()
                ->getRepository(Panier::class)
                ->findBy(['Cource' => $cource]);
            foreach ($paniers as $index => $panier) {
                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->remove($panier);
                $entityManager->flush();
            }

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($cource);
            $entityManager->flush();
        }

        return $this->redirectToRoute('admin_courses');
    }
     /**
     * @Route("/activeInst/{id}/{action}", name="activeInst")
     */
    public function activeInstitution($id,$action)
    {
        $User= $this->getDoctrine()
            ->getRepository(User::class)
            ->find($id);
            dump($User);
        $entityManager = $this->getDoctrine()->getManager();
        $institution= $entityManager->getRepository(Institution::class)->findOneBy(array("user" => $User));
        $User->setIsactive($action);
        $institution->setIslogin(1);  
        $entityManager->persist($User);
        $entityManager->persist($institution);
        $entityManager->flush();

        return $this->redirectToRoute('admin_home');

    }
    /**
     * @Route("/wallet", name="wallet")
     */
    public function wallet(BuyRepository $buyRepository,InstitutionRepository $institutionRepository,WithdrawRepository $withdrawRepository)
    {  
        $institutions = $institutionRepository->findInstitutionByUser($this->getUser());
        $user=$this->getUser();
        $em = $this->getDoctrine();
        $institution= $em->getRepository(Institution::class)->findOneBy(array("user" => $user));
        $withdraw = $withdrawRepository->findWithdrawByInstitution($institutions);
        $courses = $this->getDoctrine()
            ->getRepository(Cource::class)
            ->findBy(['Institution' => $institution]);
        $em = $this->getDoctrine();
        $inst= $em->getRepository(Institution::class)->findOneBy(array("user" => $this->getUser()));
        $amount= $em->getRepository(Amount::class)->findOneBy(array("id" => 1));
        $buys= $buyRepository->findAll();
       
        return $this->render('wallet.html.twig', [
            
            'cources' =>$courses,
            'buy' =>$buys,
            'institution' => $inst ,
            'insti' => $institutions ,
            'withdraw' => $withdraw ,
            'data' => $amount
        ]);
    }
    /**
     * @Route("/admin/withdraw/{id}/{idW}", name="withdrawEdit")
     */
    public function editWithdraw(Request $request,InstitutionRepository $institutionRepository,WithdrawRepository $withdrawRepository,$id,$idW)
    {
        $em = $this->getDoctrine();
        $institution= $em->getRepository(Institution::class)->findOneBy(array("id" => $id));
        $withdraw = $em->getRepository(Withdraw::class)->findOneBy(array("id" => $idW));
        $amount = $this->getDoctrine()
        ->getRepository(Amount::class)
        ->find(1);
       
        $entityManager = $this->getDoctrine()->getManager();
        $withdraw->setStatut(true);
        $institution->setWallet(0);
        $amount->setTotal($amount->getTotal() - $withdraw->getAmount());
        $entityManager->persist($institution);
        $entityManager->persist($withdraw);
        $entityManager->persist($amount);
        $entityManager->flush();
        return $this->redirectToRoute('admin_home');      
    }
    /**
     * @Route("/editWallet/{id}", name="updateWallet")
     */
    public function editWallet(Request $request,$id)
    {
        $amount = $this->getDoctrine()
        ->getRepository(Amount::class)
        ->findOneBy(array("id" => $id));
        $entityManager = $this->getDoctrine()->getManager();
        $amount->setEarnings(0);      
        $entityManager->persist($amount);
        $entityManager->flush();
        return $this->redirectToRoute('admin_home');      
    }

    /**
     * @Route("/withdraw/{wallet}", name="withdraw")
     */
    public function addWithdraw(Request $request,InstitutionRepository $institutionRepository,$wallet,UserPasswordEncoderInterface $encoder)
    {
        $user=$this->getUser();
        $em = $this->getDoctrine();
        $institution= $em->getRepository(Institution::class)->findOneBy(array("user" => $user));
        $data = $request->request->all(); 
        $match = $encoder->isPasswordValid($user,$data['password']);
        if($match){
            $withdraw = new Withdraw();
            $date = new \DateTime('now');
            $body = 'Earnings payout request #'.rand(10,100) ;
            $entityManager = $this->getDoctrine()->getManager();
            $withdraw->setInstitution($institution);
            $withdraw->setRequest($body);
            $withdraw->setAmount($wallet);
            $withdraw->setStatut(0);
            $withdraw->setDate($date);       
            $entityManager->persist($withdraw);
            $entityManager->flush();
            return $this->redirectToRoute('wallet');
        } else {
            return $this->respondValidationError("Invalid  password");
        }        
        
    }
    /**
     * @Route("/amounts/{id}", name="amounts")
     */
    public function addAmounts(Request $request,$id)
    {
        $em = $this->getDoctrine();
        $amount= $em->getRepository(Amount::class)->findOneBy(array("id" => $id));
        if ($request->isMethod('post')) {
            $data = $request->request->all(); 
            //$amount = new Amount();
            $entityManager = $this->getDoctrine()->getManager();
            $amount->setMinimum($data['minimum']);
            $amount->setPourcentage($data['pourcentage']);
            $entityManager->persist($amount);
            $entityManager->flush();
            return $this->redirectToRoute('admin_home');
        }
        return $this->render('homeadmin.html.twig', [
            'data' =>$data,
        ]);      
        
    }

}
