<?php
class Owner_IndexController extends Zend_Controller_Action
{
    /** 
     * Initialization
     */
    public function init()
    {
        $this->_helper->layout->disableLayout();
        $this->_redirector = $this->_helper->getHelper('Redirector');

        header('Pragma: no-cache');
        header("Cache-control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0, private");
		
		$this->session = Zend_Registry::get('defSession');
        $this->config = Zend_Registry::get('configuration');

        $this->view->ownerHost = $this->config->Domain->OwnerSecure;
        $this->view->vrapHost = $this->config->Domain->VRAPSecure;
        $this->view->wmspHost = $this->config->Domain->WMSP;

        // debug only        
        #$this->session->ownerNum = '00201221332';
        #$this->session->ownerNum = '00070000004';

        $action = $this->getRequest()->getActionName();
        if (!in_array($action,array('index','login','validate')))
        {
            if (!$this->session->ownerNum || trim($this->session->ownerNum) == '')
            {
                $this->_redirect('/ownerknowledgehub/index');
                exit; 
            }
        }

        /* BEGIN 2012-08-22 fabian.snaith@wyn.com - force HTTPS using Derek's domain variable: USING_HTTPS */
        if (ENV == 'production') {
            if (!isset($_SERVER['USING_HTTPS'])) { 
                // can't check for HTTP using Derek's domain var - email team
                $obj = new Email($this->config->Mail);
        
                $details = array(
                    'toEmail'   => $this->config->Mail->technical,
                    'toName'    => 'Development Team',
                    'subject'   => 'WMSP SSL Issue',
                    'htmlMsg'   => 'Temporary environment variable USING_HTTPS is not defined. Cannot force HTTPS on owner area of WMSP', 
                );
                $obj->send($details);
            }
            elseif ($_SERVER['USING_HTTPS'] == 'FALSE') {
                // redirect to https
                $redirectUrl = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
                header('Location: '.$redirectUrl);
                die();
            }
        }
        /* END 2012-08-22 fabian.snaith@wyn.com - force HTTPS using Derek's domain variable: USING_HTTPS */
    }

    public function indexAction()
    {
		$this->_helper->layout->setLayout('wmsp2');

        $params = $this->getRequest()->getParams();
        $section = $params['go'];
		
		$maintenance = $params["TestMaintenance"];

        $this->view->ownerNum = $this->session->ownerNum;
		
		if ($maintenance) {
			$this->session->maintenance = "true";
		}
			
        if (empty($this->session->ownerNum))
        {
            $url = '/ownerknowledgehub/index/login/';
		    $ping = false;
        }
        else
        {
            if (!in_array($section, array(
                        'finance','account','profile','booking','welcome',
                        'history','rci', 
                        #'profile-update','confirmed', - AN remove old news items 20130510
                        'autopay','autopay-confirmed'))) {

						#$section = 'welcome';
						$section = 'booking';
			}
                        

            $url = '/ownerknowledgehub/index/'.$section;
            $ping = true;

            /* disabled temporarily till i figure out why the result of the curl request isn't right

            # 06.06.2013 | Milan
            # Before finishing, do a login check to be sure the owner is logged in.
            # If not, lets show the login page
            #https://owners.wyndhamvrap.com/owners/secure/checkAvailabilityPre.do
            #echo $this->view->ownerHost.'/owners/secure/checkAvailabilityPre.do';
            $valid = $this->curl($this->view->ownerHost.'/owners/secure/checkAvailabilityPre.do');
            #var_dump(strpos($valid,'value="Sign In"'));var_dump(strpos($valid,'forgot'));echo '<pre>'.$valid;
            # How funny is this next part.
            if(strpos($output, '<base href="https://owners.wyndhamvrap.com/owners/sign-on-sp.jsp">')!==false)
            {
                # remove owner number from memory, they've timed out in USA system.
                unset($this->session->ownerNum);

                $url = '/ownerknowledgehub/index/login/';
                $ping = false;
            }
            #else echo 'p';
            # Yeah thats what happens when USA's project Voyager is 2 years late.
            # No webservices = curl requests + unreliably parsing text

            */
        }            
        
		date_default_timezone_set('Australia/Brisbane');
		
		$day = date("d/m/y");
		$time = date("H", time());
				
		if ( (strcmp($day,"11/12/14") === 0 && $time >= 4) || (strcmp($day,"12/12/14") === 0 && $time < 3))  {
			$url = "https://new.wyndhamvrap.com/underMaintenance.html";
		} 
		
        #echo $url;
        $this->view->section = $section;
        $this->view->url = $url;
        $this->view->ping = $ping;
    }
    
