<?php

require_once 'modules/admin/views/SignupView.php';
require_once 'classes/UserGateway.php';
require_once 'classes/domain.php';
require_once 'newedge/classes/NE_Network.php';
require_once 'classes/invoiceentry.php';
require_once 'newedge/classes/NE_PluginCollection.php';

/**
* @package Admin
*/
class Signup_4_CreateAccounts extends SignupView
{
    function dispatch()
    {
        $this->initialize();

        $fraudmsg = "";
        if(isset($_REQUEST['fraudmsg'])) $fraudmsg = $_REQUEST['fraudmsg'];


        // repeat checks
        if (!isset($_REQUEST['package']) || $_REQUEST['package'] <= 0 || !isset($_REQUEST['clienttype']) || $_REQUEST['clienttype'] <= 0) {
            require 'modules/admin/views/Signup_0_ShowPackages.php';
            $showPackages = new Signup_0_ShowPackages('admin', 'Signup_0_ShowPackages', $this->settings);
            $showPackages->setUser($this->user);
            $showPackages->setTpl($this->tpl);
            $showPackages->dispatch();
            return;
        }
        
        $query = "SELECT regdomain FROM promotion WHERE id = ?";
        $result = $this->db->query($query, $_REQUEST['clienttype']);
        $row = $result->fetch();
        
        if ($row['regdomain'] == 1 && $this->domain == "") {
            require 'modules/admin/views/Signup_1_DomainNameForm.php';
            $domainNameForm = new Signup_1_DomainNameForm('admin', 'Signup_1_DomainNameForm', $this->settings);
            $domainNameForm->setUser($this->user);
            $domainNameForm->setTpl($this->tpl);
            $domainNameForm->dispatch();
        }

        $arrError = $this->validateData();

        if ($arrError) {
            require 'modules/admin/views/Signup_2_OrderForm.php';
            $orderForm = new Signup_2_OrderForm('admin', 'Signup_2_OrderForm', $this->settings);
            $orderForm->setUser($this->user);
            $orderForm->setTpl($this->tpl);
            $orderForm->dispatch($arrError? $arrError : false);
            return;
        }

        // if phone verif is set and it didn't pass, user shouldn't be here
        if (@$_REQUEST['member'] != 'on') {
            $phoneVerificationPlugins = new NE_PluginCollection('phoneverification', $this->user);
            while ($phoneVerificationPlugin = $phoneVerificationPlugins->getNext(false)) {

                if ($this->settings->get("plugin_{$phoneVerificationPlugin}_Enabled") == 1
                    && !isset($_SESSION['phoneverification_passed'])
                    && $this->settings->get("plugin_{$phoneVerificationPlugin}_Minimum Bill Amount to Trigger Telephone Verification") <= $_REQUEST['totalBill']
                    && isset($_REQUEST['fraudScore']) && $this->settings->get("plugin_{$phoneVerificationPlugin}_Minimum Fraud Score to Trigger Telephone Verification") <= $_REQUEST['fraudScore'])
                {
                    require_once 'modules/admin/views/Signup_3b_PhoneVerification.php';
                    $phoneVerification = new Signup_3b_PhoneVerification('admin', 'Signup_3b_PhoneVerification', $this->settings);
                    $orderForm->setUser($this->user);
                    $orderForm->setTpl($this->tpl);
                    $orderForm->dispatch();
                    return;
                }

            }
        }

        $bolEchoOff = true; //variable for autobilling to not display to screen

        if (@$_REQUEST['member']=="on") $bMember=true;
        else $bMember=false;

        //Get ClientType For Package
        $tclienttype = $this->GetClientType($_REQUEST['package']);

        //Create Account
        $tempDateActivated = date("Y-m-d");

        //remove the _ from the payment type
        //_ was used to determine credit card info
        //for the payment types
        $pos = strpos($_REQUEST['paymenttype'],"_");
        if ($pos>0) $_REQUEST['paymenttype'] = substr($_REQUEST['paymenttype'],$pos+1);
        //end payment type formatting

        $tNextBillDate = $tempDateActivated;
        $_REQUEST['dateActivated'] = $tempDateActivated;
        $customTagsArray = unserialize(base64_decode($_REQUEST['customTagsArray']));

        //make recurring for domain = no if no payment cycle was passed.  (Means it should be a one time charge )
        if (isset($_REQUEST['paymentterm']) && $_REQUEST['paymentterm'] != 0) {
            $_REQUEST['recurring']=1;
            $tPaymentTerm = $_REQUEST['paymentterm'];
        } else {
            $_REQUEST['recurring']=0;
            $tPaymentTerm = 0;
        }
        unset($_REQUEST['paymentterm']);
        //Enter some initial commments for customer        
        
        $ip = NE_Network::getRemoteAddr();
        $host = @gethostbyaddr($ip);
        $agent = $_SERVER['HTTP_USER_AGENT'];
        
        $strInitialComments = "IP: $ip<br>\n";
        $strInitialComments .= "HOSTNAME: $host<br>\n";
        $strInitialComments .= "USER AGENT: $agent<br>\n\n\n";
        
        $strInitialCommentsAdminSection = "IP: $ip\n";
        $strInitialCommentsAdminSection .= "HOSTNAME: $host\n";
        $strInitialCommentsAdminSection .= "USER AGENT: $agent\n\n\n";
        $strInitialCommentsUserInfo = "===== ".$this->user->lang("ORIGINAL CUSTOMER DATA")." ===== \n";        
        $query = "SELECT * FROM customuserfields WHERE insignup=1 AND isrequired=1";
        $result = $this->db->query($query);
        while ($row = $result->fetch()) {
            if (isset($_REQUEST['CT_'.$row['id']]) || $_REQUEST['CT_'.$row['id']] != '') {
                $strInitialCommentsUserInfo .= $this->user->varLang($_REQUEST['r_CT_'.$row['id']]).": ".strip_tags($_REQUEST['CT_'.$row['id']])."\n";
            }
        }

        $strInitialCommentsUserInfo .= ((isset($_REQUEST['paymenttype']) && $_REQUEST['paymenttype'] != '')? $this->user->Lang("Payment Type").": ".$_REQUEST['paymenttype']."\n": "");
        $strInitialCommentsUserInfo .= ((isset($_REQUEST['coupon_code']) && $_REQUEST['coupon_code'] != '')? $this->user->Lang("Coupon Code").": ".strip_tags($_REQUEST['coupon_code'])."\n": "");
        $strInitialCommentsUserInfo .= ((isset($_REQUEST['taxrate']) && $_REQUEST['taxrate'] != '')? $this->user->Lang("Taxes").": ".$_REQUEST['taxrate']."% \n": "");
        $strInitialCommentsUserInfo .= ((isset($_REQUEST['discount']) && $_REQUEST['discount'] != '')? $this->user->Lang("Discount").": ".$_REQUEST['discount'] ."\n": "");
        $strInitialCommentsUserInfo .= ((isset($_REQUEST['totalBill']) && $_REQUEST['totalBill'] != '')? $this->user->Lang("Total").": ".sprintf("%.2f", $_REQUEST['totalBill'])."\n": "");
        $strInitialCommentsUserInfo .= ((isset($_REQUEST['currency']) && $_REQUEST['currency'] != '')? $this->user->Lang("Currency").": ".$_REQUEST['currency']."\n": "");
        $strInitialCommentsUserInfo .= ((isset($_REQUEST['domain']) && $_REQUEST['domain'] != '')? $this->user->Lang("Domain").": ".strip_tags($_REQUEST['domain'])."\n": "");
        $strInitialCommentsUserInfo .= ((isset($_REQUEST['dateActivated']) && $_REQUEST['dateActivated'] != '')? $this->user->Lang("Date").": ".$_REQUEST['dateActivated']."\n": "");
        $strInitialCommentsUserInfo .= "===== ".$this->user->lang("ORIGINAL CUSTOMER DATA")." ===== \n\n";
        
        //add fraud message to admin comments
        if ($fraudmsg!=""){
            $strInitialCommentsAdminSection .= strip_tags($fraudmsg);
        }

        //Setup welcome email
        $strMessageOutput = "<br><b>------------------------------";
        if (!$bMember) {
            $strMessageOutput .= "<br>\n".$this->user->lang("Customer Details").":";
        } else {
            $_REQUEST['new_password'] = $_REQUEST['member_password'];
            //get userid of existing member
            $tUserID = $_REQUEST['memberuserid'];
            $memberUser =& new User($tUserID);
            $memberUser->PopulateCustomFields();
            $tFirstName = $memberUser->getFirstName();
            $tLastName = $memberUser->getLastName();
            $tOrganization = $memberUser->getOrganization();
            if ($tOrganization) $tLastName .= " - $tOrganization";

            $strMessageOutput .= "<br>\n<font color=red>".$this->user->lang("Existing Member").": </font>$tFirstName $tLastName";

            // reset this field because the form's default payment method might not have the same autopayment status
            // as the existing user's.
            $_POST['autopayment'] = $_REQUEST['autopayment'] = ($memberUser->isAutopayment()? 1 : 0);
        }
        $strMessageOutput .= "<br>\n------------------------------</b><br>\n";
        if ($this->domain!="") {
            $strMessageOutput .= $this->user->lang("Domain Name").": $this->domain";
        }

        if(!$bMember) {
            $p = 0;
            $varnames="";
            $values = "";

            // TODO: prepareForDB to be handled differently
            $tMyUser =& new User();
            $tMyUser->setCurrent(false);
            $tMyUser->setIsOrganization(false);
            $tMyUser->setGroupId(1);
            $tMyUser->setCurrency($_REQUEST['currency']);
            $tMyUser->setPaymentType($_REQUEST['paymenttype']);
            if(isset($_REQUEST['ccmonth'])){
                $tMyUser->setCCMonth($_REQUEST['ccmonth']);
            }
            if(isset($_REQUEST['ccyear'])){
                $tMyUser->setCCYear($_REQUEST['ccyear']);
            }
            $tMyUser->setAutopayment(isset($_REQUEST['autopayment']) && $_REQUEST['autopayment'] == 1);
            $tMyUser->setDateCreated($_REQUEST['dateActivated']);
            $tMyUser->setComments(NE_Lib::prepareForDB($strInitialCommentsAdminSection.$strInitialCommentsUserInfo));
            $tMyUser->setStatus(0);
            $tMyUser->setRecurring($_REQUEST['recurring']);
            if (!$tMyUser->add()) {
                require 'modules/admin/views/Signup_2_OrderForm.php';
                $orderForm = new Signup_2_OrderForm('admin', 'Signup_2_OrderForm', $this->settings);
                $orderForm->setUser($this->user);
                $orderForm->setTpl($this->tpl);
                $orderForm->dispatch(array($this->user->lang('This installation has reached its number of users limit')));
                return;
            }
            $tUserID = $tMyUser->getId();

            if (!is_null($this->settings->get('plugin_paypal_Force customers to use PayPal subscriptions'))
                && $this->settings->get('plugin_paypal_Force customers to use PayPal subscriptions') == 1)
            {
                $_REQUEST['use_paypal_subscriptions'] = 1;
            }
            // set paypal subscriptions preference
            if (isset($_REQUEST['use_paypal_subscriptions'])) {
                $query = "SELECT id FROM customuserfields WHERE name='Use Paypal Subscriptions';";
                $result = $this->db->query($query);
                list($customId) = $result->fetch();
                $tMyUser->UpdateCustomTag($customId, 1);
            }

            //Get Custom Tags for profile
            foreach ($customTagsArray as $customTag) {
                $value = htmlspecialchars(strip_tags($_REQUEST[$customTag]),ENT_QUOTES);
                //Get Custom Field Name to Use in new account email
                if (substr($customTag,0,2)=="CT") {
                    //This is a profile custom tag
                    if ($customTag=="CT_1"){$tFirstName=$value;}
                    if ($customTag=="CT_2"){$tLastName=$value;}
                    $customTag = str_replace("CT_", "", $customTag);
                    if (trim($value) != '') {
                         $getCustomNameQuery = "SELECT name, type FROM customuserfields WHERE id=?";
                         $getCustomNameResult = $this->db->query($getCustomNameQuery, $customTag);
                         list($tCustomName, $tType) = $getCustomNameResult->fetch();
                         if ($tType == typeDATE) {
                             $value = NE_Lib::form_to_db($value,$this->settings->get('Date Format'), "/");
                         }
                         $strMessageOutput .= "<br>\n$tCustomName: $value";
                    }
                    if ($value != '') {
                        $tMyUser->UpdateCustomTag($customTag,$value);
                    }
                }
            }

            //Set default HTML Email format to yes
            $getHTMLEmailQuery = "SELECT id FROM customuserfields WHERE name='HTML Email Format';";
            $getHTMLEmailResult = $this->db->query($getHTMLEmailQuery);
            list($tCustomTag) = $getHTMLEmailResult->fetch();
            $tMyUser->UpdateCustomTag($tCustomTag,"1");
            //End Set HTML Email

            //set clientinformation needed
            //for password to get set
            $_SESSION['customerId'] = $tUserID;
            $_SESSION['sessionPassword'] = $_REQUEST['new_password'];
            $tMyUser->setPassword($_REQUEST['new_password']);

            // update user's tax flag
            if ($tMyUser->getTaxRate()) {
                $tMyUser->setTaxable(1);
            }
            
            $tMyUser->save();
        }

        //Determine what they wanted with the domain name if anything (REGISTRAR)
        if($_REQUEST['domain'] != '') {
            switch ($_REQUEST['transfer']) {
                case 0:
                    $strMessageOutput .= "<br>\n".$this->user->lang("Registrar Service Requested: Customer wants host to register domain");
                    break;
                case 1:
                    $strMessageOutput .= "<br>\n".$this->user->lang("Registrar Service Requested: Customer wants host to transfer domain");
                    break;
                case 2:
                    $strMessageOutput .= "<br>\n".$this->user->lang("Registrar Service Requested: Customer will manage their own domain");
                    break;
            }
        }
        else {
            $_REQUEST['transfer'] = 2;
        }

        //Enter Account Information
        $query="SELECT planid,planname FROM package WHERE id=?";
        $result = $this->db->query($query, $_REQUEST['package']);
        list($promotionid,$planname) = $result->fetch();

        require_once 'classes/PackageType.php';
        $packageType = new PackageType($promotionid);
        $strMessageOutput .= "<br>\n".$this->user->lang("Package Type").": ".$packageType->getName()." ( ".$packageType->getCode()." )";
        $strMessageOutput .= "<br>\n".$this->user->lang("Domain Package").": ".$planname;

        if (!$bMember) {
            //Extra Signup Email Info
            $strMessageOutput .= "<br>\nRequested Password: ".$_REQUEST['new_password'];
            $strMessageOutput .= "<br>\nPayment Type: ".$_REQUEST['paymenttype'];
            if ($_REQUEST['paymenttype'] == 'paypal' && isset($_REQUEST['use_paypal_subscriptions']))
                $strMessageOutput .= ' - '.$this->user->lang("Subscriptions enabled");
        }

        // Use server that hasn't been used for the longest time and that hasn't filled up his domains quota
        $query = "SELECT s.id, s.sharedip, s.domains_quota FROM server s LEFT JOIN package_server ps ON s.id=ps.server_id "
                ."WHERE ps.package_id=? ORDER BY s.last_utilization ASC, ps.id ASC";
        $result = $this->db->query($query, $_REQUEST['package']);
        $tServerID = 1;
        while ($row = $result->fetch()) {
            $query2 = "SELECT COUNT(id) AS num_domains FROM domains WHERE serverid=?";
            $result2 = $this->db->query($query2, $row['id']);
            $row2 = $result2->fetch();
            if ($row2['num_domains'] >= $row['domains_quota'] && $row['domains_quota'] != 0) {
                continue;
            }
            $tServerID = $row['id'];
            $tServerIP = $row['sharedip'];
            $query = "UPDATE server SET last_utilization=? WHERE id=?";
            $this->db->query($query, date('Y-m-d H:i:s'), $tServerID);
            break;
        }

        //Create domain
        $domainUserName="";
        if ($this->domain != '') {
            //USERNAME CREATION CODE ADDED VERSION 2.0
            //need to check and see if server has a plugin and call
            //the create username if it does otherwise use this function
            require_once 'newedge/classes/NE_PluginCollection.php';
            require_once 'classes/server.php';
            $server = New Server($tServerID);
            $pluginName = $server->GetPluginName();
            $domainUserName = substr($this->domain,0,strpos($this->domain,".")); // remove the extension of the domain
            if ($pluginName != '') {
                $server_plugins = new NE_PluginCollection("server", $this->user);
                $params = array_merge($server->GetAllServerPluginVariables($this->user, $pluginName),
                      array("UserID"=>$tUserID,"DomainUsername"=>$domainUserName,"DomainName"=>$this->domain),
                      $server->GetParams("Create",$pluginName));
                $domainUserName = $server_plugins->callFunction($pluginName,"createUsername",$params);
            }
            //END USERNAME CREATION CODE
        }

        //change next invoice date if prorate price was > 0
        if (@$_REQUEST['proratedprice'] > 0) {
            $nextInvoiceDate =  date("Y-m-d",$_REQUEST['proTmpNextBill']);
        } else {
            $nextInvoiceDate =  $tNextBillDate;
        }

        $tPassword = $_REQUEST['new_password'];
        $tDomain = new Domain(array(
            'm_DomainName'  => $this->domain,
            'm_CustomerID'  => $tUserID,
            'm_UserName'    => $domainUserName,
            'm_Password'    => $tPassword,
            'm_Recurring'   => $_REQUEST['recurring'],
            'm_dateActivated'=> $_REQUEST['dateActivated'],
            'm_PlanID'      => $_REQUEST['package'],
            'm_ServerID'    => $tServerID,
            'm_nextBillDate'=> $nextInvoiceDate,
            'm_paymentterm' => $tPaymentTerm,
            'm_PromotionID' => $tclienttype,
            'm_Current'     => 0,
            'm_Register'    => $_REQUEST['transfer'],
            'm_Signup'      => 1,
        ), $this->user);
        if (isset($_REQUEST['addonChargesStr'])) {
            $tDomain->setAddons($this->_getPriceIds($_REQUEST['addonChargesStr']));
        }
        $tDomain->updateRecord();
        $tDomainID = $tDomain->getID();


        $strMessageOutput .= "<br><br>\n\n<b>------------------------------<br>
                                 ".$this->user->lang("Package Variables")."
                                 <br>------------------------------</b><br>\n";
        //Set Custom Tags for package (domain)
        reset($customTagsArray);
        foreach ($customTagsArray as $customTag) {
            $value = htmlspecialchars(strip_tags($_REQUEST[$customTag]),ENT_QUOTES);
            //Get Custom Field Name to Use in new account email
            if (substr($customTag,0,3) == 'PCT') {
                //This is a package custom tag
                $customTag = str_replace("PCT_", "", $customTag);
                if (trim($value) != '') {
                     $getCustomNameQuery = "SELECT name, type FROM customdomainfields WHERE id=?";
                     $getCustomNameResult = $this->db->query($getCustomNameQuery, $customTag);
                     list($tCustomName, $tType) = $getCustomNameResult->fetch();
                     if ($tType == typeDATE) {
                         $value = NE_Lib::form_to_db($value,$this->settings->get('Date Format'), "/");
                     }
                     $strMessageOutput .= "<br>\n$tCustomName: $value";
                }
                if ($value != '') {
                    $tDomain->UpdateCustomTag($customTag,$value);
                }
            }
        }

        $query = "INSERT INTO domain_customdomainfields(userid,customid,value) VALUES(?,1,?)";
        $data_insert = $this->db->query($query, $tDomainID, @$tServerIP);

        // serialize extra domain attributes
        $extAttr = array();
        foreach ($_REQUEST as $attrName => $attrValue) {
            if (strpos($attrName, 'ext_attr_') === 0) {
                $extAttr[substr($attrName, 9)] = $attrValue;
            }
        }
        if ($extAttr) {
            $tDomain->setExtAttr($extAttr);
        }

        //check to see if recurring is true ( for recurringfee table synch )
        if ($_REQUEST['recurring'] == 1) {
            //determine if customer has selected to
            //offload recurring process to 3rd party processor
            $tDomain->SetRecurring(1);
        }

        $tMyUser =& new User($tUserID);
        $tMyUser->PopulateCustomFields();
        //check to see if new cc info
        if (!$bMember && $_REQUEST['ccnumber'] != '') {
            $tMyUser->StoreCreditCardInfo($_REQUEST['ccnumber'], $this->settings);
            $tMyUser->save();
        }

        //Delete Cache for Customer Summary
        require_once 'newedge/classes/NE_Cache.php';
        $tCache = new NE_Cache("ADMINSUMMARY");
        $tCache->SetContent(''); $tCache->Update();

        //if domain was passed determine how much to charge and create charge
        //If customer is going to transfer then this charge does not get added
        if($this->domain != '' && (($_REQUEST['transfer']==0)||($_REQUEST['transfer']==1))) {
             $aTLDInfo = explode("|", $_REQUEST['domainperiod']);
             $tPaymentTerm = $aTLDInfo[0] * 12;
             $tRegAction = "";
             //check to see if it is one time payment
             if ($aTLDInfo[0] == 0) {
                if ($_REQUEST['transfer'] == 1) {
                    $tRegAction = $this->user->lang("Domain Transfer");
                    $tempDomainDetails = $tRegAction." for Domain: $domain (one time payment)";
                } else {
                    $tRegAction = $this->user->lang("Domain Registration");
                    $tempDomainDetails = $tRegAction." for Domain: $domain (one time payment)";
                }
                //Create One time payment for single domain registration
                $tParams = array(
                    'm_CustomerID'        => $tUserID,
                    'm_Description'       => "$tRegAction - ".$this->domain,
                    'm_Detail'            => $tempDomainDetails,
                    'm_invoiceid'         =>  0,
                    'm_Date'              => $_REQUEST['dateActivated'],
                    'm_BillingTypeID'     => -2,
                    'm_Price'             => $aTLDInfo[1],
                    'm_Recurring'         => 0,
                    'm_IncludeNextPayment'=> 1,
                    'm_AppliesToID'       => $tDomainID,
                    'm_Setup'             => 0,
                );
                $domainRegInvEntry = new InvoiceEntry($tParams);
                $domainRegInvEntry->updateRecord();
            } else {
                $regAppliesTo = $tDomainID;
                // If it's a transfer insert an invoice entry for the transfer and setup a recurring domain registration for future renewals
                if ($_REQUEST['transfer'] == 1) {
                    $tRegAction = $this->user->lang("Domain Transfer");
                    $tempDomainDetails = $tRegAction." for Domain: ".$this->domain." x ".$aTLDInfo[0]." Years";
                    //Create One time payment for single domain transfer
                    $tParams = array(
                    'm_CustomerID'        => $tUserID,
                    'm_Description'       => "$tRegAction - ".$this->domain,
                    'm_Detail'            => $tempDomainDetails,
                    'm_invoiceid'         =>  0,
                    'm_Date'              => $_REQUEST['dateActivated'],
                    'm_BillingTypeID'     => -2,
                    'm_Price'             => $aTLDInfo[1],
                    'm_Recurring'         => 0,
                    'm_IncludeNextPayment'=> 1,
                    'm_AppliesToID'       => $tDomainID,
                    'm_Setup'             => 0,
                    );
                    $domainRegInvEntry = new InvoiceEntry($tParams);
                    $domainRegInvEntry->updateRecord();

                    // Update the values for the recurring domain registration
                    $_REQUEST['dateActivated'] = date("Y") + $aTLDInfo[0]."-".date("m-d");
                    $domainExt = substr($this->domain,strpos($this->domain,".") + 1);
                    $sql = "SELECT price FROM tld WHERE name = ? AND period = ?";
                    $result = $this->db->query($sql, $domainExt, $aTLDInfo[0]);
                    list($aTLDInfo[1]) = $result->fetch();
                    // Need to set this or the registration fee gets included in the first invoice as well as the transfer fee.
                    $regAppliesTo = 0;
                }

                $tRegAction = $this->user->lang("Domain Registration");
                $tempDomainDetails = $tRegAction." for Domain: ".$this->domain." x ".$aTLDInfo[0]." ".$this->user->lang("Years");


                if ($tMyUser->getUsePaypalSubscriptions()) {
                    // For domains registrations with package fees, disablegenerate=-1, so that the subscription for the domain registration is generated when
                    // the user manually pays the second domain registration charge (usually the following year).
                    // If it's only a domain charge disablegenerate=1 because the subscription can be generated immediately (there's no conflict with a package
                    // billing cycle).
                    if (@$_REQUEST['proratedprice'] > 0 || $tDomain->GetPrice() > 0) $disableGenerate = -1;
                    else $disableGenerate = 1;
                } else {
                    $disableGenerate = 0;
                }
                $tParams = array(
                    'customerid'      => $tUserID,
                    'paymentterm'     => $tPaymentTerm,
                    'description'     => "$tRegAction - ".$this->domain,
                    'detail'          => $tempDomainDetails,
                    'billingtypeid'   => -2,
                    'nextbilldate'    => $_REQUEST['dateActivated'],
                    'appliestoid'     => $regAppliesTo,
                    'amount'          => $aTLDInfo[1],
                    'disablegenerate' => $disableGenerate,
                );
                require_once 'classes/recurringwork.php';
                $domainRegRecurringEntry = new RecurringWork($tParams);
                $domainRegRecurringEntry->update();
                $tDomain->setRegistrationYears($aTLDInfo[0]);
             }
        }

        //Generate Invoice
        if ($_REQUEST['setup'] > 0) {
             //Create InvoiceEntry For Setup
             $tParams = array(
                'm_CustomerID'        => $tUserID,
                'm_Description'       => 'Account Setup',
                'm_Detail'            => 'Initial setup charges',
                'm_invoiceid'         =>  0,
                'm_Date'              => $_REQUEST['dateActivated'],
                'm_BillingTypeID'     => -1,
                'm_Price'             => $_REQUEST['setup'],
                'm_Recurring'         => 0,
                'm_IncludeNextPayment'=> 1,
                'm_AppliesToID'       => $tDomainID,
                'm_Setup'             => 1,
             );
             $setupInvEntry = new InvoiceEntry($tParams);
             $setupInvEntry->updateRecord();
             //$tInvoiceEntryID = mysql_insert_id();
             //if it is a one time charge make sure
             //that we process the invoice now
             /*
             if ($_POST['recurring']==0){
                 CreateInvoiceWithEntries($tInvoiceEntryID);
             }
             */
        }

        // Make the prorated charge if needed
        if (@$_REQUEST['proratedprice'] > 0) {
             // Grab the name of the package they just signed up for
             $this->package = NE_Lib::prepareForDB($_REQUEST['package']);
             $query="SELECT planname FROM package WHERE id=?";
             $result = $this->db->query($query, $this->package);
             list($pkgName) = $result->fetch();

             // Pgkname: # mm/dd/yyyy thru mm/dd/yyyy
             if($this->domain != '') {
                $description = "$pkgName: ".$this->domain.", " . date($this->settings->get('Date Format')). ' '.$this->user->lang('thru').' ' . date($this->settings->get('Date Format'), $_REQUEST['proTmpNextBill']);
             } else {
                $description = "$pkgName ($tDomainID), " . date($this->settings->get('Date Format')). ' '.$this->user->lang('thru').' ' . date($this->settings->get('Date Format'), $_REQUEST['proTmpNextBill']);
             }
             $description = NE_Lib::prepareForDB($description);
             $tParams = array(
                'm_CustomerID'        => $tUserID,
                'm_Description'       => $description,
                'm_Detail'            => 'Prorated signup charge',
                'm_invoiceid'         =>  0,
                'm_Date'              => $_REQUEST['dateActivated'],
                'm_BillingTypeID'     => 0,
                'm_Price'             => round($_REQUEST['proratedprice'] + 0.00001, 2),
                'm_Recurring'         => 0,
                'm_IncludeNextPayment'=> 1,
                'm_AppliesToID'       => $tDomainID,
             );
             $proratedInvEntry = new InvoiceEntry($tParams);
             $proratedInvEntry->updateRecord();
        }

        // Revalidate coupon and create discount negative charge
        if ($_REQUEST['discount']) {
             require_once 'classes/coupon.php';
             if ($coupon = Coupon::validate($_REQUEST['coupon_code'], $_REQUEST['clienttype'], $_REQUEST['package'], $tPaymentTerm)) {
                 $coupon = explode('|', $coupon);
                 $strMessageOutput .= "<br><br>\n\n<b>------------------------------<br>\n"
                                 .$this->user->lang("Discount Coupon")
                                 ."<br>\n------------------------------</b><br>\n"
                                 .$this->user->lang("Code").": ".$_REQUEST['coupon_code']."<br>\n"
                                 .$this->user->lang("Amount").": ".$_REQUEST['discount']."<br><br>\n\n";

                 $m_Description = $this->user->lang('Discount coupon')." ($planname";
                 if(isset($this->domain)){
                     $m_Description .= ": $this->domain";
                 }
                 $m_Description .= ')';
                 if ($coupon[4]) {
                     // create recurring entry
                     require_once 'classes/recurringwork.php';
                     $recurringEntry = new RecurringWork(array(
                        'description'       => $m_Description,
                        'detail'            => '',
                        'billingtypeid'     => -3,
                        'amount'            => $_REQUEST['discount'],
                        'disablegenerate'   => $tMyUser->getUsePaypalSubscriptions()? 1 : 0,
                        'customerid'        => $tUserID,
                        'paymentterm'       => $tDomain->m_paymentterm,
                        'nextbilldate'      => $tDomain->m_nextBillDate,
                        'appliestoid'       => $tDomain->m_ID));
                     $recurringEntry->update();
                 } else {
                     $discountInvEntry = new InvoiceEntry(array(
                        'm_CustomerID'        => $tUserID,
                        'm_Description'       => $m_Description,
                        'm_Detail'            => '',
                        'm_invoiceid'         =>  0,
                        'm_Date'              => $_REQUEST['dateActivated'],
                        'm_BillingTypeID'     => -3,
                        'm_Price'             => $_REQUEST['discount'],
                        'm_Recurring'         => 0,
                        'm_IncludeNextPayment'=> 1,
                        'm_AppliesToID'       => $tDomainID,
                     ));
                     $discountInvEntry->updateRecord();
                 }

                 Coupon::updateQuantity($_REQUEST['coupon_code']);
             }
        }

        // Process Package Add-ons
        if ($_REQUEST['addonChargesStr'] != '') {
            $strMessageOutput .= "<br><br>\n\n<b>------------------------------<br>\n
                                 ".$this->user->lang("Package Add-ons")."
                                 <br>\n------------------------------</b><br>\n";
            require_once 'classes/packageaddon.php';
            require_once("classes/Currency.php");
            $currency = new Currency($this->user);
            foreach ($this->_getPriceIds($_REQUEST['addonChargesStr']) as $selectedPriceId => $selectedPriceAttribs) {
                $addon = new PackageAddon($selectedPriceAttribs['addonId']);
                $tPrices = $addon->getPrices();

                $strMessageOutput .= "<br>\n".$addon->getName().": "
                    .$tPrices[$selectedPriceId]['detail']. " ("
                    .$currency->ShowCurrencySymbol($_REQUEST['currency'],false)
                    .sprintf("%01.2f", $tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']]);

                if ($selectedPriceAttribs['cycle'] != 0
                    && $tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']] != 0)
                {
                    $strMessageOutput .= ' ' . $this->user->lang("every %s month(s)", $selectedPriceAttribs['cycle']);
                }
                $strMessageOutput .= ")";

                if ($tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']] < 0
                    || ($selectedPriceAttribs['cycle'] != $tDomain->m_paymentterm && !$tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle'].'Force']))
                {
                    continue;
                }

                // recurring fee portion
                // (note: when $selectedPriceAttribs['cycle'] is 0 this means it's an addon for a setup-price-only package
                if ($selectedPriceAttribs['cycle'] > 0 && $tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']] >0) {
                    require_once 'classes/recurringwork.php';
                    if ($tMyUser->getUsePaypalSubscriptions() && $selectedPriceAttribs['cycle'] != $tDomain->m_paymentterm) {
                        $disableGenerate = -1;
                    } elseif ($tMyUser->getUsePaypalSubscriptions()) {
                        $disableGenerate = 1;
                    } else {
                        $disableGenerate = 0;
                    }
                    $recurringEntry = new RecurringWork(array(
                       'description'           => $addon->getName() . ': ' . $tPrices[$selectedPriceId]['detail'],
                       'detail'                => '',
                       'billingtypeid'         => -4,
                       'packageAddonPricesId'  => $selectedPriceId,
                       'amount'                => $tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']],
                       'disablegenerate'       => $disableGenerate,
                       'customerid'            => $tUserID,
                       'paymentterm'           => $selectedPriceAttribs['cycle'],
                       'nextbilldate'          => $tDomain->m_nextBillDate,
                       'appliestoid'           => $tDomain->m_ID));
                    $recurringEntry->update();

                    // prorated portion
                    if ($_REQUEST['prorating'] == 1) {
                        list($tAddonPrice, $addonProratedPrice, $addonProratedDays, $addonProIncFollowing, $addonTmpNextBill, $addonProNextBill)
                        = $this->processProrating($this->settings->get('Prorate To Day'), $this->settings->get('Include Following Payment'), $selectedPriceAttribs['cycle'], $tPrices[$selectedPriceId]['price'.$selectedPriceAttribs['cycle']]);

                        $proratedAddonInvEntry = new InvoiceEntry(array(
                            'm_CustomerID'        => $tUserID,
                            'm_Description'       => $addon->getName() . ': ' . $tPrices[$selectedPriceId]['detail']
                                                     . ', ' . date($this->settings->get('Date Format')). ' thru ' . date($this->settings->get('Date Format'), $_REQUEST['proTmpNextBill']),
                            'm_Detail'            => 'Prorated signup charge',
                            'm_invoiceid'         =>  0,
                            'm_Date'              => $_REQUEST['dateActivated'],
                            'm_BillingTypeID'     => -4,
                            'm_Price'             => $addonProratedPrice,
                            'm_Recurring'         => 0,
                            'm_IncludeNextPayment'=> 1,
                            'm_AppliesToID'       => $tDomainID,
                        ));
                        $proratedAddonInvEntry->updateRecord();
                    }
                }

                // setup portion
                if ($tPrices[$selectedPriceId]['price0'] > 0) {
                    $m_Description = $addon->getName() . ': ' . $tPrices[$selectedPriceId]['detail'] . " ($planname";
                    if(isset($this->domain)){
                        $m_Description .=  " : $this->domain";
                    }
                    $m_Description .= '), (Setup)';
                    $addonInvEntry = new InvoiceEntry(array(
                        'm_CustomerID'        => $tUserID,
                        'm_Description'       => $m_Description,
                        'm_Detail'            => '',
                        'm_invoiceid'         =>  0,
                        'm_Date'              => $_REQUEST['dateActivated'],
                        'm_BillingTypeID'     => -4,
                        'm_Price'             => $tPrices[$selectedPriceId]['price0'],
                        'm_Recurring'         => 0,
                        'm_IncludeNextPayment'=> 1,
                        'm_AppliesToID'       => $tDomainID,
                    ));
                    $addonInvEntry->updateRecord();
                }
            }
        }

        $strMessageOutput .= "<br><br>\n\n<b>------------------------------<br>\n
                                 ".$this->user->lang("Signup Environment")."
                                 <br>\n------------------------------</b><br>\n";
        $strMessageOutput .= $strInitialComments.$fraudmsg;

        $strMessageOutput .= "<br><br>\n\n".$this->user->lang("Thank you for using ClientExec!")."<br>\n";
        $strMessageOutput .= "<b>".$this->user->lang("The ClientExec Team")."</b><br>\n";
        $strMessageOutput .= "http://www.clientexec.com";
        
        require 'modules/admin/views/Signup_5_ProcessBilling.php';

        $processBilling = new Signup_5_ProcessBilling('admin', 'Signup_5_ProcessBilling');
        $processBilling->setUser($this->user);
        $processBilling->setTpl($this->tpl);
        $processBilling->dispatch($tUserID,$this->domain,$tDomainID,$strMessageOutput,$_REQUEST['autopayment'], $tFirstName,$tLastName,$bMember);
        exit;
    }

    function validateData()
    {
        $arrErrors = array();
        $userGateway = new UserGateway();
        
        // Only check the profile custom fields and duplicate email if not an existing member
        if (!isset($_REQUEST['member']) || $_REQUEST['member'] != 'on') {
            $query = "SELECT * FROM customuserfields WHERE insignup=1 AND isrequired=1";
            $result = $this->db->query($query);
            while ($row = $result->fetch()) {
                if (!isset($_REQUEST['CT_'.$row['id']]) || $_REQUEST['CT_'.$row['id']] == '') {
                    $arrErrors[] = $row['name'].' '.$this->user->lang('cannot be blank');
                }
            }
            
            if ($userGateway->checkEmailDuplicate(htmlspecialchars($_REQUEST['CT_4'], ENT_QUOTES))) {
                $arrErrors[] = $this->user->lang('This E-mail address is already in use');
            }
        }
        
        $query = "SELECT * FROM customdomainfields WHERE insignup=1 AND isrequired=1";
        $result = $this->db->query($query);
        while ($row = $result->fetch()) {
            $innerQuery = "SELECT * FROM promotion_customdomainfields WHERE promotionid=? AND customid=?";
            $innerResult = $this->db->query($innerQuery, $this->clienttype, $row['id']);
            if ($innerResult->fetch()) {
                continue;
            }
            if (!isset($_REQUEST['PCT_'.$row['id']]) || $_REQUEST['PCT_'.$row['id']] == '') {
                $arrErrors[] = $row['name'].' '.$this->user->lang('cannot be blank');
            }
        }
        
        if (isset($domain) && $domain != '' && !preg_match(DOMAIN_REGEXDOMAIN, $domain)) {
            $arrErrors[] = $this->user->lang('invalid domain name');
        }
        
        return $arrErrors;
    }

}

?>
