<?php

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

/**
* @package Admin
*/
class SignupView extends NE_View
{
    var $showHeader     = false;

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

    /**
    * @todo only load necessary templates, from each view
    */
    function initialize()
    {   
        if (isset($_GET['lang'])
            && file_exists(dirname(__FILE__).'/../../../language/'.strtolower($_GET['lang']).'.txt'))
        {
            $_SESSION['signupLanguage'] = $_GET['lang'];
        }
        if (isset($_SESSION['signupLanguage'])) {
            $this->user->setLanguage($_SESSION['signupLanguage']);
        }

        if (isset($_REQUEST['clienttype'])) {
            $this->clienttype = $_REQUEST['clienttype'];
            
            if($_REQUEST['clienttype'] != ""){
            
                $query = "SELECT id FROM promotion WHERE id=?";
                $result = $this->db->query($query, $_REQUEST['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 = $_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 = $_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');
        }
        $this->currency = htmlspecialchars($_REQUEST['currency']);

        if (isset($_REQUEST['member_email'])) {
            $this->member_email = htmlspecialchars($_REQUEST['member_email']);
        } 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 = '';
        }
    }

    function templateInit()
    {
        $this->tpl->define(array( "signup_header" => "signup/signup_header.tpl"));
        $this->tpl->define(array( "boxnosubmit"   => "signup/include/boxnosubmit.tpl"));
        $this->tpl->define(array( "progress"      => "signup/include/progress.tpl"));
        $this->tpl->define(array( "boxsubmit"     => "signup/include/boxsubmit.tpl"));
        $this->tpl->define(array( "boxsearch"     => "signup/include/boxsearch.tpl"));
        $this->tpl->define(array( "boxsubmitback" => "signup/include/boxsubmitback.tpl"));
        $this->tpl->define(array( "boxsubmit1"    => "signup/include/boxsubmit.tpl"));
        $this->tpl->define(array( "boxsearch1"    => "signup/include/boxsearch.tpl"));
        $this->tpl->define(array( "boxsubmitback1"=> "signup/include/boxsubmitback.tpl"));
        $this->tpl->define(array( "boxback"       => "signup/include/boxback.tpl"));
        $this->tpl->define(array( "signup_footer" => "signup/signup_footer.tpl"));
        $this->tpl->define(array( "form_hidden_inputs" => "../common/formhiddeninputs.tpl"));
        $this->tpl->define(array( "formstep0"     => "signup/include/formstep0.tpl"));
        $this->tpl->define(array("formstep1"      => "signup/include/formstep1.tpl"));
        $this->tpl->define(array("formstep2"      => "signup/include/formstep2.tpl"));
        $this->tpl->define(array("dropdown"       => "signup/include/dropdown.tpl"));
        $this->tpl->define(array("options_step1"  => "signup/include/options_step1.tpl"));
        $this->tpl->define(array("tables_step2"   => "signup/include/tables_step2.tpl"));
        $this->tpl->define(array("tables2_step2"  => "signup/include/tables2_step2.tpl"));
        $this->tpl->define(array("tables3_step2"  => "signup/include/tables3_step2.tpl"));
        $this->tpl->define(array("checkout"       => "signup/include/checkout.tpl"));
        $this->tpl->define(array("tables_step3"   => "signup/include/tables_step3.tpl"));
        $this->tpl->define(array("custom_fields"  => "signup/include/custom_fields.tpl"));
        $this->tpl->define(array("signupCheckDomain" => "../common/signupCheckDomain.js.tpl"));
        $this->tpl->define(array("noscript"       => "signup/include/noscript.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->settings->get("Title"),
            'TEMPLATE'      => $this->settings->getTemplate(),
            'DOMAIN'        => $this->domain,
            'CHARSET'       => $this->tpl->getCharSet(),
            'VERSION'       => strtr(NE_Registry::getAppVersion(), ' ', '_'),
            'LOGGEDIP'      => $ip,
            
        ));

        $this->_loadCSSPages();
        $this->_loadJsLibraries();
        
        // Do a check for javascript (temporary)
        // This will be removed when we add server side validation.
        if (!isset($_GET['noscript'])) {
            $this->tpl->parse('trash', 'noscriptcheck');
        } else {
            $this->tpl->parse("HEADER", "signup_header");
            $this->tpl->parse("FOOTER", "signup_footer");
            $this->tpl->FastPrint('HEADER');
            $this->showProgress($this->lang('Javascript Disabled'),0);
            $this->tpl->assign("SIZEOFBOX","65");
            $this->tpl->assign("WIDTHOFBOX","500");
            $this->tpl->assign("SIGNUPBLOCKDESCRIPTION",$this->lang("Javascript Disabled"));
            $this->tpl->parse('SIGNUPBLOCKCONTENT', 'noscript');
            $this->tpl->parse("BOXSUBMIT", "boxnosubmit");
            $this->tpl->FastPrint("BOXSUBMIT");
            $this->tpl->FastPrint('FOOTER');
            exit;
        }
        // End temporary javascript check

        $this->tpl->parse("HEADER", "signup_header");

        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->tpl->FastPrint('HEADER');  //Display Header
        
        $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);
            }
        }
    }
}

?>
