/**
 * @Route("/waivers/{id}/addPassenger", name="waiverBundle_add_passenger", requirements={"id" = "\d+"})
 * @Method("POST")
 * @Template()
 */
 public function addPassengerAction(Request $request, $id)
 {
     if ($this->get('security.authorization_checker')->isGranted('ROLE_WAIVER_REQUEST')) {
         /*
          * GET WAIVER FROM DB
          */
         $em = $this->getDoctrine()->getManager();
         $waiver = $em->getRepository('WaiverBundle:Waiver')->find($id);
         /*
          * IF WAIVER IS NEITHER REJECTED NOR CLOSED NOR CANCELED
          * && WAIVER IS OPEN OR REOPENED
          */
         if (!$waiver->isRejected() && !$waiver->getClosed() && ($waiver->isOpen() || $waiver->isReopened())) {
             // Add passengers
             if (isset($_POST['passengers'])) {
                 $em = $this->getDoctrine()->getManager();
                 $passengers = $_POST['passengers'];
                 $zl = 0;
                 foreach ($passengers['firstName'] as $firstName) {
                     $passenger = new \WaiverBundle\Entity\Passenger();
                     $passenger->setFirstName($firstName);
                     $passenger->setLastName($passengers['lastName'][$zl]);
                     $passenger->setWaiver($waiver);
                     $em->persist($passenger);
                     ++$zl;
                 }
                 $fundDeducted = $waiver->getReasonCode()->getFundstobededucted();
                 $fundAgency = $waiver->getAgency()->getFund()->getAccountAmount();
                 if ($fundDeducted * $zl > $fundAgency) {
                     $this->addFlash('danger', 'You dont have enough funds for this waiver!');
                     $response = new RedirectResponse($this->get('router')->generate('waiverBundle_show_waiver', array("code" => 100, "success" => true, 'id' => $waiver->getId())) . '#passengers');
                     $response->send();
                 } else {
                     $findCurrentAmount = $fundAgency - $fundDeducted * $zl;
                     $agencyFund = $waiver->getAgency()->getFund();
                     $agencyFund->setAccountAmount($findCurrentAmount);
                     // Persist to DB
                     $em->flush();
                 }
             }
             /*
              * REDERICT TO THE UPDATED WAIVER PROFILE
              */
             $response = new RedirectResponse($this->get('router')->generate('waiverBundle_show_waiver', array('id' => $waiver->getId())) . '#passengers');
             $response->send();
         } else {
             /*
              * REDERICT TO THE UPDATED WAIVER PROFILE
              */
             $response = new RedirectResponse($this->get('router')->generate('waiverBundle_show_waiver', array('id' => $waiver->getId())));
             $response->send();
         }
     } else {
         /*
          * THROW ERROR
          * If the acting user is not allowed to perform this action
          */
         $error_msg = 'error.access.action';
         // Error message
         $reason = implode(', ', $this->get('security.token_storage')->getToken()->getUser()->getRoles());
         return $this->render('WaiverBundle:Error:error.html.twig', array('error_msg' => $error_msg, 'reason' => $reason));
     }
 }
 /**
  * @Route("/waivers/new", name="waiverBundle_new")
  * @Template()
  */
 public function newWaiverAction(Request $request)
 {
     $role_usr = $this->container->get('security.token_storage')->getToken()->getUser()->getRoles();
     $user = $this->container->get('security.token_storage')->getToken()->getUser();
     if ($this->get('security.authorization_checker')->isGranted('ROLE_WAIVER_REQUEST')) {
         // Needed to pass the form data from one controller to another
         $session = $this->getRequest()->getSession();
         /** @var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
         $formFactory = $this->get('fos_user.registration.form.factory');
         $newWaiver = new \WaiverBundle\Entity\Waiver();
         // Instance of the waiver object which is to be created
         $form = $this->createForm(NewWaiverType::class, $newWaiver);
         $form->handleRequest($request);
         $em = $this->getDoctrine()->getManager();
         // If the form was filled out
         if (null !== $form->get('agency')->getData()) {
             // If IATA is not valid
             if (null == ($agency = $em->getRepository('AppBundle:Agency')->find($form->get('agency')->getData()))) {
                 // Throw error
                 $iataError = new FormError("Invalid IATA");
                 $form->get('agency')->addError($iataError);
             } else {
                 // Add the agency to the waiver
                 $newWaiver->setAgency($agency);
                 $statusRepository = $this->getDoctrine()->getRepository('WaiverBundle:Status');
                 $status = $statusRepository->findOneByName('OPEN');
                 $market = $agency->getSalesCountry();
                 $newWaiver->setMarket($market);
                 $newWaiver->setStatus($status);
                 $preReasoncode = $em->getRepository('WaiverBundle:ReasonCode')->find($form->get('reasonCode')->getData());
                 $newWaiver->setPreReasoncode($newWaiver->getReasonCode()->getId());
                 $newWaiver->setPreFarebasis($form->get('fareBasis')->getData());
             }
             $newWaiver->setFlightNumber($newWaiver->getFlightNumber());
             $countPassengers = 0;
             // Handle passengers
             if (isset($_POST['passengers'])) {
                 $passengers = $_POST['passengers'];
                 $zl = 0;
                 foreach ($passengers['firstName'] as $firstName) {
                     $passenger = new \WaiverBundle\Entity\Passenger();
                     $passenger->setFirstName($firstName);
                     $passenger->setLastName($passengers['lastName'][$zl]);
                     $passenger->setWaiver($newWaiver);
                     $em->persist($passenger);
                     ++$zl;
                     $countPassengers = $zl;
                 }
             } else {
                 $flightNumberPrefixError = new FormError("Please assign at least one passenger to this waiver request.");
                 $form->get('contactPerson')->addError($flightNumberPrefixError);
             }
             $agency = $newWaiver->getAgency();
             $reasoncode = $newWaiver->getReasonCode();
             $fareBasis = $newWaiver->getFareBasis();
             $bookingClassCode = $fareBasis[0];
             $bookingclass = $em->getRepository('AppBundle:BookingClass')->findOneByCode($bookingClassCode);
             $repository = $this->getDoctrine()->getRepository('WaiverBundle:PriceTag');
             $queryPriceTag = $repository->findOnePriceTag($agency, $reasoncode, $bookingclass);
             $fundDeducted = 0;
             if ($queryPriceTag != null) {
                 $fundDeducted = $queryPriceTag->getAmount();
             } else {
                 $fundsError = new FormError("");
                 $form->get('reasonCode')->addError($fundsError);
             }
             $fundAgency = $newWaiver->getAgency()->getFunds();
             $agencyBalance = array();
             foreach ($fundAgency as $fundAgency) {
                 $agencyFunds = $fundAgency->getBalance();
                 array_push($agencyBalance, $agencyFunds);
             }
             $currentAgencyBalance = implode('', $agencyBalance);
             $findCurrentAmount = $currentAgencyBalance - $fundDeducted * $countPassengers;
             $fundTotal = $fundDeducted * $countPassengers;
             if ($corporationYes = $form->get('corporation')->getData() == true) {
                 if ($corporationYes = $form->get('identifier')->getData() == true) {
                     $cuid = $form->get('identifierCode')->getData();
                     $corpRepository = $this->getDoctrine()->getRepository('AppBundle:Corporation');
                     $corpID = $corpRepository->find($cuid);
                     $corpFunds = $corpID->getFunds();
                     $balance = array();
                     foreach ($corpFunds as $corpFunds) {
                         $corpFunds = $corpFunds->getBalance();
                         array_push($balance, $corpFunds);
                     }
                     $currentBalance = implode('', $balance);
                     $CorpCurrentBalance = $currentBalance - $fundDeducted * $countPassengers;
                     $corporationRepository = $this->getDoctrine()->getRepository('AppBundle:Corporation');
                     $corporation = $corporationRepository->find($cuid);
                     $newWaiver->setCorporation($corporation);
                     if ($fundTotal > $currentBalance) {
                         $this->get('session')->getFlashBag()->add('notice', 'Insufficient funds! Please contact your account manager.');
                         $fundsError = new FormError("'Insufficient funds! Please contact your account manager.'");
                         $form->get('reasonCode')->addError($fundsError);
                     } elseif ($fundTotal <= $currentBalance) {
                         $cuid = $form->get('identifierCode')->getData();
                         $corpRepository = $this->getDoctrine()->getRepository('AppBundle:Corporation');
                         $corpID = $corpRepository->find($cuid);
                         $corpFunds = $corpID->getFunds();
                         foreach ($corpFunds as $corpFunds) {
                             $corpFunds->setBalance($CorpCurrentBalance);
                         }
                     }
                 } else {
                     $tourCode = $form->get('identifierCode')->getData();
                     $tourCodeRepository = $this->getDoctrine()->getRepository('AppBundle:TourCode');
                     $tourCodeName = $tourCodeRepository->findOneByName($tourCode);
                     $tourCodeFunds = $tourCodeName->getFunds();
                     $tourCodebalance = array();
                     foreach ($tourCodeFunds as $tourCodeFunds) {
                         $tourcFunds = $tourCodeFunds->getBalance();
                         array_push($tourCodebalance, $tourcFunds);
                     }
                     $currentTourcodeBalance = implode('', $tourCodebalance);
                     $tourCurrentBalance = $currentTourcodeBalance - $fundDeducted * $countPassengers;
                     if ($fundTotal > $currentTourcodeBalance) {
                         $this->get('session')->getFlashBag()->add('notice', 'Insufficient funds! Please contact your account manager.');
                         $fundsError = new FormError("'Insufficient funds! Please contact your account manager.'");
                         $form->get('reasonCode')->addError($fundsError);
                     } elseif ($fundTotal <= $currentTourcodeBalance) {
                         $tourCode = $form->get('identifierCode')->getData();
                         $tourCodeRepository = $this->getDoctrine()->getRepository('AppBundle:TourCode');
                         $tourCodeName = $tourCodeRepository->findOneByName($tourCode);
                         $tourCodeFunds = $tourCodeName->getFunds();
                         foreach ($tourCodeFunds as $tourCodeFunds) {
                             $tourCodeFunds->setBalance($tourCurrentBalance);
                         }
                     }
                 }
             } else {
                 if ($currentAgencyBalance != '') {
                     if ($fundTotal > $currentAgencyBalance) {
                         $this->get('session')->getFlashBag()->add('notice', 'Insufficient funds! Please contact your account manager.');
                         $fundsError = new FormError("'Insufficient funds! Please contact your account manager.'");
                         $form->get('reasonCode')->addError($fundsError);
                     } elseif ($fundTotal <= $currentAgencyBalance) {
                         $agencyFund = $newWaiver->getAgency()->getFunds();
                         foreach ($agencyFund as $agencyFund) {
                             $agencyFunds = $fundAgency->setBalance($findCurrentAmount);
                         }
                     }
                 }
             }
         }
         $usersWaiting = $this->getDoctrine()->getRepository('WaiverBundle:Passenger')->findByWaiver($newWaiver);
         if ($form->isValid()) {
             $newWaiver->setCreator($this->get('security.token_storage')->getToken()->getUser());
             // Handle file uploads
             $dir = "uploads/waivers/";
             foreach ($form['attachments']->getData() as $file) {
                 if ($file === null) {
                     break;
                 }
                 $extension = $file->guessExtension();
                 if (!$extension) {
                     $extension = 'bin';
                 }
                 $fileName = 'sp_' . mb_strimwidth(sha1(rand(1, 999999) . $file->getClientOriginalName()), 0, 20) . '.' . $extension;
                 $file->move($dir, $fileName);
                 $file = new \WaiverBundle\Entity\File();
                 $file->setFilename($fileName);
                 $file->setFileType($extension);
                 $file->setUploader($this->get('security.token_storage')->getToken()->getUser());
                 $file->setWaiver($newWaiver);
                 $em->persist($file);
             }
             // Create a new comment and link it to the waiver (reason)
             $reason = new \WaiverBundle\Entity\Comment();
             $reason->setComment($form->get('reason')->getData());
             $reason->setWaiver($newWaiver);
             $reason->setAuthor($this->get('security.token_storage')->getToken()->getUser());
             $reasonCode = $newWaiver->getReasonCode();
             // Persist the created waiver as well as the comment/reason to the database
             $em->persist($newWaiver);
             $em->persist($reason);
             $em->flush();
             /***********************Mail-Service************************/
             // Get the contact email in the field
             $usr_contactEmail = $newWaiver->getContactEmail();
             $userEmail = $this->container->get('security.token_storage')->getToken()->getUser()->getEmail();
             $userFirstName = $this->container->get('security.token_storage')->getToken()->getUser()->getFirstName();
             $usr_contactName = $newWaiver->getContactPerson();
             $waiverId = $newWaiver->getId();
             //Get the url of the waiver profile
             $route = $this->generateUrl('waiverBundle_show_waiver', array('id' => $waiverId));
             $host = $this->get('request')->getSchemeAndHttpHost();
             if (!$usr_contactEmail == null) {
                 $this->get('MailerHelper')->sendEmailMultiple('A new waiver has been created at StarPartners', $this->container->getParameter('from_email_address'), $usr_contactEmail, $userEmail, $this->renderView('NewsBundle:EMails:email_waiver_open.html.twig', array('name' => $usr_contactName, 'route' => $route, 'host' => $host)));
             } else {
                 $this->get('MailerHelper')->sendEmailSingle('A new waiver has been created at StarPartners', $this->container->getParameter('from_email_address'), $userEmail, $this->renderView('NewsBundle:EMails:email_waiver_open.html.twig', array('name' => $userFirstName, 'route' => $route, 'host' => $host)));
             }
             /***********************************************************/
             // Waiver was created: Render view with confirmation message
             return $this->render('WaiverBundle:Waiver/Request:Requested.html.twig', array('waiver' => $newWaiver, 'form' => $form->createView(), 'success' => true));
         }
         // No request has been sent yet: Render view with the request form
         return $this->render('WaiverBundle:Waiver/Request:Request.html.twig', array('form' => $form->createView(), 'user' => $user, 'waiver' => $newWaiver));
     } else {
         /*
          * THROW ERROR
          * If the acting user is not allowed to perform this action.
          */
         $this->addFlash('danger', 'You do not have the permissions to create a waiver');
         return $this->redirectToRoute('waiverBundle_waiver_list');
     }
 }