<?php

require_once 'newedge/classes/NE_View.php';
require_once 'newedge/classes/NE_Network.php';

/**
* @package Admin
*/
class SignupView extends NE_View
{
    var $showHeader     = true;
    var $jsLibs = array(
        'javascript/datefields.js',
        'javascript/signup_checkout.js',
        'javascript/common.js'
    );

    var $clienttype;
    var $domain;
    var $package;
    var $transfer;
    var $paymenttype;
    var $paymentterm;
    var $currency;
    var $selectedCurrency;
    var $couponcode;
    var $ccnumber;
    var $ccmonth;
    var $ccyear;
    var $member_email;
    var $member_password;
    var $new_password;
    var $new_password_confirm;
    var $domain_username;
    var $domain_password;

    /**
    * @todo only load necessary templates, from each view
    */
    function initialize()
    {
        if (isset($_REQUEST['clienttype'])) {
            $this->clienttype = htmlspecialchars($_REQUEST['clienttype']);
            
            if($this->clienttype != ""){
            
                $query = "SELECT id FROM promotion WHERE id=?";
                $result = $this->db->query($query, $this->clienttype);
                list($myPromotionId) = $result->fetch();
                if($myPromotionId == NULL){
                    NE_Lib::redirectPage('signup.php');
                }
            }
        } else {
            $this->clienttype = "";
        }

        if (isset($_REQUEST['domain'])) {
            $this->domain = strtolower(htmlspecialchars($_REQUEST['domain']));
        } else {
            $this->domain = "";
        }
        
        if (isset($_REQUEST['coupon_code'])) {
            $this->couponcode = htmlspecialchars($_REQUEST['coupon_code']);
        } else {
            $this->couponcode = "";
        }

        if (isset($_REQUEST['package'])) {
            $this->package = $_REQUEST['package'];
            // make sure that the package isn't set to deny signups

            require_once 'modules/admin/models/Package.php';
            
            $myPackage = new Package($this->package);
            if($this->package != 0){
                if ($myPackage->GetShow() == NULL || $myPackage->GetShow() == -1) {
                    NE_Lib::redirectPage('signup.php');
                }
            }
        } else {
            $this->package = 0;
        }

        if (!isset($_REQUEST['transfer']) || !in_array($_REQUEST['transfer'], array(-1, 0, 1, 2))) {
            $_REQUEST['transfer'] = -1;
        }
        $this->transfer = htmlspecialchars($_REQUEST['transfer']);

        if (isset($_REQUEST['paymenttype'])) {
            $this->paymenttype = htmlspecialchars($_REQUEST['paymenttype']);
        } else {
            $this->paymenttype = '';
        }

        if (isset($_REQUEST['ccnumber'])) {
            $this->ccnumber = htmlspecialchars($_REQUEST['ccnumber']);
        } else {
            $this->ccnumber = '';
        }

        if (isset($_REQUEST['ccmonth'])) {
            $this->ccmonth = htmlspecialchars($_REQUEST['ccmonth']);
        } else {
            $this->ccmonth = '';
        }

        if (isset($_REQUEST['ccyear'])) {
            $this->ccyear = htmlspecialchars($_REQUEST['ccyear']);
        } else {
            $this->ccyear = '';
        }

        if (isset($_REQUEST['paymentterm'])) {
            if(in_array($_REQUEST['paymentterm'], array(0, 1, 3, 6, 12, 24))){
                $this->paymentterm = htmlspecialchars($_REQUEST['paymentterm']);
            }else{
                NE_Lib::redirectPage('signup.php');
            }
        } else {
            $_REQUEST['paymentterm'] = 0;
            $this->paymentterm = 0;
        }

        if (!isset($_REQUEST['currency'])) {
            $_REQUEST['currency'] = $this->settings->get('Default Currency');
        }
        if(!isset($_REQUEST['selectedcurrency'])){
            $_REQUEST['selectedcurrency'] = $_REQUEST['currency'];
        }
        $this->selectedCurrency = htmlspecialchars($_REQUEST['selectedcurrency']);
        if($this->settings->get("Enable Estimated Multi-Currency") == 1){
            $_REQUEST['currency'] = $this->settings->get('Default Currency');
        }
        $this->currency = htmlspecialchars($_REQUEST['currency']);

        if (isset($_REQUEST['member_email'])) {
            $this->member_email = htmlspecialchars($_REQUEST['member_email']);
        } else if ($this->user->getEmail() != '') {
            $this->member_email = htmlspecialchars($this->user->getEmail());
        } else {
            $this->member_email = '';
        }

        if (isset($_REQUEST['member_password'])) {
            $this->member_password = htmlspecialchars($_REQUEST['member_password']);
        } else {
            $_REQUEST['member_password'] = '';
            $this->member_password = '';
        }

        if (isset($_REQUEST['new_password'])) {
            $this->new_password = htmlspecialchars($_REQUEST['new_password']);
        } else {
            $this->new_password = '';
        }
        
        if (isset($_REQUEST['new_password_confirm'])) {
            $this->new_password_confirm = htmlspecialchars($_REQUEST['new_password_confirm']);
        } else {
            $this->new_password_confirm = '';
        }
        
        if (isset($_REQUEST['new_domain_username'])) {
            $this->domain_username = htmlspecialchars($_REQUEST['new_domain_username']);
        } else {
            $this->domain_username = "";
        }
        
        if (isset($_REQUEST['new_domain_password'])) {
            $this->domain_password = htmlspecialchars($_REQUEST['new_domain_password']);
        } else {
            $this->domain_password = "";
        }
        
        if (!$this->settings->get('Show Menu On Signup') && $this->user->isAnonymous()) {
            $this->showMenu = false;
        }
    }

