/**
  * @param LoanOfficer $loanOfficer
  */
 protected function addLoanOfficerUser(LoanOfficer $loanOfficer)
 {
     $loUser = $loanOfficer->getUser();
     $loSite = $loanOfficer->getOfficerSite();
     $loCreateUser = $loanOfficer->getAutoCreateUser();
     if ($loCreateUser && !isset($loUser) && isset($loSite)) {
         $loRole = $this->em->getRepository('SudouxCmsUserBundle:Role')->findOneBy(array('role' => 'ROLE_LOAN_OFFICER'));
         // check if user already exists by email
         $existingUser = $this->em->getRepository('SudouxCmsUserBundle:User')->findOneBy(array('email' => $loanOfficer->getEmail()));
         if (isset($existingUser)) {
             // assign existing user to lo
             $loanOfficer->setUser($existingUser);
             $this->em->persist($loanOfficer);
         } else {
             $user = new User();
             $username = strtolower(substr($loanOfficer->getFirstName(), 0, 1) . $loanOfficer->getLastName());
             $username = str_replace(' ', '', preg_replace("/[^A-Za-z0-9 ]/", '', $username));
             $user->setUsername($this->getLoanOfficerUsername($username));
             $factory = $this->container->get('security.encoder_factory');
             $encoder = $factory->getEncoder($user);
             $password = $encoder->encodePassword($user->generatePassword(), $user->getSalt());
             $user->setPassword($password);
             $user->setEmail($loanOfficer->getEmail());
             $user->setFirstName($loanOfficer->getFirstName());
             $user->setLastName($loanOfficer->getLastName());
             $user->addSite($loanOfficer->getOfficerSite());
             $user->addRole($loRole);
             $user->addToken();
             $user->setTimezone($loanOfficer->getSite()->getTimezone());
             $loanOfficer->setUser($user);
             $this->em->persist($loanOfficer);
             $emailUtil = $this->container->get('sudoux.cms.message.email_util');
             $email = new Email();
             $email->setRecipient($user->getEmail());
             $email->setRecipientName($user->getFullName());
             $email->setSubject($this->container->get('sudoux.cms.site')->getSiteVar('New Website Account', 'loan_officer_user_add_email_subject'));
             $email->setUser($user);
             $email->setSite($loanOfficer->getSite());
             $resetPasswordUrl = sprintf("https://%s%s", $loanOfficer->getOfficerSite()->getPrimaryDomain()->getDomain(), $this->router->generate('sudoux_cms_user_reset_password', array('token' => $user->getToken())));
             // default message
             $message = sprintf('<p>An account has been created for you on your new website. Your username is %s</p>', $user->getUsername());
             $message .= sprintf('<p><a href="%s">Click here</a> to set your password and confirm your account.</p>', $resetPasswordUrl);
             $tokens = array('username' => $user->getUsername(), 'email' => $user->getEmail(), 'reset_password_url' => $resetPasswordUrl, 'first_name' => $user->getFirstName(), 'last_name' => $user->getLastName(), 'website_url' => 'https://' . $loanOfficer->getOfficerSite()->getPrimaryDomain()->getDomain());
             $message = $this->container->get('sudoux.cms.site')->getSiteVar($message, 'loan_officer_user_add_email_message', $tokens);
             $email->setMessage($message);
             $emailUtil->logAndSend($email);
         }
         $this->em->flush($loanOfficer);
     }
 }
 /**
  * @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()));
 }