/**
  * @param \Sudoux\Cms\UserBundle\Entity\User $user
  * @return array
  * @author Eric Haynes
  */
 public function getNewUserMessages(User $user)
 {
     $messages = array();
     $newMessages = $this->message_thread->getNewMessages();
     if (count($this->message_thread->getNewMessages()) > 0) {
         foreach ($newMessages as $message) {
             if ($message->getStatus() == 0 && $user->getId() != $message->getUser()->getId()) {
                 array_push($messages, $message);
             }
         }
     }
     return $messages;
 }
 /**
  * @param Request $request
  * @param $id
  * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
  * @throws \AccessDeniedHttpException
  * @throws \Symfony\Component\Form\Exception\FormException
  * @throws \Symfony\Component\Form\Exception\UnexpectedTypeException
  */
 public function memberAction(Request $request, $id)
 {
     $em = $this->getDoctrine()->getEntityManager();
     $securityContext = $this->container->get('security.context');
     $user = $securityContext->getToken()->getUser();
     $siteRequest = $this->get('sudoux.cms.site');
     $site = $siteRequest->getSite();
     $portalEnabled = $site->getSettings()->getInheritedMemberPortalEnabled();
     if (!$portalEnabled) {
         $request->getSession()->getFlashBag()->add('error', $this::LOAN_LOCKED_MESSAGE);
         return $this->redirect($this->generateUrl('sudoux_mortgage_admin_loan'));
     }
     $session = $request->getSession();
     $documentVocab = $site->getSettings()->getInheritedLoanDocumentVocab();
     $document = new LoanDocument();
     $documentForm = $this->createForm(new LoanDocumentType($documentVocab), $document);
     $application = $em->getRepository('SudouxMortgageBundle:LoanApplication')->findOneBySite($site, $id);
     if (!isset($application)) {
         throw $this->createNotFoundException($this::LOAN_NOT_FOUND_MESSAGE);
     }
     if ($application->getStatus() < 2) {
         $application->setStatus(2);
         $em->persist($application);
         $em->flush();
     }
     $loanForm = $this->createForm(new LoanApplicationType($site, $application), $application, array('validation_groups' => array('status')));
     $availableUsers = $em->getRepository('SudouxCmsUserBundle:User')->findAllBySingleSite($site);
     $loanUsers = $application->getClientUser();
     // remove the application user
     $applicationUser = $application->getUser();
     if (isset($applicationUser)) {
         foreach ($availableUsers as $key => $u) {
             if ($u->getId() == $applicationUser->getId()) {
                 unset($availableUsers[$key]);
             }
         }
     }
     // remove the existing client users
     foreach ($loanUsers as $loanUser) {
         foreach ($availableUsers as $key => $siteUser) {
             if ($siteUser->getId() == $loanUser->getId()) {
                 unset($availableUsers[$key]);
             }
         }
     }
     $userForm = $this->createFormBuilder()->add('additional_user_email', 'text', array('label' => 'Invite an additional person to follow the status of this loan', 'required' => true, 'attr' => array('placeholder' => 'Email'), 'constraints' => array(new NotBlank(), new \Symfony\Component\Validator\Constraints\Email())))->getForm();
     $documentChecklist = $site->getSettings()->getLoanDocumentVocab();
     $message = new Message();
     $messageForm = $this->createForm(new MessageType(), $message);
     if ($request->getMethod() == 'POST') {
         $formName = $request->query->get('form');
         $emailUtil = $this->get('sudoux.cms.message.email_util');
         switch ($formName) {
             case 'loan':
                 $loanForm->bindRequest($request);
                 if ($loanForm->isValid()) {
                     $email = new Email();
                     $email->setSubject("Your loan application status has been updated.");
                     $email->setMessage(sprintf('Your loan has been updated to %s. Please <a href="%s">click here</a> to view.', $application->getStatusName(), $this->generateUrl('sudoux_mortgage_loan_member_detail', array('id' => $application->getId()), true)));
                     $email->setRecipient($application->getBorrower()->getEmail());
                     $email->setRecipientName($application->getBorrower()->getFullName());
                     $email->setSite($site);
                     $emailUtil->logAndSend($email);
                     $application->addEmail($email);
                     $em->persist($application);
                     $em->flush();
                     $session->getFlashBag()->add('success', 'Your loan has been updated.');
                     return $this->redirect($this->generateUrl('sudoux_mortgage_admin_loan_member', array('id' => $application->getId())));
                 }
                 break;
             case 'document':
                 $documentForm->bindRequest($request);
                 if ($documentForm->isValid()) {
                     $documentData = $documentForm['file_field']->getData();
                     $file = new File();
                     $file->setName($documentForm['name']->getData());
                     $file->setUser($user);
                     $file->setSite($site);
                     $file->setFile($documentData);
                     $file->setPublic(false);
                     $document->setFile($file);
                     $document->setStatus(3);
                     // accepted
                     $em->persist($document);
                     $email = new Email();
                     $email->setSubject("A new document has been added to your loan application.");
                     $email->setMessage(sprintf('A new document has been added to your loan application. Please <a href="%s">click here</a> to view.', $this->generateUrl('sudoux_mortgage_loan_member_detail', array('id' => $application->getId()), true)));
                     $email->setRecipient($application->getBorrower()->getEmail());
                     $email->setRecipientName($application->getBorrower()->getFullName());
                     $email->setSite($site);
                     $emailUtil->logAndSend($email);
                     $application->addEmail($email);
                     $application->addDocument($document);
                     $em->persist($application);
                     $em->flush();
                     // queue the document
                     $job = new Job('sudoux:mortgage:loan', array('add_document', sprintf('--loan_id=%s', $application->getId()), sprintf('--document_id=%s', $document->getId()), '--env=' . $this->get('kernel')->getEnvironment(), '--no-debug'), true, 'loan_process_queue');
                     $em->persist($job);
                     $em->flush();
                     $session->getFlashBag()->add('success', 'The document has been added successfully.');
                     return $this->redirect($this->generateUrl('sudoux_mortgage_admin_loan_member', array('id' => $application->getId())));
                 }
                 break;
             case 'message':
                 $messageForm->bindRequest($request);
                 if ($messageForm->isValid()) {
                     $thread = $application->getMessageThread();
                     if (!isset($thread)) {
                         $thread = new Thread();
                         $thread->setSubject(sprintf("Loan Application #%s Message Thread", $application->getId()));
                         $application->setMessageThread($thread);
                     }
                     $message->setThread($thread);
                     $message->setUser($user);
                     $email = new Email();
                     $email->setSubject("You have a new message about your loan application.");
                     $email->setMessage(sprintf('You have a new message about your loan application. Please <a href="%s">click here</a> to view.', $this->generateUrl('sudoux_mortgage_loan_member_detail', array('id' => $application->getId(), 'tab' => 'messages'), true)));
                     $email->setRecipient($application->getBorrower()->getEmail());
                     $email->setRecipientName($application->getBorrower()->getFullName());
                     $email->setSite($site);
                     $emailUtil->logAndSend($email);
                     $application->addEmail($email);
                     $em->persist($application);
                     $em->persist($message);
                     $em->flush();
                     $session->getFlashBag()->add('success', 'Your message was sent successfully.');
                     return $this->redirect($this->generateUrl('sudoux_mortgage_admin_loan_member', array('id' => $id, 'tab' => 'messages')));
                 }
                 break;
             case 'user':
                 $userForm->bindRequest($request);
                 if ($userForm->isValid()) {
                     $resetPasswordUrl = null;
                     $additionalUserEmail = $userForm['additional_user_email']->getData();
                     $additionalUser = $em->getRepository('SudouxCmsUserBundle:User')->findOneBy(array('email' => $additionalUserEmail));
                     if (isset($additionalUser)) {
                         $message = sprintf('You have been invited to view a loan application for %s. Please <a href="%s">click here</a> to login and view the application.', $application->getBorrower()->getFullName(), $this->generateUrl('sudoux_mortgage_loan_member_detail', array('id' => $application->getId()), true));
                     } else {
                         $additionalUser = new User();
                         $additionalUser->setUsername($additionalUserEmail);
                         $factory = $this->get('security.encoder_factory');
                         $encoder = $factory->getEncoder($additionalUser);
                         $password = $encoder->encodePassword($additionalUser->generatePassword(), $additionalUser->getSalt());
                         $additionalUser->setPassword($password);
                         $additionalUser->setEmail($additionalUserEmail);
                         $additionalUser->addSite($site);
                         $memberRole = $em->getRepository('SudouxCmsUserBundle:Role')->findOneBy(array('role' => 'ROLE_MEMBER'));
                         $additionalUser->addRole($memberRole);
                         $additionalUser->addToken();
                         $additionalUser->setTimezone($site->getTimezone());
                         $resetPasswordUrl = $this->generateUrl('sudoux_cms_user_reset_password', array('token' => $additionalUser->getToken()), true);
                         $message = sprintf('You have been invited to view a loan application for %s. Please <a href="%s">click here</a> to complete your registration.', $application->getBorrower()->getFullName(), $resetPasswordUrl);
                         $em->persist($additionalUser);
                     }
                     $application->addClientUser($additionalUser);
                     $em->persist($application);
                     // add to audit log
                     $auditLog = new AuditLog();
                     $auditLog->setObject('Loan Application');
                     $auditLog->setAction(sprintf('%s has been added to loan application #%s', $additionalUserEmail, $application->getId()));
                     $auditLog->setUser($user);
                     $auditLog->setSite($site);
                     $em->persist($auditLog);
                     $em->flush();
                     // notify the user
                     $email = new Email();
                     $email->setRecipient($additionalUserEmail);
                     $email->setRecipientName($additionalUserEmail);
                     $email->setSubject($this->get('sudoux.cms.site')->getSiteVar('You have been invited to view a loan application', 'loan_application_invite_user_email_subject'));
                     $email->setUser($user);
                     $email->setSite($site);
                     $tokens = array('email' => $additionalUserEmail, 'reset_password_url' => $resetPasswordUrl);
                     $message = $this->get('sudoux.cms.site')->getSiteVar($message, 'loan_application_invite_user_email_message', $tokens);
                     $email->setMessage($message);
                     $this->get('sudoux.cms.message.email_util')->logAndSend($email);
                     $session->getFlashBag()->add('success', 'An additional user has been added to your application.');
                     return $this->redirect($this->generateUrl('sudoux_mortgage_admin_loan_member', array('id' => $application->getId(), 'tab' => 'users')));
                 }
                 break;
         }
     }
     return $this->render('SudouxMortgageBundle:LoanApplicationAdmin:member.html.twig', array('loanApp' => $application, 'documentChecklist' => $documentChecklist, 'documentForm' => $documentForm->createView(), 'messageForm' => $messageForm->createView(), 'loanForm' => $loanForm->createView(), 'userForm' => $userForm->createView()));
 }
 /**
  * @param Request $request
  * @param $id
  * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
  */
 public function loanDetailAction(Request $request, $id)
 {
     $em = $this->getDoctrine()->getEntityManager();
     $securityContext = $this->container->get('security.context');
     $user = $securityContext->getToken()->getUser();
     $siteRequest = $this->get('sudoux.cms.site');
     $site = $siteRequest->getSite();
     $session = $request->getSession();
     $portalEnabled = $site->getSettings()->getInheritedMemberPortalEnabled();
     if (!$portalEnabled) {
         $session->getFlashBag()->add('error', $this::PORTAL_DISABLED);
         return $this->redirect($this->generateUrl('sudoux_cms_user_account'));
     }
     $documentVocab = $site->getSettings()->getInheritedLoanDocumentVocab();
     if (!isset($documentVocab)) {
         $documentVocab = new Vocabulary();
     }
     $document = new LoanDocument();
     $documentForm = $this->createForm(new LoanDocumentType($documentVocab), $document);
     // get loans by user
     $application = $em->getRepository('SudouxMortgageBundle:LoanApplication')->findOneByUser($site, $user, $id);
     if (!isset($application)) {
         throw $this->createNotFoundException($this::LOAN_NOT_FOUND_MESSAGE);
     }
     // redirect to last step if access is manually entered
     if (!$application->getCompleted()) {
         $session->getFlashBag()->add('error', 'You cannot access your loan details until you have completed the application.');
         return $this->redirect($this->generateUrl('sudoux_mortgage_loan_apply_step' . $application->getLastStepCompleted(), array('id' => $application->getId())));
     }
     $documentChecklist = $site->getSettings()->getLoanDocumentVocab();
     $message = new Message();
     $messageForm = $this->createForm(new MessageType(), $message);
     $loanForm = $this->createForm(new LoanApplicationType($site, $application));
     if ($request->getMethod() == 'POST') {
         $formName = $request->query->get('form');
         $emailUtil = $this->get('sudoux.cms.message.email_util');
         $loanOfficer = $application->getLoanOfficer();
         if (isset($loanOfficer)) {
             $notificationEmail = $loanOfficer->getEmail();
             $notificationRecipient = $loanOfficer->getFullName();
         } else {
             $notificationEmail = $site->getSettings()->getInheritedWebsiteEmail();
             $notificationRecipient = "Site Administrator";
         }
         switch ($formName) {
             case 'document':
                 $documentForm->bindRequest($request);
                 if ($documentForm->isValid()) {
                     $documentData = $documentForm['file_field']->getData();
                     $file = new File();
                     $file->setName($documentForm['name']->getData());
                     $file->setUser($user);
                     $file->setSite($site);
                     $file->setFile($documentData);
                     $file->setPublic(false);
                     $document->setFile($file);
                     $em->persist($document);
                     $email = new Email();
                     $email->setSubject("A new document has been added to a loan application.");
                     $email->setMessage(sprintf('A new document has been added to a loan application. Please <a href="%s">click here</a> to view.', $this->generateUrl('sudoux_mortgage_admin_loan_member', array('id' => $application->getId()), true)));
                     $email->setRecipient($notificationEmail);
                     $email->setRecipientName($notificationRecipient);
                     $email->setSite($site);
                     $emailUtil->logAndSend($email);
                     $application->addEmail($email);
                     $application->addDocument($document);
                     $em->persist($application);
                     $em->flush();
                     // autosend to los?
                     $losConn = $site->getSettings()->getInheritedLos();
                     if ($losConn) {
                         $autoSendDocs = $losConn->getAutoSendDocs();
                         if ($autoSendDocs) {
                             // queue the document
                             $document->setStatus(3);
                             // accepted
                             $em->persist($document);
                             $job = new Job('sudoux:mortgage:loan', array('add_document', sprintf('--loan_id=%s', $application->getId()), sprintf('--document_id=%s', $document->getId()), '--env=' . $this->get('kernel')->getEnvironment(), '--no-debug'), true, 'loan_process_queue');
                             $em->persist($job);
                             $em->flush();
                         }
                     }
                     $session->getFlashBag()->add('success', 'Your document was uploaded successfully.');
                     return $this->redirect($this->generateUrl('sudoux_mortgage_loan_member_detail', array('id' => $application->getId())));
                 }
                 break;
             case 'message':
                 $messageForm->bindRequest($request);
                 if ($messageForm->isValid()) {
                     $thread = $application->getMessageThread();
                     if (!isset($thread)) {
                         $thread = new Thread();
                         $thread->setSubject(sprintf("Loan Application #%s Message Thread", $application->getId()));
                         $application->setMessageThread($thread);
                         $em->persist($application);
                     }
                     $message->setThread($thread);
                     $message->setUser($user);
                     $email = new Email();
                     $email->setSubject("You have a new message about a loan application.");
                     $email->setMessage(sprintf('You have a new message about a loan application. Please <a href="%s">click here</a> to view.', $this->generateUrl('sudoux_mortgage_admin_loan_member', array('id' => $application->getId(), 'tab' => 'messages'), true)));
                     $email->setRecipient($notificationEmail);
                     $email->setRecipientName($notificationRecipient);
                     $email->setSite($site);
                     $emailUtil->logAndSend($email);
                     $application->addEmail($email);
                     $em->persist($application);
                     $em->persist($message);
                     $em->flush();
                     $session->getFlashBag()->add('success', 'Your message was successfully sent.');
                     return $this->redirect($this->generateUrl('sudoux_mortgage_loan_member_detail', array('id' => $application->getId(), 'tab' => 'messages')));
                 }
                 break;
         }
     }
     return $this->render('SudouxMortgageBundle:LoanApplicationFront:loanDetail.html.twig', array('loanApp' => $application, 'documentChecklist' => $documentChecklist, 'documentForm' => $documentForm->createView(), 'messageForm' => $messageForm->createView(), 'loanForm' => $loanForm->createView()));
 }