    function templateInit()
    {
        $this->tpl->define(array( "signup_footer"           => "signup/signup_footer.tpl"));
        $this->tpl->define(array( "form_hidden_inputs"      => "signup/include/formhiddeninputs.tpl"));
        $this->tpl->define(array( "signup_0_showpackages"   => "signup/include/signup_0_showpackages.tpl"));
        $this->tpl->define(array( "signup_1_domainnameform" => "signup/include/signup_1_domainnameform.tpl"));
        $this->tpl->define(array( "signup_1_dropdown"       => "signup/include/signup_1_dropdown.tpl"));
        $this->tpl->define(array( "signup_1_options"        => "signup/include/signup_1_options.tpl"));
        $this->tpl->define(array( "signup_1_checkdomain"    => "signup/include/signupCheckDomain.js.tpl"));
        $this->tpl->define(array( "signup_2_orderform"      => "signup/include/signup_2_orderform.tpl"));
        $this->tpl->define(array( "signup_2_packageinfo"    => "signup/include/signup_2_packageinfo.tpl"));
        $this->tpl->define(array( "signup_2_billinginfo"    => "signup/include/signup_2_billinginfo.tpl"));
        $this->tpl->define(array( "signup_2_accountinfo"    => "signup/include/signup_2_accountinfo.tpl"));
        $this->tpl->define(array( "signup_2_packageaddons"  => "signup/include/signup_2_packageaddons.tpl"));
        $this->tpl->define(array( "signup_2_checkout"       => "signup/include/signup_2_checkout.tpl"));
        $this->tpl->define(array( "signup_2_customfields"   => "signup/include/signup_2_customfields.tpl"));
        $this->tpl->define(array( "signup_3_termsofservice" => "signup/include/signup_3_termsofservice.tpl"));
        $this->tpl->define(array( "signup_3b_phoneverify"   => "signup/include/signup_3b_phoneverification.tpl"));
        $this->tpl->define(array( "signup_6_finish"         => "signup/include/signup_6_finish.tpl"));

        $ip = NE_Network::getRemoteAddr();
        if($ip){
            $host = @gethostbyaddr($ip);
            $this->tpl->assign('LOGGEDHOST',$host);
        }

        $this->tpl->setKey(array(
            'CLIENTEXECURL' => NE_lib::getSoftwareURL(),
            'pageTitle'     => $this->lang("Member Center")." - Powered By ClientExec",
            'TEMPLATE'      => $this->settings->getTemplate(),
            'DOMAIN'        => $this->domain,
            'CHARSET'       => $this->tpl->getCharSet(),
            'VERSION'       => strtr(NE_Registry::getAppVersion(), ' ', '_'),
            'LOGGEDIP'      => $ip,
            // Override the default language as it may be set via the URL
            'LANGUAGE'      => $this->user->getLanguage()
            
        ));

//        $this->_loadCSSPages();
//        $this->_loadJsLibraries();

        if (($this->settings->get('plugin_maxmind_Enabled') || $this->settings->get('plugin_maxmindphone_Enabled'))
            && $this->settings->get('plugin_maxmind_Show MaxMind Logo'))
        {
            $this->tpl->parse('trash', 'maxmind');
        }
        $this->tpl->parse("FOOTER", "signup_footer");
        
        $this->tplInit = true;
    }