    public function autopayAction()
    {
        $this->view->ownerNum = $this->session->ownerNum;

        // grab data from web service
        $temp = $this->getDetail($this->session->ownerNum);
        $xml = simplexml_load_string($temp);
        $contracts = $xml->return->Contracts; 

        $t1 = array();        
        $t2 = array('AUD'=>false,'NZD'=>false);
        $t3 = array();
        foreach ($contracts->children() as $contract)
        {
            if (!$this->view->FirstContractNum)
                $this->view->FirstContractNum = $contract->ContractNum; 

            #$t1["c".$contract->ContractNum] = $contract->ContractNum.' ( Currency: '.$contract->Currency. ' )';
            $t1["c".$contract->ContractNum] = $contract->ContractNum;
            
            if ($contract->LeviesTBA == '1')
                $privilege = true;
            else
                $privilege = false;

            $t3["c".$contract->ContractNum] = $privilege;

            $temp = $contract->Currency;
            if ($temp == 'AUD') $t2['AUD'] = true;
            if ($temp == 'NZD') $t2['NZD'] = true;
            
        }

        // for testing dummy live account
        if ($this->session->ownerNum == '00201026014')
        {
            $t1 = array("c123456789012" => "123456789012");
            $t2['AUD'] = true;
            $t3 = array("c123456789012" => false);        
        }

        $this->view->ContractList = $t1;
        $this->view->CurrencyList = $t2; 
        $this->view->PrivilegeList = $t3; 

        
        // get AU state
        $temp = array(
            ''      =>  '',
            'QLD'   => 'QLD',
            'WA'    => 'WA',
            'SA'    => 'SA',
            'NT'    => 'NT',
            'NSW'   => 'NSW',
            'VIC'   => 'VIC',
            'TAS'   => 'TAS',
        );
        asort($temp);
        $this->view->StateList = $temp;

        $temp = array(
            ''     =>  '',
            'AE'   => 'Amex',
            #'BC'   => 'Bank Card',
            'DS'   => 'Discover',
            'DC'   => 'Diners',
            'JB'   => 'JCB',
            'MC'   => 'Mastercard',
            'VI'   => 'Visa',
        );
        $this->view->CardTypeList = $temp;

        $months = array(''=>'');
        for ($i=1;$i<=12;$i++)
        {
            $months[sprintf("%02d",$i)] = date('F', mktime(0,0,0,$i,1,2010));
        }
        $this->view->MonthList = $months;

        $years = array(''=>'');
        for ($i=2012;$i<=2020;$i++)
        {
            $years[sprintf("%04d",$i)] = $i;
        }
        $this->view->YearList = $years;
        
        $temp = array(
            ''    =>  '',
            'W'   => 'Week',
            'F'   => 'Fortnight',
            'M'   => 'Month',
        );
        $this->view->FinanceFeqList = $temp;

        $temp = array(
            ''    =>  '',
            'M'   => 'Month',
            'Q'   => 'Quarter',
        );
        $this->view->LeviesFeqList = $temp;

        $temp = array(
            'cc'    => 'Direct debit from my credit card',
            'bank'  => 'Direct debit from my financial institution account',
        );
        $this->view->PayMethodList = $temp;

        if ($this->getRequest()->isPost())
        {
            $data = array();
        
            // don't want rubbish, trim off space from $_POST data before validation
            foreach ($_POST as $k=>$v) { $_POST[$k] = trim($v); }
            
            #$_POST['contract_num'] = preg_replace("/[^0-9]/", "", $_POST['contract_num']);
            $_POST['bsb_num'] = preg_replace("/[^0-9]/", "", $_POST['bsb_num']);
            $_POST['acc_num'] = preg_replace("/[^0-9]/", "", $_POST['acc_num']);
            $_POST['cc_num'] = preg_replace("/[^0-9]/", "", $_POST['cc_num']);
            
            #echo '<pre>';
            #print_r($_POST);
            #echo '</pre>';

            // validation
            $fields = array(
                'contract_num' => array('alnum' ,1 ,1 ,null ,'Invalid Contract Number - enter digits only','Missing Contract Number'),
                'bank_name'    => array('regex' ,0 ,"/^[a-zA-Z\-\'\ ]*$/" ,null ,'Invalid Bank Name','Missing Bank Name'),
                'branch_name'  => array('regex' ,0 ,"/^[a-zA-Z\-\'\ ]*$/" ,null ,'Invalid Branch Name','Missing Branch Name'),
                'bsb_num'      => array('digit' ,0 ,6 ,6 ,'Invalid BSB Number - enter digits only','Missing BSB Number'),
                'acc_name'     => array('regex' ,0 ,"/^[a-zA-Z\-\'\ ]*$/" ,null ,'Invalid Account Name','Missing Account Name'),
                'acc_num'      => array('digit' ,0 ,6 ,null ,'Invalid Account Number - enter digits only','Missing Account Number'),
                'cc_type'      => array('alpha' ,0 ,2 ,2 ,'Invalid Credit Card Type','Missing Credit Card Type'),
                'cc_name'      => array('regex' ,0 ,"/^[a-zA-Z\-\'\ ]*$/" ,null ,'Invalid Card Holder Name','Missing Card Holder Name'),
                'cc_num'       => array('digit' ,0 ,14 ,16 ,'Invalid Credit Card Number','Missing Credit Card Number'),
                'cc_expiry_month' => array('digit' ,0 ,2 ,2 ,'Invalid Credit Card Expiry','Missing Credit Card Expiry'),
                'cc_expiry_year'  => array('digit' ,0 ,4 ,4 ,'Invalid Credit Card Expiry','Missing Credit Card Expiry'),
            );
            $form = FormValidator::GetInstance();
            $ok = $form->Validate($fields);
            if (!$ok)
            {
                foreach ($form->GetErrors() as $error)
                {
                    $this->view->PageError .= $error. '<br/>';
                }
                return;
            }

            if (!$_POST['finance_repayment'])
            {
                $_POST['finance_feq'] = '';
                $_POST['finance_start_opt'] = '';
                $_POST['finance_start_date'] = '';
            }
            else
            {
                if (!$_POST['finance_feq'])
                {
                    $this->view->PageError .= 'Invalid finance frequency<br/>';
                    return;
                }

                if ($_POST['finance_start_opt'] == 'first_repay_date')
                {
                    $_POST['finance_start_date'] = '';     
                }
                else
                {
                    if (!$_POST['finance_start_date'])
                    {
                        $this->view->PageError .= 'Invalid Finance Start Date<br/>';
                        return;
                    }
                    
                    $_POST['finance_start_date_formatted'] = date('mdy',strtotime($_POST['finance_start_date']));
                }
            }
            
            // get levies options
            if (!$_POST['wm_levies'])
            {
                $_POST['wm_levies_feq'] = '';
            }
            else
            {
                if (!$_POST['wm_levies_feq'])
                {
                    $this->view->PageError .= 'Invalid WM Levies payment frequency<br/>';
                    return;
                }
            }
            
            if (!$_POST['levies_priv_fees'])
            {
                $_POST['priv_levies_feq'] = '';
            }
            else
            {
                $_POST['priv_levies_feq'] = 'M';
            }
            
            // owner must commit to either finance or levy autopay
            if (!$_POST['finance_repayment'] && !$_POST['wm_levies'] && !$_POST['levies_priv_fees'])
            {
                $this->view->PageError .= 'Please tick the box for finance and/or levies payment below.<br/>';
                return;
            }

            // if direct debit from bank
            switch ($_POST['method'])
            {
                case 'bank':

                    $_POST['cc_type'] = '';
                    $_POST['cc_name'] = '';
                    $_POST['cc_num'] = '';
                    $_POST['cc_expiry_month']  = '';
                    $_POST['cc_expiry_year'] = '';
                    $_POST['cc_expiry'] = '';

                    if (!$_POST['bank_name'] || 
                        !$_POST['branch_name'] ||   
                        !$_POST['bsb_num'] ||   
                        !$_POST['acc_name'] ||   
                        !$_POST['acc_num'])   
                    {                        
                        $this->view->PageError .= 'Incomplete bank details.<br/>';
                        return;
                    }
                           
                    break;

                case 'cc':

                    $_POST['bank_name'] = ''; 
                    $_POST['branch_name'] = '';   
                    $_POST['bsb_num'] = '';  
                    $_POST['acc_name'] = '';   
                    $_POST['acc_num'] = '';  
                
                    if (!$_POST['cc_type'] || 
                        !$_POST['cc_name'] ||   
                        !$_POST['cc_num'] ||   
                        !$_POST['cc_expiry_month'] ||   
                        !$_POST['cc_expiry_year'])   
                    {    
                        $this->view->PageError .= 'Incomplete credit card details.<br/>';
                        return;
                    }
                    
                    if (strtoupper($_POST['cc_type']) == 'AX' && strlen($_POST['cc_num']) != 15) 
                    {
                        $this->view->PageError .= 'Invalid American Express card number.<br/>';
                        return;
                    }

                    if (!$this->validateCC($_POST['cc_num']))
                    {
                        $this->view->PageError .= 'Please enter a valid credit card number.<br/>';
                        return;
                    }                    
                    
                    $_POST['cc_expiry'] = $_POST['cc_expiry_month'].substr($_POST['cc_expiry_year'],-2);

                    break;

                default:

                    $this->view->PageError .= 'Invalid payment method.<br/>';
                    break;                    
            }
            
            // register via Web service
            foreach ($_POST as $k=>$v) { $data[$k] = urlencode($v); }
            
            $data['ip'] = $_SERVER['REMOTE_ADDR'];
            $data['owner_num'] = $this->session->ownerNum;
            $data['contract_num'] = preg_replace("/[^0-9]/", "", $_POST['contract_num']);
            $data['contract_num'] = sprintf("%012s", $data['contract_num']);

            $config = new Wyndham_Config_Xml(ROOT . '/config/cf.xml', ENV);
            $url = $config->WebService->Wyndham->URL;
            $secret_key = md5($config->WebService->Wyndham->Key);
            $client = new Zend_Soap_Client($url);
    		$obj = new XML();
            $post_xml = $obj->setResponse($data);
            $msg = $client->SetupAutopay($post_xml,$secret_key);
            if ($msg == 'success')
            {
                /*
                // send email to appropriate support
                ob_start();
                require ROOT.'/app/data/emails/profile-update-request.html';
                $body = ob_get_clean();        
                $obj = new Email($this->config->Mail);
    
                $details = array(
                    'toEmail'   => $this->config->Mail->owner_service,
                    'toName'    => 'Owner Support Officer',
                    'subject'   => 'Owner Profile Change Request',
                    'htmlMsg'   => $body, 
                );
                #$obj->send($details);
                */
           
                $this->_redirect('/ownerknowledgehub/index/autopay-confirmed');
                exit;
            }
            
            $this->view->PageError = $msg;
        }
        
        if (!$_POST['method']) $_POST['method'] = 'cc';
        
    }

