<?php
require_once 'modules/admin/models/Package.php';
require_once 'modules/admin/models/PackageTypeGateway.php';
require_once 'modules/admin/views/public/SignupView.php';
include_once "newedge/classes/NE_PluginCollection.php";

/**
* @package Admin
*/
class ViewSignup_4_YourInfo extends SignupView
{
    var $permission     = '';


    function dispatch()
    {

        $this->initialize();

        // Init some vars
        $this->templateInit();
        $this->currencys = new Currency($this->user);

        // Process the form post of the summary if something was done with it
        if($_POST) {
            $this->processFormPost($_REQUEST, @$_REQUEST['formId'], 'cartSummary');
        }

        // Allow Coupons?
        if(@$this->settings->get("Accept Coupons") == 1) {
            $this->tplView->acceptCoupons = true;
        }

        // Process the progress bar
        $this->tplView->progress = $this->getProgressBar(4);
        $this->tplView->progressBar = $this->tplView->fetch('progressBar.tpl.php');

         // Check if the cart has been tampered with
        if(NE_Lib::generateSignupCartHash() == @$_SESSION['cartHash'] && @$_SESSION['cartHash'] != null) {

            // Get the cart items
            $cartSummary = $this->getCartSummary();
	        $this->tplView->cartItems = $cartSummary['items'];
	        $this->tplView->cartTotal = $cartSummary['total'];
	        $this->tplView->cartCount = $cartSummary['totalCount'];            

        } else {

            // Redirect back to the first step
            include("modules/admin/views/public/Signup_0_PackageGroup.php");

            ViewSignup_0_PackageGroup::dispatch();
            //$this->showFooter(); // Show the footer to set the header vars etc properly
            return;
        }
        
        // Store a session to stop us re-adding the last cart item if we hit back
        $_SESSION['avoidaddpackage'] = true;

        // Do we have an error from processing?
        if(@$_REQUEST['errorReason']) {
            $this->tplView->fieldError = $_REQUEST['errorReason'];
        }

        // Call the custom fields. Moved it to SignupView for now so that we can re-use it.
        $customFields = $this->getCustomProfileFields(@$_REQUEST['oldFields']);

        $this->tplView->customFields = @$customFields['profileFields'];

        if ($this->user->getEmail() != '' && !$this->user->isAdmin()) {
            $this->tplView->loggedIn = true;
            $countryCode = $this->user->getCountry();
            $stateCode = $this->user->getState();
            $vatNumber = $this->user->getVatNumber();
            $isTaxable = $this->user->isTaxable();
            $userID = $this->user->getId();
        } else {
            $this->tplView->loggedIn = false;
            $countryCode = null;
            $stateCode = null;
            $vatNumber = null;
            $isTaxable = true;
            $userID = false;
        }

        // Sort out the tax
        $this->tplView->tax = $this->processCartTax($cartSummary, $countryCode, $stateCode, $vatNumber, $isTaxable, $userID);
        


        // Start billing / payment processors
        $plugins = new NE_PluginCollection("gateways", $this->user);

        // Get a list of valid payment processors
        $pluginsArray = array();
        while ($tplugin = $plugins->getNext()) {
            $tvars = $tplugin->getVariables();
            $tvalue = $this->varLang($tvars['Plugin Name']['value']);
            $pluginsArray[$tvalue] = $tplugin;
        }
        uksort($pluginsArray, "strnatcasecmp");

        // Start making the array
        $this->tplView->paymentmethods = array();

        // Loop the processors
        foreach ($pluginsArray AS $value => $plugin) {

            // Start the array
            $paymentmethod = array();

            // Is the plugin live?
            if (($plugin->getVariable("In Signup") == "1") ) {

                // Set some variables
                $paymentmethod['paymentTypeOptionValue'] = $plugin->getInternalName();
                $paymentmethod['paymentTypeOptionLabel'] = $plugin->getVariable("Signup Name"). '&nbsp;&nbsp;&nbsp;';
                $paymentmethod['description'] = $plugin->getVariable('Payment Description');

                if(isset($_REQUEST['paymentMethod'])){
                    // Select the plugin if it was already selected
                    if ($_REQUEST['paymentMethod'] == $plugin->getInternalName()){
                        $paymentmethod['paymentTypeOptionSelected'] = true;
                        $this->tplView->defaultGateway = $plugin->getInternalName();
                    } else {
                        $paymentmethod['paymentTypeOptionSelected'] = false;
                    }
                }else{
                    // Select the plugin if it's default
                    if ($this->settings->get('Default Gateway') == $plugin->getInternalName()){
                        $paymentmethod['paymentTypeOptionSelected'] = true;
                        $this->tplView->defaultGateway = $plugin->getInternalName();
                    } else {
                        $paymentmethod['paymentTypeOptionSelected'] = false;
                    }
                }

                if(@$this->settings->get("plugin_".$plugin->getInternalName()."_Auto Payment") == 1){
                    $paymentmethod['autoPayment'] = 1;
                } else {
                    $paymentmethod['autoPayment'] = 0;
                }
                
                // Handle credit card plugins
                if(@$this->settings->get("plugin_".$plugin->getInternalName()."_Accept CC Number") == 1) {

                    // Start the fields
                    $paymentmethod['extraFields'] = array();

                    // Handle the we accept list
                    $weAccept = array();
                    if(!is_null($this->settings->get("plugin_".$plugin->getInternalName()."_Visa")) && $this->settings->get("plugin_".$plugin->getInternalName()."_Visa") == 1){
                        $weAccept[] = array('id' => 'visa_logo', 'alt' => 'Visa', 'img' => 'images/creditcards/visa.gif');
                    }
                    if(!is_null($this->settings->get("plugin_".$plugin->getInternalName()."_MasterCard")) && $this->settings->get("plugin_".$plugin->getInternalName()."_MasterCard") == 1){
                        $weAccept[] = array('id' => 'mastercard_logo', 'alt' => 'MasterCard', 'img' => 'images/creditcards/mc.gif');
                    }
                    if(!is_null($this->settings->get("plugin_".$plugin->getInternalName()."_AmericanExpress")) && $this->settings->get("plugin_".$plugin->getInternalName()."_AmericanExpress") == 1){
                        $weAccept[] = array('id' => 'americanexpress_logo', 'alt' => 'American Express', 'img' => 'images/creditcards/amex1.gif');
                    }
                    if(!is_null($this->settings->get("plugin_".$plugin->getInternalName()."_Discover")) && $this->settings->get("plugin_".$plugin->getInternalName()."_Discover") == 1){
                        $weAccept[] = array('id' => 'discover_logo', 'alt' => 'Discover', 'img' => 'images/creditcards/discover.gif');
                    }
                    if(!is_null($this->settings->get("plugin_".$plugin->getInternalName()."_LaserCard")) && $this->settings->get("plugin_".$plugin->getInternalName()."_LaserCard") == 1){
                        $weAccept[] = array('id' => 'lasercard_logo', 'alt' => 'LaserCard', 'img' => 'images/creditcards/laser.gif');
                    }
                    if(!is_null($this->settings->get("plugin_".$plugin->getInternalName()."_DinersClub")) && $this->settings->get("plugin_".$plugin->getInternalName()."_DinersClub") == 1){
                        $weAccept[] = array('id' => 'dinersclub_logo', 'alt' => 'DinersClub', 'img' => 'images/creditcards/diners.gif');
                    }
                    if(!is_null($this->settings->get("plugin_".$plugin->getInternalName()."_Switch")) && $this->settings->get("plugin_".$plugin->getInternalName()."_Switch") == 1){
                        $weAccept[] = array('id' => 'switch_logo', 'alt' => 'Switch', 'img' => 'images/creditcards/switch.gif');
                    }
                    $paymentmethod['extraFields'][] = array(
                                'fieldType' => 'weaccept',
                                'fieldName' => 'ccWeAccept',
                                'fieldTitle'=> $this->lang('We Accept'),
                                'fieldValue'=> $weAccept
                             );

                    
                    // Card Number
                    $paymentmethod['extraFields'][] = array(
                            'fieldType' => 'text',
                            'fieldName' => $plugin->getInternalName().'_ccNumber',
                            'fieldTitle'=> $this->lang('Credit Card Number'),
                            'fieldSize' => '40'
                         );


                    // Expiration month
                    $paymentmethod['extraFields'][] = array(
                            'fieldType' => 'dropdown',
                            'fieldName' => $plugin->getInternalName().'_ccMonth',
                            'fieldTitle'=> $this->lang('Expiration Month'),
                            'fieldValue' => array(
                                            array('value' => 1, 'text' => "01 - ".$this->lang("January")),
                                            array('value' => 2, 'text' => "02 - ".$this->lang("February")),
                                            array('value' => 3, 'text' => "03 - ".$this->lang("March")),
                                            array('value' => 4, 'text' => "04 - ".$this->lang("April")),
                                            array('value' => 5, 'text' => "05 - ".$this->lang("May")),
                                            array('value' => 6, 'text' => "06 - ".$this->lang("June")),
                                            array('value' => 7, 'text' => "07 - ".$this->lang("July")),
                                            array('value' => 8, 'text' => "08 - ".$this->lang("August")),
                                            array('value' => 9, 'text' => "09 - ".$this->lang("September")),
                                            array('value' => 10, 'text' => "10 - ".$this->lang("October")),
                                            array('value' => 11, 'text' => "11 - ".$this->lang("November")),
                                            array('value' => 12, 'text' => "12 - ".$this->lang("December")))
                         );

                    // Expiration Year
                    $yearValues = array();
                    $currentYear = date("Y");
                    for($i = 0;$i <= 15; $i++){
                        $yearValues[] = array('value' => $currentYear, 'text' => $currentYear);
                        $currentYear++;
                    }
                    $paymentmethod['extraFields'][] = array(
                            'fieldType' => 'dropdown',
                            'fieldName' => $plugin->getInternalName().'_ccYear',
                            'fieldTitle'=> $this->lang('Expiration Year'),
                            'fieldValue' => $yearValues
                        );

                    // Handle CVV2 - Check if we're allowed to ask for it
                    if($this->settings->get('plugin_'.$plugin->getInternalName().'_Check CVV2') && $this->settings->get('Forward To Gateway')){

                        $paymentmethod['extraFields'][] = array(
                                'fieldType' => 'text',
                                'fieldName' => $plugin->getInternalName().'_ccCVV2',
                                'fieldTitle'=> $this->lang('CVV2'),
                                'fieldSize' => '5',
                                'fieldDescription' => $this->lang("<u>Visa/MasterCard/Discover:</u><br />The CVV2 number is the 3 digit value printed on the back of the card.  It follows the credit card number in the signature area of the card.")."<br>".$this->lang("<u>American Express:</u><br />The CVV2 number is the 4 digit value printed on the front of the card above the credit card number.")
                             );
                    }


                }

                // Handle paypal subscription
                if($plugin->getInternalName() == 'paypal') {

                    // 0 - let customer choose
                    // 1 - Force
                    // 2 - Disable
                    // TODO: Enable / disable subscription based on valid payment term
                    // Only show dropdown if we are permitting a subscription
                    if($this->settings->get('plugin_paypal_Paypal Subscriptions Option In Signup') != '2') {

                        $paymentmethod['extraFields'][] = array(
                            'fieldType' => 'yesno',
                            'fieldName' => 'paypalSubscription',
                            'fieldTitle'=> $this->lang('Create subscription?'),
                            'fieldDescription' => $this->lang('Select Yes to create a subscription with PayPal when checking out'),
                            'fieldValue' => $this->settings->get('plugin_paypal_Paypal Subscriptions Option In Signup'),
                            'fieldDisabled' => ($this->settings->get('plugin_paypal_Paypal Subscriptions Option In Signup'))?true:false
                        );
                    }
                }

                $this->tplView->paymentmethods[] = $paymentmethod;
            }
        }

        // Handle T&C's
        if (@$this->settings->get('Show Terms and Conditions') == 1) {

             // Site URL for T&Cs
             if (@$this->settings->get('Terms and Conditions URL')) {
                 $this->tplView->termsConditions = '-1';
                 $this->tplView->termsConditionsUrl = $this->settings->get('Terms and Conditions URL');
             } else {
                 $this->tplView->termsConditions = 1;
                 
                 $termsAndConditions = $this->settings->get('Terms and Conditions');
                 $termsAndConditions['HTML'] = str_replace('&quot;','"',$termsAndConditions['HTML']);
                 $termsAndConditions['HTML'] = str_replace('&#039;','\'',$termsAndConditions['HTML']);
                 $this->tplView->termsConditionsText = $termsAndConditions['HTML'];
             }
         }

        // Handle Captcha
        $this->tplView->showCaptcha = false;
        if ($this->settings->get('Request Access Code') == 1) {
            $this->tplView->showCaptcha = true;
        }

        // Re Captcha Stuff
        require_once('modules/clients/recaptchalib.php');
        if($this->settings->get('ReCaptcha Public Key') != "") {
            $this->tplView->publickey = $this->settings->get('ReCaptcha Public Key');
        } else {
            $this->tplView->publickey = "6LdjHLwSAAAAAAdauQwa1sD678Sxxj14JXtItd06"; // Use our hard coded key
        }

        // Set the password strength information
        if($this->settings->get('Enforce Password Strength in Signup')) {
            $this->tplView->enforcePassword = true;
            $this->tplView->minPassLength = $this->settings->get('Minimum Password Length');
        }

        // Reset any errors or old fields
        $_REQUEST['oldFields'] = null;
        $_REQUEST['errorReason'] = null;

		
		// Process the cart summary - Adding this in by default so users can choose to show the summary if they want
        $cartSummary = $this->getCartSummary();
        $this->tplView->cartItems = $cartSummary['items'];
        if ($this->tplView->cartCount == 0) {
        	NE_Lib::redirectPage('order.php?cleanCart=true');
        }

        $this->tplView->cartTotal = $cartSummary['total']['price'];
        $this->tplView->cartCancel = true;
        $this->tplView->cartSummary = $this->tplView->fetch('cartSummary.tpl.php');

		// Set the cancel order URL
		if($this->settings->get('Cancel Order URL') != '') {
			$this->tplView->cancelOrderURL = $this->settings->get('Cancel Order URL');
		} else {
			$this->tplView->cancelOrderURL = 'order.php?cleanCart=true';
		}
		
        // Output the template
        $this->tplView->display('signup_4_YourInfo.tpl.php');

        // Show the footer
        $this->tplView->display('signup_footer.tpl.php');


    }
}

?>
