/**
  * Display a list of quotes that can be retrieved after a user has identified themselves with an auth token via
  * retrieveQuoteAction().  Having this separate action allows an end user to press "Back" for up to an hour if they
  * have chosen to continue the wrong quote.
  *
  * @return void
  */
 public function retrieveMultipleQuotesAction()
 {
     if ($this->getRequest()->getParam('auth') != '') {
         $params = Zend_Registry::get('params');
         $mac = $this->getRequest()->getParam('auth');
         $securityManager = new Application_Core_Security($params->myhomelet->retrieveWithoutAccount->macSecret, $params->myhomelet->retrieveWithoutAccount->macTimestampVariance != 0, $params->myhomelet->retrieveWithoutAccount->macTimestampVariance);
         $dataKeys = array('customerEmail');
         $securityCheck = $securityManager->authenticate($mac, $dataKeys);
         if (isset($securityCheck['result']) && $securityCheck['result']) {
             // Customer has multiple quotes associated with their email address - look them up and generate a set of
             // auth tokens, show user the selection
             $email = $securityCheck['data']['customerEmail'];
             $policyCoverDatasource = new Datasource_Insurance_LegacyPolicyCovers();
             $customerManager = new Manager_Core_Customer();
             // Get all legacy quote IDs by customer e-mail address
             $legacyIDs = array();
             // Try to look up a customer record's quotes' IDs by the e-mail provided
             $newCustomer = $customerManager->getCustomerByEmailAddress($email);
             if ($newCustomer) {
                 $legacyCustomerMap = new Datasource_Core_CustomerMaps();
                 $legacyIDs = $legacyCustomerMap->getLegacyIDs($newCustomer->getIdentifier(Model_Core_Customer::IDENTIFIER));
             }
             // Also check in the legacy DB only to ensure landlords quotes are found
             $customer = $customerManager->getLegacyCustomerByEmailAddress($email);
             if ($customer) {
                 $legacyCustomerId = $customer->getIdentifier(Model_Core_Customer::LEGACY_IDENTIFIER);
                 if (!in_array($legacyCustomerId, $legacyIDs)) {
                     $legacyIDs[] = $legacyCustomerId;
                 }
             }
             // Retrieve all quotes for the linked customer reference numbers
             $quoteDatasource = new Datasource_Insurance_LegacyQuotes();
             $quotes = $quoteDatasource->getActiveQuotes($legacyIDs, '', array('policynumber', 'startdate'));
             // Build the list of policy covers and generate auth tokens for each policy
             // Should be done in a manager, but the quote manager has been written with the row data gateway
             // design pattern in mind.
             $authTokens = array();
             foreach ($quotes as $quote) {
                 // Create list of policy covers
                 $policyCoverList = array();
                 $policyOptionsplit = explode('|', $quote->policyOptions);
                 $sumInsuredSplit = explode('|', $quote->amountsCovered);
                 for ($i = 0; $i < count($policyOptionsplit); $i++) {
                     if ($sumInsuredSplit[$i] == 'yes' || floatval($sumInsuredSplit[$i]) > 0) {
                         // A sum insured value has been set so assume cover is in force
                         $policyCover = $policyCoverDatasource->getPolicyCoverByLabel($policyOptionsplit[$i]);
                         if ($policyCover) {
                             array_push($policyCoverList, array('cover' => $policyOptionsplit[$i], 'name' => $policyCover->getName()));
                         }
                     }
                 }
                 $quote->policyCovers = $policyCoverList;
                 // Generate a policy-specific authentication token
                 $securityManager = new Application_Core_Security($params->myhomelet->retrieveWithoutAccount->macSecret, $params->myhomelet->retrieveWithoutAccount->macTimestampVariance != 0, $params->myhomelet->retrieveWithoutAccount->macTimestampVariance);
                 $securityData = array('quoteNumber' => $quote->policyNumber);
                 $authTokens[$quote->policyNumber] = $securityManager->generate($securityData);
             }
             // Pass quotes and auth tokens into view and finish
             $this->view->quotes = $quotes;
             $this->view->authTokens = $authTokens;
             return;
         }
     }
     // Failover for non-auth or other issue - go to main retrieve quote form
     $this->_helper->redirector->gotoUrl('/my-homelet/retrieve-quote');
 }
 public function saveStep1(Zend_Form $pageForm)
 {
     // Get sub forms
     $subFormPersonalDetails = $pageForm->getSubForm('subform_personaldetails');
     $subFormDataProtection = $pageForm->getSubForm('subform_dataprotection');
     $subFormCorrespondenceDetails = $pageForm->getSubForm('subform_correspondencedetails');
     $subFormInsuredAddress = $pageForm->getSubForm('subform_insuredaddress');
     $subFormPolicyDetails = $pageForm->getSubForm('subform_policydetails');
     $subFormIdd = $pageForm->getSubForm('subform_idd');
     if (isset($this->_quoteID) && !is_null($this->_quoteID)) {
         $quoteManager = new Manager_Insurance_LandlordsPlus_Quote($this->_quoteID);
     } else {
         // Create a new quote
         $quoteManager = new Manager_Insurance_LandlordsPlus_Quote();
         $this->_quoteID = $quoteManager->getModel()->ID;
         // Save the ID in the session for future use
         $session = new Zend_Session_Namespace('landlords_insurance_quote');
         $session->quoteID = $this->_quoteID;
     }
     // Check to see if we have a session
     $customerManager = new Manager_Core_Customer();
     // Check to see if we are already logged in
     $auth = Zend_Auth::getInstance();
     $auth->setStorage(new Zend_Auth_Storage_Session('homelet_customer'));
     $pageSession = new Zend_Session_Namespace('landlords_insurance_quote');
     $pageSession->quoteID = $this->_quoteID;
     if (!isset($this->_customerReferenceNumber)) {
         // Do we already have a legacy customer with this email address?
         $customer = $customerManager->getLegacyCustomerByEmailAddress($subFormPersonalDetails->getElement('email_address')->getValue());
         // We don't have a session so we need to create a legacy customer/quote entry to save against
         if (!$customer) {
             $customer = $customerManager->createNewCustomer($subFormPersonalDetails->getElement('email_address')->getValue(), Model_Core_Customer::CUSTOMER, true);
         }
         // Now get the reference number from the newly created customer
         $customerRefNo = $customer->getIdentifier(Model_Core_Customer::LEGACY_IDENTIFIER);
         $this->_customerReferenceNumber = $customerRefNo;
         $pageSession->customerRefNo = $customerRefNo;
     } else {
         // We are in session so just instantiate the customer manager with the existing reference number
         $customer = $customerManager->getCustomer(Model_Core_Customer::LEGACY_IDENTIFIER, $this->_customerReferenceNumber);
         $customerRefNo = $pageSession->customerRefNo;
     }
     $pageSession->CustomerDob = $subFormPersonalDetails->getElement('date_of_birth_at')->getValue();
     $quoteManager->setLegacyCustomerReference($customerRefNo);
     //Capture and store the insurance data protections.
     if ($subFormDataProtection->getElement('dpa_phone_post')->getValue() == 1) {
         $dpaPhonePost = 1;
     } else {
         $dpaPhonePost = 0;
     }
     if ($subFormDataProtection->getElement('dpa_sms_email')->getValue() == 1) {
         $dpaSMSEmail = 1;
     } else {
         $dpaSMSEmail = 0;
     }
     if ($subFormDataProtection->getElement('dpa_resale')->getValue() == 1) {
         $dpaResale = 1;
     } else {
         $dpaResale = 0;
     }
     // Update the customer record with the form data
     if ($subFormPersonalDetails->getElement('title')->getValue() != "Other") {
         $customer->setTitle($subFormPersonalDetails->getElement('title')->getValue());
     } else {
         $customer->setTitle($subFormPersonalDetails->getElement('other_title')->getValue());
     }
     $customer->setFirstName($subFormPersonalDetails->getElement('first_name')->getValue());
     $customer->setLastName($subFormPersonalDetails->getElement('last_name')->getValue());
     $customer->setTelephone(Model_Core_Customer::TELEPHONE1, $subFormPersonalDetails->getElement('phone_number')->getValue());
     $customer->setTelephone(Model_Core_Customer::TELEPHONE2, $subFormPersonalDetails->getElement('mobile_number')->getValue());
     $customer->setEmailAddress($subFormPersonalDetails->getElement('email_address')->getValue());
     $customer->setDateOfBirthAt(Application_Core_Utilities::ukDateToMysql($subFormPersonalDetails->getElement('date_of_birth_at')->getValue()));
     $customer->setCountry($subFormCorrespondenceDetails->getElement('country')->getValue());
     if ($subFormCorrespondenceDetails->getElement('cor_foreign_address')->getValue() == 1) {
         $customer->setIsForeignAddress(true);
     } else {
         $customer->setIsForeignAddress(false);
     }
     $customerManager->updateCustomer($customer);
     if ($auth->hasIdentity()) {
         // Customer is logged in - so we need to link the new customer to the old
         $customerID = $auth->getStorage()->read()->id;
         $customer = $customerManager->getCustomer(Model_Core_Customer::IDENTIFIER, $customerID);
         $customerManager->linkLegacyToNew($customerRefNo, $customerID);
     }
     // Update the customer with the new correspondence address
     $customer->setAddressLine(Model_Core_Customer::ADDRESSLINE1, $subFormCorrespondenceDetails->getElement('cor_address_line1')->getValue());
     $customer->setAddressLine(Model_Core_Customer::ADDRESSLINE2, $subFormCorrespondenceDetails->getElement('cor_address_line2')->getValue());
     $customer->setAddressLine(Model_Core_Customer::ADDRESSLINE3, $subFormCorrespondenceDetails->getElement('cor_address_line3')->getValue());
     $customer->setPostCode($subFormCorrespondenceDetails->getElement('cor_address_postcode')->getValue());
     // Whether a new customer or an existing customer without a DoB stored, allow the DoB supplied in the form to be
     // stored if what's there now is blank
     if (null === $customer->getDateOfBirthAt() || '0000-00-00' == $customer->getDateOfBirthAt()) {
         $customer->setDateOfBirthAt(Application_Core_Utilities::ukDateToMysql($subFormPersonalDetails->getElement('date_of_birth_at')->getValue()));
     }
     $customerManager->updateCustomer($customer);
     // Update the quote with new values and save it
     $quoteManager->setStartDate(Application_Core_Utilities::ukDateToMysql($subFormPolicyDetails->getElement('policy_start')->getValue()));
     $quoteManager->setEndDate(Application_Core_Utilities::ukDateToMysql($subFormPolicyDetails->getElement('policy_end')->getValue()));
     // Check to see if the property is a 1000 flood area - if it is force the exclude_flood_cover flag
     $riskAreasDatasource = new Datasource_Insurance_LandlordsPlus_RiskAreas();
     $riskAreas = $riskAreasDatasource->getByPostcode($subFormInsuredAddress->getElement('ins_address_postcode')->getValue());
     if ($riskAreas['floodArea'] = '1000') {
         $subFormInsuredAddress->getElement('exclude_flood_cover')->setValue(true);
     }
     // Add property details
     $quoteManager->addProperty($subFormInsuredAddress->getElement('ins_address_postcode')->getValue(), $subFormInsuredAddress->getElement('ins_address_line3')->getValue(), '', $subFormInsuredAddress->getElement('ins_address_line1')->getValue(), $subFormInsuredAddress->getElement('tenants_type')->getValue(), $subFormInsuredAddress->getElement('through_letting_agent')->getValue() == 'yes' ? true : false, $subFormInsuredAddress->getElement('owned_for')->getValue(), $subFormInsuredAddress->getElement('no_claims')->getValue(), $subFormInsuredAddress->getElement('exclude_flood_cover')->getValue() == 'no' ? true : false, $subFormInsuredAddress->getElement('ins_address_line2')->getValue());
     // Set the new letting agent details if we have them
     $session = new Zend_Session_Namespace('homelet_global');
     $agentSchemeNumber = $session->agentSchemeNumber;
     // Store result to quote manager and session
     $quoteManager->setAgentSchemeNumber($agentSchemeNumber);
     $quoteManager->save();
     $session->agentSchemeNumber = $agentSchemeNumber;
     // Set the contact preferences
     $contactPreferences = new Model_Core_CustomerContactPreferences();
     $contactPreferences->addPreference(Model_Core_CustomerContactPreferences::EMAIL_METHOD);
     $quoteManager->setContactPreference($contactPreferences);
     //Record this WebLead, if not already done so. First create or
     //retrieve the WebLead summary.
     $webLeadManager = new Manager_Core_WebLead();
     if (empty($pageSession->webLeadSummaryId)) {
         $isNewWebLead = true;
         $webLeadSummary = $webLeadManager->createNewSummary();
     } else {
         $isNewWebLead = false;
         $webLeadSummary = $webLeadManager->getSummary($pageSession->webLeadSummaryId);
     }
     //Create or retrieve the step 1 blob.
     if (!$webLeadManager->getBlobExists($webLeadSummary->webLeadSummaryId, Model_Core_WebLeadStep::STEP1)) {
         $webLeadBlob = $webLeadManager->createNewBlob($webLeadSummary->webLeadSummaryId, Model_Core_WebLeadStep::STEP1);
     } else {
         $webLeadBlob = $webLeadManager->getBlob($webLeadSummary->webLeadSummaryId, Model_Core_WebLeadStep::STEP1);
     }
     //Update the WebLead summary and store.
     $webLeadSummary->title = $subFormPersonalDetails->getElement('title')->getValue();
     $webLeadSummary->firstName = $subFormPersonalDetails->getElement('first_name')->getValue();
     $webLeadSummary->lastName = $subFormPersonalDetails->getElement('last_name')->getValue();
     if ($subFormPersonalDetails->getElement('phone_number')->getValue() != '') {
         $contactNumber = $subFormPersonalDetails->getElement('phone_number')->getValue();
     } else {
         $contactNumber = $subFormPersonalDetails->getElement('mobile_number')->getValue();
     }
     $webLeadSummary->contactNumber = $contactNumber;
     $webLeadSummary->emailAddress = $subFormPersonalDetails->getElement('email_address')->getValue();
     if ($isNewWebLead) {
         $webLeadSummary->startTime = $this->_offsetDate();
     }
     $webLeadSummary->lastUpdatedTime = $this->_offsetDate();
     $webLeadSummary->product = Model_Core_WebLeadProduct::LANDLORDSPLUS;
     $webLeadSummary->quoteNumber = $quoteManager->getLegacyID();
     $webLeadManager->updateSummary($webLeadSummary);
     //Update the blob, serialize and store.
     $webLeadBlob->blob = Zend_Json::encode($_POST);
     $webLeadBlob->blobChecksum = crc32($webLeadBlob->blob);
     $webLeadManager->updateBlob($webLeadBlob);
     //Finally, record the WebLead identifier in the page session.
     $pageSession->webLeadSummaryId = $webLeadSummary->webLeadSummaryId;
     //Capture and store the Insurance and WebLead data protections.
     $this->_saveDPA($customerRefNo, Model_Core_DataProtection_ItemEntityTypes::INSURANCE, $dpaPhonePost, $dpaSMSEmail, $dpaResale);
     $this->_saveDPA($webLeadSummary->webLeadSummaryId, Model_Core_DataProtection_ItemEntityTypes::WEBLEAD, $dpaPhonePost, $dpaSMSEmail, $dpaResale);
 }