    public function autopayConfirmedAction()
    {
    }    

    public function confirmedAction()
    {
    }
    
    public function profileUpdateAction()
    {
        // get AU state
        $states = array(
            ''      =>  '',
            'QLD'   => 'QLD',
            'WA'    => 'WA',
            'SA'    => 'SA',
            'NT'    => 'NT',
            'NSW'   => 'NSW',
            'VIC'   => 'VIC',
            'TAS'   => 'TAS',
        );
        asort($states);
        $this->view->stateList = $states;

        // get country
        $obj = new Countries();
        $list = $obj->getList();
        $countries = array('AU'=>'Australia');
        foreach ($list as $k=>$v)
        {
            $countries[$v->country_code] = $v->name; 
        }
        $this->view->countryList = $countries;

        // grab data from web service
        $temp = $this->getDetail($this->session->ownerNum);
        $xml = simplexml_load_string($temp);
        $owner = $xml->return;

        foreach ($owner->Contacts->children() as $contact)
        {
            $primary->FirstName = $contact->FirstName[0];
            $primary->LastName = $contact->LastName[0];
            $primary->Email = $contact->Email;
            $primary->HomePhone = $contact->HomePhone;
            $primary->WorkPhone = $contact->WorkPhone;
            $primary->Mobile = $contact->Mobile;
        
            foreach ($contact->Addresses[0]->children() as $address)
            {
                $primary->Street = trim($address->Street);
                $primary->City = trim($address->City);
                $primary->State = trim($address->State);
                $primary->PostCode = trim($address->PostCode);
                $primary->CountryCode = trim($address->CountryCode);
                break; 
            }

            break;
        }
        $owner = array_merge((array)$owner,(array)$primary);
        $data = (object)$owner; 
        
        echo '<pre>';
        #print_r($data);
        echo '</pre>';
        
        #$data = new stdClass();
        #$data->OwnerNum = $this->session->ownerNum;
        if (!$_POST['Country']) $_POST['Country'] = 'AU';
        if ($this->getRequest()->isPost())
        {
            // don't want rubbish, trim off space from $_POST data before validation
            foreach ($_POST as $k=>$v) { $_POST[$k] = trim($v); }
            
            $_POST['HomePhone'] = preg_replace("/[^0-9]/", "", $_POST['HomePhone']);
            $_POST['WorkPhone'] = preg_replace("/[^0-9]/", "", $_POST['WorkPhone']);
            $_POST['Mobile'] = preg_replace("/[^0-9]/", "", $_POST['Mobile']);

            // validation
            $fields = array(
                'FirstName'   => array('regex' ,1 ,"/^[a-zA-Z\-\'\ ]*$/" ,null ,'Invalid Firstname','Missing Firstname'),
                'LastName'    => array('regex' ,1 ,"/^[a-zA-Z\-\'\ ]*$/" ,null ,'Invalid Lastname','Missing Lastname'),
                'Email'       => array('email' ,1 ,null ,null ,'Invalid Email','Missing Email'), 
                'WorkPhone'   => array('digit' ,0 ,10 ,null ,'Invalid Day Time Contact Phone - enter digits only','Missing Day Time Contact Phone'),
                'HomePhone'   => array('digit' ,0 ,10 ,null ,'Invalid Home Phone - enter digits only','Missing Home Phone'),
                'Mobile'      => array('digit' ,0 ,10 ,null ,'Invalid Mobile - enter digits only','Missing Mobile'),
                'Street'      => array('regex' ,0 ,"/^[a-zA-Z0-9\-\'\ \,]*$/" ,null ,'Invalid Street','Missing Street'), 
                'City'        => array('regex' ,0 ,"/^[a-zA-Z0-9\-\'\ \,]*$/" ,null ,'Invalid City','Missing City'),
                'StateChoice' => array('regex' ,0 ,"/^[a-zA-Z0-9\-\ ]*$/" ,null ,'Invalid State/Province','Missing State/Province'),
                'StateText'   => array('regex' ,0 ,"/^[a-zA-Z0-9\-\ ]*$/" ,null ,'Invalid State/Province','Missing State/Province'),
                'PostCode'    => array('digit' ,0 ,4 ,null ,'Invalid Postcode - minimum 4 digits','Missing Postcode'),
                'Country'     => array('alpha' ,0 ,2 ,2    ,'Invalid Country','Missing Country'),
            );
            $form = FormValidator::GetInstance();
            $ok = $form->Validate($fields);
            if (!$ok)
            {
                foreach ($form->GetErrors() as $error)
                {
                    $this->view->PageError .= $error. '<br/>';
                }

                $data = (array)$data;
                $data = array_merge($data,$_POST);
                $data = (object)$data;
                $this->view->data = $data;
                return;
            }

            if ($_POST['Country'] != 'AU')
            {
                $_POST['State'] = $_POST['StateText'];
            }
            else
            {
                if ($_POST['Street'] != '' || $_POST['City'] != '' || $_POST['PostCode'] != '')
                {
                    if ($_POST['StateChoice'] == '' || !in_array($_POST['StateChoice'], $states))
                    {
                        $this->view->PageError .= 'Invalid State';
                    
                        $data = (array)$data;
                        $data = array_merge($data,$_POST);
                        $data = (object)$data;
                        $this->view->data = $data;
                        return;
                    }
    
                    $_POST['State'] = $_POST['StateChoice'];
    
                    $obj = new PostCodes();
                    $ok = $obj->isValid($_POST['PostCode'], $_POST['StateChoice']);
                    if (!$ok)
                    {
                        $this->view->PageError .= 'Invalid Postcode';
                    
                        $data = (array)$data;
                        $data = array_merge($data,$_POST);
                        $data = (object)$data;
                        $this->view->data = $data;
                        return;
                    }
                }
            }
            
            $_POST['CountryName'] = $countries[$_POST['Country']];

            // send email to appropriate support
            ob_start();
            require ROOT.'/app/data/emails/profile-update-request.html';
            $body = ob_get_clean();        
            $obj = new Email($this->config->Mail);

            $details = array(
                'toEmail'   => $this->config->Mail->owner_service,
                'toName'    => 'Owner Support Officer',
                'subject'   => 'Owner Profile Change Request',
                'htmlMsg'   => $body, 
            );
            $obj->send($details);
            
            $this->_redirect('/ownerknowledgehub/index/confirmed');
            exit; 
        }

        $this->view->data = $data;
        
    }    

