public function triggerItemAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $response = array('error' => false, 'message' => "Item has been activated!");
     try {
         $req = $this->get('request')->request;
         $fighterId = $req->get('fighter_id');
         $inventoryId = $req->get('inventory_id');
         /** @var FighterRepository $fighterRepository */
         $fighterRepository = $em->getRepository('GameBaseBundle:Fighter');
         $fighter = $fighterRepository->getFighterById($fighterId);
         if (!$fighter) {
             throw new \Exception("The fighter does not exist.");
         } else {
             if ($fighter->getManager()->getId() != $_SESSION['manager']->getId()) {
                 throw new \Exception("You do not own this fighter.");
             }
         }
         /** @var InventoryRepository $inventoryRepository */
         $inventoryRepository = $em->getRepository('GameBaseBundle:Inventory');
         $inventory = $inventoryRepository->getInventoryById($inventoryId);
         if (!$inventory) {
             throw new \Exception("Inventory id does not exist.");
         } else {
             if ($inventory->getManager()->getId() != $_SESSION['manager']->getId()) {
                 throw new \Exception("You do not own that item,");
             } elseif ($inventory->getQuantity() <= 0) {
                 throw new \Exception("You have already wasted all the items of this type.");
             }
         }
         $stats = $fighter->getStats();
         /** @var Item $item */
         $item = $inventory->getItem();
         $inventory->setQuantity($inventory->getQuantity() - 1);
         $stats->setStamina($stats->getStamina() + $item->getStamina())->setStrength($stats->getStrength() + $item->getStrength())->setAgility($stats->getAgility() + $item->getAgility())->setIntelligence($stats->getIntelligence() + $item->getIntelligence())->setStrike($stats->getStrike() + $item->getStrike())->setKicking($stats->getKicking() + $item->getStamina())->setGrappling($stats->getGrappling() + $item->getGrappling())->setTakedown($stats->getTakedown() + $item->getTakedown());
         $endTimeS = new \DateTime();
         $endTimeS->add(new \DateInterval('PT' . $item->getDuration() . 'M'));
         $effect = new Effect();
         $effect->setFighter($fighter)->setItem($item)->setStartTime(new \DateTime())->setEndTime($endTimeS);
         $em->persist($effect);
         $em->flush();
     } catch (\Exception $e) {
         $response['error'] = true;
         $response['message'] = $e->getMessage();
     }
     return new JsonResponse($response);
 }
 /**
  * Save the current questionnaire state to database.
  */
 private function saveQuestionnaire(Request $request, $questionnaire)
 {
     // Parse json.
     $data = json_decode($request->getContent(), true);
     $ignore = $request->query->get('ignore');
     if ($ignore) {
         $em = $this->getDoctrine()->getManager();
         $em->persist($questionnaire);
         $em->flush();
         return null;
     }
     $questionnaire->setName($data['name']);
     $questionnaire->setDescription($data['description']);
     $expires = $data['expires'];
     // Max questionnaire duration is one week.
     if ($this->isValidExpiry($expires)) {
         $date = new \DateTime();
         $date->add(new \DateInterval('P' . $expires . 'D'));
         $questionnaire->setExpires($date);
     }
     if (isset($data['questions'])) {
         foreach ($data['questions'] as $questionData) {
             // Update each question data.
             foreach ($questionnaire->getQuestions() as $question) {
                 if ($question->getId() == $questionData['id']) {
                     $type = $questionData['type'];
                     if ($type == 'MULTIPLE' || $type == 'SINGLE' || $type == 'OPEN') {
                         $question->setType($type);
                     }
                     $question->setContent($questionData['content']);
                 }
                 // Open question does not need answers.
                 if ($question->getType() != 'OPEN') {
                     // Update each answer data.
                     foreach ($questionData['answers'] as $answerData) {
                         foreach ($question->getAnswers() as $answer) {
                             if ($answer->getId() == $answerData['id']) {
                                 $answer->setContent($answerData['content']);
                             }
                         }
                     }
                 }
             }
         }
     }
     // Persist questionnaire.
     $em = $this->getDoctrine()->getManager();
     $em->persist($questionnaire);
     $em->flush();
 }
 private function getFutureDateUtility($interval)
 {
     $dt = new \DateTime();
     $dt->add(new \DateInterval($interval));
     return $dt;
 }
 public function consultarAction(Request $request)
 {
     $form = $this->createFormBuilder()->add('fechas', 'text', array('label' => 'Rango de Fechas', 'attr' => array('placeholder' => 'Seleccione las fechas', 'describedby' => 'basic-addon1')))->add('categoria', 'entity', array('label' => 'Categoría de la Habitación', 'class' => 'LIHotelBundle:CategoriaHabitacion', 'choice_label' => 'nombre'))->add('tipo', 'entity', array('label' => 'Tipo de la Habitación', 'class' => 'LIHotelBundle:TipoHabitacion', 'choice_label' => 'nombre'))->add('cant_personas', 'integer', array('label' => 'Cantidad de Personas', 'data' => 1, 'precision' => 0))->setMethod('POST')->setAction($this->generateUrl('LIHotelBundle_consultar'))->add('submit', 'submit', array('label' => 'Realizar Consulta', 'attr' => array('class' => 'btn btn-success btn-block')))->getForm();
     $habitaciones_disponibles = [];
     $costo_disponibles = [];
     $estadiaenDias = 0;
     $form->handleRequest($request);
     if ($form->isValid()) {
         $data = $form->getData();
         /* Obteniendo los datos del formulario */
         $fechas = $data['fechas'];
         $categoria = $data['categoria'];
         $tipo = $data['tipo'];
         $personas = $data['cant_personas'];
         $fecha_a = substr($fechas, 0, 10);
         $fecha_b = substr($fechas, 14, 24);
         $fecha_inicio = new \DateTime($fecha_a);
         $fecha_final = new \DateTime($fecha_b);
         $estadiaenDias = $this->cantidad_dias($fecha_inicio, $fecha_final);
         $em = $this->getDoctrine()->getManager();
         $habitaciones_tipo = $em->getRepository('LIHotelBundle:Tipo')->habitaciones_tipo($tipo->getId(), $categoria->getId());
         foreach ($habitaciones_tipo as $tipos) {
             $habitacion = $em->getRepository('LIHotelBundle:Habitacion')->habitacion_por_tipo($tipos->getId());
             foreach ($habitacion as $room) {
                 // Estas son las habitaciones del tipo y categoria especificadas por el usuario
                 //Ahora tengo que buscar todas sus reservas
                 $reservas = $em->getRepository('LIHotelBundle:Reserva')->reservas_habitacion($room->getId());
                 if (sizeof($reservas) == 0) {
                     $cantidad = $em->getRepository('LIHotelBundle:OcupacionHabitacion')->obtener_ocupacion($tipo, $categoria->getId());
                     foreach ($cantidad as $key) {
                         if ($key->getCantidadPersonasHabitacion() >= $personas) {
                             $tipo_aux = $room->getTipo()->getTipoHabitacion()->getPrecio();
                             $categoria_aux = $room->getTipo()->getCategoriaHabitacion()->getPrecio();
                             $habitaciones_disponibles[] = [$room->getNombre(), $this->cantidad_dias($fecha_inicio, $fecha_final) * $tipo_aux * $categoria_aux];
                         } else {
                             $this->get('session')->getFlashBag()->add('consulta_info', 'No se ha encontrado habitación debido a la cantidad de personas que indicó. Intente con una cantidad menor.');
                         }
                     }
                 } else {
                     $cantidad = $em->getRepository('LIHotelBundle:OcupacionHabitacion')->obtener_ocupacion($tipo, $categoria->getId());
                     foreach ($cantidad as $key) {
                         if ($key->getCantidadPersonasHabitacion() >= $personas) {
                             foreach ($reservas as $reserva) {
                                 // si la reserva no está cancelada, solo queda ver si ya culmino, está en eso o por concretar
                                 if ($reserva->getEstadoReserva() != 'Cancelada') {
                                     //Escogiendo las cantidades permitidas de personas en las habitaciones
                                     $cantidad = $em->getRepository('LIHotelBundle:OcupacionHabitacion')->obtener_ocupacion($tipo->getId(), $categoria->getId());
                                     foreach ($cantidad as $key) {
                                         // Segun la cantidad
                                         if ($key->getCantidadPersonasHabitacion() >= $personas) {
                                             $dias_reserva = $reserva->getDiasReserva() - 1;
                                             $fecha_reserva = $reserva->getFechaDesde();
                                             $fecha_inicio_ = new \DateTime($fecha_reserva->format('Y-m-d'));
                                             $fecha_final_ = new \DateTime($fecha_inicio_->format('Y-m-d'));
                                             $fecha_final_->add(new \DateInterval('P' . $dias_reserva . 'D'));
                                             $puede = true;
                                             if ($fecha_inicio > $fecha_inicio_ && $fecha_inicio < $fecha_final_) {
                                                 $puede = false;
                                                 $this->get('session')->getFlashBag()->add('consulta_info', 'No hay habitación diponible en la fecha indicada.');
                                             }
                                             if ($fecha_final > $fecha_inicio_ && $fecha_final < $fecha_final_) {
                                                 $puede = false;
                                                 $this->get('session')->getFlashBag()->add('consulta_info', 'No hay habitación diponible en la fecha indicada.');
                                             }
                                             if ($fecha_inicio_ > $fecha_inicio && $fecha_inicio_ < $fecha_final) {
                                                 $puede = false;
                                                 $this->get('session')->getFlashBag()->add('consulta_info', 'No hay habitación diponible en la fecha indicada.');
                                             }
                                             if ($fecha_inicio == $fecha_inicio_) {
                                                 $puede = false;
                                             }
                                             if ($fecha_inicio == $fecha_final_) {
                                                 $puede = false;
                                             }
                                             if ($fecha_final == $fecha_inicio_) {
                                                 $puede = false;
                                             }
                                             if ($fecha_final == $fecha_final_) {
                                                 $puede = false;
                                             }
                                             if ($puede) {
                                                 $insertar = true;
                                                 $tipo_aux = $room->getTipo()->getTipoHabitacion()->getPrecio();
                                                 $categoria_aux = $room->getTipo()->getCategoriaHabitacion()->getPrecio();
                                                 for ($i = 0; $i < sizeof($habitaciones_disponibles); $i++) {
                                                     if ($habitaciones_disponibles[$i][0] == $room->getNombre()) {
                                                         $insertar = false;
                                                     }
                                                 }
                                                 if ($insertar) {
                                                     $habitaciones_disponibles[] = [$room->getNombre(), $this->cantidad_dias($fecha_inicio, $fecha_final) * $tipo_aux * $categoria_aux];
                                                 }
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
     }
     return $this->render('LIHotelBundle:Inicio:consultar.html.twig', array('form' => $form->createView(), 'habitaciones_disponibles' => $habitaciones_disponibles, 'estadia' => $estadiaenDias));
 }
 /**
  * Return scheduled min date taking into account the time gap possibly set in config
  *
  * @param array $methodConfig
  * @return \DateTime|string
  */
 protected function getMinDate($methodConfig)
 {
     if (!isset($methodConfig['gap']) || trim($methodConfig['gap']) == '') {
         return 'now';
     }
     $minDate = new \DateTime();
     return $minDate->add(new \DateInterval('PT' . trim($methodConfig['gap']) . 'M'));
 }