    function showProgress($description,$percentage)
    {
        $this->tpl->assign("PROGRESSPERCENTAGE",$percentage);
        $this->tpl->assign("PROGRESSDESCRIPTION",$description);
        $this->tpl->parse("PROGRESS", "progress");
        //$this->tpl->FastPrint("PROGRESS");
    }

    function processProrating($prorateToDay, $incFollPayment, $paymentTerm, $price)
    {
        $tProratedPrice = 0;
        $proratedDays = 0;
        $proIncFollowing = 0;
        $tmpNextBill = 0;
        $proNextBill = 0;

        // 0 means disable prorating
        if ($prorateToDay != 0) {
            $today = date('d');
            $month = date('m');

            if ($today < $prorateToDay) {
                  $proratedDays = $prorateToDay - $today;
                  $tmpNextBill = mktime(0,0,0, $month, $prorateToDay);
            } elseif ($today == $prorateToDay) {
                  $proratedDays = 0; // Don't pro-rate
                  $tmpNextBill = mktime(0,0,0,$month + 1, $prorateToDay);
            } else {
                  $today_stamp = mktime(0,0,0,$month, $today);
                  $end_date_stamp = mktime(0,0,0,$month + 1, $prorateToDay);
                  $proratedDays = round(($end_date_stamp-$today_stamp) / (60*60*24) ); // Conversion from seconds to days
                  $tmpNextBill = mktime(0,0,0,$month + 1, $prorateToDay);
            }
        }

        //Check to see if this sale is going to get prorated
        if ($proratedDays > 0) {
            // Assuming each month is thirty-days for pricing
            if ($paymentTerm == 1) {
                  $tProratedPrice = ($price / 30) * $proratedDays;
            } elseif ($paymentTerm == 3) {
                  $tProratedPrice = ($price / 90) * $proratedDays;
            } elseif ($paymentTerm == 6) {
                  $tProratedPrice = ($price / 180) * $proratedDays;
            } elseif ($paymentTerm == 12) {
                  $tProratedPrice = ($price / 360) * $proratedDays;
            } elseif ($paymentTerm == 24) {
                  $tProratedPrice = ($price / 720) * $proratedDays;
            }

            // Decide if we are also billing the customer for the full
            // next billing cycle, or just for this prorated ammount.
            $proIncFollowing = 1;
            // Needs to be after the previous chunk of logic
            if ($prorateToDay != 0) {
               // -1 Never bill next payment
               // 0 Bill if prorating less than 11 days
               // 1 Always bill next payment
               // We unset $price so that it is not included in the total
               // payment due line displayed to the user.  Doesn't actually
               // affect anything outside of this function.
               if ($incFollPayment == -1
                   || ($incFollPayment == 0 && $proratedDays > 10)
                   || ($incFollPayment == 2 && $paymentTerm == 1)
                   || ($incFollPayment == 3 && $paymentTerm != 1)
                   )
                {
                   $price = 0;
                   $proIncFollowing = 0;
               }
            }
            // Include the following payment if we are supposed to
            if($proIncFollowing == 1){
                   if ($paymentTerm == 12) { // 12 months == 1 year
                   $proNextBill = strtotime('+1 year', $tmpNextBill);
                } else { // X month
                   $proNextBill = strtotime('+'.$paymentTerm.' month', $tmpNextBill);
                }
            } else { // No following payment
                $proNextBill = strtotime('+0 month', $tmpNextBill);
            }
        }

        return array($price, $tProratedPrice, $proratedDays, $proIncFollowing, $tmpNextBill, $proNextBill);
    }

