/**
  * @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
  * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
  * @throws \Exception
  */
 public function quoteAction(Request $request)
 {
     $siteRequest = $this->get('sudoux.cms.site');
     $site = $siteRequest->getSite();
     $em = $this->getDoctrine()->getEntityManager();
     $lead = new Lead();
     $form = $this->createForm(new QuoteType($site), $lead);
     $showReferralSources = false;
     $referralSourceCount = $em->getRepository('SudouxCmsFormBundle:ReferralSource')->findAllActiveBySiteCount($site);
     if ($referralSourceCount > 0) {
         $showReferralSources = true;
     }
     if ($request->getMethod() == 'POST') {
         $form->bindRequest($request);
         if ($form->isValid()) {
             try {
                 $lead->setSite($site);
                 $status = $em->getRepository('SudouxCmsFormBundle:LeadStatus')->find($this->container->getParameter('default_lead_status'));
                 $lead->setLeadStatus($status);
                 $em->persist($lead);
                 $em->flush();
                 $this->get('session')->setFlash('success', 'Thank you for your submission');
                 $emailUtil = $this->get('sudoux.cms.message.email_util');
                 // lead confirmation
                 $email = new Email();
                 $email->setSubject(sprintf("Thank you for contacting %s.", $site->getName()));
                 $email->setMessage("Thank you for your submission. We will respond to your inquiry as soon as possible.");
                 $email->setRecipient($lead->getEmail());
                 $email->setSite($site);
                 $emailUtil->logAndSend($email);
                 // admin notification
                 $message = sprintf('First Name: %s<br />', $form['first_name']->getData());
                 $message .= sprintf('Last Name: %s<br />', $form['last_name']->getData());
                 $message .= sprintf('Home Phone: %s<br />', $form['home_phone']->getData());
                 $message .= sprintf('Email: %s<br />', $form['email']->getData());
                 $message .= sprintf('Loan Type: %s<br />', $form['subject']->getData());
                 $message .= sprintf('Loan Details: %s<br />', $form['message']->getData());
                 $referralSources = $lead->getReferralSourceAsString();
                 if (!empty($referralSources)) {
                     $message .= sprintf('Referral Sources: %s<br />', $referralSources);
                     $referralSourceDesc = $lead->getReferralSourceDesc();
                     if (!empty($referralSourceDesc)) {
                         $message .= sprintf('Referral Source Description:<br /> %s<br />', $referralSourceDesc);
                     }
                 }
                 $email = new Email();
                 $email->setSubject(sprintf('%s: Quote Form', $site->getName()));
                 $email->setMessage($message);
                 $email->setRecipient($site->getSettings()->getInheritedWebsiteEmail());
                 $email->setRecipientName($site->getName());
                 $email->setBcc($site->getSettings()->getInheritedWebsiteEmailBcc());
                 $email->setSite($site);
                 $emailUtil->logAndSend($email);
                 return $this->redirect($this->generateUrl('sudoux_mortgage_form_quote'));
             } catch (\Exception $e) {
                 $logger = $this->get('logger');
                 $logger->crit($e->getMessage());
                 throw $e;
             }
         }
     }
     return $this->render('SudouxMortgageBundle:FormFront:quote.html.twig', array('form' => $form->createView(), 'showReferralSources' => $showReferralSources));
 }
 /**
  * @param Request $request
  * @param $id
  * @return \Symfony\Component\HttpFoundation\RedirectResponse
  */
 public function inviteBorrowerAction(Request $request, $id)
 {
     $em = $this->getDoctrine()->getEntityManager();
     $site = $this->get('sudoux.cms.site')->getSite();
     $application = $em->getRepository('SudouxMortgageBundle:LoanApplication')->findOneBySite($site, $id);
     if (!isset($application)) {
         throw $this->createNotFoundException($this::LOAN_NOT_FOUND_MESSAGE);
     }
     $applicationUser = $application->getUser();
     if (isset($applicationUser)) {
         if ($applicationUser->hasRole('ROLE_MEMBER')) {
             $request->getSession()->getFlashBag()->add('error', "There is already a user account associated with this loan.");
             return $this->redirect($this->generateUrl('sudoux_mortgage_admin_loan_member', array('id' => $application->getId())));
         }
     }
     $borrowerEmail = $application->getBorrower()->getEmail();
     $emailUtil = $this->get('sudoux.cms.message.email_util');
     if (isset($borrowerEmail)) {
         // check if the borrower already has an account
         $existingUser = $em->getRepository('SudouxCmsUserBundle:User')->findOneBy(array('email' => $borrowerEmail));
         if (isset($existingUser)) {
             $application->setUser($existingUser);
             $em->persist($application);
             $em->flush($application);
             $emailMessage = sprintf('You have been invited to sign up at %s to send messages, documents and receive updates on your loan application. Please <a href="%s">click here</a> to login and view your application.', $site->getName(), $this->generateUrl('sudoux_mortgage_loan_member_detail', array('id' => $application->getId()), true));
         } else {
             $emailMessage = sprintf('You have been invited to sign up at %s to send messages, documents and receive updates on your loan application. Please <a href="%s">click here</a> to register.', $site->getName(), $this->generateUrl('sudoux_mortgage_loan_account_registration', array('guid' => $application->getGuid()), true));
         }
         $email = new Email();
         $email->setSubject("About your loan application");
         $email->setMessage($emailMessage);
         $email->setRecipient($borrowerEmail);
         $email->setRecipientName($application->getBorrower()->getFirstName());
         $email->setSite($site);
         $emailUtil->logAndSend($email);
     }
     $request->getSession()->getFlashBag()->add('success', "Your invitation has been sent to the borrower.");
     return $this->redirect($this->generateUrl('sudoux_mortgage_admin_loan_member', array('id' => $application->getId())));
 }
 /**
  * @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()));
 }