/**
  * RRP MTA's
  */
 public function rentRecoveryPlusMtaAction()
 {
     $request = $this->getSymfonyRequest();
     $mtaType = $this->getContainer()->get('rrp.form.mta');
     $policyNumber = null;
     if ($request->isMethod('GET')) {
         $policyNumber = $request->get('policyNumber');
     } else {
         if ($request->isMethod('POST')) {
             $postedData = $request->request->get($mtaType->getName());
             if (array_key_exists('policyNumber', $postedData)) {
                 $policyNumber = $postedData['policyNumber'];
             }
         }
     }
     if (!empty($policyNumber)) {
         /** @var object $applicationDecoratorClass */
         $applicationDecoratorClass = $this->getContainer()->get('rrp.application.decorator.class');
         /** @var RRP\Application\Decorators\RentRecoveryPlusPolicy $policy */
         $policy = $applicationDecoratorClass::getDecorator('RentRecoveryPlusPolicy');
         if (!$policy->populateByPolicyNumber($policyNumber)) {
             $this->renderTwigView('/rentguarantee/rent-recovery-plus-error.html.twig');
             return;
         }
         $policyOptionsManagerClass = $this->getContainer()->get('rrp.utility.policy_options_manager.class');
         $propertyRental = $policyOptionsManagerClass::getOption($policy->getAppData()->getPolicyOptions(), Model_Insurance_RentRecoveryPlus_LegacyPolicy::POLICY_OPTION_RRP, $policy->getAppData()->getAmountsCovered());
         $isNilExcess = $policyOptionsManagerClass::isOptionSet($policy->getAppData()->getPolicyOptions(), Model_Insurance_RentRecoveryPlus_LegacyPolicy::POLICY_OPTION_RRP_NIL_EXCESS, $policy->getAppData()->getAmountsCovered());
         /** @var RRP\Model\RentRecoveryPlusMta $mtaSetter */
         $defaultMta = $this->getContainer()->get('rrp.model.mta');
         $defaultMta->setPolicyNumber($policy->getAppData()->getPolicyNumber())->setPolicyStartedAt($policy->getAppData()->getStartDate())->setPolicyExpiresAt($policy->getAppData()->getEndDate())->setReferenceType($policy->getRrpData()->getReferenceType())->setPropertyRental($propertyRental)->setRefNo($policy->getAppData()->getRefNo());
         $referenceTypeClass = $this->getContainer()->get('rrp.reference_types.class');
         $isNilExcessAllowed = $referenceTypeClass::isNilExcessAllowed($policy->getRrpData()->getReferenceType());
         // Ensure date picker CSS and JS are available
         $this->view->headLink()->appendStylesheet('/assets/vendor/jquery-datepicker/css/datePicker.css');
         $this->view->headScript()->appendFile('/assets/vendor/jquery-date/js/date.js');
         $this->view->headScript()->appendFile('/assets/vendor/jquery-datepicker/js/jquery.datePicker.js');
         $form = $this->getFormFactory()->create($mtaType, $defaultMta);
         if ($request->isMethod('POST')) {
             $form->submit($request);
             if ($form->isValid()) {
                 // Check if only an update of the form to add/remove field. If so it will pass the isValid check
                 //  as it doesn't undergo full validation so we need catch it separately
                 if ($request->isXmlHttpRequest()) {
                     $update = true;
                 } else {
                     $update = $form->get('update')->isClicked();
                 }
                 if (!$update) {
                     // Check if only an update of the form to add/remove field. If so it will pass the isValid check
                     //  as it doesn't undergo full validation so we need catch it separately
                     /** @var RRP\Model\RentRecoveryPlusMta $mta */
                     $mta = $form->getData();
                     /** @var RRP\Rate\RateDecorators\RentRecoveryPlus $rateManager */
                     $rateDecoratorClass = $this->getContainer()->get('rrp.rate.decorator.class');
                     $referralRequired = false;
                     try {
                         /** @var RRP\Rate\RateDecorators\RentRecoveryPlus $rateManager */
                         $rateManager = $rateDecoratorClass::getDecorator('RentRecoveryPlus', $this->_agentsRateID, $this->_params->connect->settings->rentRecoveryPlus->riskArea, $this->_params->connect->settings->rentRecoveryPlus->iptPercent, $mta->getPropertyRental(), $isNilExcess, $policy->getRrpData()->getReferenceType(), $policy->getAppData()->getPolicyLength(), $policy->getAppData()->isPayMonthly(), DateTime::createFromFormat('Y-m-d', $policy->getAppData()->getStartDate()));
                     } catch (Exception $ex) {
                         $referralRequired = true;
                     }
                     $mtaDecoratorClass = $this->getContainer()->get('rrp.mta.decorator.class');
                     /** @var RRP\Mta\Decorators\RentRecoveryPlusMta $mtaDecorator */
                     $mtaDecorator = $mtaDecoratorClass::getDecorator('RentRecoveryPlusMta');
                     $mtaID = $mtaDecorator->create($policy, $mta, $rateManager->getPremium(), $rateManager->getQuote(), $rateManager->getIpt(), $rateManager->getNilExcessOption());
                     $proRataCalcClass = $this->getContainer()->get('rrp.utility.pro_rata_calcs.class');
                     /** @var RRP\Utility\ProRataCalculations $proRataCalcs */
                     $proRataCalcs = new $proRataCalcClass($mta->getPolicyStartedAt(), $mta->getMtaEffectiveAt());
                     $premiumDelta = $proRataCalcs->getAdjustment($policy->getAppData()->getPolicyLength(), $policy->getAppData()->getPolicyLength(), $rateManager->getPremium(), $policy->getAppData()->getPremium());
                     $iptDelta = $proRataCalcs->getAdjustment($policy->getAppData()->getPolicyLength(), $policy->getAppData()->getPolicyLength(), $rateManager->getIpt(), $policy->getAppData()->getIpt());
                     $quoteDelta = $proRataCalcs->getAdjustment($policy->getAppData()->getPolicyLength(), $policy->getAppData()->getPolicyLength(), $rateManager->getQuote(), $policy->getAppData()->getQuote());
                     $premiumProRata = $proRataCalcs->getProRata($policy->getAppData()->getPolicyLength(), $policy->getAppData()->getPolicyLength(), $rateManager->getPremium(), $policy->getAppData()->getPremium());
                     $iptProRata = $proRataCalcs->getProRata($policy->getAppData()->getPolicyLength(), $policy->getAppData()->getPolicyLength(), $rateManager->getIpt(), $policy->getAppData()->getIpt());
                     $quoteProRata = $proRataCalcs->getProRata($policy->getAppData()->getPolicyLength(), $policy->getAppData()->getPolicyLength(), $rateManager->getQuote(), $policy->getAppData()->getQuote());
                     /** @var RRP\Referral\RentRecoveryPlusReferral $referral */
                     $referral = $this->getContainer()->get('rrp.referral');
                     $referral->setFromMta($mta, $rateManager->getPremium());
                     if (!$referralRequired) {
                         $referralRequired = $referral->isReferralRequired();
                     }
                     if ($referralRequired) {
                         $policy->getAppData()->setPayStatus(Model_Insurance_RentRecoveryPlus_LegacyPolicy::PAY_STATUS_REFERRED);
                         $policyNote = new Datasource_Insurance_PolicyNotes();
                         $note = "This policy has been referred for the following reason(s)\n\n" . implode("\n", $referral->getReferralReason());
                         $policyNote->addNote($policy->getAppData()->getPolicyNumber(), $note);
                         // Send referral email
                         $subject = str_replace('{$policyNumber}', $policy->getAppData()->getPolicyNumber(), $this->_params->connect->settings->rentRecoveryPlus->referral->emailSubject);
                         $message = $this->getContainer()->get('twig')->render('rent-recovery-plus-mta-referral-mail.plain.twig', array('agentName' => $this->_agentObj->name, 'agentSchemeNumber' => $this->_agentSchemeNumber, 'referralReasons' => $referral->getReferralReason()));
                         $mailManager = new Application_Core_Mail();
                         $mailManager->setTo($this->_params->connect->settings->rentRecoveryPlus->referral->emailToAddress, $this->_params->connect->settings->rentRecoveryPlus->referral->emailToName)->setFrom($this->_params->connect->settings->rentRecoveryPlus->referral->emailFromAddress, $this->_params->connect->settings->rentRecoveryPlus->referral->emailFromName)->setSubject($subject)->setBodyText($message);
                         $mailManager->send();
                         $this->renderTwigView('/rentguarantee/rent-recovery-plus-mta-referral.html.twig');
                         return;
                     }
                     if ($premiumDelta == 0) {
                         $paymentDetails = 'We are pleased to confirm this has not affected your premium.';
                     } else {
                         if ($policy->getAppData()->isPayMonthly()) {
                             $paymentDetails = sprintf('From the date of the adjustment this will appear on your invoices as monthly' . ' payments of £%.02f plus £%.02f (IPT at %d%%). Total monthly payment £%.02f. ', $premiumProRata, $iptProRata, $this->_params->connect->settings->rentRecoveryPlus->iptPercent, $quoteProRata);
                         } else {
                             if ($premiumDelta < 0) {
                                 $paymentDetails = sprintf('This will appear on your next invoice as a refund of' . ' £%.02f plus £%.02f (IPT at %d%%). Total £%.02f. ', -$premiumDelta, -$iptDelta, $this->_params->connect->settings->rentRecoveryPlus->iptPercent, -$quoteDelta);
                             } else {
                                 $paymentDetails = sprintf('This will appear on your next invoice as £%.02f plus £%.02f (IPT at %d%%). Total £%.02f. ', $premiumDelta, $iptDelta, $this->_params->connect->settings->rentRecoveryPlus->iptPercent, $quoteDelta);
                             }
                         }
                     }
                     // Show premium and ask for confirmation
                     $this->renderTwigView('/rentguarantee/rent-recovery-plus-mta-quote.html.twig', array('policyNumber' => $policyNumber, 'paymentDetails' => $paymentDetails, 'mtaID' => $mtaID));
                     return;
                 }
             }
         }
         if ($this->getRequest()->isXmlHttpRequest()) {
             $this->_helper->viewRenderer->setNoRender(true);
             $this->_helper->layout->disableLayout();
         }
         $this->renderTwigView('/rentguarantee/rent-recovery-plus-mta.html.twig', array('form' => $form->createView(), 'nilExcessAllowed' => $isNilExcessAllowed));
         return;
     }
     $this->renderTwigView('/rentguarantee/rent-recovery-plus-error.html.twig');
 }
 /**
  * @inheritdoc
  */
 public function accept($policyNumber, $mtaId)
 {
     /** @var \RRP\Application\Decorators\RentRecoveryPlusPolicy $policy */
     $policy = ApplicationDecoratorFactory::getDecorator('RentRecoveryPlusPolicy');
     $policy->populateByPolicyNumber($policyNumber);
     $this->legacyMtaData = $this->legacyMta->getByMtaID($mtaId);
     $this->rrpMtaData = $this->rrpMta->getRentRecoveryPlusMta($mtaId);
     $proRataPremium = $policy->getAppData()->getPremium() + $this->legacyMtaData->getPremium();
     $proRataQuote = $policy->getAppData()->getQuote() + $this->legacyMtaData->getQuote();
     $proRataIpt = $policy->getAppData()->getIpt() + $this->legacyMtaData->getIpt();
     $propertyRental = PolicyOptionsManager::getOption($this->legacyMtaData->getPolicyOptions(), $this->getContainer()->get('rrp.legacy.const.policy_option_rrp'), $this->legacyMtaData->getAmountscovered());
     $isNilExcess = PolicyOptionsManager::isOptionSet($this->legacyMtaData->getPolicyOptions(), $this->getContainer()->get('rrp.legacy.const.policy_option_rrp-nilexcess'), $this->legacyMtaData->getAmountscovered());
     $policyPremium = PolicyOptionsManager::getOption($policy->getAppData()->getPolicyOptions(), $this->getContainer()->get('rrp.legacy.const.policy_option_rrp'), $policy->getAppData()->getOptionPremiums());
     $mtaPremium = PolicyOptionsManager::getOption($this->legacyMtaData->getPolicyOptions(), $this->getContainer()->get('rrp.legacy.const.policy_option_rrp'), $this->legacyMtaData->getOptionPremiums());
     $optionPremiums = PolicyOptionsManager::addPolicyOption($policyPremium + $mtaPremium);
     if ($isNilExcess) {
         $policyNilExcessOption = PolicyOptionsManager::getOption($policy->getAppData()->getPolicyOptions(), $this->getContainer()->get('rrp.legacy.const.policy_option_rrp-nilexcess'), $policy->getAppData()->getOptionPremiums());
         $mtaNilExcessOption = PolicyOptionsManager::getOption($this->legacyMtaData->getPolicyOptions(), $this->getContainer()->get('rrp.legacy.const.policy_option_rrp-nilexcess'), $this->legacyMtaData->getOptionPremiums());
         $optionPremiums = PolicyOptionsManager::addPolicyOption($policyNilExcessOption + $mtaNilExcessOption, $optionPremiums);
     }
     $policy->getAppData()->setPolicyOptions($this->legacyMtaData->getPolicyOptions())->setAmountsCovered($this->legacyMtaData->getAmountscovered())->setOptionPremiums($optionPremiums)->setPremium($proRataPremium)->setQuote($proRataQuote)->setIpt($proRataIpt);
     $policy->getRrpData()->setClaimInfo($this->rrpMtaData->getClaimInfo());
     $disbData = $this->disbursement->getDisbursement($policy->getAppData()->getWhiteLabelID(), $policy->getAppData()->getRateSetID());
     if (!$disbData) {
         $message = sprintf('Disbursement data not found (WhiteLabelId = %s, RateSetID = %d)', $policy->getAppData()->getWhiteLabelID(), $policy->getAppData()->getRateSetID());
         throw new \RuntimeException($message);
     }
     $getter = sprintf('getRrpi%s%dm', ReferenceTypes::isFullReference($policy->getRrpData()->getReferenceType()) ? 'FullRef' : 'CreditCheck', $policy->getAppData()->getPolicyLength());
     if ($isNilExcess) {
         $getter .= '0xs';
     }
     if (!method_exists($disbData, $getter)) {
         $message = sprintf('Unknown disbursement type (%s)', $getter);
         throw new \RuntimeException($message);
     }
     $disbursement = $disbData->{$getter}();
     if (empty($disbursement)) {
         $message = sprintf('Disbursement data not set (WhiteLabelId = %s, RateSetID = %d, %s)', $policy->getAppData()->getWhiteLabelID(), $policy->getAppData()->getRateSetID(), $getter);
         throw new \RuntimeException($message);
     }
     $termData = $this->policyTerm->getPolicyTerm($policy->getAppData()->getPolicyNumber(), $policy->getAppData()->getStartDate());
     if (!$termData->id) {
         throw new \RuntimeException('Invalid Term Id');
     }
     if ($propertyRental < RentRecoveryPlus::BAND_A_LIMIT) {
         $band = $disbData::BAND_A;
         $transBand = RentRecoveryPlus::BAND_A;
     } else {
         $band = $disbData::BAND_B;
         $transBand = RentRecoveryPlus::BAND_B;
     }
     $insuranceNetAmount = $disbData->extractBandDisbursement($disbursement, $band);
     $proRataCalcs = new ProRataCalculations($policy->getAppData()->getStartDate(), $this->legacyMtaData->getDateOnRisk());
     $netPremium = $proRataCalcs->getProRata($policy->getAppData()->getPolicyLength(), $policy->getAppData()->getPolicyLength(), $insuranceNetAmount, $termData->netPremium);
     $this->policyTerm->updatePolicyTerm($policy->getAppData(), $termData->term, array('netPremium' => $netPremium));
     $this->policyNotes->addNote($policyNumber, $this->legacyMtaData->getDisplayNotes());
     if ($policy->save()) {
         if ($this->legacyMta->updateStatus($policyNumber, $mtaId, $this->mtaStatusLive)) {
             $coverOptions = array();
             foreach ($policy->getAppData()->getValidPolicyOptionNames() as $optionName) {
                 if (PolicyOptionsManager::isOptionSet($policy->getAppData()->getPolicyOptions(), $optionName, $policy->getAppData()->getAmountsCovered())) {
                     $optionId = $this->policyOptions->fetchOptionsByName($optionName);
                     $sumInsured = PolicyOptionsManager::getOption($policy->getAppData()->getPolicyOptions(), $optionName, $policy->getAppData()->getAmountsCovered());
                     $premium = PolicyOptionsManager::getOption($policy->getAppData()->getPolicyOptions(), $optionName, $policy->getAppData()->getOptionPremiums());
                     $coverOptions[] = array('policyNumber' => $policyNumber, 'policyOptionID' => $optionId, 'sumInsured' => $sumInsured, 'premium' => $premium);
                 }
             }
             $this->policyCover->setCover($policyNumber, $coverOptions);
             if ($this->legacyMtaData->getPremium() == 0) {
                 //If no premium change there's no need to store anything in the transaction
                 return true;
             }
             $transaction = TransactionDecoratorFactory::getDecorator(TransactionDecoratorFactory::TRANSACTION_UPDATE, $policy->getAppData()->getPremium(), $insuranceNetAmount, $termData->id, $mtaId, $transBand, $this->legacyMtaData->getDateOnRisk(), $policy->getAppData());
             $transaction->processAllTransactions();
             return true;
         }
     }
     return false;
 }
 /**
  * Accept the quote and change it to a policy
  *
  * @param string $quoteNumber
  * @return null|string
  * @throws \RuntimeException
  */
 public function acceptQuote($quoteNumber)
 {
     /** @var \Manager_Core_PolicyNumber $policyNumberManager */
     $policyNumberManager = $this->getContainer()->get('rrp.legacy.manager.policy_number');
     if ($policyNumberManager->isRentRecoveryPlusQuote($quoteNumber)) {
         $this->isNewApplication = false;
         $policyNumber = $policyNumberManager::convertQuoteToPolicyNumber($quoteNumber);
         if ($this->populateByPolicyNumber($quoteNumber)) {
             //Set the issueDate and timecompleted fields (which oddly record the same value but
             // in different formats).
             $timeCompleted = time();
             $issueDate = new \DateTime();
             $issueDate->setTimestamp($timeCompleted);
             $this->setPolicyNumber($policyNumber)->appData->setStatus($this->getContainer()->get('rrp.legacy.const.status_policy'))->setPayStatus($this->getContainer()->get('rrp.legacy.const.pay_status_up-to-date'))->setIssueDate($issueDate)->setTimeCompleted($timeCompleted);
             $disbData = $this->disbursement->getDisbursement($this->appData->getWhiteLabelID(), $this->appData->getRateSetID());
             if (!$disbData) {
                 $message = sprintf('Disbursement data not found (WhiteLabelId = %s, RateSetID = %d)', $this->appData->getWhiteLabelID(), $this->appData->getRateSetID());
                 throw new \RuntimeException($message);
             }
             $getter = sprintf('getRrpi%s%dm', ReferenceTypes::isFullReference($this->rrpData->getReferenceType()) ? 'FullRef' : 'CreditCheck', $this->appData->getPolicyLength());
             if (PolicyOptionsManager::isOptionSet($this->appData->getPolicyOptions(), $this->container->get('rrp.legacy.const.policy_option_rrp-nilexcess'), $this->appData->getAmountsCovered())) {
                 $getter .= '0xs';
             }
             if (!method_exists($disbData, $getter)) {
                 $message = sprintf('Unknown disbursement type (%s)', $getter);
                 throw new \RuntimeException($message);
             }
             $disbursement = $disbData->{$getter}();
             if (empty($disbursement)) {
                 $message = sprintf('Disbursement data not set (WhiteLabelId = %s, RateSetID = %d, %s)', $this->appData->getWhiteLabelID(), $this->appData->getRateSetID(), $getter);
                 throw new \RuntimeException($message);
             }
             $propertyRental = PolicyOptionsManager::getOption($this->appData->getPolicyOptions(), $this->getContainer()->get('rrp.legacy.const.policy_option_rrp'), $this->appData->getAmountscovered());
             if ($propertyRental < RentRecoveryPlus::BAND_A_LIMIT) {
                 $band = $disbData::BAND_A;
                 $transBand = RentRecoveryPlus::BAND_A;
             } else {
                 $band = $disbData::BAND_B;
                 $transBand = RentRecoveryPlus::BAND_B;
             }
             $insuranceNetAmount = $disbData->extractBandDisbursement($disbursement, $band);
             $termId = $this->policyTerm->insertPolicyTerm($this->appData, $insuranceNetAmount);
             if ($termId) {
                 $policy = $this->container->get('rrp.legacy.datasource.policy');
                 if ($policy->save($this->appData)) {
                     //Delete the legacy quote.
                     $policyConstType = $this->container->get('rrp.legacy.const.quote_policy_number');
                     $this->application->remove(array($policyConstType => $quoteNumber));
                     // Now move the RRP / LL Interest parts
                     if ($this->rrp->accept($quoteNumber, $policyNumber)) {
                         if ($this->rrpTenantReference->accept($quoteNumber, $policyNumber, $termId)) {
                             if ($this->llInterest->accept($quoteNumber, $policyNumber)) {
                                 $this->policyNotes->changeQuoteToPolicy($quoteNumber, $policyNumber);
                                 $transaction = TransactionDecoratorFactory::getDecorator(TransactionDecoratorFactory::TRANSACTION_ADD, $this->getAppData()->getPremium(), $insuranceNetAmount, $termId, 0, $transBand, $this->appData->getStartDate(), $this->appData);
                                 $transaction->processAllTransactions();
                                 $underwriting = UnderwritingDecoratorFactory::getDecorator(UnderwritingDecoratorFactory::UNDERWRITING_RENT_RECOVERY_PLUS, $this->container->get('rrp.config.underwriting_question_set_id'), $this->appData->getIssueDate(), $quoteNumber);
                                 $underwriting->changeQuoteToPolicy();
                                 /** @var \Datasource_Insurance_Policy_Cover $policyCover */
                                 $policyCover = $this->container->get('rrp.legacy.datasource.policy_cover');
                                 $policyCover->changeQuoteToPolicy($quoteNumber, $policyNumber);
                                 return $policyNumber;
                             }
                         }
                     }
                 }
             }
         }
     }
     return null;
 }
 /**
  * Decline a rent guarantee policy renewal by populating the declined renewal table
  * and recording the reasons for non-renewal.
  *
  * @param string $policynumber Policy number
  * @param string $reason Reason label for non renewal
  * @param string $why Option reason why renewal was not performed
  * @param string $name Name of individual who declined the renewal
  * @param string $from Source of change
  * @return void
  */
 public function declinePolicyRenewal($policynumber, $reason, $why, $name, $from)
 {
     // Record the response reason
     $questionid = $this->_declinerenewalquestionsModel->getQuestionId($reason);
     $this->_declinerenewalresponsesModel->addResponse($policynumber, $questionid, $reason, $why);
     // add the policy to the black list table
     $this->_declinerenewalModel->declinePolicyRenewal($policynumber);
     // Add note to policy numbers
     $date = date("Y-m-d h:i:s a");
     $note = $name . " selected not to renew Rent Guarantee on {$from} {$date}. Reason stated: {$reason}.\n\n";
     $policynotesmodel = new Datasource_Insurance_PolicyNotes();
     $policynotesmodel->addNote($policynumber, $note);
 }
 /**
  * Dispatched each time the listener is triggered.
  *
  * @param ReferredEvent $event
  */
 public function onReferral(ReferredEvent $event)
 {
     $referral = $event->getReferral();
     $note = sprintf("This policy has been referred for the following reason(s)\n\n%s", implode("\n", $referral->getAllReferralReasons()));
     $this->policyNote->addNote($referral->getPolicyNumber(), $note);
 }