<?php

require_once 'modules/admin/views/SignupView.php';
require_once 'modules/billing/models/BillingGateway.php';

/**
* @package Admin
*/
class Signup_5_ProcessBilling extends SignupView
{
    var $permission     = '';
    var $showHeader     = false;
    
    function preHeaders()
    {
        $this->initialize();
    }

    function dispatch($tUserID, $domain, $domainID, $strMessageOutput, $autopayment, $tFirstName, $tLastName, $bMember)
    {
        //Forward to Thank you page or Gateway
        $myUser = new User($tUserID);

        $billingGateway = new BillingGateway($this->user);

        if (@$_POST['prorating'] > 0 && !$_POST['includeFollowingPayment']) {
            // when we're prorating and not including the following payment we must skip processing of the package recurring charges
            // to avoid the inclusion of the following payment (otherwise it may get included when the invoice generation offset is small)
            $returnArray = $billingGateway->processCustomerBilling($myUser->getId(),$myUser->isAutoPayment(),1,$domainID,1);
        } else {
            // specifying which package we're talking about avoids mixing with other recurring entries from other packages of this
            // same customer.
            $returnArray = $billingGateway->processCustomerBilling($myUser->getId(),$myUser->isAutoPayment(),1,$domainID,0);
        }
        
        //Get invoiceid and price ( should have ProcessCustomerBilling ) return the these values in its returnArray **
        $query="SELECT id,balance_due FROM invoice WHERE status = 0 AND customerid=? ORDER BY id DESC";
        $result = $this->db->query($query, $tUserID);
        list($tinvoiceid,$invoicebalancedue) = $result->fetch();
        
        $_SESSION['affiliate'] = array(
				'affcode' => $_REQUEST['affcode'],
                                'procode' => $_REQUEST['clienttype'],
                                'domainID'=> $domainID,
                                'invoiceNumber' => $tinvoiceid, 
                                'invoiceAmount' => $invoicebalancedue,
                                'customerID' => $tUserID);
        
        // If invoice balance due is 0 mark it paid so the order processor can do it's work.
        $processInvoice = true;
        if ($invoicebalancedue == 0) {
            // No need to register free signups as an affiliate signup
            $today = strftime("%Y-%m-%d",mktime (0,0,0,date("m"),date("d"),  date("Y")));
            $query = "UPDATE `invoice` SET status = 1, datepaid= ? WHERE id = ?";
            $result = $this->db->query($query, $today, $tinvoiceid);

            // process invoice if user has recurring entries with subscriptions that'll generate
            // a non null payment in the future
            $query = "SELECT nextbilldate, "
                    ."paymentterm, "
                    ."SUM(amount) "
                    ."FROM recurringfee "
                    ."WHERE customerid = ? "
                    ."AND disablegenerate != 0 "
                    ."AND status = 1 "
                    ."GROUP BY nextbilldate, "
                    ."paymentterm "
                    ."HAVING SUM(amount) > 0 ";
            $result = $this->db->query($query, $tUserID);
            if (!$result->getNumRows()) {
                $processInvoice = false;
            }
        }

        if (!$autopayment || !$processInvoice || $this->settings->get('Forward To Gateway') != 1

            // special case: quantum gateway is autopayment, but may redirect at signup when using VbV or MC SecureCode verifications,
            // so we need to send the signup notification before it gets redirected
            || (    $myUser->getPaymentType() == 'quantum'
                    && (    $this->settings->get('plugin_quantum_Use Verify By Visa and MasterCard SecureCode')
                            || $this->settings->get('plugin_quantum_Use DialVerify Service')
                       )
                    && !isset($_POST['member']) // when it's an existing member, there's no redirection
               )
           )
        {
            // Send out the notification before the user is redirected
            $this->sendOutNotifications($tFirstName,$tLastName,$domain,$strMessageOutput,$bMember);
        }

        //Only Send invoice if not forwarding to invoice
        if (($this->settings->get('Forward To Gateway')==1) && $processInvoice) {
            //Need to get invoice and then forward to gateway
            //prep variables needed for sendToBill
            $tSendToBill_InvoiceID=$tinvoiceid;
            $tSendToBill_Signup=true;
            $tSendToBill_FirstTime=true;
            $tSendToBill_CreditCardNumber = $_REQUEST['ccnumber'];
            if( isset($_REQUEST['ccmonth']) && isset($_REQUEST['ccyear'])){
                $tSendToBill_CreditCardExp = sprintf("%02d", $_REQUEST['ccmonth'])."/".$_REQUEST['ccyear'];
                if (isset($_POST['cvv2'])) {
                    $tSendToBill_CreditCardCVV2 = htmlspecialchars($_POST['cvv2']);
                }
            }
            require_once 'modules/billing/actSendToBill.php';
            if ($tError != '') {
                // ** don't delete client if he's an existing member !! **
                if (!isset($_POST['member'])) {
                    $tUser = new User($tUserID);
                    $tUser->delete();
                }

                require 'modules/admin/views/Signup_2_OrderForm.php';
                $orderForm = new Signup_2_OrderForm('admin', 'Signup_2_OrderForm');
                $orderForm->setUser($this->user);
                $orderForm->setTpl($this->tpl);
                $orderForm->preHeaders();
                $orderForm->forceShowHeader();
                $orderForm->dispatch('', $tError);
                exit;
            } elseif ($autopayment) {
                $this->sendOutNotifications($tFirstName,$tLastName,$this->domain,$strMessageOutput,$bMember);
            }
            
        }
                //$cancelledUser = new User($tUserId);
                if($myUser->getStatus() == -2){
                    $myUser->setStatus(0);
                    $myUser->save();
                }

                
        NE_Lib::redirectPage("signup.php?step=6&pass=1");
    }
}

?>