    public function maintenanceAction()
    {
    }
    
    public function financeAction()
    {
        #$this->_forward('maintenance');
        #return;
    
        // grab data from web service
        $temp = $this->getDetail($this->session->ownerNum);
        $xml = simplexml_load_string($temp);
        $data = $xml->return;
        
        $this->view->OwnerNum = $data->OwnerNum;

        $primary = new stdClass();
        $primary->OwnerNum = $data->OwnerNum;

        foreach ($data->Contacts->children() as $contact)
        {
            #echo '<pre>';
            #print_r($contact);
            #echo '<hr>',$contact->FirstName[0];
            #echo '</pre>';
            
            $primary->Contact = $contact->FirstName[0].' '.$contact->LastName[0];
            $primary->Email = $contact->Email;
            $primary->HomePhone = $contact->HomePhone;
            $primary->WorkPhone = $contact->WorkPhone;
            $primary->Mobile = $contact->Mobile;
        
            foreach ($contact->Addresses[0]->children() as $address)
            {
                $full_address = '';
                
                $temp = trim($address->Street);
                if (substr($temp,-1) == ',') $temp = substr($temp,0,-1);
                if ($temp) $full_address .= $temp;
                
                $temp = trim($address->City);
                if (substr($temp,-1) == ',') $temp = substr($temp,0,-1);
                if ($temp) 
                {
                    if ($full_address != '') $full_address .= ', ';
                    $full_address .= $temp;
                }
                
                $temp = trim($address->State).' '.trim($address->PostCode);
                if (substr($temp,-1) == ',') $temp = substr($temp,0,-1);
                if ($temp) 
                {
                    if ($full_address != '') $full_address .= ', ';
                    $full_address .= $temp;
                }

                $temp = trim($address->CountryCode);
                if (substr($temp,-1) == ',') $temp = substr($temp,0,-1);
                if ($temp) 
                {
                    if ($full_address != '') $full_address .= ', ';
                    $full_address .= $temp;
                }

                $primary->Address = $full_address;
                
                break; 
            }

            break;
        }
        #echo '<pre>';
        #print_r($primary);
        #echo '</pre>';
        $this->view->Primary = $primary; 

        $finances = array();
        foreach ($data->Contracts->children() as $contract)
        {
            if ($contract->FinanceDirectDebit == 1)
                $contract->FinanceDD = 'Yes';
            else
                $contract->FinanceDD = 'No';                
            
            if ($contract->LeviesDirectDebit == 1)
                $contract->LeviesDD = 'Yes';
            else
                $contract->LeviesDD = 'No';                

            switch ($contract->CycleDay)
            {
                case '1':
                case '11':
                case '21':
                case '31':
                    $suffix = 'st';
                    break;
                case '2':
                case '22':
                    $suffix = 'nd';
                    break;
                case '3':
                    $suffix = 'rd';
                    break;
                default:
                    $suffix = 'th';
                    break;                                                            
            }
            $suffix .= ' of each month';
            
            if ($contract->CycleDay > 0)
                $contract->CycleDaySuffix = $suffix;                
                
            $finances[] = $contract;
        }

        #echo '<pre>';
        #print_r($finances);
        #echo '</pre>';
        $this->view->Finances = $finances;
        
    }

