/**
  * @Route(path="/import", name="cva_membership_payments_import")
  * @param Request $request
  * @return \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  */
 public function importAction(Request $request)
 {
     if ($request->isMethod('POST')) {
         $out = "";
         $var = $request->request->get('students');
         $em = $this->get('doctrine.orm.entity_manager');
         $em->beginTransaction();
         $product = $em->getRepository("CvaGestionMembreBundle:Produit")->getCurrentVA()[0];
         $out .= '<b>Importation de ' . count($var) . ' étudiant(s) :</b><br>';
         if ($var != null) {
             foreach ($var as $student) {
                 if ($student['student'] == '') {
                     $out .= '<span class="text-error">' . $student['firstname'] . ' ' . $student['lastname'] . ' (' . $student['mail'] . ') est déjà adhérant</span><br>';
                     continue;
                 }
                 $new = false;
                 $r = $em->getRepository("CvaGestionMembreBundle:Etudiant")->findOneBy(array('numEtudiant' => $student['student']));
                 if ($r == null) {
                     $r = new Etudiant();
                     $r->setFirstName($student['firstname']);
                     $r->setName($student['lastname']);
                     $r->setCivilite($student['sex']);
                     $r->setMail($student['mail']);
                     $r->setNumEtudiant($student['student']);
                     if ($student['birthday'] != null) {
                         $birthday = new \DateTime();
                         $birthday->setTimestamp(strtotime($student['birthday']));
                         $r->setBirthday($birthday);
                     }
                     $new = true;
                 } else {
                     $c = $em->getRepository("CvaGestionMembreBundle:Payment")->createQueryBuilder('p')->select('COUNT(p.id)')->where('p.student = ?1')->andWhere('p.product IN (?2)')->setParameter(1, $r)->setParameter(2, $em->getRepository("CvaGestionMembreBundle:Produit")->getCurrentVAIds())->getQuery()->getSingleScalarResult();
                     if ($c > 0) {
                         $out .= '<span class="text-warning">' . $r . ' (' . $r->getNumEtudiant() . ') est déjà adhérant</span><br>';
                         continue;
                     }
                 }
                 $r->setAnnee($student['year']);
                 $r->setDepartement($student['depart']);
                 $em->persist($r);
                 $payment = Payment::generate($r, $product, $student['payment']);
                 $em->persist($payment);
                 $out .= '<span class="text-' . ($new ? 'success' : 'info') . '">' . $r . ' (' . $r->getNumEtudiant() . ')' . ($new ? ' a été créé et' : '') . ' a acheté le produit ' . $product->getName() . '</span><br>';
             }
         }
         $em->flush();
         $em->commit();
         return $this->render("CvaGestionMembreBundle:Payments:importResult.html.twig", array('out' => $out));
     } else {
         return $this->render("CvaGestionMembreBundle:Payments:import.html.twig");
     }
 }
 /**
  * @Route(path="/student/{id}", name="wizard_student")
  * @param Request $request
  * @return \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  */
 public function studentAction($id, Request $request)
 {
     $em = $this->get('doctrine.orm.entity_manager');
     $students = $em->getRepository("CvaGestionMembreBundle:Etudiant");
     if ($id == "new") {
         $student = new Etudiant();
         $student->setDepartement("PC");
     } else {
         $student = $students->find($id);
         if (!$student) {
             throw $this->createNotFoundException('Not found student ' . $id);
         }
     }
     $preRegisteredForWEI = $this->_is_preregistered_for_wei($student) || $student->hasProduct($em->getRepository("CvaGestionMembreBundle:Produit")->getCurrentWEI()) || $student->hasProduct($em->getRepository("CvaGestionMembreBundle:Produit")->getCurrentWEIWaiting());
     $formBuilder = $this->createFormBuilder();
     $formBuilder->add('student', new StudentType(), array('label' => false, 'data' => $student));
     $hasVa = $this->get("bde.va_check")->checkVA($student);
     $hasWei = $student->hasProduct($em->getRepository("CvaGestionMembreBundle:Produit")->getCurrentWEI()) || $student->hasProduct($em->getRepository("CvaGestionMembreBundle:Produit")->getCurrentWEIWaiting());
     if (!$hasVa) {
         $formBuilder->add('wei', 'choice', ["label" => "WEI", "choices" => ["WEI" => $preRegisteredForWEI ? "Confirme qu'il vient au WEI" : "Veut s'inscrire au WEI", "NOWEI" => $preRegisteredForWEI ? "Ne veut plus aller au WEI" : "Ne veut pas s'inscrire au WEI"], "expanded" => true, 'required' => true, "multiple" => false, 'data' => $preRegisteredForWEI ? "WEI" : "NOWEI", 'disabled' => $hasWei]);
         $formBuilder->add('va', 'choice', ["label" => "Adhesion VA", "choices" => ["VA" => "Veut adhérer à la VA", "NOVA" => "Ne veut pas adhérer à la VA"], "expanded" => true, 'required' => true, "multiple" => false, "disabled" => $this->get("bde.va_check")->checkVA($student), 'data' => "VA"]);
         $formBuilder->add('methodPayment', 'choice', array('choices' => array('CHQ' => 'Cheque', 'CB' => 'Carte Bancaire', 'ESP' => 'Espèces'), 'mapped' => true, 'required' => true, 'expanded' => true, "disabled" => $this->get("bde.va_check")->checkVA($student), 'label' => "Moyen de paiement", 'data' => 'CHQ'));
     }
     $formBuilder->add('target', 'hidden');
     $form = $formBuilder->getForm();
     $form->handleRequest($request);
     if ($form->isValid()) {
         $data = $form->getData();
         /** @var Etudiant $student */
         $student = $data['student'];
         if ($student->getAnnee() == '1' || $student->getAnnee() == '2') {
             $student->setDepartement('PC');
             $this->addFlash('info', "L'étudiant a été réaffecté en Premier Cycle car il est en 1A ou 2A");
         }
         $em->persist($student);
         $em->flush();
         $wantWei = isset($data['wei']) ? $data['wei'] == 'WEI' && !$hasWei : false;
         $wantVA = isset($data['va']) ? $data['va'] == 'VA' && !$hasVa : false;
         $methodPayement = $data['methodPayment'];
         if (!$wantVA && !$this->get("bde.va_check")->checkVA($student)) {
             $this->addFlash("warning", "L'Etudiant a refusé l'adhésion VA !");
         } else {
             if ($wantVA) {
                 $va = null;
                 if (!$this->get("bde.va_check")->checkVA($student)) {
                     // if the current user is not VA
                     if ($student->getAnnee() == '1') {
                         $va = $em->getRepository("CvaGestionMembreBundle:Produit")->getVAProduct('B');
                     } else {
                         $va = $em->getRepository("CvaGestionMembreBundle:Produit")->getVAProduct('A');
                     }
                     $paymentVA = Payment::generate($student, $va, $methodPayement);
                     $em->persist($paymentVA);
                 }
                 if ($wantWei && $student->getAnnee() == '1') {
                     $this->get("bde.wei.registration_management")->register($student, $methodPayement);
                 } elseif ($student->getAnnee() == '1') {
                     $this->get("bde.wei.registration_management")->unregister($student);
                 }
                 $em->flush();
             }
         }
         return $this->redirectToRoute("wizard_student_abstract", array('id' => $student->getId()));
     }
     $products = $em->getRepository("CvaGestionMembreBundle:Produit")->createQueryBuilder('p')->where('p.active = true')->getQuery()->getArrayResult();
     $productsIndexed = [];
     foreach ($products as $product) {
         if (isset($product['name'])) {
             $productsIndexed[$product['name']] = $product;
         }
     }
     return $this->render("CvaGestionMembreBundle:Wizard:edit.html.twig", array('form' => $form->createView(), 'products' => $productsIndexed, 'va' => $this->get('bde.va_check'), 'student' => $student));
 }
 /**
  * Unregister a student from the WEI.
  * This function will look for all products related to the WEI and will refund it, if it's not.
  * @param Etudiant $student The student to refund
  */
 public function unregister(Etudiant $student)
 {
     $products = $this->em->getRepository("CvaGestionMembreBundle:Produit");
     $weiWithoutRefundProducts = [$products->getCurrentWEIPreWaiting(), $products->getCurrentWEIPreInscription()];
     $weiWithRefundProducts = [$products->getCurrentWEI(), $products->getCurrentWEIWaiting()];
     if ($student->hasProduct($products->getCurrentWEIRemboursement())) {
         return;
     }
     foreach ($student->getPayments() as $payment) {
         if (in_array($payment->getProduct(), $weiWithoutRefundProducts)) {
             $this->em->remove($payment);
             if ($payment->getProduct()->hasWaitingList()) {
                 $this->removeFromWaitingList($student, $payment->getProduct());
             }
         } elseif (in_array($payment->getProduct(), $weiWithRefundProducts)) {
             if ($payment->getProduct()->hasWaitingList()) {
                 $this->removeFromWaitingList($student, $payment->getProduct());
             }
             $payment = Payment::generate($student, $products->getCurrentWEIRemboursement());
             $this->em->persist($payment);
         }
     }
     $this->em->flush();
 }