    function getClientType($package)
    {
        $clienttype = false;

        $query = "SELECT planid FROM package WHERE id=?";
        $result = $this->db->query($query, $package);
        if ($row = $result->fetch()) {
            $clienttype = $row['planid'];
        }

        return $clienttype;
    }

    function _getPriceIds($str)
    {
        static $priceIds = array();
        if (count($priceIds)) {
            return $priceIds;
        }

        $packageaddonsStr = explode('|', $str);
        foreach ($packageaddonsStr as $packageAddonStr) {
            if (!$packageAddonStr) {
                continue;
            }
            list($addonId, $priceId, $cycle) = explode('_', $packageAddonStr);
            $priceIds[$priceId] = array(
                'addonId'   => $addonId,
                'cycle'     => $cycle,
            );
        }

        return $priceIds;
    }

    function SendOutNotifications($firstname, $lastname, $domain, $strMessageOutput, $isMember = false, $success = true)
    {

        require_once 'newedge/classes/NE_MailGateway.php';
        $mailGateway = new NE_MailGateway();
        
        if ($success) {
    	    //Get all the emails I need to send out an email for (emails in settings->admin->signup->email for new templates
    	    $strMessage = $this->lang("Dear Support Member,<br />\n<br />\nThis E-mail confirms that there has been a new signup via the ClientExec signup script.<br /><br />\n\nView the details of this signup online at")." ".NE_Lib::getSoftwareURL()."<br /><br />\n\n".$strMessageOutput;
        } else {
        	$strMessage = $this->lang("Dear Support Member,<br />\n<br />\nThis E-mail confirms that there has been a rejected signup via the ClientExec signup script.")."<br /><br />\n\n".$strMessageOutput;
        }
        if ($this->settings->get('E-mail For New Signups') != '') {
            if ($success) {
    	    	if ($isMember) {
    	            $subject = $this->lang("Existing Customer Signup").": ".$firstname." ".$lastname;
    	        } else {
    	            $subject = $this->lang("New Customer Signup").": ".$firstname." ".$lastname;
    	        }
            } else {
            	$subject = $this->lang("Rejected Customer Signup").": ".$firstname." ".$lastname;
            }
            $aSupportEmail = explode("\r\n", $this->settings->get('E-mail For New Signups'));
            foreach ($aSupportEmail as $email)
            {
                $email = trim($email);
                if ($email!="") $mailGateway->mailMessageEmail( array('HTML' => $strMessage, 'plainText' => null),
                                                                $this->settings->get('Support E-mail'),
                                                                $this->settings->get('Support E-mail'),
                                                                $email,
                                                                '',
                                                                $subject,
                                                                3,
                                                                0,
                                                                '',
                                                                '',
                                                                MAILGATEWAY_CONTENTTYPE_HTML);
            }
        }
    }
    
    function forceShowHeader()
    {
        $this->loadPublicHeaderTemplates();
        $this->setHeaderVars();            
        $this->parsePublicMenuBar();
        $this->parseHeader();
        $this->showHeader();
    }
}

?>