    public function rciAction()
    {
        $this->_helper->viewRenderer->setNoRender();            
        $this->_redirect($this->view->ownerHost.'/owners/secure/continueToRci.do');            

        exit; 
    }
    
    public function historyAction()
    {
        $this->_helper->viewRenderer->setNoRender();            
        $this->_redirect($this->view->ownerHost.'/owners/secure/showReservationHistory.do');            

        exit; 
    }
    
    public function bookingAction()
    {
        $this->_helper->viewRenderer->setNoRender();            
        $this->_redirect($this->view->ownerHost.'/owners/secure/checkAvailabilityPre.do');            

        exit; 
    }

    public function profileAction()
    {
        $this->_helper->viewRenderer->setNoRender();            
        $this->_redirect($this->view->ownerHost.'/owners/secure/editProfile.do');            

        exit; 
    }
    
    public function accountAction()
    {
        $this->_helper->viewRenderer->setNoRender();            
        $this->_redirect($this->view->ownerHost.'/owners/secure/getFinancialInfo.do');            

        exit; 
    }

    public function welcomeAction()
    {
    }

    public function loginAction()
    {
        $this->view->errorMsg = $this->session->loginError;
$this->session->loginStatus == 2;
	if($this->session->loginStatus == 1) {
		// fial login
		$this->view->errorMsgTitle = 'An incorrect Owner Number or password has been entered.';
		$this->view->errorMsgContent = 'Please try again; entering your 11-digit Owner Number and checking your CAPs lock is turned off. If you have seen this error more than once, please click \'I forgot my password\' to retrieve your password or <a href="http://www.wyndhamap.com/wps/wcm/connect/wyndham/home/sitetools/contact-us?contactType=owner&enquiryTypeId=3">contact</a> Owner Services who can assist with your query.';

	} else if ($this->session->loginStatus == 2) {
		// no server
		$this->view->errorMsgTitle = 'Your Owner Login section is currently unavailable.';
		$this->view->errorMsgContent = 'We are currently experiencing technical difficulties and are unable to action your login request. Please try again shortly or, if your query is urgent, please <a href="http://www.wyndhamap.com/wps/wcm/connect/wyndham/home/sitetools/contact-us?contactType=owner&enquiryTypeId=3">contact</a> your Owner Services team.';
	}




		$params = $this->getRequest()->getParams();		
		$maintenance = $params["TestMaintenance"];
		
		if ($maintenance || $this->session->maintenance) {
			$this->view->maintenance = "true";
		}
		
        unset($this->session->loginError);
    }
    
    public function logoffAction()
    {
        unset($this->session->ownerNum);
        $this->_redirect('http://www.wyndhamap.com/wps/wcm/connect/Wyndham/home/WorldMarkSP');   
    }
    
	public function devLog($str,$val="") {

    	try {
    		
    		if (isset($val)) {
    			ob_start();
    			var_dump($val);
    		
    			$str .= " : " . ob_get_clean();
    		}
    		
    		file_put_contents("/var/tmp/LogFile.txt",date("d/m/y g:i:s")." ".$str."\r\n",FILE_APPEND);
    		
    	} catch (Exception $e) {
    		
    	}
    }
	
    /** Validate an owner login attempt - 2012-08-21 - documented by fabian.snaith@wyn.com
     *
     *  Because we don't have any interface to authenticate users we must spoof the login proceedure and sniff the response. 
     *  How it works is we catch the user login form submission via javascript and submit it back here via Ajax. 
     *  We then curl the response to the U.S and sniff the repsonse and output a flag for the authentication outcome back to the browser's executing JS. 
     *  If the outcome was unsuccessful we display an error, otherwise we allow the form to officially submit and 
     *  hence the standard authentication proceedure takes place as per normal unbeknown to the user. 
     */
    public function validateAction()
    {
        $success = false; // flag whether authentication was successful

        $this->_helper->viewRenderer->setNoRender();            
    
        if ($this->getRequest()->isPost())
        {
            $params = $this->getRequest()->getParams();
			
            $ownerNum = $params['Number'];
            $password = $params['Password'];
            
			$url = $this->view->ownerHost.'/owners/signIn.do';
			$headers = array();
			  
            $ch = curl_init();
            
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_HEADER, 0);          // get the header
            curl_setopt($ch, CURLOPT_NOBODY, 1);          // ONLY get the header
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  // get the response as a string from curl_exec(), rather than echoing it
            curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);   // don't use a cached version of the url
    
            curl_setopt($ch, CURLOPT_URL, $url); # this is where you first time connect - GET method authorization in my case, if you have POST - need to edit code a bit
            curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, "number=$ownerNum&password=$password&region=sp"); # form params that'll be used to get form results
			
			$output = curl_exec($ch);
            $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            
            curl_close ($ch);
	
            /** 2012-08-21 - fabian.snaith@wyn.com - BEGIN positive result guarding logic **/
            if ($output) {
                // check page response for elements in page from secure area
                // method is primitive but our only option is to spoof login and sniff response
                if (strpos($output, '<base href="https://owners.wyndhamvrap.com/owners/secure/availability-main.jsp">')) {
                    $success = true; // set flag to true
		    $this->session->loginStatus = 0; // success
                } else if(strpos($output, 'invalid')) {
		    $this->session->loginStatus = 1; // fail login
		} else {
		    $this->session->loginStatus = 2; // no server
		}
            } else {
		$this->session->loginStatus = 2; // no server
 	    }
			
            // now output result back to browser ajax call
            // We're safe here as a successful result merely resubmits the original login form, so if this request
            // is spoofed the authentication resubmission will still fail
            if ($success) 
            {
                $this->session->ownerNum = $ownerNum;
				echo 'Success';
            } else {
                $this->session->loginError = 'Error: Invalid Owner Number/Password specified.';

                echo 'Fail';
            }
            /** 2012-08-21 - fabian.snaith@wyn.com - END positive result guarding logic **/
        }                    
    }
    
    private function getDetail($owner_num)
    {
        $config = new Wyndham_Config_Xml(ROOT . '/config/cf.xml', ENV);
        $url = $config->WebService->Wyndham->URL;
        $secret_key = md5($config->WebService->Wyndham->Key);
        $client = new Zend_Soap_Client($url);
		$obj = new XML();
        $post_xml = $obj->setResponse($data);
        return $client->GetFinanceInfo($owner_num,$secret_key);
    }

	private function validateCC($cc_number) {
		$cc_number = trim($cc_number);
		$first_number = substr($cc_number, 0, 1);
		switch ($first_number)
		{
			case 3:
				if (preg_match('/^3\d{2}[ \-]?\d{6}[ \-]?\d{5}$/', $cc_number)){
					return true; // American Express number is correct. Process the credit card.
				}
				if (preg_match('/^3\d{3}[ \-]?\d{6}[ \-]?\d{5}$/', $cc_number)){
					return true; // American Express number is correct. Process the credit card.
				}
				break;
				
			case 4:
				if (preg_match('/^4\d{3}[ \-]?\d{4}[ \-]?\d{4}[ \-]?\d{4}$/', $cc_number)) {
					return true; // Visa number is correct. Process the credit card.
				}
				break;
				
			case 5:
				if (preg_match('/^5\d{3}[ \-]?\d{4}[ \-]?\d{4}[ \-]?\d{4}$/', $cc_number)) {
					return true; // MasterCard number is correct. Process the credit card.
				}
				break;
				
			case 6:
				if (preg_match('/^6011[ \-]?\d{4}[ \-]?\d{4}[ \-]?\d{4}$/', $cc_number)) {
					return true; // Discover Card number is correct. Process the credit card.
				}
				break;
				
			default:
				// error
		}
		return false;
	}


    // Simple curl request
    private function curl($url,$params=array())
    {
        #http://10.56.190.131/owner/get-owner-information/owner/00202405136
        #http://10.56.190.131/owner/get-contract-information/owner/00201908338
        #http://10.56.190.131/owner/get-reservation-information/owner/00201955591

        $ch = curl_init();

        $headers = array(
            'User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11',
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language: en-au,en;q=0.5',
            'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
            'Keep-Alive: 300',
            'Connection: Keep-Alive',
            'Cache-Control: max-age=0',
            'Content-type: application/x-www-form-urlencoded;charset=UTF-8',
            'Pragma: ', // browsers keep this blank
        );
        
        $params_string = http_build_query($params);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_HEADER, 0);          // get the header
        curl_setopt($ch, CURLOPT_NOBODY, 1);          // ONLY get the header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  // get the response as a string from curl_exec(), rather than echoing it
        curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);   // don't use a cached version of the url

        curl_setopt($ch, CURLOPT_URL, $url); # this is where you first time connect - GET method authorization in my case, if you have POST - need to edit code a bit
        curl_setopt($ch, CURLOPT_POST, 0); # Use Get
        #curl_setopt($ch, CURLOPT_POSTFIELDS, $params_string); # form params that'll be used to get form results
        $output = curl_exec($ch);
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        
        curl_close ($ch);

        #echo'<pre>'.htmlentities(print_r($output,true));
        return $output;
    }
}
