<?

/*/
	(c) 2001-2020 by Locke Enterprises (iLocke.com) - All rights reserved. Partial credit to BMAC and dmtech.
	License:  Authorized for use on the AutoGlassHosting.com website.
	File:  admin/invoices.php
	Purpose:  A multifunctional invoice tool which lists, searches, updates, and inserts new invoices
	Created:  6/1/2002 - based on Nathan's original admin/invoices.php circa y2k - dmtech
	Modification History:
		* 00/00/2000 - Nathan - original wizard and invoice manager
		* 11/01/2003 - OmniOp - calendar modifications
		* 07/30/2004 - Nathan - adapter for the new AGH master administrator; enforce admin login; major code cleanup
		* 06/25/2006 - Nathan - added the isJoined stuff so that Beau can see invoices from any independent affiliates that are really joined to him
		* 09/16/2011 - Nathan - htmlspecialchars in the edit invoice for certain unsafe product fields
		* 04/10/2018 - Nathan - new CyberSourceSOAP functionality like tokenization
		* 04/09/2020 - Nathan - duplicate invoice feature
		* 05/22/2022 - Nathan - added login requirement back in
		* mm/dd/yyyy - [name] - [comment]
/*/

	/// ENFORCE admin login...
	@include("../admin.phi");

	/// toolbox...
	//include "../../inc/includes/main.inc.php"; // disabled a ways back
	include_once "../../inc/GLOBAL.phi";
	require '/home/auto11/public_html/vendor/autoload.php';
	include_once "../../inc/N.phi";
	include_once "../../inc/encrypt.phi";
	include_once "../../inc/Globals_old.phi";
	include_once "../../inc/cal.phi";
	include_once "../../inc/includes/classes/oMail.phi";
	include_once "../../inc/includes/functions/mymarket.inc.php";
	include_once "../../account/checkout/checkout_lib.phi";  // for GenerateCustomerKey()
	include_once "../../inc/CyberSourceSoapClientEx.phi";
	include_once "invoicingFunctions.phi";

	/// dont keep QUERY_STRING when editing or updating -- [N20040730] because??
	//$A = strlen(trim($_GET['A']))==0 ? $_GET['a'] : $_GET['A'];
	if( $A == "U" || $A == "E" || $A == "S" || $A == "DUP" || $A=="CAN" ) {
		$QUERY_STRING = "";
	}
	if( !isset($site) || $site=="" ) {
		$site = "Windshieldstogo.com";
	}

	// strip site from QUERY_STRING if its already there, and replace with altSite for toggling
	// [N] don't need this in the same way anymore: $altSite = $site=="Windshield.Net" ? "WindshieldsToGo.com" : "Windshield.Net";
	if( stristr($QUERY_STRING, $site) ) {
		$len = 6 + strlen($site);
		$altQueryString = substr_replace($QUERY_STRING, "", 0, $len );
	} elseif ( $pos = strpos($QUERY_STRING, "site=$altSite") ) {
		$len = 6 + strlen($altSite);
		$altQueryString = substr_replace($QUERY_STRING, "", 0, $len );
	}
	$altQueryString = "site=".$altSite."&".$altQueryString;

	/// check for delete, don't do it if switching sites
	$hDB = dbConnect();
	echo mysql_error();
	if( $_GET['delete'] && $invoiceID != 0 && !$toggle) {
		mysql_query( "DELETE FROM invoice WHERE ID=$invoiceID", $hDB );
		mysql_query( "ALTER TABLE invoice AUTO_INCREMENT=0" );
		mysql_query( "DELETE FROM invoiceEvents WHERE invoiceID=$invoiceID", $hDB );
		$altQueryString .= "&toggle=1";
	}
    
    $partData = array();
	/// first handle the toggle of any flag...
	if( $A=="TOG" ) {
		if( isset($f) && isset($v) && isset($invoiceID) ) {
			mysql_query( "UPDATE invoice SET ".$f."='".$v."' WHERE ID=".$invoiceID );
			if( $f=="installerPaid" && $v=="Y" ) {  // special event message that posts when their order is complete
				if( intval($g_oNDB->getField("SELECT Max(ID) FROM invoiceEvents WHERE invoiceID='".$invoiceID."' AND subject='Order Complete'")) < 1 ) {  // don't repost
					$msg = $g_oNDB->getField(0,"SELECT event FROM messagePrefill WHERE subject='Order Complete'","");
					$g_oNDB->execute("INSERT INTO invoiceEvents SET invoiceID='".$invoiceID."', stamp=Now(), postedBy='system', subject='Order Complete', event=".$g_oNDB->escape($msg).", isVisible='Y'");
				}
			}
		}
		$A = $A2;
	} elseif( $A=="JTLIA" ) {  // jump to login page
		JumpToLoginInvoiceAdmin();
	} elseif( $A == "JLP" ) {
		$S = strlen(trim($_GET['S']))==0 ? $_GET['s'] : $_GET['S'];
		JumpLookupPhone( $S );
		exit;
	} elseif( $A == "PLF" ) {
		$S = strlen(trim($_GET['S']))==0 ? $_GET['s'] : $_GET['S'];
		PhoneLookupFrames( $S );
		exit;
	}

	/// action handler...
	showHeader();
	if( $A=="EC" ) {  // (re)email the customer their invoice
		emailCustomer( $invoiceID, $checkoutID );
	} elseif( $A=="S" ) {  // display the customer's invoice
		if( $F == "CCCI" ) {
			$g_oNDB->execute("UPDATE checkout SET c_num = ConCat('XX-',Right(c_num, 4)), c_cvv='' WHERE ID = '".$checkoutID."'");
			$Backup_oNDB = new nDB( $g_Config->dbInfoI['database'], $g_Config->dbInfoI['user'], $g_Config->dbInfoI['password'], $g_Config->dbInfoI['server'], $NDB_Debugging );
			$backupCheckoutID = $Backup_oNDB->getField("SELECT checkoutID FROM invoice WHERE refID='".$invoiceID."'");
			$Backup_oNDB->execute("UPDATE checkout SET c_num = ConCat('XX-',Right(c_num, 4)), c_cvv='' WHERE ID = '".$backupCheckoutID."'");
			mysql_select_db('windshi_main', $g_oNDB->hDB);  // don't let the older code below think to use the backup db
		}
		ShowItem( $invoiceID, $checkoutID );
	} elseif( $A=="SFR" ) {  // list certain search results
		if( !isset($field) || $field=="" ) $field = "NOTHING";
		ListItems( $field, $value );
	} elseif( $A=="E" ) {  // edit invoice form
		EditInvoice( $invoiceID, $checkoutID );
	} elseif( $A=="SF" ) {  // form to search invoices
		SearchForm();
	} elseif( $A=="U" ) {  // update an invoice
		SaveInvoice( $invoiceID, $checkoutID );
	} elseif( $A=="DUP" ) {  // update an invoice
		DuplicateInvoice( $invoiceID);
	} elseif( $A=="CAN") { // Cancel Lock
		CancelLock( $invoiceID,$checkoutID);
	} elseif( $A=="CAL" ) {  // special time slice from the calendar
		strlen($day) == 1 ? $day = "0" . $day : 0;
		strlen($month) == 1 ? $month = "0" . $month : 0;
		if( $dateSort == "purchaseDate" ) {
			$dateVal = "$year";
			$month ? $dateVal .= "-$month" : 0;
			$day ? $dateVal .= "-$day" : 0;
			ListItems( $dateSort, $dateVal, '', false );
		} else { // s_InstallDate
			$month ? $dateVal = trim( "$day " . date( "F", mktime(0,0,0,$month,1,$year) ) ) : $dateVal = " ";
			ListItems( $dateSort, $dateVal, $year, false );
		}
	} elseif( $A=="HA-F" ) {  // by-hand, admin ticket authorization
	    if( $_SERVER['REMOTE_ADDR'] == "91.196.220."){
		    HandAuthForm( $invoiceID );
	    }else{
	        HandAuthForm_Stripe( $invoiceID );
	    }
	} elseif( $A=="HA-RUN" ) {  // run manual auth from the admin form 
		HandPreauthorization( $invoiceID );
	} elseif( $A=="HA-RUN-STRIPE" ) {  // run manual auth from the admin form 
		HandPreauthorization_stripe( $invoiceID );
	} elseif( $A=="COCC" ) { // clears out old credit card #s
		ClearOldCCs();
	} elseif( substr($A,0,7)=="RUNAUTH" ) { // run an authorization on the person's card
		if( !RunAUTH($invoiceID) ) {
			$checkoutID = $g_oNDB->getField("SELECT checkoutID FROM invoice WHERE ID='".$invoiceID."'");
			ShowItem( $invoiceID, $checkoutID );
		}
	} elseif( substr($A,0,7)=="re-auth" ) { // run an authorization on the person's card
	    
	    if( $_SERVER['REMOTE_ADDR'] == "91.196.220."){
	        $localID = CreateSubscription_CyberSourceSOAP( $invoiceID ); // tokenize
    		if( $localID > 0 ) {
    			$txLogID = SubscriptionCharge_CyberSourceSOAP( $invoiceID, $localID ); // run the re-auth charge
    			$g_oNDB->execute( "UPDATE invoice SET auth='Y', declined='N' WHERE ID='".$invoiceID."'");
    				
    		}
	    }else{    
	        $localID = CreateSubscription_Stripe( $invoiceID ); // tokenize
	    }
		
		
		$checkoutID = $g_oNDB->getField("SELECT checkoutID FROM invoice WHERE ID='".$invoiceID."'");
		ShowItem( $invoiceID, $checkoutID );
	} elseif($A=="captured" ) { // captured the invoice cancelAuth
	
	    $configPath = '/home/auto11/var/config.php';
	    $config = require $configPath;	
	    $amount = $_GET['amount'];
	    $transationID = $_GET['ID'];
	    $invoiceTransactions =  $g_oNDB->getRow("SELECT * FROM invoiceTransactions WHERE ID='".$transationID."'");
	    
	    // Set your secret key. Remember to switch to your live secret key in production!
        $secretKey = $config['stripe_secret_key'];
        $apiUrl = 'https://api.stripe.com/v1';
        
        $capturedAmt = [];
        if($amount !='' && $amount > 0 ){
            $capturedAmt = [
                'amount'=> $amount * 100
            ];
        }
        
	    
	    $initialPaymentIntentResponse = curlRequest("{$apiUrl}/payment_intents/{$invoiceTransactions['reqID']}/capture", $capturedAmt, $secretKey);
        $initialPaymentIntent = json_decode($initialPaymentIntentResponse,true);
        
        if (isset($initialPaymentIntent['id'])) {
            echo "<p class='action'>[Success] The payment captured successful. Reason code: 100</p>\n";
            $g_oNDB->execute("UPDATE invoiceTransactions SET reconciliation = 'captured' WHERE ID='".$transationID."'");  
            
            $SQL = "INSERT INTO invoiceSubscriptions SET ";
        	$SQL .= "invoiceID='".$invoiceTransactions['invoiceID']."', ";
        	$SQL .= "stamp=Now(), ";
        	$SQL .= "refCode='', ";
        	$SQL .= "ip=".$g_oNDB->escape($_SERVER['REMOTE_ADDR']).", ";
        	$SQL .= "source='admin', ";
        	$SQL .= "gatewayType='Stripe', ";
        	$SQL .= "invoiceTransactionID='".$invoiceTransactions['ID']."', ";
        	$SQL .= "originalRequestID='".$invoiceTransactions['reqID']."', ";
        	$SQL .= "result='100', ";
        	$SQL .= "decision='ACCEPT', ";
        	$SQL .= "subID='', ";
        	$SQL .= "token='".$initialPaymentIntent['id']."' ";
        	$g_oNDB->execute($SQL);
        	
        	if($amount !='' && $amount > 0){
            	$SQL = "INSERT INTO invoiceTransactions SET stamp=Now(), ";
            	$SQL .= "invoiceID='".$invoiceTransactions['invoiceID']."', ";
            	$SQL .= "ip='".$_SERVER['REMOTE_ADDR']."', ";
            	$SQL .= "total='".$amount."', ";
            	$SQL .= "source='admin', ";
            	$SQL .= "archive='capture-updated', ";
            	$SQL .= "result='".intval(100)."', ";
            	$SQL .= "decision='ACCEPT', ";
            	$SQL .= "reqID='".$initialPaymentIntent['id']."', ";
            	$SQL .= "avs='Y', ";
            	$SQL .= "gatewayType='Stripe', ";
            	$SQL .= "factor='', ";
            	$SQL .= "shortMsg='".$initialPaymentIntent['customer'] ."', "; 
            	$SQL .= "customer_id='".$initialPaymentIntent['customer']."', ";
            	$SQL .= "authCode='', ";
            	$SQL .= "reconciliation='capture a smaller amount than the original auth', ";
            	$SQL .= "token='".$initialPaymentIntent['payment_method']."' ";
        	    
        	    $g_oNDB->execute($SQL);
        	}	
        	
        	$g_oNDB->execute( "UPDATE invoice SET auth='Y', declined='N', paid='Y' WHERE ID='".$invoiceTransactions['invoiceID']."'");
        	$invoiceID1 = $invoiceTransactions['invoiceID'];
		    $checkoutID1 = $g_oNDB->getField("SELECT checkoutID FROM invoice WHERE ID='".$invoiceID1."'");

        	autoPartPriceSave($checkoutID1,$invoiceID1);
             
        }else{
            echo "<p class=error>CAPTURED ERROR: ".$initialPaymentIntent['error']['message']."</p>\n";
            $g_oNDB->execute("UPDATE invoiceTransactions SET reconciliation = 'capturedFail' WHERE ID='".$transationID."'"); 
             
            $SQL = "INSERT INTO invoiceTransactions SET stamp=Now(), ";
        	$SQL .= "invoiceID='".$invoiceTransactions['invoiceID']."', ";
        	$SQL .= "ip='".$_SERVER['REMOTE_ADDR']."', ";
        	$SQL .= "total='".$invoiceTransactions['total']."', ";
        	$SQL .= "source='admin', ";
        	$SQL .= "archive='capture', ";
        	$SQL .= "result='".intval(101)."', ";
        	$SQL .= "decision='REJECT', ";
        	$SQL .= "reqID='', ";
        	$SQL .= "avs='Y', ";
        	$SQL .= "gatewayType='Stripe', ";
        	$SQL .= "factor='', ";
        	$SQL .= "shortMsg='".$initialPaymentIntent['error']['message']."', ";
        	$SQL .= "authCode='', ";
        	$SQL .= "reconciliation='".$initialPaymentIntent['error']['code']."', ";
        	$SQL .= "token='' ";
        	
        	$g_oNDB->execute($SQL);
             
            
        }
		$invoiceID = $invoiceTransactions['invoiceID'];
		$checkoutID = $g_oNDB->getField("SELECT checkoutID FROM invoice WHERE ID='".$invoiceID."'");
		ShowItem( $invoiceID, $checkoutID );
	} elseif($A=="cancelAuth" ) { // captured the invoice 
	
	    $configPath = '/home/auto11/var/config.php';
	    $config = require $configPath;	
	    
	    $transationID = $_GET['ID'];
	    $invoiceTransactions =  $g_oNDB->getRow("SELECT * FROM invoiceTransactions WHERE ID='".$transationID."'");
	    
	    // Set your secret key. Remember to switch to your live secret key in production!
        $secretKey = $config['stripe_secret_key'];
        $apiUrl = 'https://api.stripe.com/v1';
	    try {
    	    $initialPaymentIntentResponse = curlRequest("{$apiUrl}/payment_intents/{$invoiceTransactions['reqID']}/cancel", [], $secretKey);
            $initialPaymentIntent = json_decode($initialPaymentIntentResponse);
            echo "<p class='action'>[Success] The auth was successfully canceled. Reason code: 100</p>\n";
            $g_oNDB->execute("UPDATE invoiceTransactions SET result='404', reconciliation = 'canceled Auth' WHERE ID='".$transationID."'");

	    } catch (\Exception $e) {
            echo "<p class=error>Cancel ERROR: ".$e->getMessage()."</p>\n";
        }
		$invoiceID = $invoiceTransactions['invoiceID'];
		$checkoutID = $g_oNDB->getField("SELECT checkoutID FROM invoice WHERE ID='".$invoiceID."'");
		ShowItem( $invoiceID, $checkoutID );
	} elseif($A=='LAA'){ //Search Part Price
        ShowItem( $invoiceID, $checkoutID );
	} elseif($A=='LAAS'){ //Saved searched part price

        	$partNumber = $_GET['partnumber'];		
        	$pilC = $g_oNDB->getRow("SELECT cost,ID FROM supplierParts WHERE part='".$partNumber."' AND supplierID = 93 ORDER BY ID ASC LIMIT 1"); 
        	$MyC = $g_oNDB->getRow("SELECT cost,ID FROM supplierParts WHERE part='".$partNumber."' AND supplierID = 95 ORDER BY ID ASC LIMIT 1"); 
        	$PgwC = $g_oNDB->getRow("SELECT cost,ID FROM supplierParts WHERE part='".$partNumber."' AND supplierID = 94 ORDER BY ID ASC LIMIT 1"); 
            
            if( intval($pilC['ID']) > 1){//Override Price
                if($_GET['picost'] > 0){
                    $g_oNDB->execute("UPDATE supplierParts SET cost='".$_GET['picost']."' WHERE ID='".$pilC['ID']."'");
                    echo "<p class='info'>[Success] For Part: <b>".$partNumber."</b> price override in <b>Pilkington</b> list. </p>\n";
                }else{
                    echo "<p class='info'>[Info] For Part: <b>".$partNumber."</b> price not found in <b>Pilkington</b>. </p>\n";
                }
            }else{ //new added
                    if($_GET['picost'] > 0){ //Only saved the if price found in part search
                        $PISQL = "INSERT INTO supplierParts SET 
                     	supplierID ='93',
                     	part ='".$partNumber."',
                     	normalizedPart ='".$partNumber."',
                     	supplierCode ='".$partNumber."',
                     	description ='',
                     	cost = '".$_GET['picost']."',
                     	listPrice =0,
                     	isAvailable ='Y',
                     	allowImport ='Y'";
                     	
                     	$g_oNDB->execute($PISQL);
                     	
                     	echo "<p class='info'>[Success] For Part: <b>".$partNumber."</b> new price added in <b>Pilkington</b> list. </p>\n";
                    }else{
                        echo "<p class='info'>[Info] For Part: <b>".$partNumber."</b> price not found in <b>Pilkington</b>. </p>\n";
                    }
            }
            
            if( intval($MyC['ID']) > 1){ //Override price
                if($_GET['mycost'] > 0){
                    $g_oNDB->execute("UPDATE supplierParts SET cost='".$_GET['mycost']."' WHERE ID='".$MyC['ID']."'");
                    echo "<p class='info'>[Success] For Part: <b>".$partNumber."</b> price override in <b>Mygrant</b> list. </p>\n";
                }else{
                    echo "<p class='info'>[Info] For Part: <b>".$partNumber."</b> price not found in <b>Mygrant</b>. </p>\n";
                }    
            }else{ //new added
                    if($_GET['mycost'] > 0){ //Only saved the if price found in part search
                        $MySQL = "INSERT INTO supplierParts SET 
                     	supplierID ='95',
                     	part ='".$partNumber."',
                     	normalizedPart ='".$partNumber."',
                     	supplierCode ='".$partNumber."',
                     	description ='',
                     	cost = '".$_GET['mycost']."',
                     	listPrice =0,
                     	isAvailable ='Y',
                     	allowImport ='Y'";
                     	
                     	$g_oNDB->execute($MySQL);
                     	
                     	echo "<p class='info'>[Success] For Part: <b>".$partNumber."</b> new price added in <b>Mygrant</b> list. </p>\n";
                    }else{
                        echo "<p class='info'>[Info] For Part: <b>".$partNumber."</b> price not found in <b>Mygrant</b>. </p>\n";
                    }
            }
            
            if( intval($PgwC['ID']) > 1){ //Override price
                if($_GET['pwgcost'] > 0){
                    $g_oNDB->execute("UPDATE supplierParts SET cost='".$_GET['pwgcost']."' WHERE ID='".$PgwC['ID']."'");
                    echo "<p class='info'>[Success] For Part: <b>".$partNumber."</b> price override in <b>PGW</b> list. </p>\n";
                }else{
                    echo "<p class='info'>[Info] For Part: <b>".$partNumber."</b> price not found in <b>PGW</b>. </p>\n";
                }       
            }else{ //new added
                if($_GET['pwgcost'] > 0){ //Only saved the if price found in part search
                        $PWSQL = "INSERT INTO supplierParts SET 
                     	supplierID ='94',
                     	part ='".$partNumber."',
                     	normalizedPart ='".$partNumber."',
                     	supplierCode ='".$partNumber."',
                     	description ='',
                     	cost = '".$_GET['pwgcost']."',
                     	listPrice =0,
                     	isAvailable ='Y',
                     	allowImport ='Y'";
                     	
                     	$g_oNDB->execute($PWSQL);
                     	
                     	echo "<p class='info'>[Success] For Part: <b>".$partNumber."</b> new price added in <b>PGW</b> list. </p>\n";
                }else{
                        echo "<p class='info'>[Info] For Part: <b>".$partNumber."</b> price not found in <b>PGW</b>. </p>\n";
                }
            }
        	
	    
        ShowItem( $invoiceID, $checkoutID );
	} else {  // default is to list all of the invoices
		ListItems( "NOTHING" );
	}
	
	/// done...
	exit;


/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

function autoPartPriceSave($checkoutID,$invoiceID){
    
    global $g_oNDB;
    
	$SQL = "SELECT checkout.cartID FROM checkout LEFT JOIN invoice ON checkout.ID=invoice.checkoutID WHERE checkout.ID=$checkoutID and invoice.ID=$invoiceID";

    $hCheckout = mysql_query( $SQL );
	if( !$hCheckout ) exit( "Checkout information not found." );
	$rCheckout = mysql_fetch_array($hCheckout,  MYSQL_ASSOC) or die("</td></tr></table><blockquote><b>Invoice not found</b></blockquote>");


    /// get the cartItems...
	$cartID = $rCheckout['cartID'];
	$sql = "SELECT part,nspart FROM cartItems LEFT JOIN product ON cartItems.productID=product.ID WHERE cartID=$cartID";
	$hCartItems = mysql_query($sql);
	$rCartItem = mysql_fetch_array($hCartItems, MYSQL_ASSOC) or die("<blockquote><b>Invoice not found</b></blockquote>");
	$partNormalized = $rCartItem['nspart'];
    
    $SQL = "INSERT INTO partQueues SET 
             	checkoutID ='".$checkoutID."',
             	invoiceID ='".$invoiceID."',
             	partNumber ='".$partNormalized."'";
             	
    $g_oNDB->execute($SQL);
    
    return true;
    
    //Part price search	
	$MyGrantCost = getMygrantPrice($partNormalized);
	$PWGCost = 0;//getPWGPrice($partNormalized);
	//Pilkington
	$PilkingtonCost1=getPilkingtonData($partNormalized);

	// Filter out zero values
	$nonZeroValues = array_filter($PilkingtonCost1, function($value) {
		return $value > 0;
	});

	// Find the minimum non-zero value
	if (!empty($nonZeroValues)) {
		$PilkingtonCost = min($nonZeroValues);
	}else{
		$PilkingtonCost = 0;
	}
	
	$partNumber = $partNormalized;
    $pilC = $g_oNDB->getRow("SELECT cost,ID FROM supplierParts WHERE part='".$partNumber."' AND supplierID = 93 ORDER BY ID ASC LIMIT 1"); 
	$MyC = $g_oNDB->getRow("SELECT cost,ID FROM supplierParts WHERE part='".$partNumber."' AND supplierID = 95 ORDER BY ID ASC LIMIT 1"); 
	$PgwC = $g_oNDB->getRow("SELECT cost,ID FROM supplierParts WHERE part='".$partNumber."' AND supplierID = 94 ORDER BY ID ASC LIMIT 1"); 
    
    if( intval($pilC['ID']) > 1){//Override Price
        if($PilkingtonCost > 0){
            $g_oNDB->execute("UPDATE supplierParts SET cost='".$PilkingtonCost."' WHERE ID='".$pilC['ID']."'");
            echo "<p class='info'>[Success] For Part: <b>".$partNumber."</b> price override in <b>Pilkington</b> list. </p>\n";
        }      
    }else{ //new added
            if($PilkingtonCost > 0){ //Only saved the if price found in part search
                $PISQL = "INSERT INTO supplierParts SET 
             	supplierID ='93',
             	part ='".$partNumber."',
             	normalizedPart ='".$partNumber."',
             	supplierCode ='".$partNumber."',
             	description ='',
             	cost = '".$PilkingtonCost."',
             	listPrice =0,
             	isAvailable ='Y',
             	allowImport ='Y'";
             	
             	$g_oNDB->execute($PISQL);
             	
             	echo "<p class='info'>[Success] For Part: <b>".$partNumber."</b> new price added in <b>Pilkington</b> list. </p>\n";
            }else{
                echo "<p class='info'>[Info] For Part: <b>".$partNumber."</b> price not found in <b>Pilkington</b>. </p>\n";
            }
    }
    
    if( intval($MyC['ID']) > 1){ //Override price
        if($MyGrantCost > 0){
            $g_oNDB->execute("UPDATE supplierParts SET cost='".$MyGrantCost."' WHERE ID='".$MyC['ID']."'");
            echo "<p class='info'>[Success] For Part: <b>".$partNumber."</b> price override in <b>Mygrant</b> list. </p>\n";
        }
    }else{ //new added
            if($MyGrantCost > 0){ //Only saved the if price found in part search
                $MySQL = "INSERT INTO supplierParts SET 
             	supplierID ='95',
             	part ='".$partNumber."',
             	normalizedPart ='".$partNumber."',
             	supplierCode ='".$partNumber."',
             	description ='',
             	cost = '".$MyGrantCost."',
             	listPrice =0,
             	isAvailable ='Y',
             	allowImport ='Y'";
             	
             	$g_oNDB->execute($MySQL);
             	
             	echo "<p class='info'>[Success] For Part: <b>".$partNumber."</b> new price added in <b>Mygrant</b> list. </p>\n";
            }else{
                echo "<p class='info'>[Info] For Part: <b>".$partNumber."</b> price not found in <b>Mygrant</b>. </p>\n";
            }
    }
    
    if( intval($PgwC['ID']) > 1){ //Override price
        if($PWGCost > 0){
            $g_oNDB->execute("UPDATE supplierParts SET cost='".$PWGCost."' WHERE ID='".$PgwC['ID']."'");
            echo "<p class='info'>[Success] For Part: <b>".$partNumber."</b> price override in <b>PGW</b> list. </p>\n";
        }
    }else{ //new added
        if($PWGCost > 0){ //Only saved the if price found in part search
                $PWSQL = "INSERT INTO supplierParts SET 
             	supplierID ='94',
             	part ='".$partNumber."',
             	normalizedPart ='".$partNumber."',
             	supplierCode ='".$partNumber."',
             	description ='',
             	cost = '".$PWGCost."',
             	listPrice =0,
             	isAvailable ='Y',
             	allowImport ='Y'";
             	
             	$g_oNDB->execute($PWSQL);
             	
             	echo "<p class='info'>[Success] For Part: <b>".$partNumber."</b> new price added in <b>PGW</b> list. </p>\n";
        }else{
                echo "<p class='info'>[Info] For Part: <b>".$partNumber."</b> price not found in <b>PGW</b>. </p>\n";
        }
    }
	
	return true;
}

//-------------------------------------------------------------------------
// ListItems:  List all invoices, or single by request
//-------------------------------------------------------------------------
function ListItems( $field, $value=0, $extra="", $hidden=false ) {

	global $PHP_SELF, $g_oNDB, $hDB, $A, $startAt, $displayNum, $site, $dateSort, $showTotals, $QUERY_STRING, $flag;

	//$rData = mysql_fetch_array(mysql_query("SELECT Database()")); echo $rData[0]."<br>";
	if( !isset($startAt) || $startAt<0 ) $startAt = 0;
	if( !isset($displayNum) || intval($displayNum)<1 ) $displayNum = 1000;
	
	/// get a list of the independent W2G affiliates...
	$rJoinedAffs = $g_oNDB->getColumn( 0, "SELECT ID FROM affiliate WHERE isJoined='Y'", "-1" );
	$rJoinedAffs[] = "0";
	$JoinedAffs = join(",", $rJoinedAffs);
	$filterPaid == "";
	//PrintArray($rJoinedAffs,false);  print "<br>".$JoinedAffs."<br>";
	$value = str_replace("'", "\'", $value);
	
	// format display field
	$orig = $field;
	$dateRow = "purchaseDate";
	$clause = "";
	switch( $field ) {
		case "s_InstallDateCAOnly":  //a bit of ugly code/case for the CA only stuff
			$displayField = "Install Date CA Only";
			$caOnly = "s_InstallDateCAOnly";
			$value != " " ? list($day,$month) = split (" ", $value, 2) : 0;  // split values for normal date display
			if( !$month ) {  // if no day, swap month for day
				$month = $day;
				$day = "";
			}
			$year = "$extra" ;
			$day ? $searchVal .= " $day," : 0;
			$year ? $searchVal .= " $year" : 0;
			$month ? $searchVal = $month . $searchVal : $searchVal = "All of  $year";
			$field = "s_InstallDate";
			$dataSort = $field;
			$filterPaid = $_GET['paid']=='Y' ? "Y" : ($_GET['paid']=='N' ? "N" : "");
			$clause = " invoice.hidden='N' ";
		break;
		case "s_InstallDate":
			$displayField = "Install Date";
			$value != " " ? list($day,$month) = split (" ", $value, 2) : 0;  // split values for normal date display
			if( !$month ) {  // if no day, swap month for day
				$month = $day;
				$day = "";
			}
			$year = "$extra" ;
			$day ? $searchVal .= " $day," : 0;
			$year ? $searchVal .= " $year" : 0;
			$month ? $searchVal = $month . $searchVal : $searchVal = "All of  $year";
			$filterPaid = $_GET['paid']=='Y' ? "Y" : ($_GET['paid']=='N' ? "N" : "");
		break;
		case "purchaseDate":
			$displayField = "Purchase Date";
			$dateRow = "purchaseDate";
			list($year,$month, $day)= split ("-", $value, 3);
			$month ? $searchVal = (date( "F", mktime(0,0,0,$month,1,$year) ) ) : $searchVal = "All of";
			$day ? $searchVal .= " $day, $year" : $searchVal .= " $year";
		break;			
		case "s_Zip":
			$displayField = "Zip";
			if( strlen($value) < 1 ) {
				$searchVal = "(none)";
				$clause = "(checkout.s_Zip = '')";
			} elseif( strlen($value) < 5 ) {
				$searchVal = "starts with ".$value;
				$clause = "(checkout.s_Zip LIKE '".$value."%')";
			}
		break;
		case "s_City":
			$displayField = "City";
		break;
		case "s_LastName":
			$displayField = "Shipping Last Name";		
		break;
		case "s_Unit":
			$displayField = "Unit#";		
		break;
		case "s_VIN":
			$displayField = "VIN";		
			$clause = "checkout.s_VIN LIKE '%".$value."%'";	
		break;
		case "s_CrossStreet":
			$displayField = "Dealer#";		
		break;
		case "s_PO":
			$displayField = "PO#";
		break;
		case "s_Odometer":
			$displayField = "Odometer";
		break;
		case "part":
			$displayField = "Part Number";
			$field = "part";
		break;			
		case "partDetails":
			$displayField = "Part Details";
			$field = "partDetails";
		break;			
		case "invoice.ID":
			$displayField = "Invoice ID";
		break;			
		case "total":
			$displayField = "Total Charge";
			$clause = "checkout.total LIKE '%".$value."%'";
		break;
		case "shopLabor":
			$displayField = "Shop Labor";
			$clause = "checkout.shopLabor = '".$value."'";
		break;
		case "referrer":
			$displayField = "Referrer";
			$clause = "checkout.referrer LIKE '%".$value."%'";
		break;
		case "shipperNum":
			$displayField = "Shipper Number";
			$clause = "checkout.shipperNum LIKE '%".$value."%'";
		break;			
		case "AffCode":
			$displayField = "Affiliate";
			if( trim($value) == "" ){ $clause = "invoice.referrerID=0";}
			else{
			    if($value==163){
			        $clause = "invoice.orderCode ='W2G'";
			    }else{
			        $clause = "invoice.affiliateID ='".$value."'";        
			    }
			}
			//Below commented by Mukund to search by affiliateID = 182 not working
			//$clause = "invoice.referrerID='".$g_oNDB->getField("SELECT ID FROM affiliate WHERE aff='".$value."'")."'";
		break;
		case "orderNum":
			$displayField = "Order #";
			$clause = "invoice.orderNum LIKE '%".$value."%'";
		break;
		case "b_LastName":
			$displayField = "Billing Last Name";
			$clause = "checkout.b_LastName LIKE '%".$value."%'";
		break;
		case "s_Phone":
			$displayField = "Phone #";
			// [NL:2012-09-14] upgraded from default
			$phone = ereg_replace( "[^[:digit:]]", '', $value );
			if( strlen($phone) == 10 ) {
				$search = substr($phone,0,3)."[^[:digit:]]{0,2}".substr($phone,3,3)."[^[:digit:]]{0,1}".substr($phone,6,4);
				$clause = "(checkout.s_Phone REGEXP '".$search."' OR checkout.b_Phone REGEXP '".$search."')"; 
			} else {
				$clause = "(checkout.s_Phone LIKE '%".$value."%' OR checkout.b_Phone LIKE '%".$value."%')";
			}
		break;
		case "s_Email":
			$displayField = "Email Address";
			$clause = "(checkout.s_Email LIKE '%".$value."%' OR checkout.b_Email LIKE '%".$value."%')";
		break;
		case "installer":
			$dateRow = "s_InstallDate";
			$displayField = "Installer";
			$clause = "checkout.installer LIKE '%".$value."%'";
		break;
		case "installer_exact":
			$dateRow = "s_InstallDate";
			$displayField = "Exact Installer";
			$clause = "checkout.installer = '".$value."'";
		break;
		case "waiting":  // universal for any flag
			if( !isset($flag) || $flag=="" ) $flag = "waiting";
			$clause = "invoice.".$flag."='Y'";
			$displayField = $flag;
			$searchVal = "Yes";
			if( $flag=="waiting" ) $value = ""; // necessary to display the waitings
		break;
		case "flag":  // universal for any flag
			if( !isset($flag) || $flag=="" ) $flag = "hidden";
			$clause = "invoice.".$flag."='Y'";
			$displayField = $flag;
			$searchVal = "Yes";
			if( $flag=="hidden" ) $value = ""; // necessary to display the hiddens
		break;
		default:
			$clause = "invoice.hidden='N'";
			$displayField = "Shipping Last Name";
			$field = "s_LastName";
			$value = "";
		break;
	}
	$value = str_replace("\'", "'", $value);
	if( !$searchVal ) {
		$searchVal = $value;
	}

	if( intval($_SESSION['ADMIN_LEVEL']) >= 3 && $flag != "hidden" ) {
		?><div style="float: right;"><A class=nav style='color: #980000;' target=main HREF="invoices.php?site=Windshield.Net&A=SFR&value=&field=flag" onClick="window.location='menu.php?site=auto--glass.com&A=R&month=<? echo $month; ?>&year=<? echo $year ?>'">Show Hidden</A></div><?
	}
	?><font face="verdana"><u><b><blockquote style='margin-left: 10px;'><? 
	if( isset($searchVal) && $searchVal != null && $searchVal != "" ) {
		echo "Search Results</u></font> -- $displayField:&nbsp;</b> ".$searchVal;
	} else {
		echo "Invoices</b>";
	}
	echo "</font><br><small><br></small>";
	
	/// all searches except by part#...
	$bShowTotals = true;
	if( $field && $value && ($field != "part") ) {
		
		// ugly code for CA...
		if( $field == $dateSort || $field == "partDetails" || $caOnly == "s_InstallDateCAOnly" ) {
			if( $value != " " ) {
				if( $caOnly == "s_InstallDateCAOnly" ) {
					$clause = " AND " . $clause;  // needs the conjunction
				} else {
					$clause = "";  // reset in other conditions
				}
				$clause .= " AND $field LIKE '%$value%' ";  // space = special bypass
			}
			$orderby = "invoice.blink DESC, invoice.feedback DESC, $dateRow DESC, invoice.ID DESC";
		} else {
			$clause = "AND ". ($clause!="" ? $clause : "$field = '$value' ");
			$orderby = "invoice.blink DESC, invoice.waiting DESC, invoice.feedback DESC, purchaseDate DESC, invoice.ID DESC";
		}
		if( $dateSort == "s_InstallDate" ) {
			$clause .= "AND s_InstallYear = '$extra' AND hidden = '".($hidden ? 'Y' : 'N')."' ";
		} elseif( $dateSort == "purchaseDate" ) {
			$clause .= "AND hidden = '".($hidden ? 'Y' : 'N')."' ";
		}
		
		/// for the california only stuff. replaced substring mysql from search the Zip = 9 for CA to State = CA
		if( $caOnly == "s_InstallDateCAOnly" )	{ 
			$conditional = "1A";
			$SQL = "SELECT invoice.*, checkout.s_LastName, checkout.s_FirstName, checkout.b_LastName, checkout.s_InstallDate, checkout.s_InstallYear, checkout.subtotal, checkout.shipping, checkout.tax, checkout.total, checkout.profit, checkout.cartID, checkout.shopLabor, checkout.glassCost, checkout.b_Zip, checkout.s_Zip, checkout.s_City, checkout.b_State, checkout.s_State, checkout.referrer, cartItems.parameters ";
			$SQL .= " FROM checkout LEFT JOIN invoice ON checkout.ID=invoice.checkoutID LEFT JOIN cartItems ON checkout.cartID=cartItems.cartID ";
			$SQL .= " WHERE invoice.ID>10000 AND invoice.affiliateID IN(".$JoinedAffs.") ".$clause." AND s_InstallYear LIKE '%".$year."%' AND SUBSTRING(checkout.s_State,1,2) = 'CA' AND checkout.s_InstallDate != '' ";
			$SQL .= " ORDER BY invoice.blink DESC, invoice.ID DESC";
		} else {
			$conditional = "1B";
			$SQL = "SELECT invoice.*, checkout.s_LastName, checkout.s_FirstName, checkout.b_LastName, s_InstallDate, s_InstallYear, checkout.subtotal, checkout.shipping, checkout.tax, checkout.total, checkout.profit, checkout.cartID, checkout.shopLabor, checkout.glassCost, checkout.b_Zip, checkout.s_Zip, checkout.s_City, checkout.b_State, checkout.s_State, checkout.referrer, cartItems.parameters ";
			$SQL .= " FROM checkout LEFT JOIN invoice ON checkout.ID=invoice.checkoutID LEFT JOIN cartItems ON checkout.cartID=cartItems.cartID ";
			$SQL .= " WHERE invoice.ID>10000 AND invoice.affiliateID IN(".$JoinedAffs.") ".$clause." ";
			$SQL .= " ORDER BY invoice.blink DESC, invoice.ID DESC";
		}
               
              // echo $SQL; 
		$hResult = mysql_query( $SQL, $hDB ) or die( mysql_error() );  // echo $SQL;
		$numRows = mysql_num_rows($hResult);
		if ($numRows == 1) {
			$rData = mysql_fetch_array($hResult, MYSQL_ASSOC);
			echo "</blockquote>";
			return ShowItem($rData['ID'], $rData['checkoutID']);
		}  elseif ($numRows == 0) {
			exit( "<blockquote><b>No matching results found</b></blockquote><!--\n\n".$SQL."\n\n-->" );
		}
	
	/// default and part# searches...
	} else {
	
		if( $field == "part" ) {  // also searches in the `product.nspart` field
			$conditional = "2A";
			$SQL = "SELECT i.ID AS ID, i.referrerID as referrerID, i.partnerID, i.partnerAnswer, i.purchaseDate, i.orderNum, i.orderCode, c.ID as checkoutID, c.s_InstallDate, c.s_InstallYear, i.purchaseDate,  c.subtotal, c.shipping, c.tax, c.total, c.profit, c.shopLabor, c.glassCost, c.cartID, i.fulfilled, c.s_LastName, c.s_FirstName, s_City, c.b_State, s_State, s_Zip, c.referrer, cI.parameters ";
			$SQL .= " FROM invoice i LEFT JOIN checkout c ON c.ID = i.checkoutID LEFT JOIN cartItems cI ON cI.cartID = c.cartID LEFT JOIN product p ON p.ID = cI.productID ";
			$SQL .= " WHERE i.ID > 10000 AND i.affiliateID IN(".$JoinedAffs.") AND (p.part LIKE '%".$value."%' OR p.nspart LIKE '%".$value."%')";
			//$SQL .= " ORDER BY i.blink DESC, i.feedback DESC, i.purchaseDate DESC, i.ID DESC";
			$SQL .= " ORDER BY i.blink DESC, i.ID DESC";

		} else {  // order date
			$bShowTotals = false;
			if( $clause != "" ) $clause = " AND ".$clause;
			$conditional = "2B";
			$SQL = "SELECT invoice.*, checkout.cartID, checkout.s_LastName, checkout.s_FirstName, checkout.b_LastName, checkout.s_InstallYear, checkout.s_InstallDate, checkout.b_State, s_State, s_City, s_Zip, checkout.referrer, checkout.tax, checkout.shopLabor, checkout.glassCost, checkout.total, checkout.profit, cartItems.parameters ";
			$SQL .= " FROM invoice LEFT JOIN checkout ON checkout.ID=invoice.checkoutID LEFT JOIN cartItems ON checkout.cartID=cartItems.cartID ";
			$SQL .= " WHERE invoice.ID>10000 AND (invoice.affiliateID IN(".$JoinedAffs.")) ".$clause." ";
			//$SQL .= " ORDER BY blink DESC, feedback DESC, purchaseDate DESC, invoice.ID DESC";
			$SQL .= " ORDER BY invoice.blink DESC, invoice.ID DESC";
		}
		
		$hResult = mysql_query( $SQL, $hDB ) or die( mysql_error() );
		$numRows = mysql_num_rows($hResult);
	}
	
	/// info...
	if( $g_Config->isDev ) {
		echo $conditional.": ".$SQL."<br><br>";
	}

	echo "<b>".$numRows."</b> records found -- listing results <b>".($startAt+1)."</b> through <b>".($startAt+$displayNum>$numRows ? $numRows : $startAt+$displayNum)."</b><br><!--\nconditional: ".$conditional." | orig field = '".$orig."' / field = '".$field."'\nSQL: ".$SQL."\n-->";

	/// column headers for the list...
	?>
	<table border=0 bordercolor=black cellspacing=1 cellpadding=2 nowrap bgcolor="#808080">
		<tr bgcolor="#E0E0E0">
			<td nowrap style="vertical-align: bottom;"><b>S</b><br>c<br>h<br>e<br>d</td>
			<td nowrap style="vertical-align: bottom;" align="center"><b>Order #</td>
			<td nowrap style="vertical-align: bottom;"><b>Inst</b></td>
			<? if( $dateRow == "purchaseDate" ) { ?>
			<td nowrap style="vertical-align: bottom;"><b>Purchased</td>
			<? } ?>
			<td nowrap style="vertical-align: bottom;"><b>Installed</td>
			<td nowrap style="vertical-align: bottom;"><b>Year</td>
			<td nowrap style="vertical-align: bottom;"><b>Last Name</td>
			<td nowrap style="vertical-align: bottom;"><b>Billing</td>
			<td nowrap style="vertical-align: bottom;"><b>City</td>
			<td nowrap style="vertical-align: bottom;"><b>State</td>
			<td nowrap style="vertical-align: bottom;"><b>Zip</td>
			<td bgcolor=#E0E8F8 style="vertical-align: top;"><a class=text href="<?= $PHP_SELF ?>?A=SFR&field=flag&flag=waitForCallback&value=Y"><b>A</b></a><br>u<br>t<br>h</td><!-- auth -->
			<td bgcolor=#CCF0EC style="vertical-align: top;"><b>P</b><br>a<br>i<br>d</td><!-- paid -->
			<td bgcolor=#C0E8C8 style="vertical-align: top;"><b>R</b><br>e<br>a<br>d<br>y</td><!-- ready -->
			<td bgcolor=#C8F8D8 style="vertical-align: top;"><b>S</b><br>h<br>o<br>p</td><!-- paid shop -->
			<td bgcolor=#F8F8E0 style="vertical-align: top;"><a class=text href="<?= $PHP_SELF ?>?A=SFR&field=flag&flag=waitForCallback&value=Y"><b>L</b></a><br>c<br>a<br>l<br>l</td><!-- callback -->
			<td bgcolor=#F0E8D8 style="vertical-align: top;"><a class=text href="<?= $PHP_SELF ?>?A=SFR&field=flag&flag=onHold&value=Y"><b>H</b></a><br>o<br>l<br>d</td><!-- hold -->
			<td bgcolor=#C8C8C8 style="vertical-align: top;"><a class=text href="<?= $PHP_SELF ?>?A=SFR&field=flag&flag=waiting&value=Y"><b>W</b><br>a<br>i<br>t</a></td><!-- waiting -->
			<td bgcolor=#F4F4F4 style="vertical-align: top;"><a class=text href="<?= $PHP_SELF ?>?A=SFR&field=flag&flag=notServiced&value=Y"><b>N</b></a><br>o<br>S<br>v<br>c</td><!-- no service -->
			<td bgcolor=#E0E0E0 style="vertical-align: top;"><a class=text href="<?= $PHP_SELF ?>?A=SFR&field=flag&flag=declined&value=Y"><b>D</b></a><br>e<br>c<br>l</td><!-- declined -->
			<td bgcolor=#E8C8F0 style="vertical-align: top;"><a class=text href="<?= $PHP_SELF ?>?A=SFR&field=flag&flag=fraudulent&value=Y"><b>I</b></a><br>s<br>s<br>u<br>e</td><!-- fraud -->
			<td bgcolor=#F8D8D8 style="vertical-align: top;">C<br>a<br>n<br><a class=text href="<?= $PHP_SELF ?>?A=SFR&field=flag&flag=cancelled&value=Y"><b>X</b></a></td><!-- cancelled -->
			<td bgcolor=#DDBCBC style="vertical-align: top;">H<br>i<br>d<br><a class=text href="<?= $PHP_SELF ?>?A=SFR&field=flag&flag=hidden&value=Y"><b>e</b></a></td><!-- hidden -->
			<td bgcolor=#D4DCF2 style="vertical-align: top;"><b>C</b><br>p<br>l<br>t<br>d</td><!-- fulfilled / completed -->
			<td bgcolor=#FFFFFF style='text-align: center; vertical-align: top'>P<br>r<br>t<br>n<br>r</td><!-- partnering -->
			<td nowrap style="vertical-align: bottom;" align=center><b>CA</b></td>
			<td nowrap style="vertical-align: bottom;" align=center><b>Tax</b></td>
			<td nowrap style="vertical-align: bottom;" align=center><b>Total</b></td>
			<? if( $_SESSION['ADMIN_LEVEL'] >=3 ) { ?>
				<td nowrap style="vertical-align: bottom;" align=center><b>Labor</b></td>
				<td nowrap style="vertical-align: bottom;" align=center><b>Glass</b></td>
				<td nowrap style="vertical-align: bottom;" align=center><b>Profit</b></td>
			<? } ?>
			<!--<td nowrap style="vertical-align: bottom;" align=center><b>ExtRef</b></td>
			<td nowrap style="vertical-align: bottom;" align=center><b>AffRef</b></td>-->
			<td nowrap style="vertical-align: bottom;" align=center><b>Product</b></td>
			<!--<td nowrap style="vertical-align: bottom;" align=center><b>Part #</b></td>-->
			<td nowrap style="vertical-align: bottom;" align=center><b>Nags#</b></td>
			<td nowrap style="vertical-align: bottom;" align=center><b><font color="#C00000">Delete</td>
		</tr>
	<?

	/// set up the colors...
	$colorings = array(
		'installation' => "#FCFCB8",
		'installationS' => "#FFFFE0",
		'glassOnly' => "#E0E0E0",
		'glassOnlyS' => "#F0F0F0",
		'scheduled' => "#E0E8F8",
		'scheduledA' => "#D0D8F0",
		'auth' => "#CCF0EC",
		'authA' => "#",
		'paid' => "#C0E8C8",
		'paidA' => "#",
		'installerPaid' => "#C8F8D8",
		'installerPaidA' => "#",
		'waiting' => "#C4C4C4",  // #C8E4CC, #D2D2D2
		'waitingA' => "#",
		'waitForCallback' => "#F8F8E0",
		'waitForCallbackA' => "#",
		'onHold' => "#F0E8D8",
		'onHoldA' => "#",
		'notServiced' => "#E0E0E0",
		'notServicedA' => "#",
		'cancelled' => "#F8D8D8",
		'cancelledA' => "#",
		'declined' => "#E0E0E0",
		'declinedA' => "#",
		'fraudulent' => "#E8C8F0",
		'fraudulentA' => "#",
		'ready' => "#E0E8F8",
		'readyA' => "#E0E8F8",
		'fulfilled' => "#D4DCF2",
		'fulfilledA' => "#D4DCF2",
		'partnerP' => "#E8E8E8",
		'partnerF' => "#C8D0FF",
		'partnerL' => "#D0F8D8",
		'partnerD' => "#F0D8D8",
		'partnerX' => "#F0D8D8",
	);
	
	
	// initz
	$count = 0;
	$displayed = 0;
	$mt = "-";
	// tallies
	$instTally = 0.00;
	$subTally = 0.00;
	$caTotalTally = 0.00;
	$shipTally = 0.00;
	$taxTally = 0.00;
	$laborTally = 0.00;
	$glassCostTally = 0.00;
	$laborTallyPaid = 0.00;
	$profitTallyPaid = 0.00;
	$glassCostTallyPaid = 0.00;
	$totalTally = 0.00;
	$profitTally = 0.00;
	$paidTally = 0.00;
	$unpaidTally = 0.00;

	/// display
	while( ($rData = mysql_fetch_array($hResult, MYSQL_ASSOC))  &&  ($displayed < $displayNum) ) {

		// handle any skip factors
		if( $count++ < $startAt ) {
			continue;
		} else {
			$displayed++;
		}
		if( $filterPaid != "" && $rData['paid'] != $filterPaid ) {
			continue;
		}
		
		/// lookup the cart item data...
		$SQL2 = "SELECT cartItems.ID, cartItems.productID, cartItems.partDetails, cartItems.parameters, product.year, product.make, product.model, product.style, product.part, product.nspart ";
		$SQL2 .= " FROM cart LEFT JOIN cartItems ON cart.ID=cartItems.cartID LEFT JOIN product ON cartItems.productID=product.ID WHERE cart.ID='".$rData['cartID']."'";
		$rCartItem = $g_oNDB->getRow($SQL2);
		if( intval($rCartItem['productID']) < 1 ) {
			$rCartItem['year'] = "(unknown)";
			$rCartItem['part'] = "<i>( ".substr($rCartItem['partDetails'],0,15)." )</i>";
		}
		
		/// determine if this row is getting displayed then the bgcolor...
		if( $rData['parameters'] == "inst" ) {
			$bgColor = $rData['scheduled']=="Y" ? $colorings['installationS'] : $colorings['installation'];
		} else {
			$bgColor = $rData['scheduled']=="Y" ? $colorings['glassOnlyS'] : $colorings['glassOnly'];
		}
		if( $rData['onHold']=="Y" || $rData['waiting']=="Y" || $rData['waitForCallback']=="Y" || $rData['declined']=="Y" ) {
			$bgColor = $colorings['onHold'];
		}
		if( $rData['waiting']=="Y" ) {
			$bgColor = $colorings['waiting'];
		}
		if( $rData['cancelled']=="Y" || $rData['notServiced']=="Y" ) {
			$bgColor = $colorings['cancelled'];
		}
		if( $rData['fraudulent']=="Y" ) {
			$bgColor = $colorings['fraudulent'];
		}
		
		/// other initz...
		$thisTotal = sprintf("%01.2f", (($rData['subtotal'] + $rData['shipping']) + $rData['tax']), 2);
		$thisTax   = sprintf("%01.2f", $rData['tax'], 2);
		if( strstr(strtolower($rData['s_State']), strtolower("ca")) && (strstr(strtolower($rData['s_State']), strtolower("can")) == false || !strstr(strtolower($rData['s_State']), strtolower("car")) == false) ) {
			$CA = "<font color=\"#FF0000\">Y</font>";
		} else {
			$CA = "N";	
		}
		
		/// start the row...
		$ToggleCarryFields = "&A2=".$A.QueryString( array('startAt','displayNum','dateSort','year','month','day','field','value','flag'), "&", true );
		echo "<tr bgcolor=\"".$bgColor."\" onMouseOver=\"return setBG(this,'#FFFFFF');\" onMouseOut=\"return setBG(this,'".$bgColor."');\">";
		echo "<td style='text-align: center;' bgcolor=".($rData['scheduled']=="Y" ? $colorings['scheduledA'] : $colorings['scheduled'])." nowrap><a title='scheduled' style='color: #000000; text-decoration: none;' href=\"".$PHP_SELF."?site=$site&A=TOG&f=scheduled&invoiceID=".$rData['ID']."&v=".($rData['scheduled']=="N"?"Y":"N").$ToggleCarryFields."\">".($rData['scheduled'] =="Y" ? "S" : $mt)."</a>";
		//if( intval($rCartItem['ID']) < 0 ) { echo $SQL2."<br><br>"; printArray($rData); }
		echo "</td>";
		$orderLinkStyle = "";
		$orderAlign = "right";
		$orderNum = sprintf("%05d",$rData['orderNum']);
		if( $rData['orderCode'] != "W2G" ) {
			$orderNum = $rData['orderCode']."-".$orderNum;
			$orderAlign = "left";
			$orderLinkStyle = " color: black;";
		}
		if( $rData['blink']=="Y" ) {
			$orderLinkStyle = "font-weight: bold; color: #FF0000;";
		} elseif( $rData['waiting']=="Y" ) {
			$orderLinkStyle = "font-weight: bold; color: #009800;";
		} elseif( $rData['feedback']=="Y" ) {
			$orderLinkStyle .= " font-weight: bold;";
		}
		echo "<td nowrap style='text-align: ".$orderAlign.";'><a style='".$orderLinkStyle."' title=\"orderNum: ".$rData['orderCode']."-".$rData['orderNum']."  |  ID: ".$rData['ID']."\" href=\"".$PHP_SELF."?site=".$site."&A=S&invoiceID=".$rData['ID']."&checkoutID=".$rData['checkoutID']."\">".$orderNum."</a></td>";
		echo "<td nowrap>".$rData['parameters']."</td>";
		
		/// the date...
		if( $dateRow == "purchaseDate" ) {
			list($year,$month, $day) = split("-", $rData['purchaseDate'], 3);
			//list(,$time_hms) = split(" ", $rData['purchaseDate'],2);
			//list($time_h, $time_m) = split(":", $time_hms);
			echo "<td nowrap title=\"".$rData['purchaseDate']."\">" . ereg_replace(" 0"," ",date("F d", mktime(0,0,0,$month, $day, $year) ))."</td>"; // ." ".$time_h.":".$time_m
		}
		list($installDay, $installMonth, $installTime) = split (" ", $rData['s_InstallDate'], 3);
		$installDay = intval($installDay);
		echo "<td nowrap>" . (is_numeric($installDay) ? "$installMonth $installDay" : $installMonth) . "</td>";
		
		/// special handling for the partner column...
		if( intval($rData['partnerID'])>0 ) {
			if( $rData['partnerAnswer']=="pending" ) {
				$PartnerCode = "P";
				$bgColor = $colorings['partnerP'];
			} elseif( $rData['partnerAnswer']=="full" ) {
				$PartnerCode = "F";
				$bgColor = $colorings['partnerF'];
			} elseif( $rData['partnerAnswer']=="install-only" ) {
				$PartnerCode = "L";
				$bgColor = $colorings['partnerL'];
			} elseif( $rData['partnerAnswer']=="none" ) {
				$PartnerCode = "D";
				$bgColor = $colorings['partnerD'];
			} else {
				$PartnerCode = $rData['partnerAnswer'];
				$bgColor = $colorings['partnerX'];
			}
		} else {
			$PartnerCode = "&nbsp;";
			$bgColor = "#FFFFFF";
		}
		
		/// dump out the remaining columns...
		?>
			<td nowrap align=center><?= LimitChars($rData['s_InstallYear'], 4) ?></td>
			<td nowrap align=center><?= LimitChars($rData['s_LastName'], 15) ?></td>
			<td nowrap align=center><?= LimitChars($rData['b_LastName'], 15) ?></td>
			<td nowrap align=center><?= LimitChars($rData['s_City'], 15) ?></td>
			<td nowrap align=center><?= LimitChars($rData['s_State'], 2) ?></td>
			<td nowrap align=center><?= LimitChars($rData['s_Zip'], 5) ?></td>
			<!-- auth --><td bgcolor=#E0E8F8 nowrap align=center><a title="<?= "order # ".$orderNum." is ".($rData['auth']=="Y"?"":"NOT")." paid" ?>" style="font-family: Courier New, Courier, Monospace, Monotype; color: '#000000'; text-decoration: none;" href="<?= $PHP_SELF ?>?site=<? echo "$site&A=TOG&f=auth&invoiceID=".$rData['ID']; ?>&v=<? echo ($rData['auth']=="N"?"Y":"N").$ToggleCarryFields."\">".($rData['auth'] =="Y" ? "A" : $mt); ?></a></td>
			<!-- paid --><td bgcolor=#CCF0EC nowrap align=center><a title="<?= "order # ".$orderNum." is ".($rData['paid']=="Y"?"":"NOT")." paid" ?>" style="font-family: Courier New, Courier, Monospace, Monotype; color: '#000000'; text-decoration: none;" href="<?= $PHP_SELF ?>?site=<? echo "$site&A=TOG&f=paid&invoiceID=".$rData['ID']; ?>&v=<? echo ($rData['paid']=="N"?"Y":"N").$ToggleCarryFields."\">".($rData['paid'] =="Y" ? "P" : $mt); ?></a></td>
			<!-- ready --><td bgcolor=#C0E8C8 nowrap align=center><a title="<?= "order # ".$orderNum.($rData['ready']=="Y"?" HAS ":" hasn't")." received a ready status" ?>" style="font-family: Courier New, Courier, Monospace, Monotype; color: '#000000'; text-decoration: none;" href="<?= $PHP_SELF ?>?site=<? echo "$site&A=TOG&f=ready&invoiceID=".$rData['ID']; ?>&v=<? echo ($rData['ready']=="N"?"Y":"N").$ToggleCarryFields."\">".($rData['ready'] =="Y" ? "R" : $mt); ?></a></td>
			<!-- paid shop --><td bgcolor=#C8F8D8 nowrap align=center><a title="<?= "the shop for order # ".$orderNum." was ".($rData['installerPaid']=="Y"?"":"NOT")." paid" ?>" style="font-family: Courier New, Courier, Monospace, Monotype; color: '#000000'; text-decoration: none;" href="<?= $PHP_SELF ?>?site=<? echo "$site&A=TOG&f=installerPaid&invoiceID=".$rData['ID']; ?>&v=<? echo ($rData['installerPaid']=="N"?"Y":"N").$ToggleCarryFields."\">".($rData['installerPaid'] =="Y" ? "I" : $mt); ?></a></td>
			<!-- callback --><td bgcolor=#F8F8E0 nowrap align=center><a title="<?= "order # ".$orderNum.($rData['waitForCallback']=="Y"?" IS":" is not")." waiting for a callback" ?>" style="font-family: Courier New, Courier, Monospace, Monotype; color: '#000000'; text-decoration: none;" href="<?= $PHP_SELF ?>?site=<? echo "$site&A=TOG&f=waitForCallback&invoiceID=".$rData['ID']; ?>&v=<? echo ($rData['waitForCallback']=="N"?"Y":"N").$ToggleCarryFields."\">".($rData['waitForCallback'] =="Y" ? "W" : $mt); ?></a></td>
			<!-- on hold --><td bgcolor=#F0E8D8 nowrap align=center><a title="<?= "order # ".$orderNum." is".($rData['onHold']=="Y"?"":" NOT")." on hold" ?>" style="font-family: Courier New, Courier, Monospace, Monotype; color: '#000000'; text-decoration: none;" href="<?= $PHP_SELF ?>?site=<? echo "$site&A=TOG&f=onHold&invoiceID=".$rData['ID']; ?>&v=<? echo ($rData['onHold']=="N"?"Y":"N").$ToggleCarryFields."\">".($rData['onHold'] =="Y" ? "H" : $mt); ?></a></td>
			<!-- waiting --><td bgcolor=#C8C8C8 nowrap align=center><a title="<?= "order # ".$orderNum." is".($rData['waiting']=="Y"?"":" NOT")." waiting" ?>" style="font-family: Courier New, Courier, Monospace, Monotype; color: '#000000'; text-decoration: none;" href="<?= $PHP_SELF ?>?site=<? echo "$site&A=TOG&f=waiting&invoiceID=".$rData['ID']; ?>&v=<? echo ($rData['waiting']=="N"?"Y":"N").$ToggleCarryFields."\">".($rData['waiting'] =="Y" ? "W" : $mt); ?></a></td>
			<!-- no service --><td bgcolor=#F4F4F4 nowrap align=center><a title="<?= "order # ".$orderNum." is".($rData['notServiced']=="Y"?" NOT":"")." serviced" ?>" style="font-family: Courier New, Courier, Monospace, Monotype; color: '#000000'; text-decoration: none;" href="<?= $PHP_SELF ?>?site=<? echo "$site&A=TOG&f=notServiced&invoiceID=".$rData['ID']; ?>&v=<? echo ($rData['notServiced']=="N"?"Y":"N").$ToggleCarryFields."\">".($rData['notServiced'] =="Y" ? "N" : $mt); ?></a></td>
			<!-- fraud --><td bgcolor=#E0E0E0 nowrap align=center><a title="<?= "order # ".$orderNum.($rData['declined']=="Y"?" WAS ":" wasn't")." declined" ?>" style="font-family: Courier New, Courier, Monospace, Monotype; color: '#000000'; text-decoration: none;" href="<?= $PHP_SELF ?>?site=<? echo "$site&A=TOG&f=declined&invoiceID=".$rData['ID']; ?>&v=<? echo ($rData['declined']=="N"?"Y":"N").$ToggleCarryFields."\">".($rData['declined'] =="Y" ? "D" : $mt); ?></a></td>
			<!-- declined --><td bgcolor=#E8C8F0 nowrap align=center><a title="<?= "order # ".$orderNum.($rData['fraudulent']=="Y"?" WAS ":" wasn't")." fraudulent" ?>" style="font-family: Courier New, Courier, Monospace, Monotype; color: '#000000'; text-decoration: none;" href="<?= $PHP_SELF ?>?site=<? echo "$site&A=TOG&f=fraudulent&invoiceID=".$rData['ID']; ?>&v=<? echo ($rData['fraudulent']=="N"?"Y":"N").$ToggleCarryFields."\">".($rData['fraudulent'] =="Y" ? "F" : $mt); ?></a></td>
			<!-- cancelled --><td bgcolor=#F8D8D8 nowrap align=center><a title="<?= "order # ".$orderNum.($rData['cancelled']=="Y"?" HAS":" hasn't")." been cancelled" ?>" style="font-family: Courier New, Courier, Monospace, Monotype; color: '#000000'; text-decoration: none;" href="<?= $PHP_SELF ?>?site=<? echo "$site&A=TOG&f=cancelled&invoiceID=".$rData['ID']; ?>&v=<? echo ($rData['cancelled']=="N"?"Y":"N").$ToggleCarryFields."\">".($rData['cancelled'] =="Y" ? "X" : $mt); ?></a></td>
			<!-- hidden --><td bgcolor=#DDBCBC nowrap align=center><a title="<?= "order # ".$orderNum.($rData['hidden']=="Y"?" HAS":" hasn't")." been hidden" ?>" style="font-family: Courier New, Courier, Monospace, Monotype; color: '#000000'; text-decoration: none;" href="<?= $PHP_SELF ?>?site=<? echo "$site&A=TOG&f=hidden&invoiceID=".$rData['ID']; ?>&v=<? echo ($rData['hidden']=="N"?"Y":"N").$ToggleCarryFields."\">".($rData['hidden'] =="Y" ? "H" : $mt); ?></a></td>
			<!-- fulfilled --><td bgcolor=#D4DCF2 nowrap align=center><a title="<?= "order # ".$orderNum.($rData['fulfilled']=="Y"?" IS ":" isn't")." completed" ?>" style="font-family: Courier New, Courier, Monospace, Monotype; color: '#000000'; text-decoration: none;" href="<?= $PHP_SELF ?>?site=<? echo "$site&A=TOG&f=fulfilled&invoiceID=".$rData['ID']; ?>&v=<? echo ($rData['fulfilled']=="N"?"Y":"N").$ToggleCarryFields."\">".($rData['fulfilled'] =="Y" ? "C" : $mt); ?></a></td>
			<!-- partnering --><td bgcolor="<?= $bgColor ?>" nowrap align=center><?= $PartnerCode ?></td>
			<td nowrap align=center><?=$CA?></td>
			<!--<td nowrap align=center><?=$thisTax?></td>
			<td nowrap align=center><?=$thisTotal?></td>-->
			<td nowrap style='text-align: right;'><?= zeroed(sprintf("%.2f",$rData['tax'])) ?></td>
			<td nowrap style='text-align: right;'><?= zeroed(sprintf("%.2f",$rData['total'])) ?></td>
			<?
			if( $_SESSION['ADMIN_LEVEL'] >=3 ) {
				?>
				<td nowrap style='text-align: right;'><?= zeroed(sprintf("%.2f",$rData['shopLabor'])) ?></td>
				<td nowrap style='text-align: right;'><?= zeroed(sprintf("%.2f",$rData['glassCost'])) ?></td>
				<td nowrap style='text-align: right;'><?= zeroed(sprintf("%.2f",$rData['profit'])) ?></td>
				<?
			}
				
			//echo "<td nowrap>" . $rData['referrer'] . "</td>";
			//echo "<td nowrap>" . (intval($rData['referrerID']) < 1 ? "--" : $g_oNDB->getField("SELECT aff FROM affiliate WHERE ID='".$rData['referrerID']."'")) . "</td>";
			
			if( intval($rCartItem['productID']) > 0 ) {
				?><td nowrap><?= LimitChars(strtolower($rCartItem['year']." ".$rCartItem['make']." ".$rCartItem['model']." ".$rCartItem['style']), 25) ?></td><?
				?><!--<td nowrap><a title="<?= htmlspecialchars($rCartItem['year']." ".$rCartItem['make']." ".$rCartItem['model']." ".$rCartItem['style']) ?>" href="../products.php?A=L&wF=part&wV=<?= urlencode($rCartItem['part']) ?>"><?= htmlspecialchars(maxstr($rCartItem['part'],12)) ?></a></td>--><?

			} else {
					?><td nowrap><i>(<?= substr($rCartItem['partDetails'],0,15) ?>)</i></td><?
					//echo "<td nowrap></td>";
			}
			if( $rCartItem['nspart'] != "" ) {
				?><td nowrap><a title="<?= htmlspecialchars($rCartItem['year']." ".$rCartItem['make']." ".$rCartItem['model']." ".$rCartItem['style']) ?>" href="../products.php?A=L&wF=part&wV=<?= urlencode($rCartItem['part']) ?>"><?= htmlspecialchars(maxstr($rCartItem['nspart'],15)) ?></a></td><?
			} elseif( intval($rCartItem['productID']) == 0 ) {
				echo "<td nowrap style='color: #C0C0C0;'>(none)</td>";
			} else {
				?><td nowrap><a style='color: #808080;' title="<?= htmlspecialchars($rCartItem['year']." ".$rCartItem['make']." ".$rCartItem['model']." ".$rCartItem['style']) ?>" href="../products.php?A=L&wF=part&wV=<?= urlencode($rCartItem['part']) ?>"><?= htmlspecialchars(maxstr($rCartItem['part'],12)) ?></a></td><?
			}
			?>
			<td nowrap style='text-align: center;'><a onClick="return confirm('Really delete this invoice from <?= str_replace("'", "", $rData['s_FirstName']." ".$rData['s_LastName']) ?>?')" href="<?= $PHP_SELF ?>?<? echo $QUERY_STRING; ?>&delete=1&invoiceID=<? echo $rData['ID']; ?>"><font color="#C00000">delete</font></a></td>
		</tr>
		<?
		$instTally += (trim($rCartItem['parameters']) == "inst") ? $rData['subtotal'] : $rData['subtotal'];
		$subTally += $rData['subtotal'];
		/* Get the California Total Sales */
		if( strstr(strtolower($rData['s_State']), strtolower("ca")) && (strstr(strtolower($rData['s_State']), strtolower("can")) == false || !strstr(strtolower($rData['s_State']), strtolower("car")) == false) ) {
			$caTotalTally += ($rData['subtotal'] + $rData['shipping']);
		}
		$shipTally += $rData['shipping'];
		$taxTally += $rData['tax'];
		$laborTally += $rData['shopLabor'];
		$glassCostTally += $rData['glassCost'];
		if( $rData['paid'] == 'Y' ) {
			$laborTallyPaid += $rData['shopLabor'];
			$glassCostTallyPaid += $rData['glassCost'];
			$profitTallyPaid += floatval($rData['profit']);
		}
		$totalTally += $rData['total'];
		if( $rData['paid']=='Y' ) {
			$paidTally += $rData['total'];
		} elseif( $rData['paid']=='N' ) {
			$unpaidTally += $rData['total'];
		}
		$profitTally += floatval($rData['profit']);
		flush();
	}
	echo "</td></tr></table><span style='font-size: 4px;'><br><br></span><nobr>";
	
	/// links...
	echo "<table width=100% border=0 cellspacing=0 cellpadding=0><tr><td nowrap align=left>";
	$newStart = $startAt - $displayNum;
	if( $newStart<0 ) $newStart = 0;
	if( $startAt > 0 ) echo "<a href='".$PHP_SELF."?site=$site&startAt=$newStart".QueryString( array('displayNum','A','dateSort','year','month','day','field','value'), "&", true )."'>&lt;&lt; PREV</a> &nbsp;&nbsp; ";
	$newStart = $startAt + $displayed;
	if( $rData ) echo "<a href='".$PHP_SELF."?site=$site&A=L&startAt=$newStart".QueryString( array('displayNum','A','dateSort','year','month','day','field','value'), "&", true )."'>NEXT &gt;&gt;</a>";
	echo "&nbsp; &nbsp; &nbsp; Display (&nbsp; ";
	foreach( array(100,300,600,1000,2000) as $num ) {
		echo "<a style='".($num==$displayNum?"font-weight: bold;":"text-decoration: underline;")."' href=\"".$PHP_SELF."?displayNum=".$num.QueryString( array('A','startAt','dateSort','year','month','day','field','value','flag'), "&", true )."\">".$num."</a>&nbsp; ";
	}
	echo "<a style='".($displayNum==9999?"font-weight: bold;":"text-decoration: underline;")."' href=\"".$PHP_SELF."?startAt=0&displayNum=9999".QueryString( array('A','dateSort','year','month','day'), "&", true )."\">ALL</a> ";
	echo ") at a time.</nobr></td><td nowrap>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</td>";
	echo "<td align=right nowrap>Partnering Key: <b>P</b>ending, <b>F</b>ull, <b>L</b>abor (install-only), <b>D</b>eclined, <b>X</b> unknown, or none</td></tr></table>\n";

	/*/ -- Totalling data. -- /*/
	
	/// when ordered by purchase date...
	if( $_SESSION['ADMIN_LEVEL'] >= 3 ) {
		if( $bShowTotals && (true || $_SESSION["auth"] == true) ) {
			echo "<br><table border=0 bordercolor=black cellspacing=1 cellpadding=2 nowrap bgcolor=#808080>";
			/// formatting...
			$subTotalAfterShipping = sprintf("%01.2f", ($subTally + $shipTally) + $taxTally);
			$subTotalMinusTax = $subTotalAfterShipping - $taxTally;
			$subTotalMinusLabor = $subTotalMinusTax - $laborTally;
			$subTotalMinusGlassCost = $subTotalMinusLabor - $glassCostTally;		
			$subTotalAfterShipping = number_format( sprintf("%01.2f", $subTotalAfterShipping), 2);
			$total = number_format( sprintf("%01.2f", $subTotalMinusGlassCost), 2);
			$grandTotal = number_format( sprintf("%01.2f", $totalTally), 2);
			$profitTotal = number_format( sprintf("%01.2f", $profitTally), 2);
			$instTally = number_format( sprintf("%01.2f", $instTally), 2);
			$nInstTally = number_format( sprintf("%01.2f", $nInstTally), 2);
			$shipTally = number_format( sprintf("%01.2f", $shipTally), 2);
			$caTotalTally = number_format( sprintf("%01.2f", $caTotalTally), 2);
			$subTally = number_format( sprintf("%01.2f", $subTally), 2);
			$taxTally = number_format( sprintf("%01.2f", $taxTally), 2);
			$laborTally = number_format( sprintf("%01.2f", $laborTally), 2);
			$glassCostTally = number_format( sprintf("%01.2f", $glassCostTally), 2);
			$paidTally = number_format( sprintf("%01.2f", $paidTally), 2);
			$unpaidTally = number_format( sprintf("%01.2f", $unpaidTally), 2);
			/// business profit summary...
			?>
			<tr bgcolor="#EEEEEE" class=right align=right><td class=right colspan=22><b>Installed Subtotal:&nbsp;</b></td><td class=right>$<? echo $instTally ?></td></tr>
			<tr bgcolor="#FFFFFF" class=right align=right><td class=right colspan=22><b>Non-Installed Subtotal:&nbsp;</b></td><td class=right>$<? echo $nInstTally ?></td></tr>
			<tr bgcolor="#EEEEEE" class=right align=right><td class=right colspan=22><b>CA Total:&nbsp;</b></td><td class=right>$<?echo $caTotalTally; ?></td></tr>		
			<tr bgcolor="#FFFFFF" class=right align=right><td class=right colspan=22><b>Base Subtotal:&nbsp;</b></td><td class=right>$<? echo $subTally ?></td></tr>
			<tr bgcolor="#EEEEEE" class=right align=right><td class=right colspan=22><b>Shipping:&nbsp;</b></td><td class=right><font color="green"> + $<?echo $shipTally; ?></font></td></tr>
			<tr bgcolor="#EEEEEE" class=right align=right><td class=right colspan=22><b>Tax:&nbsp;</b></td><td class=right><font color="green"> + $<?echo $taxTally; ?></font></td></tr>			
			<tr bgcolor="#FFFFFF" class=right align=right><td class=right colspan=22><b>Subtotal:&nbsp;</b></td><td class=right>$<? echo $subTotalAfterShipping ?></td></tr>	
			<tr bgcolor="#EEEEEE" class=right align=right><td class=right colspan=22><b>Tax:&nbsp;</b></td><td class=right><font color="red"> - $<?echo $taxTally; ?></font></td></tr>		
			<tr bgcolor="#FFFFFF" class=right align=right><td class=right colspan=22><b>Total Shop Labor:&nbsp;</b></td><td class=right><font color="red"> - $<?echo $laborTally; ?></font></td></tr>		
			<tr bgcolor="#EEEEEE" class=right align=right><td class=right colspan=22><b>Total Glass Cost:&nbsp;</b></td><td class=right><font color="red"> - $<?echo $glassCostTally; ?></font></td></tr>				
			<tr bgcolor="#FFFFFF" class=right align=right><td class=right colspan=22><b>"Profit":&nbsp;</b></td><td class=right>$<?echo $total; ?></td></tr>
			<tr bgcolor="#E8F0FF" class=right align=right><td class=right colspan=22><b>Grand Total:&nbsp;</b></td><td class=right><b>$<?echo $grandTotal; ?></b></td></tr>
			<tr bgcolor="#FFFFFF" class=right align=right><td class=right colspan=22><b>Gross Profit:&nbsp;</b></td><td class=right>$<?echo $profitTotal; ?></td></tr>
			<tr bgcolor="#ECFCF4" class=right align=right><td class=right colspan=22><b><i style="color: #689868;">Paid</i>&nbsp; Shop Labor:&nbsp;</b></td><td class=right><font color="red"> - $<?echo $laborTallyPaid; ?></font></td></tr>		
			<tr bgcolor="#ECFCF4" class=right align=right><td class=right colspan=22><b><i style="color: #689868;">Paid</i>&nbsp; Glass Cost:&nbsp;</b></td><td class=right><font color="red"> - $<?echo $glassCostTallyPaid; ?></font></td></tr>				
			<tr bgcolor="#ECFCF4" class=right align=right><td class=right colspan=22><b><i style="color: #689868;">Paid</i>&nbsp; "Profit":&nbsp;</b></td><td class=right>$<?echo $profitTallyPaid; ?></td></tr>
			<?
			if( $dateSort == "s_InstallDate" || $caOnly = "s_InstallDateCAOnly" ) {
				if( $filterPaid == "" ) {
					?>
					<tr bgcolor="#FFFFFF" class=right align=right><td class=right colspan=22><b><a style="font-family: inherit; font-weight: inherit; font-size: inherit; color: #000088;" href="<?= $PHP_SELF . '?' . $QUERY_STRING ?>&paid=Y">Paid:</a>&nbsp;</b></td><td class=right>$<?echo $paidTally; ?></td></tr>
					<tr bgcolor="#FFFFFF" class=right align=right><td class=right colspan=22><b><a style="font-family: inherit; font-weight: inherit; font-size: inherit; color: #000088;" href="<?= $PHP_SELF . '?' . $QUERY_STRING ?>&paid=N">Unpaid:</a>&nbsp;</b></td><td class=right>$<?echo $unpaidTally; ?></td></tr>
					<?
				} else {
					?>
					<tr bgcolor="#FFFFFF" class=right align=right><td class=right colspan=22><b>Paid:&nbsp;</b></td><td class=right>$<?echo $paidTally; ?></td></tr>
					<tr bgcolor="#FFFFFF" class=right align=right><td class=right colspan=22><b>Unpaid:&nbsp;</b></td><td class=right>$<?echo $unpaidTally; ?></td></tr>
					<?
				}
			}
			echo "</table>";
		}
	}
	
	/// all done...
	echo "</blockquote></blockquote></body></html>";

} // ListItems()

//-------------------------------------------------------------------------
// ShowItem:  Show the full invoice for the specified invoice ID. 
//-------------------------------------------------------------------------
function ShowItem( $invoiceID, $checkoutID ) {

	global $g_Config, $g_oNDB, $PHP_SELF, $hDB, $site;

	/// un-set the new feedback flag on any viewing whatsoever...
	if( intval($invoiceID)>0 ) $g_oNDB->execute("UPDATE invoice SET feedback='N' WHERE ID=".$invoiceID);
	
	/// get the info...
	$SQL = "SELECT checkout.*, invoice.edited, invoice.orderCode, invoice.orderNum, invoice.customerKey, location.name as installerName FROM checkout LEFT JOIN invoice ON checkout.ID=invoice.checkoutID LEFT JOIN location ON checkout.installerID=location.id WHERE checkout.ID=$checkoutID and invoice.ID=$invoiceID";  // echo "<br>$SQL<br>";
	$hCheckout = mysql_query( $SQL );
	if( !$hCheckout ) exit( "Checkout information not found." );
	$rCheckout = mysql_fetch_array($hCheckout,  MYSQL_ASSOC) or die("</td></tr></table><blockquote><b>Invoice not found</b></blockquote>");
	$affiliateID = intval($g_oNDB->getField("SELECT affiliateID FROM invoice WHERE checkoutID=".$checkoutID));
	$acct = "w2g";
	if( $affiliateID > 0 ) $acct = $g_oNDB->getField("SELECT aff FROM affiliate WHERE ID=".$affiliateID);
	$numTxns = $g_oNDB->getField("SELECT Count(*) FROM invoiceTransactions WHERE invoiceID='".$invoiceID."'");
	$numAuthOK = $g_oNDB->getField("SELECT Count(*) FROM invoiceTransactions WHERE invoiceID='".$invoiceID."' AND result=100");
	$numSubs = $g_oNDB->getField("SELECT Count(*) FROM invoiceSubscriptions WHERE invoiceID='".$invoiceID."'");

	/// start the page with a header table...
	?>
	<div style="margin-left: 1em;">
	<table width=500>
	<tr>
	<td nowrap valign=top style="vertical-align: top;">
		<div><u><font face="Arial" size=3><b>Order # <? echo $rCheckout['orderCode']."-".$rCheckout['orderNum']; ?></font></b></u></div>
	<div style="margin-top: 0.5ex; text-align: center;"><a style="color: #C868D4;" href="?A=DUP&invoiceID=<? echo $invoiceID; ?>" onClick="return confirm('Really duplicate this order?   ');">Not Used</a></div>
	</td>
	<td style='color: #808080; text-align: right;' align=right nowrap>
				PDF:&nbsp;
		 <a href="printshop.php?site=<? echo $site ?>&invoiceID=<? echo $invoiceID; ?>&checkoutID=<? echo $checkoutID; ?>&format=shop&showPdf=1" target=blank><font face=arial size=-1 >mac shop</font></a> &nbsp;|&nbsp;
		&nbsp;|&nbsp; EVENTS:&nbsp;
		<a href="invoiceEvents.php?invoiceID=<? echo $invoiceID; ?>"><font face=arial size=-1>manage</font></a> &middot; 
		<a href="invoiceEvents.php?A=E&ID=0&invoiceID=<? echo $invoiceID; ?>"><font face=arial size=-1>add</font></a> &middot; 
		<a href="<?= $PHP_SELF ?>?site=<? echo $site; ?>&A=CAN&invoiceID=<? echo $invoiceID; ?>&checkoutID=<? echo $checkoutID; ?>"><font face=arial size=-1>cancel lock</font></a><br><br></span>
		&nbsp;&nbsp; SEND:&nbsp; 
		<a href="printInvoice.php?A=EMAIL&site=<? echo $site ?>&invoiceID=<? echo $invoiceID; ?>&checkoutID=<? echo $checkoutID; ?>"><font face=arial size=-1>email</font></a> &middot; 
		<a href="printInvoice.php?A=FAX&site=<? echo $site ?>&invoiceID=<? echo $invoiceID; ?>&checkoutID=<? echo $checkoutID; ?>"><font face=arial size=-1>fax</font></a>
		&nbsp;|&nbsp; VIEW&nbsp;: 
		<a href="printInvoice.php?site=<? echo $site ?>&invoiceID=<? echo $invoiceID; ?>&checkoutID=<? echo $checkoutID; ?>&format=shop" target=blank><font face=arial size=-1 >shop</font></a> &middot; 
        <a href="printInvoice.php?site=<? echo $site ?>&invoiceID=<? echo $invoiceID; ?>&checkoutID=<? echo $checkoutID; ?>&format=cust" target=blank><font face=arial size=-1 >customer</font></a> &middot;
        <a href="print.php?site=<? echo $site ?>&invoiceID=<? echo $invoiceID; ?>&checkoutID=<? echo $checkoutID; ?>&format=cust&showPdf=1" target=blank><font face=arial size=-1 >ar invoice</font></a> &nbsp;|&nbsp;
		<a href="<?= $PHP_SELF ?>?site=<? echo $site; ?>&A=E&invoiceID=<? echo $invoiceID; ?>&checkoutID=<? echo $checkoutID; ?>"><font face=arial size=-1><b>edit</b></font></a>
		
		

		
	<?
	echo "<span style='font-size: 4px;'><br>&nbsp;</span></td></tr></table>";
	
	/// get the cartItems...
	$cartID = $rCheckout['cartID'];
	$sql = "SELECT quantity,productID,parameters,part,moldingPart,year,make,model,style,price,installPrice,partDetails,part,nspart,nsinfo FROM cartItems LEFT JOIN product ON cartItems.productID=product.ID WHERE cartID=$cartID";
	$hCartItems = mysql_query($sql);
	$rCartItem = mysql_fetch_array($hCartItems, MYSQL_ASSOC) or die("<blockquote><b>Invoice not found</b></blockquote>");
	$rInvoice = mysql_fetch_array(mysql_query("SELECT * FROM invoice WHERE ID=".$invoiceID));

	/// check if installed
	if( $rCartItem['parameters'] == "inst" ) {
		$inst = "Yes";
		$hardware = "N/A";
	} else {
		$inst = "No";
		$hardware = $rCartItem['parameters']=="" ? "none" : $rCartItem['parameters'];
	}
	
	// fix certain fields
	$rCartItem['make'] = htmlspecialchars($rCartItem['make']);
	$rCartItem['model'] = htmlspecialchars($rCartItem['model']);
	$rCartItem['style'] = htmlspecialchars($rCartItem['style']);

	/// format date and time
	$date = preg_replace("/\s+/", " ", $rCheckout['s_InstallDate']);
	list($installDay,$installMonth,$installTime)= split (" ", $date, 3);
	
	/// null bad dates
	if( !$installDay ) {
		$installTime = "";
		$installMonth = "";
		$installDay = "";
	}

	/// [NL:2021-05-12] DISABLED, now "Return Part" old: only show dollar sign if deductible present
	//if ($rCheckout['i_Deductible'] != "") $deductible = "\$" . $rCheckout['i_Deductible'];

	// phone quick call links
	$phoneback = "";
	if( isset($_SESSION['ADMIN_PHONE']) ) {
		$phoneback = clean_phone( $_SESSION['ADMIN_PHONE'] );
		$urlphone = "https://w2g.us/RC/rcCalls.php?to=" . $phoneback . "&from=";
	}
	$link_sPhone = $rCheckout['s_Phone'];
	$link_bPhone = $rCheckout['b_Phone'];
	$link_iPhone = $rCheckout['i_Phone'];
	if( strlen($urlphone) > 0 ) {
		$link_sPhone = trim($link_sPhone);
		if( ($link_sPhone) > 9 || ($link_sPhone > 10 && substr($link_sPhone, 0, 1) == "1") ) {
			$link_sPhone = "<a href=\"".$urlphone.$link_sPhone."\" target=\"_blank\">".$rCheckout['s_Phone']."</a>";
		}
		$link_bPhone = trim($link_bPhone);
		if( ($link_bPhone) > 9 || ($link_bPhone > 10 && substr($link_bPhone, 0, 1) == "1") ) {
			$link_bPhone = "<a href=\"".$urlphone.$link_bPhone."\" target=\"_blank\">".$rCheckout['b_Phone']."</a>";
		}
		$link_iPhone = trim($link_iPhone);
		if( ($link_iPhone) > 9 || ($link_iPhone > 10 && substr($link_iPhone, 0, 1) == "1") ) {
			$link_iPhone = "<a href=\"".$urlphone.$link_iPhone."\" target=\"_blank\">".$rCheckout['i_Phone']."</a>";
		}
	}

	/// show the data...
	?>
	<script>
		function email( ref ) {
			<? if( empty($rCheckout['s_Email']) && empty($rCheckout['b_Email']) ) { ?>
				alert("This user does not have any email address to email the confirmation to.   ");
				ref.href = document.location;
			<? } ?>	
		}
	</script>
	<table cellpadding=0 cellspacing=0 border=0 bordercolor=red><tr valign=top>
	<td valign=top style='vertical-align: top;' width=250><table style='text-align: right; border: #C0C0C0 1px solid;' cellpadding=0 cellspacing=0 border=0 bgcolor="#FCF0EC" width=248>
		<!-- customer info -->
		<tr bgcolor="#ECD8DC" align=center><td style='font-size: 14px; padding: 4px;' colspan=2><b>Customer Information</b></td></tr>
		<tr valign=top><td style='text-align: right;' align=right valign=top><b>Name:&nbsp;<br>&nbsp;Address:</b>&nbsp;<br>&nbsp;</td><td width=150 nowrap><? echo $rCheckout['s_FirstName']; ?>&nbsp;<? echo $rCheckout['s_LastName']; ?><br><nobr><? echo $rCheckout['s_Address']; ?><br><? echo $rCheckout['s_City']; ?>,&nbsp;<? echo $rCheckout['s_State']; ?>&nbsp;&nbsp;&nbsp;<? echo $rCheckout['s_Zip']; ?>&nbsp;</nobr></td></tr>
		<tr><td height=2 colspan=2><spacer type=block width=1 height=1></td></tr>
		<tr><td style='text-align: right;' align=right><b>Email:</b>&nbsp;</td><td><? echo $rCheckout['s_Email']; ?>&nbsp;</td></tr>
		<tr><td style='text-align: right;' align=right><b>&nbsp;Company:</b>&nbsp;</td><td><? echo $rCheckout['s_Company']; ?>&nbsp;</td></tr>		
		<tr>
			<td style='text-align: right;' align=right><b>Phone:</b>&nbsp;</td>
			<td><? echo $link_sPhone; ?>&nbsp;</td>
		</tr>
		<tr><td height=4 colspan=2><spacer type=block width=1 height=1></td></tr>
		<tr><td valign=top style='text-align: right; vertical-align: top;' align=right>&nbsp;<b>VIN:</b>&nbsp;</td><td><? echo $rCheckout['s_VIN']; ?></td></tr>
		<tr><td valign=top style='text-align: right; vertical-align: top;' align=right>&nbsp;<b>Dealer #:</b>&nbsp;</td><td><? echo $rCheckout['s_CrossStreet']; ?></td></tr>
		<tr><td height=4 colspan=2><spacer type=block width=1 height=1></td></tr>
		<tr><td valign=top style='text-align: right; vertical-align: top;' align=right>&nbsp;<b>PO #:</b>&nbsp;</td><td><? echo $rCheckout['s_PO']; ?></td></tr>
		<tr><td height=4 colspan=2><spacer type=block width=1 height=1></td></tr>
		<tr><td valign=top style='text-align: right; vertical-align: top;' align=right>&nbsp;<b>Unit #:</b>&nbsp;</td><td><? echo $rCheckout['s_Unit']; ?></td></tr>
		<tr><td height=4 colspan=2><spacer type=block width=1 height=1></td></tr>
		<tr><td valign=top style='text-align: right; vertical-align: top;' align=right>&nbsp;<b>Odometer:</b>&nbsp;</td><td><? echo $rCheckout['s_Odometer']; ?></td></tr>
		<tr><td height=4 colspan=2><spacer type=block width=1 height=1></td></tr>
		
		<tr><td colspan=2 style="padding-left: 0.75ex;"><b>&nbsp;Requested Date:</b>&nbsp;<? echo $installMonth; ?>&nbsp;<? echo $installDay; ?>&nbsp;<? echo $rCheckout['s_InstallYear'] ?><br><b>&nbsp;Requested Time:</b>&nbsp;<? echo $installTime; ?></td></tr>
		<tr><td height=8><spacer type=block width=1 height=1></td></tr>
		</table></td>
		<td width=8>&nbsp;&nbsp;</td>
		<!-- billing info -->
		<td align=left valign=top style='text-align: left; vertical-align: top;'><table style='text-align: right; border: #C0C0C0 1px solid;' cellpadding=0 cellspacing=0 border=0 bgcolor="#ECF0FC" width=248>
		<tr bgcolor="#D8DCEC" align=center><td colspan=2 style='font-size: 14px; padding: 4px;'><b>Billing Information</b></td></tr>
		<tr valign=top><td style='text-align: right;' align=right><b>Name:&nbsp;<br>Address:</b>&nbsp;</td><td width=150 nowrap><? echo $rCheckout['b_FirstName']; ?>&nbsp;<? echo $rCheckout['b_LastName']; ?><br><nobr><? echo $rCheckout['b_Address']; ?><br><? echo $rCheckout['b_City']; ?>,&nbsp;<? echo $rCheckout['b_State']; ?>&nbsp;&nbsp;&nbsp;<? echo $rCheckout['b_Zip']; ?></nobr></td></tr>
		<tr><td height=10 colspan=2><spacer type=block width=1 height=1></td></tr>
		<tr><td style='text-align: right;' align=right><b>Email:</b>&nbsp;</td><td><? echo $rCheckout['b_Email']; ?>&nbsp;</td></tr>
		<tr><td style='text-align: right;' align=right><b>&nbsp;Company:</b>&nbsp;</td><td><? echo $rCheckout['b_Company']; ?>&nbsp;</td></tr>		
		<tr>
			<td style='text-align: right;' align=right><b>Phone:</b>&nbsp;</td>
			<td><? echo $link_bPhone; ?>&nbsp;</td>
		</tr>
		<tr><td height=8 colspan=2><spacer type=block width=1 height=1></td></tr>
		</table><table style="margin-top: 1.25ex; text-align: right; border: #C0C0C0 1px solid;" cellpadding=0 cellspacing=0 border=0 bgcolor="#ECF0FC" width=248>
		<!-- charge info -->
		<tr bgcolor="#D8DCEC" align=center><td colspan=2 style='font-size: 14px; padding: 4px;'><b>Charge Info</b></td></tr>
		<tr><td height=4 colspan=2><spacer type=block width=1 height=4></td></tr>
		<tr><td colspan=2 align=center style="text-align: center;">
			<? if( strlen($rCheckout['c_num']) > 7 && strtoupper(substr($rCheckout['c_num'], 0, 1)) != "X" ) { ?>
			<a onClick="return confirm('Really run an AUTH for this order?   ');" href="<?= $PHP_SELF ?>?<? echo "site=".urlencode($site)."&A=RUNAUTH".intval($g_oNDB->getField("SELECT Count(*) FROM invoiceTransactions WHERE invoiceID='".$invoiceID."'"))."&invoiceID=".$invoiceID; ?>" style='color: #008800;'>Run CC AUTH</a> &nbsp;<font color=#808080 size=1>&bull;</font>&nbsp; 
			<a onClick="return confirm('Really dump the CC info for this invoice?   ');" href="<?= $PHP_SELF ?>?<? echo "site=".urlencode($site)."&A=S&invoiceID=".$invoiceID."&checkoutID=".$checkoutID; ?>&F=CCCI" style='color: #B00000;'>Clear CC Info</a><br>
			<? } ?>
			<a style="color: #0072FF;" href="<?= $PHP_SELF ?>?<? echo "site=".urlencode($site)."&A=HA-F&invoiceID=".$invoiceID; ?>">Enter New Auth</a>
			<? if( $numAuthOK > 0 ) { ?>
			&nbsp;<font color=#808080 size=1>&bull;</font>&nbsp; 
			<?php 	    
	    if( $_SERVER['REMOTE_ADDR'] == "91.196.220."){ ?>
	    			<a onClick="return confirm('Re-authorize the card on file with CyberSource (transactions below)?     \n\n ...for the new total amount? ($<?= $rCheckout['total'] ?>)     \n');" href="<?= $PHP_SELF ?>?<? echo "site=".urlencode($site)."&A=re-auth".intval($g_oNDB->getField("SELECT Count(*) FROM invoiceTransactions WHERE invoiceID='".$invoiceID."'"))."&invoiceID=".$invoiceID; ?>" style='font-weight: bold; color: #FF00FF;'>Re-Auth</a>

<?php } else { ?>


		<a onClick="return validateAmount(<?= $rCheckout['total'] ?>, 0.5);" 
   href="<?= $PHP_SELF ?>?site=<?= urlencode($site) ?>&A=re-auth&transactionCount=<?= intval($g_oNDB->getField("SELECT Count(*) FROM invoiceTransactions WHERE invoiceID='".$invoiceID."'")) ?>&invoiceID=<?= $invoiceID ?>" 
   style='font-weight: bold; color: #FF00FF;'>Re-Auth</a>

<script>
function validateAmount(total, threshold) {
    if (total < threshold) {
        alert('The amount ($' + total + ') is smaller than the required threshold ($' + threshold + ').');
        return false; // Prevents the link from being followed
    }
    return confirm('Re-authorize the card on file with Stripe (transactions below)?\n\n ...for the new total amount? ($' + total + ')\n');
}
</script>

<?php  } ?>
			
			
			
			<? } ?>
			<font size=1 color=#808080><br><? echo "(".$numTxns." transactions on file.)" ?></font></td>
		</tr>
		<tr><td nowrap style="padding-left: 1em; text-align: right;"><b>&nbsp;Payment:</b>&nbsp;</td><td><? echo $rCheckout['c_type']; ?>&nbsp;</tr>
		<tr><td nowrap style="padding-left: 1em; text-align: right;"><b>&nbsp;Card Number:&nbsp;</b>&nbsp;</td><td nowrap style="padding-right: 0.5em;"><? echo $rCheckout['c_num']; ?>&nbsp;</tr>
		<tr><td nowrap style="padding-left: 1em; text-align: right;"><b>&nbsp;Expires:</b>&nbsp;</td><td><? echo trim($rCheckout[c_expmonth]) == "" ? "" : $rCheckout[c_expmonth]." / "; ?><? echo $rCheckout['c_expyear']; ?>&nbsp; &nbsp; <? echo trim($rCheckout['c_cvv']) == "" ? "" : "<b>CVV #:</b> ".$rCheckout['c_cvv']; ?> &nbsp;</td></tr>
		<tr><td height=8 colspan=2><spacer type=block width=1 height=8></td></tr>
		</table></td>
		
		
		<!--Start Search part from 3 suppliers-->
		<td align="left" valign="top" style="text-align: left; vertical-align: top;">
		<table style="margin-left: 1.25ex; text-align: right; border: #C0C0C0 1px solid; width:350px" cellpadding=2 cellspacing=0 border=1 bgcolor="#ECF0FC" width=248>
		<!-- charge info -->
		<tr bgcolor="#D8DCC" align=center><td colspan=3 style='font-size: 14px; padding: 4px;'><b>Search Part Prices <small style="font-size: xx-small;">(Pilkington, PGW, Mygrant)</small></b></td></tr>
		<!--<tr><td height=4 colspan=2><spacer type=block width=1 height=4></td></tr>-->
		<tr>
		    <td colspan=3 style="padding: 4px;">
			    <form action='<? echo $PHP_SELF; ?>' method=GET>
        			<input type=hidden name=A value=LAA>
        			<input type=hidden name=invoiceID value=<? echo $invoiceID; ?>>
        			<input type=hidden name=checkoutID value=<? echo $checkoutID; ?>>
        			Search For:
        			<input class=normal type=text size=15 maxlength=20 name=partno value=''>
        			
        			<input type=submit class=button value='Search'>
        		</form>
			</td>
		</tr>
		<?php if(isset($_GET['partno'])){ 
		    echo '<tr>';
		    echo '<td colspan=3 style="border: 1px inset;"> Part: <b>'.$_GET['partno'].'</b></td>';
		    echo '</tr>';
		    
		 }?>
		
		
		<tr style="background: gainsboro;">
		    <td>Pilkington</td>
		    <td>PGW</td>
		    <td>Mygrant</td>
		</tr>
		
		<?php if(isset($_GET['partno'])){

    		$partNormalized = $_GET['partno'];
    		$MyGrantCost = getMygrantPrice($partNormalized);
    		$PWGCost = 0;//getPWGPrice($partNormalized);
    		//Pilkington
    		$PilkingtonCost1=getPilkingtonData($partNormalized);
    
    		// Filter out zero values
    		$nonZeroValues = array_filter($PilkingtonCost1, function($value) {
    			return $value > 0;
    		});
    
    		// Find the minimum non-zero value
    		if (!empty($nonZeroValues)) {
    			$PilkingtonCost = min($nonZeroValues);
    		}else{
    			$PilkingtonCost = 0;
    		}
    
            echo '<tr>';
            if( $PilkingtonCost > 0 ){
                echo '<td>'.$PilkingtonCost.'</td>';
            }else{
                echo '<td>--</td>';
            }
            if( $PWGCost > 0 ){
                echo '<td>'.$PWGCost.'</td>';
            }else{
                echo '<td>--</td>';
            }
            if( $MyGrantCost > 0 ){
                echo '<td>'.$MyGrantCost.'</td>';
            }else{
                echo '<td>--</td>';
            }
            echo '</tr>';
            
            echo '<tr>';
                echo '<td colspan="3" style="border: 1px inset;padding: 5px;">'; ?>
                
                    <form action='<? echo $PHP_SELF; ?>' method=GET>
        			<input type=hidden name=A value=LAAS>
        			<input type=hidden name=invoiceID value=<? echo $invoiceID; ?>>
        			<input type=hidden name=checkoutID value=<? echo $checkoutID; ?>>
        			<input type=hidden name=partnumber value=<? echo $partNormalized; ?>>
        			<input type=hidden name=picost value=<? echo $PilkingtonCost; ?>>
        			<input type=hidden name=pwgcost value=<? echo $PWGCost; ?>>
        			<input type=hidden name=mycost value=<? echo $MyGrantCost; ?>>
        			<input type=submit class=button value='Save' style='display: block;justify-self: center;width: 110px;background: darkseagreen;'>
        			</form>
                    
                <?php echo '</td>';
            echo '</tr>';
    
        }
        ?>
		
		</table>
		</td>
		<!--End-->
		
		</tr>
		<tr><td height=10><spacer type=block width=1 height=10></td></tr>
		<!-- customer info -->
		<td valign=top colspan=3 align=center>
		<table style='text-align: right; border: #C0C0C0 1px solid;' cellpadding=0 cellspacing=0 border=0 bgcolor="#ECFCF0" width=500>
		<tr bgcolor="#D8ECDC"><td style='font-size: 14px; padding: 4px;' colspan=5 align=center><b>Order Summary</b></td></tr>
		<tr><td style='text-align: right;' align=right><b>Year:</b>&nbsp;</td><td><? echo $rCartItem['year']; ?>&nbsp;</td><td rowspan=3 width=8><spacer type=block width=1 height=1></td><td style='text-align: right;' align=right><b>Model:</b>&nbsp;</td><td width=150><? echo $rCartItem['model']; ?>&nbsp;</td></tr>
		<tr><td style='text-align: right;' align=right><b>Make:</b>&nbsp;</td><td><? echo $rCartItem['make']; ?>&nbsp;</td><td style='text-align: right;' align=right><b>Style:</b>&nbsp;</td><td><? echo $rCartItem['style']; ?>&nbsp;</td></tr>
		<tr><td height=20 colspan=5><spacer type=block width=1 height=1></td></tr>
		<tr><td style='text-align: right;' align=right><b>Installed:&nbsp;<br>Hardware:&nbsp;</b></td><td><? echo $inst ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<b>Qty:</b>&nbsp;<? echo $rCartItem['quantity']; ?>&nbsp;<br><?= $hardware ?></td>
		<td style='text-align: right;' align=right colspan=2><b>Part:</b>&nbsp;<br><b>NAGS&reg;&nbsp;#:</b>&nbsp;<br><b>Molding Part:</b>&nbsp;</td><td><? echo eregi("^ns:",$rCartItem['part']) ? "<a style='color:#000088; text-decoration: none;' href=\"#\"><font face=Arial size=2>".$rCartItem['part']."</font></a>" : $rCartItem['part']; ?>&nbsp;&nbsp;<br><? echo $rCartItem['nspart']; ?>&nbsp;&nbsp;<br><? echo $rCartItem['moldingPart']; ?>&nbsp;&nbsp;</td><tr>
		<tr><td colspan=4 align=right style='text-align: right;'><b>Details:&nbsp;</b></td><td><? echo $rCartItem['partDetails']; ?>&nbsp;&nbsp;</td></tr>
		<a href="<?= $PHP_SELF ?>?site=<? echo $site; ?>&A=E&invoiceID=<? echo $invoiceID; ?>&checkoutID=<? echo $checkoutID; ?>"><font face=arial size=-1><b>edit</b></font></a>
		<?
		
		if(isset($rCartItem['nsinfo']) && $rCartItem['nsinfo'] != "") {
			?><tr align=right><td class=right valign=top><b>NAGS Info:</b> &nbsp;</td><td colspan=4><? echo $rCartItem['nsinfo']; ?>&nbsp;</td></tr><?
		}
		
		?><tr><td height=20 colspan=5><spacer type=block width=1 height=1></td></tr><? 
		
		if( strlen(trim($rCheckout['discountCode'])) > 0 ) {
			?>
			<tr align=right>
				<td colspan=3 class=right style="color: #990000;"><span style="background: #D8ECDC;">&nbsp;Discount Code:&nbsp;&nbsp;</span></td>
				<td style="color: #990000; font-weight: bold;"><span style="background: #D8ECDC;">&nbsp;<? echo strtolower($rCheckout['discountCode']); ?>&nbsp;</span></td>
				<td rowspan=3>&nbsp;</td>
			</tr>
			<?
		}
		
		?>
		<tr align=right><td colspan=3 class=right><b>Subtotal:</b> &nbsp;</td><td>$<? echo $rCheckout['subtotal']; ?>&nbsp;</td><td rowspan=3>&nbsp;</td></tr>
		<tr align=right><td colspan=3 class=right><b>Shipping:</b> &nbsp;</td><td>$<? echo $rCheckout['shipping']; ?>&nbsp;</td></tr>
		<tr align=right><td colspan=3 class=right><b>Tax Amount:</b> &nbsp;</td><td>$<? echo $rCheckout['tax']; ?>&nbsp;</td></tr>
		<tr align=right><td colspan=3 class=right><b>Total:</b> &nbsp;</td><td>$<? echo $rCheckout['total']; ?>&nbsp;</td></tr>
		<tr><td height=10 colspan=5><spacer type=block width=1 height=1></td></tr>
		<tr><td height=10 colspan=5><spacer type=block width=1 height=1></td></tr>
		<tr valign=top><td style='vertical-align: top; text-align: right;' align=right><b>&nbsp;Installer:&nbsp;</td><td colspan=4><? echo $rCheckout['installer']; ?>&nbsp;</td></tr>
		<tr><td height=10 colspan=5><spacer type=block width=1 height=1></td></tr>
		<tr valign=top><td style='vertical-align: top; text-align: right;' align=right><b>&nbsp;Comments:&nbsp;</td><td colspan=4><? echo str_replace("\n","<br>",$rCheckout['comments']); ?>&nbsp;<br><br></td></tr>
		<tr><td style='text-align: right;' align=right><b>Shop Amount:</b>&nbsp;</td><td>$<? echo $rCheckout['shopLabor']; ?>&nbsp;</td></tr>
		<tr valign=top><td style='vertical-align: top; text-align: right;' align=right><b>&nbsp;Shop&nbsp;Comments:&nbsp;</td><td colspan=4><? echo str_replace("\n","<br>",$rCheckout['shopComments']); ?>&nbsp;<br><br></td></tr>
		<tr valign=top><td style='vertical-align: top; text-align: right;' align=right><b>&nbsp;Warehouse&nbsp;Comments:&nbsp;</td><td colspan=4><? echo str_replace("\n","<br>",$rCheckout['warehouseComments']); ?>&nbsp;<br><br></td></tr>
		<tr valign=top><td style='vertical-align: top; text-align: right;' align=right><b>&nbsp;Internal&nbsp;Comments:&nbsp;<br><br>First Call&nbsp;<br>Then Post&nbsp;<br>Then Text&nbsp;<br>And say&nbsp;<br>you did&nbsp;<br></td><td colspan=4><? echo str_replace("\n","<br>",$rCheckout['i_comments']); ?>&nbsp;<br><br></td></tr>	
		<tr><td height=10 colspan=5><spacer type=block width=1 height=1></td></tr>
		<tr valign=top><td style='text-align: right;' align=right><b>&nbsp;Flags:&nbsp;</td><td colspan=4>
			<?= $rInvoice['scheduled']=="Y" ? "scheduled &nbsp;&nbsp; " : "" ?>
			<?= $rInvoice['auth']=="Y" ? " auth'd &nbsp;&nbsp; " : "" ?>
			<?= $rInvoice['paid']=="Y" ? " paid &nbsp;&nbsp; " : "" ?>
			<?= $rInvoice['installerPaid']=="Y" ? " paidShop &nbsp;&nbsp; " : "" ?>
			<?= $rInvoice['ready']=="Y" ? " ready &nbsp;&nbsp; " : "" ?>
			<?= $rInvoice['fulfilled']=="Y" ? " completed &nbsp;&nbsp; " : "" ?>
			<?= $rInvoice['waitForCallback']=="Y" ? " waitForCallback &nbsp;&nbsp; " : "" ?>
			<?= $rInvoice['onHold']=="Y" ? " onHold &nbsp;&nbsp; " : "" ?>
			<?= $rInvoice['waiting']=="Y" ? " waiting &nbsp;&nbsp; " : "" ?>
			<?= $rInvoice['notServiced']=="Y" ? " notServiced &nbsp;&nbsp; " : "" ?>
			<?= $rInvoice['cancelled']=="Y" ? " cancelled &nbsp;&nbsp; " : "" ?>
			<?= $rInvoice['declined']=="Y" ? " declined &nbsp;&nbsp; " : "" ?>
			<?= $rInvoice['fraudulent']=="Y" ? " issues &nbsp;&nbsp; " : "" ?>
			<?= $rInvoice['hidden']=="Y" ? " hidden &nbsp;&nbsp; " : "" ?>
			<?= $rInvoice['blink']=="Y" ? " highlighted &nbsp;&nbsp; " : "" ?>
		</td></tr>
		<tr><td height=8><spacer type=block width=1 height=1></td></tr>
		</table></td></tr>
		<tr><td height=12><spacer type=block width=1 height=1></td></tr>
		<!-- other info -->
		<tr><td align=center colspan=3>
		<table width=500 border=0 cellpadding=0 cellspacing=0 bgcolor=#FAF2FD style='text-align: right; border: #C0C0C0 1px solid;'>
		<tr bgcolor="#F2DCF4"><td colspan=4 style='font-size: 14px; padding: 4px;' align=center><table align=right cellpadding=0 cellspacing=0 border=0><tr><td>Customer Key: <a target=_blank href="http://account.autoglasshosting.com/status/?acct=<?= $acct ?>&A=LO&LoginAuth_LogoutFlag=Y&url=<?= urlencode("http://account.autoglasshosting.com/status/?acct=".$acct."&LoginAuth_FormFlag=Y&LoginAuth_UserName=".$rCheckout['orderNum']."&LoginAuth_PassKey=".$rCheckout['customerKey']) ?>"><?= $rCheckout['customerKey'] ?></a></td></tr></table><b>Other Information</b></td></tr>
		<tr><td style='text-align: right;' align=right colspan=2 nowrap><b>Requested&nbsp;Location:</b>&nbsp;</td><td  colspan=2 width=200><? echo $rCheckout['s_Warehouse']; ?>&nbsp;</td></tr>
		<tr><td style='text-align: right;' align=right colspan=2 nowrap><b>Pickup&nbsp;Warehouse:</b>&nbsp;</td><td  colspan=2 width=200><?= intval($rCheckout['warehouseID']) > 0 ? $g_oNDB->getField("SELECT Concat(city, ', ', state, ' - ', name) as location FROM warehouse WHERE ID=".$rCheckout['warehouseID']) : "" ?>&nbsp;</td></tr>
		<tr><td style='text-align: right;' align=right><b>Service Type:</b>&nbsp;</td><td><? echo $rCheckout['serviceType']; ?>&nbsp;</td><td style='text-align: right;' align=right nowrap><b>&nbsp;Payment Method:</b>&nbsp;</td><td width=100><? echo $rCheckout['paymentMethod']; ?>&nbsp;</td></tr>
		<tr>
			<td style='text-align: right;' align=right><b>PO:</b>&nbsp;</td><td><? echo $rCheckout['i_Name']; ?>&nbsp;</td>
			<td style='text-align: right;' align=right nowrap><b>Return Company:</b>&nbsp;</td>
			<td><? echo $link_iPhone; ?>&nbsp;</td>
		</tr>
		<tr><td style='text-align: right;' align=right nowrap>(Return Moldings!)&nbsp;<b>Return Number:</b>&nbsp;</td><td><? echo $rCheckout['i_Policy']; ?>&nbsp;</td><td style='text-align: right;' align=right><b>Return Part:</b>&nbsp;</td><td><? echo $rCheckout['i_Deductible']; ?>&nbsp;</td></tr>
		<tr><td style='text-align: right;' align=right><b>AgreeLowPrice:</b>&nbsp;</td><td><? echo $rCheckout['agreeLowPrice']; ?>&nbsp;</td><td style='text-align: right;' align=right><b>AgreeFactors:</b>&nbsp;</td><td><? echo $rCheckout['agreeFactors']; ?>&nbsp;</td></tr>
		<tr><td>&nbsp;</td><td>&nbsp;</td><td style='text-align: right;' align=right><b>Glass Cost:</b>&nbsp;</td><td>$<? echo $rCheckout['glassCost']; ?>&nbsp;</td></tr>
		<tr><td style='text-align: right;' align=right>&nbsp;</td><td>&nbsp;</td><td style='text-align: right;' align=right><b>&nbsp;Shipper#:</b>&nbsp;</td><td><? echo $rCheckout['shipperNum']; ?>&nbsp;</td></tr>
		<?
			if( $_SESSION['ADMIN_LEVEL'] >= 3 ) {
				?><tr>
					<td style='text-align: right;' align=right><b>Profit:</b>&nbsp;</td>
					<td>$<? echo $rCheckout['profit']; ?>&nbsp;</td><td style='text-align: right;' align=right><b>ExtRef from:</b>&nbsp;</td>
					<td><? echo $rCheckout['referrer']; ?>&nbsp;</td>
				</tr><?
			}
		?>
		<tr><td colspan=4 style='text-align: center;'><b>Affiliate Referrer:&nbsp;</b> <?= intval($rInvoice['referrerID']) < 1 ? "(none)" : $g_oNDB->getField("SELECT ConCat(name,' (',aff,')') as name FROM affiliate WHERE ID='".$rInvoice['referrerID']."'"); ?></td></tr>
		<a href="<?= $PHP_SELF ?>?site=<? echo $site; ?>&A=E&invoiceID=<? echo $invoiceID; ?>&checkoutID=<? echo $checkoutID; ?>"><font face=arial size=-1><b>edit</b></font></a>
		
		<tr><td height=8><spacer type=block width=1 height=1></td></tr>
		</table></td></tr>
		<!-- status info -->
	<?
		
	/// display the order statæs...
	echo "<tr><td colspan=3 style='padding-top: 12px'><table width=500 cellpadding=2 cellspacing=1 border=0 bgcolor=#C0C0C0>\n";
	$logins = $g_oNDB->getField("SELECT Count(*) FROM customerLogins WHERE invoiceID='".$invoiceID."'");
	echo "<tr bgcolor=#F8F4D4><td colspan=4 style='font-size: 14px; padding: 4px;' align=center><table align=right cellpadding=0 cellspacing=0 border=0><tr><td>Events: <a href='invoiceEvents.php?invoiceID=".$invoiceID."'>Manage</a> | <a href='invoiceEvents.php?A=E&ID=0&invoiceID=".$invoiceID."'>Add</a></td></tr></table><b>Status Entries</b> &nbsp; (".$logins." logins)</td></tr>\n";
	$oNRS = new nRS("SELECT *, Date_Format(Date_Sub(stamp, INTERVAL 2 HOUR),'%m/%d/%Y %h:%i%p Pacific Time') as posted FROM invoiceEvents WHERE invoiceID=".$invoiceID." ORDER BY stamp DESC");
	if( $oNRS->numRows == 0 ) {
		echo "<tr><td bgcolor=#F0F0F0>(no order status items on file)</td></tr>\n";
	} else {
		while( $rEvent = $oNRS->read() ) {
			if( $rEvent['postedBy'] == "customer" ) {
				$cellbg = "#FFFCE8";
				$style = " style='color: #980000;'";
			} else {
				$cellbg = "#FCF8F4";
				$style = "";
			}
			echo "<tr bgcolor=".$cellbg."><td nowrap><table width=100% cellspacing=0 cellpadding=2 border=0 bordercolor=green><tr><td valign=top style='vertical-align: top;' width=20%".$style."><b>".$rEvent['postedBy']."</b></td><td valign=top width=50%".$style.">".htmlspecialchars($rEvent['subject'])."</td><td valign=top style='vertical-align: top;' width=30% nowrap align=right".$style."><i>".$rEvent['posted']."</i></td></tr>";
			echo "<tr bgcolor=".$cellbg."><td colspan=3".$style.">".htmlspecialchars($rEvent['event'])."</td></tr></table></td></tr>\n";
		}
	}
	echo "</table></td></tr></table>\n";
	?>
	<br><a href="https://docs.stripe.com/error-codes"  target="_blank">Error Codes</a><br>
	
    <?
	/// quickly display the transaction log...
	if( $numTxns > 0) {
		$SQL = "SELECT invoiceTransactions.*, gatewayResult.reply_flag, gatewayResult.description, gatewayResult.info, Date_Format(stamp, '%m/%d/%Y %H:%i') as theDate ";
		$SQL .= "FROM invoiceTransactions LEFT JOIN gatewayResult ON invoiceTransactions.gatewayType = gatewayResult.gatewayType AND invoiceTransactions.result = gatewayResult.code ";
		$SQL .= "WHERE invoiceTransactions.invoiceID='".$invoiceID."' ORDER BY ID";
		$oNRS = new nRS( $SQL );
		echo "<div style='display: inline-block; margin-top: 1.25em; padding: 0.75em; border: #E8E8E8 1px solid; border-radius: 4px; padding-bottom: 4px; margin-bottom: 1ex;'>\n";
		echo "<table cellpadding=0 cellspacing=0 border=0>\n";
		echo "<caption style='text-align: left; font-size: 10pt; padding: 0; padding-bottom: 2px; margin: 0;'><font color=#808080>There ".($numTxns == 1 ? "is" : "are")." <b>".$numTxns."</b> transaction".($numTxns > 1 ? "s" : "")." logged on file.</caption>\n";
		echo "<tr style='background: #F4F4F4;'>";
		echo "<td nowrap><font size=1 color='#929292'><u>Date</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "<td align=right><font size=1 color='#929292'><u>Total</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "<td align=right><font size=1 color='#929292'><u>Request#</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "<td><font size=1 color='#929292'><u>Decision</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "<td><font size=1 color='#929292'><u>Result</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "<td><font size=1 color='#929292'><u>Archive</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "<td><font size=1 color='#929292'><u>AVS</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "<td><font size=1 color='#929292'><u>CVV</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "<td><font size=1 color='#929292'><u>Reconciliation</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "<td><font size=1 color='#929292'><u>AuthCode</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "<td><font size=1 color='#929292'><u>Actions</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "</tr>\n";
		while( $rData = $oNRS->read() ) {
			$col = ($rData['result']==1 || $rData['result']==100) ? "#008800" : "#B00000";
			echo "<tr>";
			echo "<td><a style=\"font-family: Arial, Helvetica, Sans-Serif; text-decoration: none;\" href=\"invoiceTransaction.php?A=V&ID=".$rData['ID']."\"><font size=1 color=".$col.">".$rData['theDate']."</font></a></td><td><font size=1>&nbsp; &nbsp;</td>";
			echo "<td align=right><font size=1 color=".$col.">\$".sprintf("%01.2f",$rData['total'])."</td><td><font size=1>&nbsp; &nbsp;</td>";
			echo "<td align=right><font size=1 color=".$col.">".$rData['reqID']."</td><td><font size=1>&nbsp; &nbsp;</td>";
			echo "<td align=right><font size=1 color=".$col.">".$rData['decision']."</td><td><font size=1>&nbsp; &nbsp;</td>";
			if( $rData['reply_flag'] ) {
				$tooltip = $rData['result']." = <b>".$rData['reply_flag']."</b> ".$rData['description']." <span style='color: #A4A4A4;'>".$rData['info'];
			} else {
				$tooltip = $rData['result'].": <span style=\"color: #A4A4A4;\">(lookup failed for ".$rData['archive']." + ".$rData['source']." transaction)</span>";
			}
			echo "<td class='tooltip'><font size=1 color=".$col.">".$rData['result']."<span class='tooltiptext'>".$tooltip."</span></td><td><font size=1>&nbsp; &nbsp;</td>";
			echo "<td><font size=1 color=".$col.">".$rData['archive']."</td><td><font size=1>&nbsp; &nbsp;</td>";
			echo "<td><font size=1 color=".$col.">".$rData['avs']."</td><td><font size=1>&nbsp; &nbsp;</td>";
			echo "<td><font size=1 color=".$col.">".$rData['cvv']."</td><td><font size=1>&nbsp; &nbsp;</td>";
			echo "<td><font size=1 color=".$col.">".$rData['reconciliation']."</td><td><font size=1>&nbsp; &nbsp;</td>";
			echo "<td><font size=1 color=".$col.">".$rData['authCode']."</td><td><font size=1>&nbsp; &nbsp;</td>";
			
		
			if( $rData['reconciliation'] =='' || $rData['reconciliation'] =='zipcode_fail') {
        			echo "<td>
        			<input type=\"text\" name=\"updated_amount\" id=\"updated_amount_{$rData['ID']}\" style=\"width: 75px;\">
        			
        			&nbsp; | &nbsp;
                           
              
              <a style=\"font-family: Arial, Helvetica, Sans-Serif; text-decoration: none; color:green; font-size: 12px;\" 
                href=\"#\" 
                onclick=\"var updatedAmount = parseFloat(document.getElementById('updated_amount_{$rData['ID']}').value.trim()) || 0; 
                          var totalAmount = parseFloat('{$rData['total']}'); 
                          if (updatedAmount >= totalAmount) {
                              alert('Updated amount must be smaller than the total: $' + totalAmount);
                              return false;
                          } 
                          var totAMT = totalAmount;
                          if(updatedAmount!=0){
                             totAMT = updatedAmount;
                          }
                          if (confirm('Are you sure you want to capture this invoice with amount: $' + totAMT + '?')) {
                              window.location='invoices.php?A=captured&ID={$rData['ID']}&amount=' + encodeURIComponent(updatedAmount);
                          } return false;\">
                Capture
              </a>

                   
                  &nbsp; | &nbsp;
                <a style=\"font-family: Arial, Helvetica, Sans-Serif; text-decoration: none; color:red; font-size: 12px;\" 
                   href=\"invoices.php?A=cancelAuth&ID={$rData['ID']}\">Cancel auth</a>
                  
              </td>
              
              
              <td>
                <span style=\"font-size: 12px;\">&nbsp; &nbsp;</span>
             </td>";
  
			}
			
			echo "</tr>\n";
		}
		echo "</table></div>";
	} else {
		echo "<div style=\"padding-top: 4px; padding-bottom: 8px;\">(no transactions logged on file)</div>\n";
	}

	/// quickly display the transaction log...
	if( $numSubs > 0) {
		$oNRS = new nRS("SELECT *, Date_Format(stamp, '%m/%d/%Y %H:%i') as theDate FROM invoiceSubscriptions WHERE invoiceID='".$invoiceID."' ORDER BY ID");
		echo "<div style='display: inline-block; background: #FAFAFA; border: #E8E8E8 1px solid; border-radius: 4px; margin-top: 1.25em; padding: 0.75em;'>\n";
		echo "<table cellpadding=0 cellspacing=0 border=0>\n";
		echo "<caption style='text-align: left; font-size: 10pt;'><font color=#A4A4A4>There ".($numSubs == 1 ? "is" : "are")." <b>".$numSubs."</b> subscription(s) tokenized from this invoice.</caption>\n";
		echo "<tr>";
		echo "<td><font size=1 color='#A4A4A4'><u>Date</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "<td><font size=1 color='#A4A4A4'><u>Order#</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "<td><font size=1 color='#A4A4A4'><u>Decision</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "<td><font size=1 color='#A4A4A4'><u>Result</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "<td><font size=1 color='#A4A4A4'><u>SubscriptionID#</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "<td><font size=1 color='#A4A4A4'><u>Original Req#</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "<td><font size=1 color='#A4A4A4'><u>Action</u></td><td><font size=1>&nbsp; &nbsp;</td>";
		echo "</tr>\n";
		while( $rData = $oNRS->read() ) {
			$col = $rData['result']==100 ? "#666666" : "#980000";
			echo "<tr>";
			echo "<td><font size=1 color=".$col.">".$rData['theDate']."</td><td><font size=1>&nbsp; &nbsp;</td>";
			echo "<td><font size=1 color=".$col.">".$rData['refCode']."</td><td><font size=1>&nbsp; &nbsp;</td>";
			echo "<td><font size=1 color=".$col.">".$rData['decision']."</td><td><font size=1>&nbsp; &nbsp;</td>";
			echo "<td><font size=1 color=".$col.">".$rData['result']."</td><td><font size=1>&nbsp; &nbsp;</td>";
			echo "<td><a style=\"font-family: Arial, Helvetica, Sans-Serif; text-decoration: none;\" href=\"invoiceSubscription.php?A=V&ID=".$rData['ID']."\"><font size=1 color=".$col.">".$rData['subID']."</font></a></td><td><font size=1>&nbsp; &nbsp;</td>";
			echo "<td><font size=1 color=".$col.">".$rData['originalRequestID']."</td><td><font size=1>&nbsp; &nbsp;</td>";
			$toggle_text = $rData['invalidated'] == 'N' ? "disable" : "re-enable";
			$toggle_text = "";
			$toggle_url = $PHP_SELF . "?site=".urlencode($site)."&A=SUBD&invoiceID=".$invoiceID."&subID=".$rData['ID'];
			echo "<td><font size=1 color=".$col."><a title=\"This subscription is enabled. Click to disable it.\" style=\"font: Arial; color: red;\" href=\"".$toggle_url."\">".$toggle_text."</a></td><td><font size=1>&nbsp; &nbsp;</td>";
			echo "</tr>\n";
		}
		echo "</table>";
	} else {
		echo "<br><span style='background: #FEFCE0;'><i>(no subscription tokenizations logged on file)</i></span>";
	}
	echo "</div></div><br>\n";

} // ShowItem()

function getPilkingtonData($partNo) {
    $output = shell_exec("/usr/bin/python3 /home/auto11/public_html/scripts/pilkington_newapi_seperate.py ".escapeshellarg($partNo). " 2>&1");
    $prices = explode(",", trim($output));
    return $prices;
}

function getPWGPrice($part_no){
    
    // Login details
    $username = 'PPG6014';
    $password = 'Order2107';
    $quotepass = '1313';
    
    // Login URL and protected page URL
    $loginUrl = 'https://www.buypgwautoglass.com/rspAuthenticate.asp';
    $protectedPageUrl = 'https://www.buypgwautoglass.com/PartSearch/result.asp?REG=&PB=704&UserType=F&ShipToNo=4163&PartNo='.$part_no.'&PartUID=410090&PartType=A'; // Replace with the actual URL
    $quoteURL = 'https://www.buypgwautoglass.com/Order/xt_orderform_pinnumber.asp?REG=&PB=704&UserType=F&ShipToNo=4163';
    
    // Cookie file for session management
    $cookieFile = 'cookies.txt';
    
    // Step 1: Perform login
    $ch = curl_init();
    
    curl_setopt_array($ch, [
        CURLOPT_URL => $loginUrl,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'txtUsername' => $username,
            'txtPassword' => $password,
            'URL' => '/default.asp',
            'realSubmit' => 'fromButton',
        ]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_COOKIEJAR => $cookieFile, // Save cookies
        CURLOPT_COOKIEFILE => $cookieFile, // Use cookies
    ]);
    
    $loginResponse = curl_exec($ch);
    
    
    // Step 2: Access the protected page
    curl_setopt_array($ch, [
        CURLOPT_URL => $protectedPageUrl,
        CURLOPT_POST => false, // Default is GET request
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_COOKIEJAR => $cookieFile, // Use cookies
        CURLOPT_COOKIEFILE => $cookieFile, // Maintain session
    ]);
    
    $protectedPageResponse = curl_exec($ch);
    
    curl_setopt_array($ch, [
        CURLOPT_URL => $quoteURL,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query([
            'Query' => 'PB=704&UserType=F&PartNo='.$part_no.'&PartType=A&LastBranchID=7042',
            'SQ' => '',
            'TargetURL' => 'PartSearch/result.asp',
            'LostSales' => '',
            'CommitLS' => 'false',
            'PinNumber' => $quotepass
        ]),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_COOKIEJAR => $cookieFile, // Save cookies
        CURLOPT_COOKIEFILE => $cookieFile, // Use cookies
    ]);
    
    $quoteResponse = curl_exec($ch);
    
    // Close cURL
    curl_close($ch);
    
    
    // 4. Process the page content and Parse the HTML for price
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($protectedPageResponse);
    libxml_clear_errors();
    
    // Use DOMXPath to query the DOM
    $xpath = new DOMXPath($dom);
    // $query = "//td[@align='center']/font[contains(text(), '$')]";
    // $query = "//tr[.//td[@class='partdesc' and contains(., 'Windshield')]]//td[@align='center']/font[contains(text(), '$')]";
    $query = "//tr[.//td[@class='partdesc' and contains(., 'Windshield')] and .//td[@class='partdesc' and contains(., '".$part_no."')]]//td[@align='center']/font[contains(text(), '$')]";

    $priceNode = $xpath->query($query);
    if ($priceNode->length > 0) {
        $prices = [];
        for( $i = 0; $i < $priceNode->length; $i++ ) {
            $price = (float) str_replace(',','',str_replace('$', '', trim($priceNode->item($i)->nodeValue)));
            if($price < 50 ){
                //Email Notification
        //         $content = "Hello Beau, <br><br>";
        //         $content .= "During the live search we captured the part price is less then 50. <br> ";
        //         $content .= "Source = PGW <br>";
        //         $content .= "Part = ".$part_no." <br>";
        //         $content .= "Cost = $".$price." <br>";
        // 		@SendMail( "no-reply@autoglasshosting.com", "8056807305@tmomail.net", "Notification: Live Search Found Part Price Below $50!", $content, true,"mukundsojitra5464@gmail.com" );   
            }else{
                $prices[] = $price;
            }
        }
        
        if (count($prices) > 0) {
            return min($prices);    
        }else{
            return 0;
        }
        
    } else {
        return 0;
    }
}

function getMygrantPrice($partNo){
    // 1. Fetch the Login Page
    $url = "https://www.mygrantglass.com/pages/login.aspx"; // Replace with the actual URL
    $ch = curl_init($url);
    
    // Set options
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); // Save cookies
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
    
    // Execute the request
    $response = curl_exec($ch);
    
    // Extract dynamic fields
    preg_match('/<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="([^"]+)"/', $response, $viewstate);
    preg_match('/<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="([^"]+)"/', $response, $eventvalidation);
    
    // Safely extract values
    $viewstateValue = isset($viewstate[1]) ? $viewstate[1] : '';
    $eventvalidationValue = isset($eventvalidation[1]) ? $eventvalidation[1] : '';
    
    // Debugging output
    // if (!$viewstateValue || !$eventvalidationValue) {
    //      $searchResult = "Searched for part: " . $partNo." Failed to extract in MyGrant";
    //     // Log the result
    //     $logFile = "search_log.txt";
    //     file_put_contents($logFile, date("Y-m-d H:i:s") . " - " . $searchResult . "\n", FILE_APPEND);
    //     return 0;
    // }
    
    curl_close($ch);
    
    // 2. Perform Login
    $loginUrl = "https://www.mygrantglass.com/pages/login.aspx"; // Replace with actual login URL
    $ch = curl_init($loginUrl);
    
    $postFields = [
        '__VIEWSTATE' => $viewstateValue,
        '__EVENTVALIDATION' => $eventvalidationValue,
        'clogin:TxtUsername' => 'mdr1', // Replace with actual field names and values
        'clogin:TxtPassword' => '1217',
        'clogin:ButtonLogin' => 'Login' // This might vary depending on the form
    ];
    
    // Set options
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postFields));
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
    
    // Execute the request
    $response = curl_exec($ch);
    curl_close($ch);
    
    
    // 3. After login, use the saved cookies to access other MyGrant part search page.
    $protectedUrl = "https://www.mygrantglass.com/pages/search.aspx?q=".$partNo."&sc=n&do=Search"; // Replace with the target URL
    $ch = curl_init($protectedUrl);
    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
    
    // Execute the request
    $response = curl_exec($ch);
    curl_close($ch);
    
    // 4. Process the page content and Parse the HTML for price
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($response);
    libxml_clear_errors();
    
    // Use DOMXPath to query the DOM
    $xpath = new DOMXPath($dom);
    $priceNode = $xpath->query("//td[contains(@class, 'price')]");
    if ($priceNode->length > 0) {
        $price = (float) str_replace(',','',str_replace('$', '', trim($priceNode->item(0)->nodeValue)));
        
        if($price < 50 ){
    //         //Email Notification
    //         $content = "Hello Beau, <br><br>";
    //         $content .= "During the live search we captured the part price is less then 50. <br> ";
    //         $content .= "Source = MyGrant <br>";
    //         $content .= "Part = ".$partNo." <br>";
    //         $content .= "Cost = $".$price." <br>";
    // 		@SendMail( "no-reply@autoglasshosting.com", "8056807305@tmomail.net", "Notification: Live Search Found Part Price Below $50!", $content, true,"mukundsojitra5464@gmail.com" );   
    		
            return 0;
        }else{
            return $price;    
        }
    } else {
        return 0;
    }
}

//-------------------------------------------------------------------------
// EditInvoice:  A form to edit an invoice.
//-------------------------------------------------------------------------
function EditInvoice( $invoiceID, $checkoutID, $Notice="" ) {

	global $PHP_SELF, $g_oNDB, $HTTP_SESSION_VARS, $hDB, $site;

	/// automatically mark the invoice to assist with multi-personnel order handling...
	if( intval($invoiceID)>0 ) mysql_query( "UPDATE invoice SET edited='Y' where ID=$invoiceID", $hDB );

	/// get the info...
	$SQL = "SELECT checkout.*, invoice.orderCode, invoice.orderNum, location.id as installerID, location.name as installerName FROM checkout LEFT JOIN invoice ON checkout.ID=invoice.checkoutID LEFT JOIN location ON checkout.installerID=location.id WHERE checkout.ID='$checkoutID'";
	$hCheckout = mysql_query( $SQL );
	if( !$hCheckout && $checkoutID ) exit( "Checkout information not found." );
	if( $checkoutID ) $rCheckout = mysql_fetch_array($hCheckout);
	if( !$rCheckout && $invoiceID ) exit( "Could not retrieve checkout information." );
	$hCartItems = mysql_query( "SELECT quantity,productID,parameters,part,moldingPart,year,make,model,style,price,installPrice,partDetails,nspart,nsinfo FROM cartItems LEFT JOIN product ON cartItems.productID=product.ID WHERE cartID=".$rCheckout['cartID'] );
	if( $invoiceID ) $rCartItem = mysql_fetch_array($hCartItems);
	if( !$rCartItem && $invoiceID) exit( "Could not retrieve cart information." );
	$rInvoice = array();
	if( $invoiceID ) {
		if( !($hInvoice = mysql_query( "SELECT * FROM invoice WHERE ID=".$invoiceID )) ) exit("Unable to load the invoice record.");
		$rInvoice = mysql_fetch_array($hInvoice);
	}
	
	/*******
	 * Start locking mechanism
	 * By Mukund
	 * On: 11/01/2024
	 */
	$is_locked =  $rInvoice['is_locked'];
	$lockingUser =  $rInvoice['is_locked_by'];
	$loginUser = $_SESSION['ADMIN_NAME'];
	// Add locking
	if( intval($is_locked)==0 ) {mysql_query( "UPDATE invoice SET is_locked='1', is_locked_by='".$loginUser."' where ID=$invoiceID", $hDB );
	}

	if(intval($is_locked)==1 && $lockingUser != $loginUser) { 
		//Already Invoice open and updating so, display a message and redirect to Invoice Listing
		echo "<div class=\"message err\"><b> This invoice is currently being edited by user : <b>".$lockingUser."</b></div>\n";
		ListItems( "NOTHING" );
		return;
	}
	//End locking
	
	$oNum = ($rCheckout['orderCode']=="W2G" ? "" : $rCheckout['orderCode']."-") . $rCheckout['orderNum'];
	$rProduct = $g_oNDB->getRow("SELECT * FROM product WHERE ID='".intval($rCartItem['productID'])."'");
	$productCartRefs = $g_oNDB->getField("SELECT Count(*) FROM cartItems WHERE productID='".intval($rCartItem['productID'])."'");
	$productInvoiceRefs = $g_oNDB->getField("SELECT Count(invoice.ID) FROM invoice LEFT JOIN checkout ON invoice.checkoutID=checkout.ID LEFT JOIN cartItems ON checkout.cartID=cartItems.cartID LEFT JOIN product ON cartItems.productID=product.ID WHERE cartItems.productID='".intval($rCartItem['productID'])."'");

	/// start the page...
	$backJavaScript = " onClick=\"window.location.href='".$PHP_SELF."?A=CAN&site=".urlencode($site)."&invoiceID=".$invoiceID."&checkoutID=".$checkoutID."'; return true;\" ";
	if( strlen($Notice) > 0 ) {
		echo "<div><h3 style=\"display: inline-block; color: #C868D4; padding: 0.5ex 1.5ex 0.5ex 1ex; background: #FEFCC0; border: #E2E098 1px solid; border-radius: 4px;\">".$Notice."</h3></div>\n";
		echo "<div style=\"display: inline-block;\"><div style=\"background: #FEFCE8; margin: 0.5ex; padding: 2ex 4ex; border: #E2E098 1px solid; border-radius: 6px;\">\n";
	}
	?>
		<table cellpadding="0" cellspacing="0" border="0" background="#E8E8E8" style="display: inline-block;">
			<form method=post action="<?= $PHP_SELF ?>" name="InvoiceForm" onSubmit="return validate(InvoiceForm);">
				<input type=hidden name=site value="<? echo $site; ?>"><input type=hidden name=A value=U>
				<input type=hidden name=checkoutID value=<? echo $checkoutID ?>>
				<input type=hidden name=invoiceID value=<? echo $invoiceID ?>>
			<tr><td nowrap align=left><table align=right cellpadding=0 cellspacing=0><tr><td><input type=button class=button value=" Cancel " <?= $backJavaScript ?>></td></tr></table><b>
	<?
	$securityreminder = "style=\"background: #C0C0C0; color: #666;\" ";
	if( $invoiceID ) {
		echo "<font face=verdana size=4><u><b>Order # ".$oNum."</font></u>";
	} else {
		echo "<font face=verdana size=4><u><b>Add Invoice</font></b></u>";
		$securityreminder .= "onfocus=\"alert('Please do not use.'); return true;\" ";
	}
	?>
		</td>
		<td style='text-align: right;' align=right colspan=2><input type=submit class=button value=" Update "> &nbsp; &nbsp; &nbsp; &nbsp;</td></tr>
		<tr><td height=4 colspan=3><spacer type=block width=1 height=1></td></tr>
	<?

	/// format date and time
	$date = preg_replace("/\s+/", " ", $rCheckout['s_InstallDate']);
	list($installDay,$installMonth,$installTime)= split (" ", $date, 3);
	
	/// some s_InstallDate values are missing a day; swap values if so
	if( !is_numeric($installDay) ) {
		$installTime = $installMonth;
		$installMonth = $installDay;
		$installDay = 0;
	}
		
	// fix certain fields
	$rCartItem['make'] = htmlspecialchars($rCartItem['make']);
	$rCartItem['model'] = htmlspecialchars($rCartItem['model']);
	$rCartItem['style'] = htmlspecialchars($rCartItem['style']);

	/// installed is required, so cannot be blank, but parameter only "inst" so...
	if( $rCartItem['parameters'] == "inst" ) {
		$inst = "Yes";
		$hardware = "N/A";
	} else {
		$inst = "No";
		$hardware = $rCartItem['parameters']=="" ? "none" : $rCartItem['parameters'];
	}
		
	/// show the data...
	?>
	<tr valign=top><td style='vertical-align: top;' valign=top>
	<table style='border: #C0C0C0 1px solid;' cellpadding=1 cellspacing=0 border=0 bgcolor="#FCF0EC">
	<tr bgcolor="#F0D6D4" align=center><td colspan=2 style='font-size: 14px; padding: 4px;'><b>Customer Information</b></td></tr>
	<tr><td height=4 colspan=2><spacer type=block width=1 height=1></td></tr>
	<tr valign=top><td style='text-align: right;' align=right valign=top>&nbsp;<b>Name:&nbsp;<p>&nbsp;Address:&nbsp;</b></td><td><input type=text name=s_FirstName class=normal value="<? echo $rCheckout['s_FirstName']; ?>" size=6>&nbsp;&nbsp;<input type=text name=s_LastName class=normal value="<? echo $rCheckout['s_LastName']; ?>" size=10><br><input type=text name=s_Address class=normal value="<? echo $rCheckout['s_Address']; ?>" size=25><br><input type=text name=s_City class=normal value ="<? echo $rCheckout['s_City']; ?>" size=10>,&nbsp;<input type=text name=s_State class=normal value="<? echo $rCheckout['s_State']; ?>" size=3>&nbsp;&nbsp;<input type=text name=s_Zip class=normal value="<? echo $rCheckout['s_Zip']; ?>" size=5>&nbsp;&nbsp;</td></tr>
		<tr><td height=2 colspan=2><spacer type=block width=1 height=1></td></tr>
		<tr><td style='text-align: right;' align=right><b>Email:</b>&nbsp;</td><td><input type=text name=s_Email class=normal value="<? echo $rCheckout['s_Email']; ?>" size=25></td></tr>
		<tr><td style='text-align: right;' align=right><b>&nbsp;Company:</b>&nbsp;</td><td><input type=text name=s_Company class=normal value="<? echo $rCheckout['s_Company']; ?>" size=25>&nbsp;</td></tr>		
		<tr><td style='text-align: right;' align=right><b>Phone:</b>&nbsp;</td><td><input type=text name=s_Phone class=normal value="<? echo $rCheckout['s_Phone']; ?>" size=25></td></tr>
		
		<tr><td style='text-align: right;' align=right><b>VIN:</b>&nbsp;</td><td><input type="text" name="s_VIN" class="normal" value="<? echo $rCheckout['s_VIN']; ?>" size=25></td></tr>
		<tr><td height=4 colspan=2><spacer type=block width=1 height=1></td></tr>
		<tr><td style='text-align: right;' align=right><b>Dealer #:</b>&nbsp;</td><td><input type=text name=s_CrossStreet class=normal value="<? echo $rCheckout['s_CrossStreet']; ?>" size=25></td></tr>
		<tr><td height=4 colspan=2><spacer type=block width=1 height=1></td></tr>
		<tr><td style='text-align: right;' align=right><b>PO #:</b>&nbsp;</td><td><input type="text" name="s_PO" class="normal" value="<? echo $rCheckout['s_PO']; ?>" size=25></td></tr>
		<tr><td style='text-align: right;' align=right><b>Unit #:</b>&nbsp;</td><td><input type="text" name="s_Unit" autocomplete="off" class="normal" value="<? echo $rCheckout['s_Unit']; ?>" size=25></td></tr>
		<tr><td height=4 colspan=2><spacer type=block width=1 height=1></td></tr>
		<tr><td style='text-align: right;' align=right><b>Odometer:</b>&nbsp;</td><td><input type="text" name="s_Odometer" autocomplete="off" class="normal" value="<? echo $rCheckout['s_Odometer']; ?>" size=25></td></tr>
		<tr><td height=4 colspan=2><spacer type=block width=1 height=1></td></tr>
		
		<tr><td colspan=2><b>&nbsp;Requested Date:</b>&nbsp;
	<?
		
	getDropDown("installMonth", $installMonth, 0, "normal");
	echo "&nbsp;";
	getDropDown("installDay", $installDay, 0, "normal");
	echo "&nbsp;&nbsp;";
	getDropDown("s_InstallYear", $rCheckout['s_InstallYear'], 0, "normal");
	echo "<br><b>&nbsp;Requested Time:</b>&nbsp;";
	getDropDown("installTime", $installTime, 0, "normal");
    
	?>
	</td></tr>
	<tr><td height=4 colspan=2><spacer type=block width=1 height=1></td></tr></table></td>
	<td width=4>&nbsp;</td>
	<td valign=top style='vertical-align: top;'><table style='border: #C0C0C0 1px solid;' cellpadding=1 cellspacing=0 border=0 bgcolor="#ECF0FC">
	<tr bgcolor="#D8DCEC" align=center><td colspan=2 style='font-size: 14px; padding: 4px;'><b>Billing Information</b></td></tr>
	<tr><td colspan=2 valign=top>&nbsp;<input type=checkbox onClick=" this.checked? shipToBill('on') : shipToBill('off')" name=b_SameAsShipping value=1><font face=arial size=-1>&nbsp;Same as shipping</font></td></tr>
	<tr><td height=4 colspan=2><spacer type=block width=1 height=1></td></tr>
	<tr valign=top><td style='text-align: right;' align=right><b>Name:&nbsp;<p>Address:&nbsp;</b></td><td><input type=text name=b_FirstName class=normal value="<? echo $rCheckout['b_FirstName']; ?>" size=6>&nbsp;&nbsp;<input type=text name=b_LastName class=normal value="<? echo $rCheckout['b_LastName']; ?>" size=10><br><input type=text name=b_Address class=normal value="<? echo $rCheckout['b_Address']; ?>" size=25><br><input type=text name=b_City class=normal value ="<? echo $rCheckout['b_City']; ?>" size=10>,&nbsp;<input type=text name=b_State class=normal value="<? echo $rCheckout['b_State']; ?>" size=3>&nbsp;&nbsp;<input type=text name=b_Zip class=normal value="<? echo $rCheckout['b_Zip']; ?>" size=5>&nbsp;&nbsp;</td></tr>
	<tr><td height=2 colspan=2><spacer type=block width=1 height=1></td></tr>
	<tr><td style='text-align: right;' align=right><b>Email:</b>&nbsp;</td><td><input type=text name=b_Email class=normal value="<? echo $rCheckout['b_Email']; ?>" size=25></td></tr>
	<tr><td style='text-align: right;' align=right><b>&nbsp;Company:</b>&nbsp;</td><td><input type=text name=b_Company class=normal value="<? echo $rCheckout['b_Company']; ?>" size=25>&nbsp;</td></tr>		
	<tr><td style='text-align: right;' align=right><b>Phone:</b>&nbsp;</td><td><input type=text name=b_Phone class=normal value="<? echo $rCheckout['b_Phone']; ?>" size=25></td></tr>
	<!-- card info -->
	<tr><td height=8 colspan=2><spacer type=block width=1 height=1></td></tr></table><table style="margin-top: 1.5ex; border: #C0C0C0 1px solid;" cellpadding=1 cellspacing=0 border=0 bgcolor="#E8E8E8">
	<tr bgcolor="#D4D4D4" align=center><td colspan=2 style='font-size: 14px; padding: 4px; color: #888888;'><b>Charge Info</b></td></tr>
	<tr><td height=4 colspan=2><spacer type=block width=1 height=1></td></tr>
	<tr><td style='text-align: right;' align=right nowrap>&nbsp;<b>Payment:</b>&nbsp;</td><td>
	<?
	
		getDropDown("c_type", $rCheckout['c_type'], 0, "normal");
	
		?></tr><tr><td style='text-align: right;' align=right><b>Number:&nbsp;</b></td><td nowrap style="padding-right: 0.5em;"><input type="text" name="c_num" return true;" class=normal value="<? echo $rCheckout[c_num]; ?>" size="20"></td></tr><?
		?><tr><td style='text-align: right;' align=right><b>Expires:</b>&nbsp;</td><td><?
	
		getDropDown("c_expmonth", $rCheckout['c_expmonth'], 0, "normal");
		echo "/";
		getDropDown("c_expyear", $rCheckout['c_expyear'], 0, "normal");
		if( $invoiceID && $checkoutID ) {
			echo "</td></tr>";
		}
	
	?><tr><td style='text-align: right;' align=right><b>&nbsp;CVV #:</b>&nbsp;</td><td><input type="text" name="c_cvv" class=normal value="<? echo $rCheckout["c_cvv"]; ?>" size="4"><?= !$invoiceID ? "" : "" ?></td></tr>
	<tr><td height=5 colspan=4><spacer type=block width=1 height=5></td></tr>
	</table></td>
	
	
		<!--Start Live Search 3 suppliers in Edit page-->
		
		
		<!--End-->
	
	</tr>
	<tr><td height=12><spacer type=block width=1 height=1></td></tr>
		<td style='text-align: right;' align=right colspan=2><input type=submit class=button value=" Update "> &nbsp; &nbsp; &nbsp; &nbsp;</td></tr>
		<td valign=top colspan=3 align=center><table style='border: #C0C0C0 1px solid;' cellpadding=1 cellspacing=0 border=0 bgcolor="#ECFCF0" width=568>
	<tr bgcolor="#D8ECDC"><td colspan=4 style='font-size: 14px; padding: 4px;' align=center><b>Order Summary</b></td>
		<td style="text-align: right;" align="right" nowrap><a href="javascript:popup('partWizard.php?A=W&year=<? echo $rCartItem['year'] ?>'+'&zip='+document.InvoiceForm.s_Zip.value)"><font face=arial size=-1 color="#000088">Part Wizard</font></a> &nbsp;&middot;&nbsp; 
			<a href="javascript:void(0);" name="Part Search" title="Part Search" onClick="window.open('/admin/products.php?A=SF','PartPopup','width=960,height=750,0,status=0,');"><font face=arial size=-1 color="#000088">Part Search</a> &nbsp;&middot;&nbsp; 
			<?
				if( $productCartRefs <= 1 && $productInvoiceRefs <= 1 && eregi("ns:",$rProduct['part']) ) {
					?><a href="javascript:void(0);" name="Edit Part" title="Edit Part" onClick="window.open('/admin/products.php?A=E&ID=<? echo $rCartItem['productID'] ?>','PartPopup','width=960,height=750,0,status=0,');"><font face=arial size=-1 color="#000088">Edit Part</a> &nbsp;<?
				} else {
					?><strike style="color: #E80000;"><span style="color: #808080;" title="( Cannot safely edit product <?= $rCartItem['productID'] .' - used in '. $productCartRefs . ' carts and ' . $productInvoiceRefs ?> invoices. )">Edit Part</span></strike> &nbsp;<? 
				} 
			?>
		</td>
	</tr>
	<tr><td height=4 colspan=5><spacer type=block width=1 height=1></td></tr>
	<tr><td style='text-align: right;' align=right><b>Year:</b>&nbsp;</td><td><input type=text name=year value="<? echo $rCartItem['year']; ?>" size=5 onKeyDown="return disabledWarning();" class=readonly readonly locked></td>
		<td style='text-align: right;' align=right><b>Model:</b>&nbsp;</td><td colspan=2><input type=text name=model value="<? echo $rCartItem['model']; ?>" onKeyDown="return disabledWarning();" class=readonly readonly locked>&nbsp;&nbsp;</td></tr>
	<tr><td style='text-align: right;' align=right><b>Make:</b>&nbsp;</td><td><input type=text name=make value="<? echo $rCartItem['make'] ?>" onKeyDown="return disabledWarning();" class=readonly readonly locked>&nbsp;&nbsp;</td>
		<td style='text-align: right;' align=right><b>Style:</b>&nbsp;</td><td colspan=2><input type=text name=style value="<? echo $rCartItem['style']; ?>" onKeyDown="return disabledWarning();" class=readonly readonly locked>&nbsp;&nbsp;</td></tr>
	<tr><td height=10 colspan=5><spacer type=block width=1 height=1></td></tr>
	<tr><td style='text-align: right;' align=right><b>Installed:&nbsp;<span style='font-size: 8px;'><br><br></span>Hardware:&nbsp;</b></td>
		<td><? getDropDown("inst", $inst, 0, "normal"); ?>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<b>Qty:</b>&nbsp;<input type=text name=quantity class=normal value="<? echo $rCartItem['quantity']; ?>" size=1><br><input type=text name=hardware size=10 maxlength=20 value="<? echo $hardware ?>" class=readonly readonly locked onKeyDown="return disabledWarning();"></td>
		<td colspan=2 class=right align=right><span style='font-size: 2px;'><br></span><b>Part:&nbsp;<span style='font-size: 6px;'><br><br></span>NAGS&reg;&nbsp;#:&nbsp;<span style='font-size: 6px;'><br><br></span>Molding&nbsp;Part:&nbsp;</b></td>
		<td><input type=text name=part value="<? echo $rCartItem['part']; ?>" size=15 onKeyDown="return disabledWarning();" class=readonly readonly locked>&nbsp;&nbsp;<br><input type=text name=nspart value="<? echo $rCartItem['nspart']; ?>" size=15 onKeyDown="return disabledWarning();" class=readonly readonly locked>&nbsp;&nbsp;<br><input type=text name=moldingPart value="<? echo $rCartItem['moldingPart']; ?>" size=15 onKeyDown="return disabledWarning();" class=readonly readonly locked>&nbsp;&nbsp;</td></tr>
	<tr><td  class=right align=right colspan=4><b>Details:&nbsp;</b></td><td><input type=text name=partDetails class=normal value="<? echo $rCartItem['partDetails'] ?>">&nbsp;&nbsp;</td></tr>
	<tr><td height=18 colspan=5><spacer type=block width=1 height=1></td></tr><tr>
	<? if( strlen(trim($rCheckout['discountCode'])) > 0 ) { ?>
	<tr class=right align=right>
		<td colspan=2 class=right style="color: #990000;"><span style="background: #D8ECDC;">&nbsp;Discount Code:&nbsp;&nbsp;</span></td>
		<td style="color: #990000; font-weight: bold;"><span style="background: #D8ECDC;">&nbsp;<? echo strtolower($rCheckout['discountCode']); ?>&nbsp;</span></td>
		<td colspan=2 rowspan=3>&nbsp;</td>
	</tr>
	<? } ?>
	<tr class=right align=right><td style='text-align: right;' colspan=2><b>Subtotal:</b>&nbsp;</td><td><input type=text name=subtotal class=normal value="<? echo $rCheckout[subtotal]; ?>" size=5 style="text-align:right"></td><td colspan=2 rowspan=3>&nbsp;</td></tr>
	<tr class=right align=right><td style='text-align: right;' colspan=2><b>Shipping:</b>&nbsp;</td><td><input type=text name=shipping class=normal value="<? echo $rCheckout[shipping]; ?>" size=5 style="text-align:right"></td></tr>
	<tr class=right align=right><td style='text-align: right;' colspan=2><b>Tax Amount:</b>&nbsp;</td><td><input type=text name=tax class=normal value="<? echo $rCheckout[tax]; ?>" size=5 style="text-align:right"></td></tr>
	<tr class=right align=right><td style='text-align: right;' colspan=2><b>Total:</b>&nbsp;</td><td><input type=text name=total class=normal value="<? echo $rCheckout[total]; ?>" size=5  style="text-align:right"></td></tr>
	<tr><td height=10 colspan=5><spacer type=block width=1 height=1></td></tr>
	<tr bgcolor="#D8ECDC">
		<td colspan=5 style='font-size: 14px; padding: 4px;' align=center><b>Comments</b></td>
	<tr><td height=10 colspan=5><spacer type=block width=1 height=1></td></tr>
		<input type=hidden name=installerID value="<? echo $rCheckout['installerID']; ?>">
	<tr><td valign=top align=right style='vertical-align: top; text-align: right;'><b>&nbsp;Installer:&nbsp;</b></td><td colspan=4>
		<input name=installerName size=40 value="<? echo $rCheckout['installerName']; ?>" class=readonly locked readonly onKeyDown="return disabledWarning();">
		<? echo "&nbsp; <a href=\"javascript:popup('installerWizard.php?A=L&zip=".$rCheckout['s_Zip']."');\">Installer Wizard</a>"; ?><br>
		<textarea rows=5 cols=65 name=installer class=normal><? echo $rCheckout['installer']; ?></textarea>
	</td></tr>
	<tr><td height=10 colspan=5><spacer type=block width=1 height=1></td></tr>
	<tr><td valign=top style='vertical-align: top; text-align: right;' align=right><b>&nbsp;Comments:&nbsp;</b><span style='font-size: 4px;'><br><br></span><a href="javascript:AddPrefill(document.InvoiceForm.comments, 35);">Paid</a><br><a href="javascript:AddPrefill(document.InvoiceForm.comments, 39);">Calibration</a><br></td><td colspan=4><textarea rows=3 cols=65 name=comments class=normal><? echo $rCheckout[comments]; ?></textarea></td></tr>
	<tr><td style='text-align: right;' align=right><b> Shop Amount:</b>&nbsp;</td><td><input type=text name=shopLabor class=normal value="<? echo $rCheckout['shopLabor']; ?>" size=10></td></tr>
	<tr><td valign=top style='vertical-align: top; text-align: right;' align=right><b>&nbsp;Shop Comments:&nbsp;</b><span style='font-size: 4px;'><br><br></span><a href="javascript:AddPrefill(document.InvoiceForm.shopComments, 17);">Note</a></td><td colspan=4><textarea rows=3 cols=65 name=shopComments class=normal placeholder="Please start by clicking on 'note'"><? echo $rCheckout[shopComments]; ?></textarea></td></tr>		
	<tr><td valign=top style='vertical-align: top; text-align: right;' align=right><b>&nbsp;Warehouse Comments:&nbsp;</b></td><td colspan=4><textarea rows=5 cols=65 name=warehouseComments class=normal><? echo $rCheckout[warehouseComments]; ?></textarea></td></tr>
		
		</td>
		<td style='text-align: right;' align=right colspan=2><input type=submit class=button value=" Update "> &nbsp; &nbsp; &nbsp; &nbsp;</td></tr>
		<tr><td height=4 colspan=3><spacer type=block width=1 height=1></td></tr>
	
	<tr><td valign=top style='vertical-align: top; text-align: right;' align=right><b>&nbsp;Internal Comments:&nbsp;<br><br>First Call&nbsp;<br>Then Post&nbsp;<br>Then Text&nbsp;<br>And say&nbsp;<br>you did&nbsp;<br></td><td colspan=4><textarea rows=8 cols=65 name=i_comments class=normal><? echo $rCheckout[i_comments]; ?></textarea></td></tr>
	
	
	<tr><td height=10 colspan=5><spacer type=block width=1 height=10></td></tr>
	<tr bgcolor="#D8ECDC"><td colspan=5 style='font-size: 14px; padding: 4px;' align=center><b>Flags</b></td>
	<tr><td height=5 colspan=5><spacer type=block width=1 height=5></td></tr>
	<!-- flags --><input type=hidden name='i_installerPaid_old' value='<?= $rInvoice['installerPaid'] ?>'>
	<tr valign=top><td style='text-align: right;' align=right><b>&nbsp;Flags:&nbsp;</td><td colspan=4>
		<input type=checkbox<?= $rInvoice['scheduled']=="Y" ? " CHECKED" : "" ?> name=i_scheduled value=Y>&nbsp;scheduled &nbsp; &nbsp;
		<input type=checkbox<?= $rInvoice['auth']=="Y" ? " CHECKED" : "" ?> name=i_auth value=Y>&nbsp;auth'd &nbsp; &nbsp;
		<input type=checkbox<?= $rInvoice['paid']=="Y" ? " CHECKED" : "" ?> name=i_paid value=Y>&nbsp;paid &nbsp; &nbsp;
		<input type=checkbox<?= $rInvoice['installerPaid']=="Y" ? " CHECKED" : "" ?> name=i_installerPaid value=Y>&nbsp;paidShop &nbsp; &nbsp;
		<input type=checkbox<?= $rInvoice['fulfilled']=="Y" ? " CHECKED" : "" ?> name=i_fulfilled value=Y>&nbsp;completed<br>
		<input type=checkbox<?= $rInvoice['waitForCallback']=="Y" ? " CHECKED" : "" ?> name=i_waitForCallback value=Y>&nbsp;waitForCallback &nbsp; &nbsp;
		<input type=checkbox<?= $rInvoice['waiting']=="Y" ? " CHECKED" : "" ?> name=i_wait value=Y>&nbsp;Wait &nbsp; &nbsp;
		<input type=checkbox<?= $rInvoice['onHold']=="Y" ? " CHECKED" : "" ?> name=i_onHold value=Y>&nbsp;onHold &nbsp; &nbsp;
		<input type=checkbox<?= $rInvoice['notServiced']=="Y" ? " CHECKED" : "" ?> name=i_notServiced value=Y>&nbsp;notServiced &nbsp; &nbsp;
		<input type=checkbox<?= $rInvoice['cancelled']=="Y" ? " CHECKED" : "" ?> name=i_cancelled value=Y>&nbsp;cancelled &nbsp; &nbsp;<br>
		<input type=checkbox<?= $rInvoice['declined']=="Y" ? " CHECKED" : "" ?> name=i_declined value=Y>&nbsp;declined &nbsp; &nbsp;
		<input type=checkbox<?= $rInvoice['fraudulent']=="Y" ? " CHECKED" : "" ?> name=i_fraudulent value=Y>&nbsp;issues &nbsp; &nbsp;
		<input type=checkbox<?= $rInvoice['blink']=="Y" ? " CHECKED" : "" ?> name=i_blink value=Y>&nbsp;highlighted&nbsp; &nbsp;
		<!--pointless since it auto-unsets<input type=checkbox<?= $rInvoice['feedback']=="Y" ? " CHECKED" : "" ?> name=i_feedback value=Y>&nbsp;bolded&nbsp; &nbsp;-->
		<!--<input type=checkbox<?= $rInvoice['edited']=="Y" ? " CHECKED" : "" ?> name=i_edited value=Y>&nbsp;edited &nbsp; &nbsp;-->
		<input type=checkbox<?= $rInvoice['hidden']=="Y" ? " CHECKED" : "" ?> name=i_hidden value=Y>&nbsp;hidden &nbsp; &nbsp;
		<input type=checkbox<?= $rInvoice['ready']=="Y" ? " CHECKED" : "" ?> name=i_ready value=Y>&nbsp;ready &nbsp; &nbsp;
	</td></tr>
	<tr><td height=4 colspan=5><spacer type=block width=1 height=1></td></tr></table></td></tr>
	<tr><td height=12><spacer type=block width=1 height=1></td></tr>
	<td align=center colspan=3><table style='border: #C0C0C0 1px solid;' cellpadding=1 cellspacing=0 border=0 bgcolor="#FAF2FD" width=570 height=200>
	<tr bgcolor="#F2DCF4"><td colspan=4 style='font-size: 14px; padding: 4px;' align=center><b>Other Information</b></td></tr>
	<tr><td height="6" colspan="4"><spacer type=block width=1 height=6></td></tr>
	<tr><td style='text-align: right; padding-right: 5.5em;' align=right colspan=4 nowrap><b>Requested Location:</b>&nbsp; <select name="s_Warehouse" class="normal" style="max-width: 20em;"><option value=""></option><? echo "<option value=\"".$rCheckout['s_Warehouse']."\" SELECTED>".$rCheckout['s_Warehouse']."</option>"; printWarehouseSel( $rCheckout['s_Warehouse'] ); ?> &nbsp;</td></tr>
		<script language=JavaScript src=/%22windshield.js/%22></script>
		<script language=JavaScript src=/%22/inc/global.js/%22></script>
		<script language=javascript>
			/// all of the warehouse info...
			var warehouseInfo = new Array();
			var bAutoComment = false;
			<?
				$oNRS = new nRS("SELECT * FROM warehouse WHERE pickupAddress<>'' ORDER BY pickupCity, pickupState, name");
				while( $rData = $oNRS->read() ) {
					echo "\t\t\twarehouseInfo['ID:".$rData['ID']."'] = \"".js_encode_N(str_replace("\"","\\\"",$rData['name']."\n".$rData['pickupAddress']."\n".$rData['pickupCity'].", ".$rData['pickupState']." ".$rData['pickupZip']."\n".$rData['phone']))."\";\n";
				}
			?>
			/// all of the non-status prefills...
			var prefillText = new Array();
			<?
				$oNRS = new nRS("SELECT * FROM messagePrefill WHERE type='shopComment' ORDER BY ordering, subject");
				while( $rData = $oNRS->read() ) {
					echo "\t\t\tprefillText['ID:".$rData['ID']."'] = \"".js_encode_N(str_replace("\"","\\\"",$rData['message']))."\";\n";
				}
			?>
			/// dumps in the 'will-call' info from the data above for the selected warehouseID...
			function AutoFillWarehouseComments( prefix ) {
				if( bAutoComment ) if( !confirm("Auto-comment already done. Really append warehouse info again?   ") ) return;
				var warehouseComment = document.InvoiceForm.warehouseComments.value;
				if( warehouseComment != ""  &&  warehouseComment.substr(warehouseComment.length-1) != "\n" ) warehouseComment += "\n";
				var index = 'ID:'+document.InvoiceForm.warehouseID[document.InvoiceForm.warehouseID.selectedIndex].value;
				if( String(warehouseInfo[index])=="undefined" ) {
					alert("No warehouse selected or data error.   ");
					return;
				}
				warehouseComment += prefix + js_decode_N(warehouseInfo[index]);
				document.InvoiceForm.warehouseComments.value = warehouseComment;
				bAutoComment = true;
			}
			/// dump-adds text such as 'DT' info into the Shop Comments or a "Paid" image into the installer comments...
			function AddPrefill( element, prefillID ) {
				var newTextValue = element.value;
				if( newTextValue != ""  &&  newTextValue.substr(newTextValue.length-1) != "\n" ) newTextValue += "\n";
				var index = 'ID:'+prefillID;
				if( String(prefillText[index])=="undefined" ) {
					alert("Prefill data retrieve/parse error.   ");
					return;
				}
				newTextValue += js_decode_N(prefillText[index]);
				element.value = newTextValue;
			}
		</script>
	<tr><td style='text-align: right; padding-right: 5.5em;' align=right colspan=4 nowrap><b>Pickup Warehouse:</b>&nbsp;
		<?
			$rValues = $g_oNDB->getColumn( 0, "SELECT ID FROM warehouse ORDER BY city, state, name", "ERROR!" );
			$rTexts = $g_oNDB->getColumn( 0, "SELECT Concat(city, ', ', state, ' - ', name) AS location FROM warehouse ORDER BY city, state, name", "ERROR!" );
			ShowSelect( "warehouseID", $rValues, $rTexts, $rCheckout['warehouseID'], "", false, "normal", "max-width: 20em;" );
		?><br>&nbsp; <a href="javascript:AutoFillWarehouseComments('will call at ');">will call</a> &nbsp;&middot;&nbsp; <a href="javascript:AutoFillWarehouseComments('deliver from ');">deliver</a></td></tr>
	<tr><td height=1 colspan=4><spacer type=block width=1 height=1></td></tr>
	<tr><td height=1 colspan=4><div style="border-top: #C0C0C0 1px solid; max-height: 1px;"></div></td></tr>
	<tr><td height=6 colspan=4><spacer type=block width=1 height=6></td></tr>
	<tr><td style='text-align: right;' align=right><b>Service Type:</b>&nbsp;</td><td><? getDropDown("serviceType", $rCheckout['serviceType'], 0, "normal"); ?>
	</td><td style='text-align: right;' align=right nowrap><b>&nbsp;Payment Method:</b>&nbsp;</td><td><? getDropDown("paymentMethod", $rCheckout['paymentMethod'], 0, "normal"); ?>
	&nbsp;</td></tr>
	<tr><td style='text-align: right;' align=right><b>PO:</b>&nbsp;</td><td><input type=text name=i_Name class=normal value="<? echo $rCheckout['i_Name']; ?>" size=10></td><td style='text-align: right;' align=right nowrap><b>Return Company:</b>&nbsp;</td><td><input type=text name=i_Phone class=normal value="<? echo $rCheckout['i_Phone']; ?>" size=10></td></tr>
	<tr><td style='text-align: right;' align=right nowrap>(Return Moldings!)&nbsp;<b>Return Number:</b>&nbsp;</td><td><input type=text name=i_Policy class=normal value="<? echo $rCheckout['i_Policy']; ?>" size=10></td><td style='text-align: right;' align=right><b>Return Part:</b>&nbsp;</td><td><input type=text name =i_Deductible class=normal value="<? echo $rCheckout['i_Deductible']; ?>" size=15>&nbsp;</td></tr>
	<tr><td style='text-align: right;' align=right><b>AgreeLowPrice:</b>&nbsp;</td><td><? getDropDown("agreeLowPrice", $rCheckout['agreeLowPrice'], 0, "normal"); ?>
	</td><td style='text-align: right;' align=right><b>AgreeFactors:</b>&nbsp;</td><td><? getDropDown("agreeFactors", $rCheckout['agreeFactors'], 0, "normal"); ?>
	</td></tr>
	<tr><td>&nbsp;</td><td>&nbsp;</td><td style='text-align: right;' align=right nowrap><b>Glass Cost:</b>&nbsp;</td><td><input type=text name=glassCost class=normal value="<? echo $rCheckout['glassCost']; ?>" size=10></td></tr>
	<tr><td style='text-align: right;' align=right>&nbsp;</td><td>&nbsp;</td><td style='text-align: right;' align=right nowrap><b>&nbsp;Shipper#:</b>&nbsp;</td><td><input type=text name=shipperNum class=normal value="<? echo $rCheckout['shipperNum']; ?>" size=10 maxlength=25></td></tr>
	<?
	
	if(isset($rCartItem['nsinfo']) && $rCartItem['nsinfo'] != "") {
		$nsSupplierCost = $nsNagsList = "";
		$nvs = explode(',', $rCartItem['nsinfo']);
		foreach($nvs as $nvsi) {
			$nvx = explode('=', $nvsi, 2);
			$nvx[0] = trim($nvx[0]);
			if($nvx[0] == "supplierCost") $nsSupplierCost = "$".trim($nvx[1]);
			if($nvx[0] == "nagsListPrice") $nsNagsList = "$".trim($nvx[1]);
		}
		?>
		<tr><td style='text-align: right;' align=right><b>NAGS List:</b>&nbsp;</td><td><? echo $nsNagsList; ?></td><td style='text-align: right;' align=right nowrap><b>Supplier Cost:</b>&nbsp;</td><td><? echo $nsSupplierCost; ?></td></tr>
		<?
	}
	if( $_SESSION['ADMIN_LEVEL'] >= 3 ) {
		?>
		<tr><td style='text-align: right;' align=right colspan=2><b>Gross Profit:</b>&nbsp;</td><td colspan=2><input type=text name=profit class=normal value="<? echo $rCheckout['profit']; ?>" size=10>
		<tr><td style='text-align: right;' align=right colspan=2><b>ExtRef from:</b>&nbsp;</td><td colspan=2><? getDropDown("referrer", $rCheckout['referrer'], 0, "normal"); ?></td></tr>
		<?
	}
	
	?><tr><td colspan=4 style='text-align: center;'><b>Affiliate Referrer:&nbsp;</b><!--:<?= $rCheckout['referrerID']; ?>:--><?
	
	$rValues = $g_oNDB->getColumn("SELECT ID FROM affiliate ORDER BY name");
	$rTexts = $g_oNDB->getColumn("SELECT ConCat(name,' (',aff,')') FROM affiliate ORDER BY name");
	ShowSelect( "i_referrerID", $rValues, $rTexts, $rInvoice['referrerID'], "(none)" );
	
	?>
	</td></tr>
	<tr><td height=8 colspan=4><spacer type=block width=1 height=1></td></tr></table></td></tr>
	<tr><td height=12 colspan=3><spacer type=block width=1 height=4></td></tr>
	<tr><td style='text-align: right;' align=right><input type=button class=button value=" Cancel " <?= $backJavaScript ?>></td><td style='text-align: right;' align=right colspan=2><input type=hidden name=site value="<? echo $site; ?>"><input type=hidden name=A value=U><input type=hidden name=checkoutID value=<? echo $checkoutID ?>><input type=hidden name=invoiceID value=<? echo $invoiceID ?>> &nbsp; <input type=submit class=button value=" Update "></td></tr>
	<tr><td height=4 colspan=3><spacer type=block width=1 height=1></td></tr>
	<tr><td height=20><spacer type=block width=1 height=1></td></tr></table>
	</form>
	<?
	if( strlen($Notice) > 0 ) {
		echo "</div></div>\n";
	}

} // EditInvoice()


//-------------------------------------------------------------------------
// SearchForm:  Selects field and value to search on.
//-------------------------------------------------------------------------
function SearchForm() {

	global $g_oNDB, $PHP_SELF, $site;
	
	?>
	<body bgcolor="#F8F8F8" text="#000088" VLINK="#ff0000"><form action="<?= $PHP_SELF ?>" method="GET">
	<blockquote>
	<table border=0><tr align=right style='text-align: right;'><td><input type=hidden name=site value="<? echo $site; ?>">
		<input type="hidden" name="A" value="SFR"><b>Search For:&nbsp;</td><td><input type=text name=value size=22></td></tr>
		<tr class=right align=right><td><b>In Field:</b></b></td>
		<td>
			<select name="field">
				<option value="orderNum" selected>Order #</option>
				<option value="partDetails">Details</option>
				<option value="total">Total Charge</option>
				<option value="invoice.ID">Invoice ID</option>
				<option value="part">Part Number</option>
				<option value="s_LastName">Shipping Last Name</option>
				<option value="b_LastName">Billing Last Name</option>
				<option value="s_Phone">Phone Number</option>
				<option value="s_Email">Email Address</option>
				<option value="s_Zip">Zip Code</option>
				<option value="s_CrossStreet">Dealer#</option>
				<option value="s_VIN">VIN</option>
				<option value="s_PO">PO #</option>
				<option value="s_Unit">Unit #</option>
				<option value="installer">Installer</option>
				<option value="shipperNum">Shipper #</option>
				<option value="shopLabor">Shop Labor</option>
				<option value="glassCost">Glass Cost</option>
				<option value="referrer">ExtRef</option>
				<option value="AffCode">Aff Code (exact)</option>
				<option value="waiting">Waiting (ALL)</option>
				<option value="flag">Hidden (ALL)</option>
				
			</select>
			<input type=submit value='Search'>
		</td>
	</tr></table></form>
	
	<br><br><br>
	<p>
	<form action="<?= $PHP_SELF ?>" method="GET" target="_blank"><input type="hidden" name="A" value="JTLIA">
	Go to aff invoice managment for:<br>
	<select name="ID">
	<?
	$oNRS = new nRS("SELECT ID, name, aff FROM affiliate WHERE isJoined='Y' AND isW2G='N' AND isActive='Y' AND isArchived='N' AND isEnabled='Y' AND isHidden='N' AND isDeleted='N' ORDER BY name");
	while( $rInfo = $oNRS->read() ) {
		echo "<option value=\"" . $rInfo['ID'] . "\" " . ($rInfo['aff']=="prax" ? "selected" : "") . ">" . $rInfo['aff'] . " - " . $rInfo['name'] . "</option>\n";
	}
	?>
	</select> &nbsp; <input type=submit value="Log In"></form></blockquote>
	<?

} // SearchForm()


//-------------------------------------------------------------------------
// HandAuthForm:  Selects field and value to search on.
//-------------------------------------------------------------------------
function HandAuthForm( $InvID, $LocalTransID ) {

	global $g_Config, $g_oNDB, $PHP_SELF, $site;
			
	// grab data
	$rInvoice = $g_oNDB->getRow("SELECT * FROM invoice WHERE ID='".$InvID."'");
	$checkoutID = $g_oNDB->getField("SELECT checkoutID FROM invoice WHERE ID='".$InvID."'");
	$rCheckout = $g_oNDB->getRow("SELECT * FROM checkout WHERE ID='".$checkoutID."'");
	$TxNum_Now = $g_oNDB->getField("SELECT Count(*) FROM invoiceTransactions WHERE invoiceID='".$InvID."'");
	
	// input
	$month = isset($_POST['c_expmonth']) ? $_POST['c_expmonth'] : $rCheckout['c_expmonth'];
	$year = isset($_POST['c_expyear']) ? $_POST['c_expyear'] : $rCheckout['c_expmonth'];
	$cvv = isset($_POST['c_cvv']) ? $_POST['c_cvv'] : $rCheckout['c_cvv'];
	$num = $LocalTransID > 0 ? $_POST['c_num'] : ''; // avoid re-charge when it was successful
	if( $LocalTransID > 0 ) {
		if( $g_oNDB->getField("SELECT result FROM invoiceTransactions WHERE ID=".$LocalTransID) == 100 ) {
			$num = '';
		}
	}
	
	// the form
	?>
	<body bgcolor="#F8F8F8" text="#000088" VLINK="#ff0000">
	<blockquote>
		<h2 style="margin-bottom: 0.25em;">Authorization for Hand Ticket</h2>
		<h3 style="background: #F0FAFF; display: inline-block; padding: 4px 8px; border-radius: 2px;"><a href="<?= $PHP_SELF ?>?site=<?= $site ?>&A=S&invoiceID=<?= $InvID ?>&checkoutID=<?= $checkoutID ?>">Order # <?= $rInvoice['orderCode'].'-'.$rInvoice['orderNum'] ?></a></h3>
		<br>
		<form action="<?= $PHP_SELF ?>" name="ChargeForm" method="POST">
			<input type="hidden" name="site" value="<?= $site ?>">
			<input type="hidden" name="A" value="HA-RUN">
			<input type="hidden" name="invoiceID" value="<?= $InvID ?>">
			<input type="hidden" name="TxNum_File" value="<?= $TxNum_Now ?>">
		<table cellpadding="5" cellspacing="5" border="0" rules="0">
			<caption style="background: #F8F8F8; border: #C0C0C0 1px dotted; font-weight: bold;"><br><span style="white-space: nowrap;">Enter Charge Information</span><br><span style='font-weight: normal; font-size: 0.85em; color: #808080;'>(Card will <i>not</i> be saved. &nbsp;&nbsp;&nbsp;<br>&nbsp;&nbsp; Transaction will be on file.)</span><br>&nbsp;</caption>
			<tr><td style='text-align: right;' align=right nowrap>&nbsp;<b>Payment:</b>&nbsp;</td><td>
			<?
			getDropDown("c_type", $rCheckout['c_type'], 0, "normal");
			?></tr><tr><td style='text-align: right;' align=right><b>Number:&nbsp;</b></td><td><input type="text" name="c_num" class="normal" value="<? echo $num; ?>" size="20"></td></tr><?
			?><tr><td style='text-align: right;' align=right><b>Expires:</b>&nbsp;</td><td><?
			getDropDown("c_expmonth", $month, 0, "normal");
			echo "/";
			getDropDown("c_expyear", $rCheckout['c_expyear'], 0, "normal");
			echo "</td></tr>";
			?>
			<tr><td style='text-align: right;' align=right><b>&nbsp;CVV #:</b>&nbsp;</td><td><input type =text name=c_cvv class=normal value="<? echo $cvv; ?>" size=4></td></tr>
		</table>
	<?
	
	// only allow attempt if the order isn't missing info
	if( 
		$rCheckout['b_FirstName'] != ""
		&& $rCheckout['b_LastName'] != ""
		&& $rCheckout['b_Address'] != ""
		&& $rCheckout['b_City'] != ""
		&& $rCheckout['b_State'] != ""
		&& $rCheckout['b_Zip'] != ""
	) {
		?><p style="padding-left: 2em;"><input type="submit" class="button" style="padding: 0.5ex 1em;" value="Run $.06 Pre-Auth"></p><?
	} else {
		echo "<p class=error>Billing information is required on file! &nbsp;<span style='font-weight: normal;'>(first, last, address, city, state, zip)</span></p>";
	}
	
	echo "</form>&nbsp;\n";

	// more info
	$SQL = "SELECT ID, stamp, ip, total, source, archive, gatewayType, reqID, result, decision, avs, cvv, shortMsg FROM invoiceTransactions WHERE invoiceID=".$InvID;
	$oNRS = new nRS( $SQL );
	if( $oNRS->numRows > 0 ) {
		echo "<br><h2>Transactions</h2>\n";
		/*
		improvements:
			1. highlight the $LocalTransID (if>0)
			2. add the reasoncode overlay lookup thing, as well
		*/
		echo "<table border=0 bordercolor=black cellspacing=1 cellpadding=1 bgcolor=#808080>\n";
		echo "\t<tr bgcolor=\"#D8D8D8\">\n";
		$columns = array('ID','stamp','ip','total','source','archive','gatewayType','reqID','result','decision','avs','cvv','shortMsg');
		for( $i=0; $i<count($columns); $i++) {
			echo "\t\t<td nowrap><b>".$columns[$i]."</b></td>\n";
		}
		echo "\t</tr>\n";
		while( $rTrans = $oNRS->read() ) {
			echo "\t<tr bgcolor=\"".($rTrans['ID']==$LocalTransID ? ($rTrans['result']==100 ? "#D0FCD2" : "#FCD4D2") : "#F0F0F0")."\">\n";
			for( $i=0; $i<count($columns); $i++) {
				echo "\t\t<td nowrap>".htmlspecialchars($rTrans[$columns[$i]])."</td>\n";
			}
			echo "\t</tr>\n";
		}
		echo "</table>\n";
		//$oNRS->showData();
	}
	/*
	$oNRS = new nRS("SELECT refCode, ID, stamp, ip, source, gatewayType, invoiceTransactionID, decision, result, subID FROM invoiceSubscriptions WHERE invoiceID=".$InvID);
	if( $oNRS->numRows > 0 ) {
		echo "<br><h2>Subscriptions <span style=\"font-size: 0.8em; font-weight: normal; color: #C80000;\">&nbsp; (<u>Not</u> created at this stage.)</span></h2>\n";
		$oNRS->showData(false);
	}*/
	echo "</blockquote><p></p>&nbsp;";

} // HandAuthForm()

//-------------------------------------------------------------------------
// HandAuthForm_Stripe:  Selects field and value to search on. 
//-------------------------------------------------------------------------
function HandAuthForm_Stripe( $InvID ) {

	global $g_Config, $g_oNDB, $PHP_SELF, $site;
	
	$configPath = '/home/auto11/var/config.php';
	$config = require $configPath;
	
	// Set your secret key. Remember to switch to your live secret key in production!
    $secretKey = $config['stripe_secret_key'];
    $apiUrl = 'https://api.stripe.com/v1';
    
			
	// grab data
	$rInvoice = $g_oNDB->getRow("SELECT * FROM invoice WHERE ID='".$InvID."'");
	$checkoutID = $g_oNDB->getField("SELECT checkoutID FROM invoice WHERE ID='".$InvID."'");
	$rCheckout = $g_oNDB->getRow("SELECT * FROM checkout WHERE ID='".$checkoutID."'");
	$TxNum_Now = $g_oNDB->getField("SELECT Count(*) FROM invoiceTransactions WHERE invoiceID='".$InvID."'");
	$invoiceTransactions = $g_oNDB->getRow("SELECT * FROM invoiceTransactions WHERE invoiceID='".$InvID."' AND result=100 Order by ID desc");

	$paymentMethodID = $invoiceTransactions['reqID'];
	
	$address = [];
	$namee = '';
    $addresss = '';  
    $cityy =  '';
    $statee =  '';
	if (strpos($paymentMethodID, 'pi_') === 0) {
	    $billingResponse = curlRequest("{$apiUrl}/payment_intents/{$paymentMethodID}", [], $secretKey);
        $billingAddress = json_decode($billingResponse,true);
        
        $customerResponse = curlRequest("{$apiUrl}/customers/{$invoiceTransactions['customer_id']}", [], $secretKey);
        $customerInfo = json_decode($customerResponse,true);
        
        $address = $billingAddress['charges']['data'][0]['billing_details']['address'];
        $namee = $customerInfo['name'];
        $addresss =  $address['line1'];
        $cityy =  $address['city'];
        $statee =  $address['state'];
	}else{
    	$namee = $rCheckout['b_FirstName']." ". $rCheckout['b_LastName'];
    	$addresss = $rCheckout['b_Address'];
    	$cityy = $rCheckout['b_City'];
    	$statee = $rCheckout['b_State'];
	}
	
	
	// the form
	?>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://js.stripe.com/v3/"></script>
 <!--   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">-->
	<!--<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"> -->
	<!--<link rel="stylesheet" href="//www.autoglasshosting.com/account/quote/ui-within.css">-->
	
	 <style>
        /* Basic styles for the Stripe Elements */
        .StripeElement {
            box-sizing: border-box;
            height: 40px;
            padding: 10px 12px;
            border: 1px solid #ccc;
            border-radius: 4px;
            background-color: white;
            font-size: 16px;
            transition: border-color 150ms ease;
        }
        .StripeElement--focus {
            border-color: #0070f3;
        }
        .StripeElement--invalid {
            border-color: #fa755a;
        }
        .StripeElement--webkit-autofill {
            background-color: #fefde5 !important;
        }
    </style>
    
        <script>
        
         function useExistingBillingInfo(checkbox) {
            // Get the billing fields
            const nameField = document.getElementById('fullname');
            const addressField = document.getElementById('address');
            const cityField = document.getElementById('city');
            const stateField = document.getElementById('state');
            
            if (checkbox.checked) {
                // Fill the fields with existing billing info
                nameField.value = "<?php echo $namee; ?>";
                addressField.value = "<?php echo $addresss; ?>";
                cityField.value = "<?php echo $cityy; ?>";
                stateField.value = "<?php echo $statee; ?>";
            } else {
                // Clear the fields if unchecked
                nameField.value = '';
                addressField.value = '';
                cityField.value = '';
                stateField.value = '';
            }
        }
        
        function validateCity(city) {
            return city.length > 0; // Must not be empty
        }
        
        function validateName(name) {
            return name.length > 0; // Must not be empty
        }
        
        function validateState(state) {
             return state.length > 0; // Must not be empty
        }
        
        function validateAddress(address) {
             return address.length > 0; // Must not be empty
        }
        
        $(document).ready(function() {
            // Initialize Stripe
           var stripe = Stripe('pk_live_Fly0vQ667Bb7vjemByz2KsI000Y6RTUcbK'); // Live public key
           // var stripe = Stripe('pk_test_k9ReEXFvtqFiNYWi49RFkIoS00LKRSmLP4'); // Sandbox key
            var elements = stripe.elements();

            // Create an instance of the card Element
            var card = elements.create('card');
            // Add an instance of the card Element into the `card-element` div
            card.mount('#card-element');
            
             // Real-time error handling
            card.on('change', function(event) {
                var errorElement = document.getElementById('payment-errors');
                if (event.error) {
                    // Display the error message
                    errorElement.textContent = event.error.message;
                } else {
                    // Clear the error message
                    errorElement.textContent = '';
                }
            });
            

            // Handle form submission
            $("#payment-form").submit(function(event) {
                event.preventDefault(); // Prevent default form submission
                const activeButton = document.activeElement; // Gets the currently focused button
                
                 // Get values
                const city = document.getElementById('city').value;
                const state = document.getElementById('state').value;
                const address = document.getElementById('address').value;
                const fullname = document.getElementById('fullname').value;
            
                // Clear previous error messages
                document.getElementById('city-error').textContent = '';
                document.getElementById('state-error').textContent = '';
                document.getElementById('address-error').textContent = '';
                document.getElementById('fullname-error').textContent = '';
                
                // Hide invalid-feedback elements
                document.getElementById('city-error').style.display = 'none';
                document.getElementById('state-error').style.display = 'none';
                document.getElementById('address-error').style.display = 'none';
                document.getElementById('fullname-error').style.display = 'none';
            
                // Validate fields
                let valid = true;
            
                if (!validateCity(city)) {
                    document.getElementById('city-error').textContent = 'City is required.';
                    document.getElementById('city-error').style.display = 'block'; // Show error message

                    valid = false;
                }
                
                if (!validateName(fullname)) {
                    document.getElementById('fullname-error').textContent = 'Name is required.';
                    document.getElementById('fullname-error').style.display = 'block'; // Show error message

                    valid = false;
                }
            
                if (!validateState(state)) {
                    document.getElementById('state-error').textContent = 'State is required.';
                    document.getElementById('state-error').style.display = 'block'; // Show error message

                    valid = false;
                }
            
                if (!validateAddress(address)) {
                    document.getElementById('address-error').textContent = 'Address is required.';
                    document.getElementById('address-error').style.display = 'block'; // Show error message

                    valid = false;
                }
            
                if (!valid) {
                    return; // Stop form submission if validation fails
                }
                
                $('#auth_type').val(activeButton.id)
                // Disable the submit button to prevent repeated clicks
                $('.payBtn').attr("disabled", true);
                
                const addresses = {
                    line1: document.getElementById('address').value,
                    city: document.getElementById('city').value,
                    state: document.getElementById('state').value,
                    country : 'US'
                };
                
                // Create a payment method with the card and billing details
               stripe.createPaymentMethod({
                    type: 'card',
                    card: card,
                    billing_details: {
                        address: addresses,
                    },
                }).then(function(result) {
                
                    if (result.error) {
                        // Show the error on the form
                        $('#payment-errors').text(result.error.message);
                        // Re-enable the submit button
                        $('.payBtn').attr("disabled", false);
                    } else {
                        // Insert the token into the form so it gets submitted to the server
                        $('#payment-form').append($('<input type="hidden" name="paymentMethodID" />').val(result.paymentMethod.id));
                        
                        // Submit the form
                         $('#payment-form').get(0).submit();
                    }
                
                });

                // Create a token using the card Element
                // stripe.createToken(card).then(function(result) {
                //     if (result.error) {
                //         // Show the error on the form
                //         $('#payment-errors').text(result.error.message);
                //         // Re-enable the submit button
                //          $('.payBtn').attr("disabled", false);

                //     } else {
                //         // Get the token from the result
                //         var token = result.token.id;

                //         // Insert the token into the form so it gets submitted to the server
                //         $('#payment-form').append($('<input type="hidden" name="stripeToken" />').val(token));
                //         // Submit the form
                //         $('#payment-form').get(0).submit();
                //     }
                // });

                return false;
            });
        });
    </script>
	
	<body bgcolor="#F8F8F8" text="#000088" VLINK="#ff0000">
	<blockquote>
		<h2 style="margin-bottom: 0.25em;">Authorization for Hand Ticket</h2>
		<h3 style="background: #F0FAFF; display: inline-block; padding: 4px 8px; border-radius: 2px;"><a href="<?= $PHP_SELF ?>?site=<?= $site ?>&A=S&invoiceID=<?= $InvID ?>&checkoutID=<?= $checkoutID ?>">Order # <?= $rInvoice['orderCode'].'-'.$rInvoice['orderNum'] ?></a></h3>
		<br>
		<form id="payment-form" action="<?= $PHP_SELF ?>" name="ChargeForm" method="POST">
			<input type="hidden" name="site" value="<?= $site ?>">
			<input type="hidden" name="A" value="HA-RUN-STRIPE">
			<input type="hidden" name="invoiceID" value="<?= $InvID ?>">
			<input type="hidden" name="TxNum_File" value="<?= $TxNum_Now ?>">
			<input type="hidden" name="auth_type" id="auth_type" value="">
			<input type="hidden" name="invoiceTotal" id="invoiceTotal" value="<?= $rCheckout['total'] ?>">
			
			<caption style="background: #F8F8F8; border: #C0C0C0 1px dotted; font-weight: bold;">
			    <br><span style="white-space: nowrap;">Enter Charge Information</span>
			    <br><span style='font-weight: normal; font-size: 0.85em; color: #808080;'>(Card will be saved. Transaction will be on file.)</span><br>&nbsp;
			 </caption>
		        <div id="card-element" class="StripeElement form-control" style="width:30%"></div>
                <div id="payment-errors" style="color: red;"></div>
                
                 <div id="row-3" class="row mt-1 mb-1">
                        <div class="col-sm-9 col-md-8 col-lg-9 text-left info-text" style="margin-top: 10px;font-size: medium;">
                           <u>Billing details:</u> 
                               <input type="checkbox" id="useExisting" onclick="useExistingBillingInfo(this)"> Use existing billing info
   
                        </div>
                    </div>
                    
                   <div id="row-3" class="row mt-1 mb-1">
                        
                        <div class="col-sm-12 col-md-12 col-lg-6 text-left info-text" style="margin: 10px;">
                            <div class="form-group">
                                <label for="fullname">Name</label>
                                <input type="text" class="form-control" id="fullname" name="fullname" value="" >
                                <div class="invalid-feedback" style="color: red;" id="fullname-error"></div>
                            </div>
                        </div>   
                       
                       <div class="col-sm-12 col-md-12 col-lg-6 text-left info-text" style="margin: 10px;">
                            <div class="form-group">
                                <label for="address">Address</label>
                                <input type="text" class="form-control" id="address" name="address" value="">
                                <div class="invalid-feedback" style="color: red;" id="address-error"></div>
                            </div>
                        </div>    
                        
                        <div class="col-sm-12 col-md-12 col-lg-3 text-left info-text" style="margin: 10px;">
                            <div class="form-group">
                                <label for="city">City</label>
                                <input type="text" class="form-control" id="city" name="city" value="">
                                <div class="invalid-feedback" style="color: red;" id="city-error"></div>
                            </div>
                        </div>
                        
                        <div class="col-sm-12 col-md-12 col-lg-3 text-left info-text" style="margin: 10px;">
                           <div class="form-group">
                                <label for="state">State</label>
                                	<select class="form-control input-sm" id="state" name="state" placeholder="billing state" style="width: 12em; min-width: 8em; max-width: 14em;">
    									<option value="">Select State</option>
    									<option value="AK" <?php echo ('AK' === $statee) ? 'selected' : ''; ?>>Alaska</option>
    									<option value="AL" <?php echo ('AL' === $statee) ? 'selected' : ''; ?>>Alabama</option>
    									<option value="AR" <?php echo ('AR' === $statee) ? 'selected' : ''; ?>>Arkansas</option>
    									<option value="AZ" <?php echo ('AZ' === $statee) ? 'selected' : ''; ?>>Arizona</option>
    									<option value="CA" <?php echo ('CA' === $statee) ? 'selected' : ''; ?>>California</option>
    									<option value="CO" <?php echo ('CO' === $statee) ? 'selected' : ''; ?>>Colorado</option>
    									<option value="CT" <?php echo ('CT' === $statee) ? 'selected' : ''; ?>>Connecticut</option>
    									<option value="DC" <?php echo ('DC' === $statee) ? 'selected' : ''; ?>>District of Columbia</option>
    									<option value="DE" <?php echo ('DE' === $statee) ? 'selected' : ''; ?>>Delaware</option>
    									<option value="FL" <?php echo ('FL' === $statee) ? 'selected' : ''; ?>>Florida</option>
    									<option value="GA" <?php echo ('GA' === $statee) ? 'selected' : ''; ?>>Georgia</option>
    									<option value="HI" <?php echo ('HI' === $statee) ? 'selected' : ''; ?>>Hawaii</option>
    									<option value="IA" <?php echo ('IA' === $statee) ? 'selected' : ''; ?>>Iowa</option>
    									<option value="ID" <?php echo ('ID' === $statee) ? 'selected' : ''; ?>>Idaho</option>
    									<option value="IL" <?php echo ('IL' === $statee) ? 'selected' : ''; ?>>Illinois</option>
    									<option value="IN" <?php echo ('IN' === $statee) ? 'selected' : ''; ?>>Indiana</option>
    									<option value="KS" <?php echo ('KS' === $statee) ? 'selected' : ''; ?>>Kansas</option>
    									<option value="KY" <?php echo ('KY' === $statee) ? 'selected' : ''; ?>>Kentucky</option>
    									<option value="LA" <?php echo ('LA' === $statee) ? 'selected' : ''; ?>>Louisiana</option>
    									<option value="MA" <?php echo ('MA' === $statee) ? 'selected' : ''; ?>>Massachusetts</option>
    									<option value="MD" <?php echo ('MD' === $statee) ? 'selected' : ''; ?>>Maryland</option>
    									<option value="ME" <?php echo ('ME' === $statee) ? 'selected' : ''; ?>>Maine</option>
    									<option value="MI" <?php echo ('MI' === $statee) ? 'selected' : ''; ?>>Michigan</option>
    									<option value="MN" <?php echo ('MN' === $statee) ? 'selected' : ''; ?>>Minnesota</option>
    									<option value="MO" <?php echo ('MO' === $statee) ? 'selected' : ''; ?>>Missouri</option>
    									<option value="MS" <?php echo ('MS' === $statee) ? 'selected' : ''; ?>>Mississippi</option>
    									<option value="MT" <?php echo ('MT' === $statee) ? 'selected' : ''; ?>>Montana</option>
    									<option value="NC" <?php echo ('NC' === $statee) ? 'selected' : ''; ?>>North Carolina</option>
    									<option value="ND" <?php echo ('ND' === $statee) ? 'selected' : ''; ?>>North Dakota</option>
    									<option value="NE" <?php echo ('NE' === $statee) ? 'selected' : ''; ?>>Nebraska</option>
    									<option value="NH" <?php echo ('NH' === $statee) ? 'selected' : ''; ?>>New Hampshire</option>
    									<option value="NJ" <?php echo ('NJ' === $statee) ? 'selected' : ''; ?>>New Jersey</option>
    									<option value="NM" <?php echo ('NM' === $statee) ? 'selected' : ''; ?>>New Mexico</option>
    									<option value="NV" <?php echo ('NV' === $statee) ? 'selected' : ''; ?>>Nevada</option>
    									<option value="NY" <?php echo ('NY' === $statee) ? 'selected' : ''; ?>>New York</option>
    									<option value="OH" <?php echo ('OH' === $statee) ? 'selected' : ''; ?>>Ohio</option>
    									<option value="OK" <?php echo ('OK' === $statee) ? 'selected' : ''; ?>>Oklahoma</option>
    									<option value="OR" <?php echo ('OR' === $statee) ? 'selected' : ''; ?>>Oregon</option>
    									<option value="PA" <?php echo ('PA' === $statee) ? 'selected' : ''; ?>>Pennsylvania</option>
    									<option value="PR" <?php echo ('PR' === $statee) ? 'selected' : ''; ?>>Puerto Rico</option>
    									<option value="RI" <?php echo ('RI' === $statee) ? 'selected' : ''; ?>>Rhode Island</option>
    									<option value="SC" <?php echo ('SC' === $statee) ? 'selected' : ''; ?>>South Carolina</option>
    									<option value="SD" <?php echo ('SD' === $statee) ? 'selected' : ''; ?>>South Dakota</option>
    									<option value="TN" <?php echo ('TN' === $statee) ? 'selected' : ''; ?>>Tennessee</option>
    									<option value="TX" <?php echo ('TX' === $statee) ? 'selected' : ''; ?>>Texas</option>
    									<option value="UT" <?php echo ('UT' === $statee) ? 'selected' : ''; ?>>Utah</option>
    									<option value="VA" <?php echo ('VA' === $statee) ? 'selected' : ''; ?>>Virginia</option>
    									<option value="VT" <?php echo ('VT' === $statee) ? 'selected' : ''; ?>>Vermont</option>
    									<option value="WA" <?php echo ('WA' === $statee) ? 'selected' : ''; ?>>Washington</option>
    									<option value="WI" <?php echo ('WI' === $statee) ? 'selected' : ''; ?>>Wisconsin</option>
    									<option value="WV" <?php echo ('WV' === $statee) ? 'selected' : ''; ?>>West Virginia</option>
    									<option value="WY" <?php echo ('WY' === $statee) ? 'selected' : ''; ?>>Wyoming</option>
    								</select>
    								<div class="invalid-feedback" style="color: red;" id="state-error"></div>
                            </div>
                        </div>
                        
                    </div>
		
	<?
	
// 	// only allow attempt if the order isn't missing info
// 	if( 
// 		$rCheckout['b_FirstName'] != ""
// 		&& $rCheckout['b_LastName'] != ""
// 		&& $rCheckout['b_Address'] != ""
// 		&& $rCheckout['b_City'] != ""
// 		&& $rCheckout['b_State'] != ""
// 		&& $rCheckout['b_Zip'] != ""
// 	) {
		?><p style=""><input type="submit" id="pre" class="button payBtn" style="padding: 0.5ex 1em; margin-top: 5px;" value="Run $0.50 Pre-Auth"></p>
		
		<p style=""><input type="submit" id="<?= $rCheckout['total'] ?>" class="button payBtn" style="padding: 0.5ex 1em; margin-top: 5px;" value="Run $<?= $rCheckout['total'] ?> Auth for Invoice Total"></p>
		
		<p style=""><input type="submit" id="penske" class="button payBtn" style="padding: 0.5ex 1em; margin-top: 5px;" value="Auth $<?= $rCheckout['total'] ?> for Invoice Total (Penske Only)"></p>

		<? echo "</form>&nbsp;\n";

	// more info
	$SQL = "SELECT ID, stamp, ip, total, source, archive, gatewayType, reqID, result, decision, avs, cvv, shortMsg FROM invoiceTransactions WHERE invoiceID=".$InvID;
	$oNRS = new nRS( $SQL );
	if( $oNRS->numRows > 0 ) {
		echo "<br><h2>Transactions</h2>\n";
		/*
		improvements:
			1. highlight the $LocalTransID (if>0)
			2. add the reasoncode overlay lookup thing, as well
		*/
		echo "<table border=0 bordercolor=black cellspacing=1 cellpadding=1 bgcolor=#808080>\n";
		echo "\t<tr bgcolor=\"#D8D8D8\">\n";
		$columns = array('ID','stamp','ip','total','source','archive','gatewayType','reqID','result','decision','avs','cvv','shortMsg');
		for( $i=0; $i<count($columns); $i++) {
			echo "\t\t<td nowrap><b>".$columns[$i]."</b></td>\n";
		}
		echo "\t</tr>\n";
		while( $rTrans = $oNRS->read() ) {
			echo "\t<tr bgcolor=\"".($rTrans['ID']==$LocalTransID ? ($rTrans['result']==100 ? "#D0FCD2" : "#FCD4D2") : "#F0F0F0")."\">\n";
			for( $i=0; $i<count($columns); $i++) {
				echo "\t\t<td nowrap>".htmlspecialchars($rTrans[$columns[$i]])."</td>\n";
			}
			echo "\t</tr>\n";
		}
		echo "</table>\n";
		//$oNRS->showData();
	}
	/*
	$oNRS = new nRS("SELECT refCode, ID, stamp, ip, source, gatewayType, invoiceTransactionID, decision, result, subID FROM invoiceSubscriptions WHERE invoiceID=".$InvID);
	if( $oNRS->numRows > 0 ) {
		echo "<br><h2>Subscriptions <span style=\"font-size: 0.8em; font-weight: normal; color: #C80000;\">&nbsp; (<u>Not</u> created at this stage.)</span></h2>\n";
		$oNRS->showData(false);
	}*/
	echo "</blockquote><p></p>&nbsp;";

} // HandAuthForm_Stripe()


//-------------------------------------------------------------------------
// HandPreauthorization:  Runs a manually-entered charge. (Does NOT save CC info.)
//-------------------------------------------------------------------------
function HandPreauthorization( $InvID ) {

	global $g_Config, $g_oNDB;
	
	// check that we're not re-posting a transaction
	$TxNum_File = isset($_POST['TxNum_File']) ? intval($_POST['TxNum_File']) : 0;
	$TxNum_Now = $g_oNDB->getField("SELECT Count(*) FROM invoiceTransactions WHERE invoiceID='".$InvID."'");
	if( $TxNum_Now > $TxNum_File ) {
		echo "<div class=\"message err\"><b>[Error]</b> Transaction already processed. Not repeating.<br>TRANSACTION CANCELLED. PAGE REFRESH BLOCKED.</div>\n";
		HandAuthForm( $InvID );
		return;
	}
	
	// run the charge attempt
	$transID = HandAuth_CyberSourceSOAP( $InvID );
	
	// display the result
	echo "<br><div class=\"bq\">\n";
	if( $transID < 1 ) {
		echo "<div class=\"message err\"><b>[Warning]</b> Transaction data save failure.</div>\n";
	} else {
		$rTrans = $g_oNDB->getRow("SELECT * FROM invoiceTransactions WHERE ID = ".$transID);
		if( !is_array($rTrans) || count($rTrans)<1 ) {
			echo "<div class=\"message err\"><b>[Warning]</b> Transaction log lookup failure.</div>\n";
		} elseif( intval($rTrans['result']) == 100 ) {
			echo "<div class=\"message ok\"><b>[Approved]</b> The authorization was successful. Details below.</div>\n";
			$g_oNDB->execute( "UPDATE invoice SET auth='Y', declined='N' WHERE ID=".$InvID );
		} else {
			echo "<div class=\"message err\"><b>[Error]</b> The transaction failed. See below or view the invoice page for details.";
			if( $rTrans['shortMsg'] != "" ) {
				echo "<br>(Message = \"" . $rTrans['shortMsg'].")\"";
			}
			echo "</div>\n";
			$rInfo = $g_oNDB->getRow("SELECT * FROM gatewayResult WHERE gatewaytype='CyberSourceSOAP' AND code = ".$rTrans['result']);
			echo "<div style=\"padding: 2px 4px; margin-top: 0.5em; color: #000; max-width: 50em; background: #FCD4D2;\"><b>".$rInfo['reply_flag'].":</b> ".$rInfo['description']."<br><span style=\"color: #A4A4A4;\">".$rInfo['info']."</span></div>\n";
		}
	}
	echo "</div>\n";
	
	/*
	MORE tasks...
		1. re-save the checkout billing info ?
		2. auto-mark the invoice as NOT "declined" when the auth was successful
	*/

	// done...
	HandAuthForm( $InvID, $transID );

} // HandPreauthorization()


function HandPreauthorization_stripe( $InvID ){
  
    global $g_Config, $g_oNDB;
	$configPath = '/home/auto11/var/config.php';
	$config = require $configPath;
	
	// Set your secret key. Remember to switch to your live secret key in production!
    $secretKey = $config['stripe_secret_key'];
    $apiUrl = 'https://api.stripe.com/v1';
    $paymentMethodID = $_POST['paymentMethodID'];
    
    $invoiceID = intval($g_oNDB->getField("SELECT ID FROM invoice WHERE ID='".$InvID."'"));
    $invoiceTransactions = $g_oNDB->getRow("SELECT * FROM invoiceTransactions where invoiceID='".$InvID."' and result='100' ");
    $rCheckout = $g_oNDB->getRow("SELECT invoice.orderCode, invoice.orderNum, checkout.* FROM invoice LEFT JOIN checkout ON invoice.checkoutID=checkout.ID WHERE invoice.ID=".$invoiceID);

	$merchantOrderRef = $rCheckout['orderCode'] . '-' . $rCheckout['orderNum'];
	
	if($_POST['auth_type']=='penske'){
	    
        $charge_total = $_POST['invoiceTotal'];
        
        $initialPaymentIntentData = [
            'amount' => $charge_total *100, // Amount in cents, // Amount in cents
            'currency' => 'usd',
            'customer' => 'cus_QzdlyhEcjVJEkT',
            'description' =>  $merchantOrderRef, // Add your description here\
            "capture_method" => "manual", //automatic and manual
            // "confirm" => true,
            'payment_method' => $paymentMethodID,
            // "payment_method_options" => [
            //     "card" => [
            //         "moto" => true //  for Mail Order/Telephone Order (MOTO) transactions in Stripe. This is typically used when the merchant enters card details on behalf of the customer
            //     ]
            // ],
            "payment_method_types" => ["card"],
            "receipt_email" => "sales@w2g.us",
            "statement_descriptor" => "Windshields To Go USA",
            "expand" => ["latest_charge"]
        ];
        
         $initialPaymentIntentResponse = curlRequest("{$apiUrl}/payment_intents", $initialPaymentIntentData, $secretKey);
         $initialPaymentIntent = json_decode($initialPaymentIntentResponse,true);
         
         if (isset($initialPaymentIntent['id'])) {
            $confirmData = [
                'payment_method' =>  $initialPaymentIntent['payment_method'], // Use the payment method ID
            ];
            
            $confirmResponse = curlRequest("{$apiUrl}/payment_intents/{$initialPaymentIntent['id']}/confirm", $confirmData, $secretKey);
            $confirmedPaymentIntent = json_decode($confirmResponse,true);
            if (isset($confirmedPaymentIntent['id'])) {
                $reqID = $confirmedPaymentIntent['id'];
                $shortMsg = $confirmedPaymentIntent['customer'];
                $token = $confirmedPaymentIntent['payment_method'];
                $reconciliation = '';
                $result = 100;
                $decision = "ACCEPT";
                $customer_id = $confirmedPaymentIntent['customer'];
                
                echo "<div class=\"message ok\"><b>[Approved]</b> The authorization was successful. Details below.</div>\n";
                
            }else{
                $reqID = $confirmedPaymentIntent['payment_intent']['id'];
                $shortMsg = $confirmedPaymentIntent['error']['message'];
                $token = '';
                $reconciliation = $confirmedPaymentIntent['error']['code'];
                $result = 101;
                $decision = "REJECT";
                $customer_id = '';
                
                echo "<div class=\"message err\"><b>[Error]</b>". $confirmedPaymentIntent['error']['message']."</div>\n";
            }     
                    
         }else{
            $reqID = $initialPaymentIntent['payment_intent']['id'];
            $shortMsg = $initialPaymentIntent['error']['message'];
            $token = '';
            $reconciliation = $initialPaymentIntent['error']['code'];
            $result = 101;
            $decision = "REJECT";
            $customer_id = '';
            
            echo "<div class=\"message err\"><b>[Error]</b>". $initialPaymentIntent['error']['message']."</div>\n";
         }
         
         // log this transaction
    	$sql = "INSERT INTO invoiceTransactions SET stamp=Now()";
    	$sql .= ", invoiceID='".$InvID."'";
    	$sql .= ", ip='".$_SERVER['REMOTE_ADDR']."'";
    	$sql .= ", total='".$charge_total."'";
    	$sql .= ", source='admin'";
    	$sql .= ", archive='new-auth'";
    	$sql .= ", result='".$result."'";
    	$sql .= ", reqID='".$reqID."'";
    	$sql .= ", avs='Y'";
    	$sql .= ", gatewayType='Stripe'";
    	$sql .= ", factor=''";
    	$sql .= ", shortMsg= '".str_replace("'", "", $shortMsg)."'";
    	$sql .= ", authCode=''";
    	$sql .= ", decision='".$decision."'";
    	$sql .= ", customer_id='".$customer_id."'";
    	$sql .= ", reconciliation='".$reconciliation."'";
    	$sql .= ", token='".$token."'";
    	
    	$g_oNDB->execute($sql);
             
         // done...
	    HandAuthForm_Stripe( $InvID);
    }else{
    
        if($_POST['auth_type']=='pre'){
            $charge_total = 0.5;
        }else{
            $charge_total = $_POST['auth_type'];
        }
        
    	// Step 1: Create a customer
        $customerData = [
            
            // 'payment_method' => $paymentMethodID,
            'email' => $rCheckout['s_Email'], // Customer's email
            'name' => $_POST['fullname'],
            // 'address' => [
            //      'line1' => $_POST['address'],
            //      'city' => $_POST['city'],
            //      'state' => $_POST['state']
            // ],
            // 'invoice_settings' => [
            //     'default_payment_method' => $paymentMethodID,
            // ],
        ];
        
        $customerResponse = curlRequest("{$apiUrl}/customers", $customerData, $secretKey);
        $customer = json_decode($customerResponse,true);
        
        if (isset($customer['id'])) {
            
             // Step 2: Attache payment method in customer
            $paymentMethodResponse = curlRequest("{$apiUrl}/payment_methods/{$paymentMethodID}/attach",['customer' => $customer['id']], $secretKey);
            $paymentMethods = json_decode($paymentMethodResponse,true);
            
            if (isset($paymentMethods['id'])) {
                // Step 3: Create an initial payment intent for a small amount (e.g., $0.50) with card token from the customer
                $initialPaymentIntentData = [
                    'amount' => $charge_total *100, // Amount in cents, // Amount in cents
                    'currency' => 'usd',
                    'customer' => $customer['id'],
                   // 'payment_method' => $customer['default_source'], // Use the customer's default card
                    'payment_method' => $paymentMethodID,
                    'capture_method' => 'manual', // Authorize only, do not capture
                    'description' =>  $merchantOrderRef, // Add your description here\
                ];
                
                $initialPaymentIntentResponse = curlRequest("{$apiUrl}/payment_intents", $initialPaymentIntentData, $secretKey);
                $initialPaymentIntent = json_decode($initialPaymentIntentResponse,true);
                
                if (isset($initialPaymentIntent['id'])) {
                    // Step 4: Confirm the payment intent
                    $confirmData = [
                        'payment_method' =>  $initialPaymentIntent['payment_method'], // Use the payment method ID
                    ];
                    
                    $confirmResponse = curlRequest("{$apiUrl}/payment_intents/{$initialPaymentIntent['id']}/confirm", $confirmData, $secretKey);
                    $confirmedPaymentIntent = json_decode($confirmResponse,true);
                    if (isset($confirmedPaymentIntent['id'])) {
                        $charge = $confirmedPaymentIntent['charges']['data'][0];
                        if ($charge['payment_method_details']['card']['checks']['address_postal_code_check'] === 'fail') {
                            $reqID = $confirmedPaymentIntent['id'];
                            $shortMsg = 'Payment succeeded, but the postal code verification failed. Please check the billing details.';
                            $token = $confirmedPaymentIntent['payment_method'];
                            $reconciliation = 'zipcode_fail';
                            $result = 101;
                            $decision = "ACCEPT";
                            $customer_id = $confirmedPaymentIntent['customer'];
                            
                            echo "<div class=\"message ok\"><b>[Approved]</b> The authorization was successful but the postal code verification failed. Details below.</div>\n";
                                
                        }else{
                            $reqID = $confirmedPaymentIntent['id'];
                            $shortMsg = $confirmedPaymentIntent['customer'];
                            $token = $confirmedPaymentIntent['payment_method'];
                            $reconciliation = '';
                            $result = 100;
                            $decision = "ACCEPT";
                            $customer_id = $confirmedPaymentIntent['customer'];
                            
                            echo "<div class=\"message ok\"><b>[Approved]</b> The authorization was successful. Details below.</div>\n";
                            
                        }
                        
                    }else{
                        $reqID = $confirmedPaymentIntent['payment_intent']['id'];
                        $shortMsg = $confirmedPaymentIntent['error']['message'];
                        $token = '';
                        $reconciliation = $confirmedPaymentIntent['error']['code'];
                        $result = 101;
                        $decision = "REJECT";
                        $customer_id = '';
                        
                        echo "<div class=\"message err\"><b>[Error]</b>". $confirmedPaymentIntent['error']['message']."</div>\n";
                    }
                    
                }else{
                    //echo "<font color=red> Auth Error: ".$initialPaymentIntent['error']['message']."</font>";
                    $reqID = '';
                    $shortMsg = $initialPaymentIntent['error']['message'];
                    $token = '';
                    $reconciliation = $initialPaymentIntent['error']['code'];
                    $result = 101;
                    $decision = "REJECT";
                    $customer_id = '';
                    
                    echo "<div class=\"message err\"><b>[Error]</b>". $initialPaymentIntent['error']['message']."</div>\n";
                }
            }else{
                $reqID = '';
                $shortMsg = $paymentMethods['error']['message'];
                $token = '';
                $reconciliation = $paymentMethods['error']['code'];
                $result = 101;
                $decision = "REJECT";
                $customer_id= '';
            }
        
        } else{
           // echo "<font color=red> Customer creating Error: ".$customer['error']['message']."</font>";
            $reqID = '';
            $shortMsg = $customer['error']['message'];
            $token = '';
            $reconciliation = $customer['error']['code'];
            $result = 101;
            $decision = "REJECT";
            $customer_id = '';
            
            echo "<div class=\"message err\"><b>[Error]</b>". $customer['error']['message']."</div>\n";
        }
        
        // log this transaction
    	$sql = "INSERT INTO invoiceTransactions SET stamp=Now()";
    	$sql .= ", invoiceID='".$InvID."'";
    	$sql .= ", ip='".$_SERVER['REMOTE_ADDR']."'";
    	$sql .= ", total='".$charge_total."'";
    	$sql .= ", source='admin'";
    	$sql .= ", archive='new-auth'";
    	$sql .= ", result='".$result."'";
    	$sql .= ", reqID='".$reqID."'";
    	$sql .= ", avs='Y'";
    	$sql .= ", gatewayType='Stripe'";
    	$sql .= ", factor=''";
    	$sql .= ", shortMsg= '".str_replace("'", "", $shortMsg)."'";
    	$sql .= ", authCode=''";
    	$sql .= ", decision='".$decision."'";
    	$sql .= ", customer_id='".$customer_id."'";
    	$sql .= ", reconciliation='".$reconciliation."'";
    	$sql .= ", token='".$token."'";
    	
    	$g_oNDB->execute($sql);
    	/*
    	MORE tasks...
    		1. re-save the checkout billing info ?
    		2. auto-mark the invoice as NOT "declined" when the auth was successful
    	*/
    
    	// done...
    	HandAuthForm_Stripe( $InvID);
    }    	
}


//-------------------------------------------------------------------------
// JumpToLoginInvoiceAdmin:  Jumps to the login link for an affiliate.
//-------------------------------------------------------------------------
function JumpToLoginInvoiceAdmin() {

	global $g_oNDB, $ID;
	
	$rInfo = $g_oNDB->getRow("SELECT aff, password FROM affiliate WHERE ID='".intval($ID)."'");
	//PrintArray($rData);
	header( "Location: https://www.autoglasshosting.com/account/management/invoices/?A=LI&U=" . urlencode($rInfo['aff']) . "&P=".urlencode($rInfo['password']) . "&g=R" );
	exit;

} // JumpToLoginInvoiceAdmin()


//-------------------------------------------------------------------------
// JumpLookupPhone:  
// Link (order): https://www.autoglasshosting.com/admin/invoices/invoices.php?A=JLP&S=%2B18057122887
// Link (shop): https://www.autoglasshosting.com/admin/invoices/invoices.php?A=JLP&S=%2B16618310100
//-------------------------------------------------------------------------
function JumpLookupPhone( $SearchPhone ) {

	global $g_oNDB;
	
	/* util:
		SELECT 
			invoice.affiliateID, affiliate.aff, affiliate.name, checkout.ID, s_Phone, b_Phone, invoice.ID 
		FROM 
			checkout 
			LEFT JOIN invoice on invoice.checkoutID = checkout.ID AND checkout.ID > 70000 
			LEFT JOIN affiliate on invoice.affiliateID = affiliate.id 
		ORDER BY checkout.id desc 
		LIMIT 500
	*/

	$url = "/admin/invoices/invoices.php?site=Windshieldstogo.com&A=SFR&field=s_Phone&jlp={:JLP:}&value=";
	if( strlen($SearchPhone) < 10 || strlen($SearchPhone)!=12 || substr($SearchPhone,0,2)!="+1" ) {
		header( "Location: ".str_replace("{:JLP:}","fail",$url).urlencode($SearchPhone) );
		exit;
	}
	
	/// see if there's an order on file...
	$phone = substr($SearchPhone, 2);
	$search = substr($phone,0,3)."[^[:digit:]]{0,2}".substr($phone,3,3)."[^[:digit:]]{0,1}".substr($phone,6,4);
	$sql = "
		SELECT Count(*) 
		FROM checkout LEFT JOIN invoice ON checkout.ID=invoice.checkoutID 
		WHERE 
			invoice.ID > 10000 
			AND invoice.affiliateID IN(156,134,135,136,141,162,163,168,164,167,173,182,272,249,225,227,266,274,275,308,321,329,331,332,333,364,365,368,0) 
			AND invoice.hidden='N' 
			AND (checkout.s_Phone REGEXP '".$search."' OR checkout.b_Phone REGEXP '".$search."') 
			ORDER BY invoice.blink DESC, invoice.waiting DESC, invoice.feedback DESC, purchaseDate DESC, invoice.ID DESC
	";
	$num = intval($g_oNDB->getField($sql));
	if( $num > 0 ) {
		header( "Location: ".str_replace("{:JLP:}","success",$url).urlencode($phone) );
		exit;
	}
	
	/// go to a shop search if there are results there...
	$sql = "
		SELECT Count(*)
		FROM location 
		WHERE 
			REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(fax,'-',''),'.',''),' ',''),'(',''),')','') LIKE '%8057122887%' 
			OR telephone REGEXP '".substr($phone,0,3)."[^[:digit:]]{0,2}".substr($phone,3,3)."[^[:digit:]]{0,1}".substr($phone,6,4)."'
	";
	$num = intval($g_oNDB->getField($sql));
	if( $num > 0 ) {
		header( "Location: /admin/invoices/installerWizard.php?jlp=success&zip=".urlencode($phone) );
		exit;
	}
	
	// default failover to a search (it can right-click to Google, as well)
	$lookupurl = "http://search.yahoo.com/search?p=";  // OLD: "http://www.freephonetracer.com/FCPT.aspx?_act=Free&_pho="
	header( "Location: " . $lookupurl . urlencode($phone) );
	exit;
	
} // JumpLookupPhone()


//-------------------------------------------------------------------------
// PhoneLookupFrames:  Spit out a frameset to do invoice and phone lookups.
//-------------------------------------------------------------------------
function PhoneLookupFrames( $SearchPhone ) {

	$SearchPhone = preg_replace("/[^0-9]/", "", $SearchPhone);
	if( substr($SearchPhone,0,1) == "1" ) {
		$SearchPhone = substr($SearchPhone, 1);
	}
	while( strlen($SearchPhone) < 10 ) {
		$SearchPhone .= '0';
	}
	$SearchPhone_Last4 = substr($SearchPhone, 6);
	$SearchPhone_Last7 = substr($SearchPhone, 4);
	$SearchPhone_NXX = substr($SearchPhone, 3, 3);
	$SearchPhone_AreaCode = substr($SearchPhone, 0, 3);
	
	?>
	<html>
		<head>
			<title>Invoice Manager - Phone Number Lookup</title>
		</head>
		<frameset cols=185,2,*  FRAMEBORDER="0" BORDER="0">
			<frame name="menu" src="menu.php">
			<frame name="border" src="../black.htm" bordercolor=#000000 noresize>
			<frameset cols="*, 2, 500"  FRAMEBORDER="0" BORDER="0">
				<frame name="border" src="invoices.php?A=JLP&S=<?= $SearchPhone ?>" bordercolor="#000000" marginwidth="10" marginheight="10">
				<frame name="border" src="../black.htm" bordercolor=#000000 noresize>
				<!--<frame name="border" src="https://www.intelius.com/results.php?ReportType=33&searchform=phone&qnpa=<?= $SearchPhone_AreaCode ?>&qnxx=<?= $SearchPhone_NXX ?>&qp=<?= $SearchPhone_Last7 ?>&qstation=<?= $SearchPhone_Last4 ?>" bordercolor="#000000" marginwidth="10" marginheight="10">-->
				<!--<frame name="border" src="https://www.411.com/reverse_phone/<?= $SearchPhone ?>" bordercolor="#000000" marginwidth="10" marginheight="10">-->
				<frame name="border" src="http://www.reversephonelookup.com/number/<?= $SearchPhone ?>" bordercolor="#000000" marginwidth="10" marginheight="10">

				<!--<frameset rows="600,2,600"  FRAMEBORDER="0" BORDER="0">-->
					<!--<frame name="border" src="http://www.igcall.net/located.php?num=<?= $SearchPhone ?>" bordercolor="#000000" marginwidth="10" marginheight="10">-->
					<frame name="border" src="http://www.reversephonelookup.com/number/<?= $SearchPhone ?>" bordercolor="#000000" marginwidth="10" marginheight="10">
					<frame name="border" src="../black.htm" bordercolor=#000000 noresize>
					<frame name="border" src="http://www.freephonetracer.com/FCPT.aspx?_act=Free&_pho=<?= $SearchPhone ?>" bordercolor="#000000" marginwidth="10" marginheight="10">
				<!--</frameset>-->
			</frameset>
		</frameset>
		<noframes></noframes>
	</html>
	<?

} // PhoneLookupFrames


//-------------------------------------------------------------------------
// SaveInvoice:  Saves changes to an item.
//-------------------------------------------------------------------------
function SaveInvoice( $invoiceID, $checkoutID) {

	global $g_Config, $g_oNDB, $hDB;
	$debug = false;
	
	/*******
	 * Start locking mechanism
	 * By Mukund
	 * On: 11/01/2024
	 */
	mysql_query( "UPDATE invoice SET is_locked='0',is_locked_by=0 where ID=$invoiceID", $hDB );
	//End
	
	$productID = getProductID($_POST['year'], $_POST['make'], $_POST['model'], $_POST['style'], $_POST['part']);

	// determine whether new invoice or update
	if( $checkoutID == 0 ) {
		$verb = "INSERT INTO ";
		$cartID = 0;
	} else {
		$verb = "UPDATE";
		$cartID = getCartIDfromCheckout( $checkoutID );
		$cartItemsID = getCartItemsID( $cartID );
	}
	// Cart Query, do first to key on cartID
	$cartSQL = $verb." cart SET ";

	// set a new random key if UPDATE	
	$cartSQL .= "subtotal = '".$_POST['subtotal']."', ";
	$cartSQL .= "zip = '".$_POST['s_Zip']."' ";
	if( $verb == "UPDATE" ) {
		$cartSQL .= " WHERE ID='".$cartID."'";
	} else {
		$cartSQL .= ", randomKey = '(obsolete)'";
	}
	
	/// run the query...
	$g_oNDB->execute( htmlspecialchars($cartSQL) );
	// deprecated: (if( $result ) echo "'cartID' successfully added/updated<br>\n";

	// Checkout Query
	if( $verb != "UPDATE" ) {
		$cartID = $g_oNDB->getLastInsertID( "cart" );
	}
	$checkoutSQL .= $verb." checkout SET ";
	if( $verb != "UPDATE" ) {
		$checkoutSQL .= "cartID = '".$cartID."', ";
	}
	
	/// pad single digit day with zero
	if( strlen($_POST[installDay]) == 1 ) {
		$installDay = "0" . $_POST[installDay];
	} else {
		$installDay = $_POST[installDay];
	}
	
	/// precalcs for california...
	if( strtoupper($_POST['s_State']) == "CA" ) {
		$tax = floatval($_POST['glassCost']) * 0.0775;  // (was 0.0775) before: changed to .0875 from .0725 after checkoutID=29291, invoiceID=29542
		$subtotal = floatval($_POST['total']) - $tax;
	} else {
		$subtotal = floatval($_POST['subtotal']);
		$tax = floatval($_POST['tax']);
	}

	/// safely escape all input...
	foreach($_POST as $key => $val) {
		$_POST[$key] = mysql_real_escape_string($_POST[$key]);
	}
        $_POST['b_SameAsShipping'] = (int)$_POST['b_SameAsShipping'];
	$_POST['shopLabor'] = (float)$_POST['shopLabor'];
	$_POST['glassCost'] = (float)$_POST['glassCost'];
	$_POST['warehouseID'] = (int)$_POST['warehouseID'];
	/// build the command string...
	$checkoutSQL .= "s_FirstName = '$_POST[s_FirstName]', ";
	$checkoutSQL .= "s_LastName = '$_POST[s_LastName]', ";
	$checkoutSQL .= "s_Email = '$_POST[s_Email]', ";
	$checkoutSQL .= "s_Company = '$_POST[s_Company]', ";
	$checkoutSQL .= "s_Address = '$_POST[s_Address]', ";
	$checkoutSQL .= "s_City = '$_POST[s_City]', ";
	$checkoutSQL .= "s_State = '$_POST[s_State]', ";
	$checkoutSQL .= "s_Zip = '$_POST[s_Zip]', ";
	$checkoutSQL .= "s_Phone = '$_POST[s_Phone]', ";
	$checkoutSQL .= "s_Fax = '$_POST[s_Fax]', ";
	$checkoutSQL .= "s_VIN = '$_POST[s_VIN]', ";
	$checkoutSQL .= "s_PO = '$_POST[s_PO]', ";
	$checkoutSQL .= "s_Odometer = '$_POST[s_Odometer]', ";
	$checkoutSQL .= "s_Unit = '$_POST[s_Unit]', ";
	$checkoutSQL .= "b_SameAsShipping = '$_POST[b_SameAsShipping]', ";
	$checkoutSQL .= "b_FirstName = '$_POST[b_FirstName]', ";
	$checkoutSQL .= "b_LastName = '$_POST[b_LastName]', ";
	$checkoutSQL .= "b_Email = '$_POST[b_Email]', ";
	$checkoutSQL .= "b_Company = '$_POST[b_Company]', ";
	$checkoutSQL .= "b_Address = '$_POST[b_Address]', ";
	$checkoutSQL .= "b_City = '$_POST[b_City]', ";
	$checkoutSQL .= "b_State = '$_POST[b_State]', ";
	$checkoutSQL .= "b_Zip = '$_POST[b_Zip]', ";
	$checkoutSQL .= "b_Phone = '$_POST[b_Phone]',  ";
	$checkoutSQL .= "c_type = '$_POST[c_type]',  ";
	$checkoutSQL .= "c_num = '$_POST[c_num]',  ";
	$checkoutSQL .= "c_expmonth = '$_POST[c_expmonth]',  ";
	$checkoutSQL .= "c_expyear = '$_POST[c_expyear]',  ";
	$checkoutSQL .= "c_cvv = '$_POST[c_cvv]',  ";
	$checkoutSQL .= "subtotal = '".$subtotal."',  ";
	$checkoutSQL .= "shipping = '$_POST[shipping]',  ";
	$checkoutSQL .= "tax = '".$tax."',  ";
	$checkoutSQL .= "total = '$_POST[total]',  ";
	$checkoutSQL .= "shopLabor = '$_POST[shopLabor]',  ";
	$checkoutSQL .= "glassCost = '$_POST[glassCost]',  ";
	$checkoutSQL .= "shipperNum = '$_POST[shipperNum]',  ";
	if( $_SESSION['ADMIN_LEVEL'] >= 3 ) {
		$checkoutSQL .= "profit = '$_POST[profit]',  ";
		$checkoutSQL .= "referrer = '$_POST[referrer]', ";
	}
	$checkoutSQL .= "serviceType = '$_POST[serviceType]', ";
	$checkoutSQL .= "paymentMethod = '$_POST[paymentMethod]', ";
	$checkoutSQL .= "i_Name = '$_POST[i_Name]', ";
	$checkoutSQL .= "i_Phone = '$_POST[i_Phone]', ";
	$checkoutSQL .= "i_Policy = '$_POST[i_Policy]', ";
	$checkoutSQL .= "i_Deductible = '$_POST[i_Deductible]', ";
	$checkoutSQL .= "shopComments = '$_POST[shopComments]', ";	
	$checkoutSQL .= "warehouseComments = '$_POST[warehouseComments]', ";
	$checkoutSQL .= "i_comments = '$_POST[i_comments]', ";
	$checkoutSQL .= "agreeLowPrice = '$_POST[agreeLowPrice]', ";
	$checkoutSQL .= "agreeFactors = '$_POST[agreeFactors]', ";
	$checkoutSQL .= "s_Warehouse = '$_POST[s_Warehouse]', ";
	$checkoutSQL .= "warehouseID = '$_POST[warehouseID]', ";
	$checkoutSQL .= "s_CrossStreet = '$_POST[s_CrossStreet]', ";
	$checkoutSQL .= "s_InstallDate = '$installDay". " " . "$_POST[installMonth] $_POST[installTime]', ";
	$checkoutSQL .= "s_InstallYear = '$_POST[s_InstallYear]', ";
	$checkoutSQL .= " installer = '$_POST[installer]', ";
	$checkoutSQL .= " installerID = '".intval($_POST['installerID'])."', ";
	$checkoutSQL = htmlspecialchars($checkoutSQL);
	$checkoutSQL .= "comments = '$_POST[comments]' ";

	// use WHERE clause to key on if UPDATE	
	if( $verb == "UPDATE" ) $checkoutSQL .= " WHERE ID=".$checkoutID;
	
	// execute checkoutSQL
	echo "<!--\n\n".$checkoutSQL."\n\n-->";
	$result = mysql_query( $checkoutSQL, $hDB ) or die(mysql_error() );
	
	/// initz...
	$_POST['inst'] == "Yes" ? $parameters = "inst" : $parameters = "";
	if( $_POST['hardware']=="molding" || $_POST['hardware']=="clips" ) $parameters = $_POST['hardware'];

	/// update the cartItems table...
	$cartItemsSQL .= $verb." cartItems SET ";
	if( $verb != "UPDATE" ) {
		$cartItemsSQL .= "cartID = $cartID, ";
	}
	$cartItemsSQL .= "productID = '".$productID."', ";
	$cartItemsSQL .= "quantity = '".$_POST[quantity]."', ";
	$cartItemsSQL .= "parameters = '".$parameters."', ";
	$cartItemsSQL .= "partDetails = '".$_POST[partDetails]."' ";
	if( $verb == "UPDATE" ) {
		$cartItemsSQL .= " WHERE cartID=".$cartID;
	}
	echo "<!--\n\n".$cartItemsSQL."\n\n-->";
	$result = mysql_query( htmlspecialchars($cartItemsSQL), $hDB ) or die(mysql_error() );
	if( $g_Config->isDev && $debug ) DumpInfo( $cartItemsSQL );
	if( $g_Config->isDev && $debug ) DumpInfo( htmlspecialchars($cartItemsSQL) );

	/// invoice query, only needed if new record
	if( $verb != "UPDATE" ) {
		$checkoutID = getCheckoutID($cartID);
		$invoiceSQL = $verb." invoice SET ";
		$invoiceSQL .= "cartID = $cartID, ";
		$invoiceSQL .= "checkoutID = $checkoutID, ";
		$invoiceSQL .= "purchaseDate = '" . date("Y-m-d  H:i:s") ."', ";
		$invoiceSQL .= "customerKey = '".GenerateCustomerKey()."', ";
		$invoiceSQL .= "isHandTicket = 'Y'";
		$result = mysql_query( htmlspecialchars($invoiceSQL), $hDB ) or die(mysql_error() );
		echo "<!--\n\n".$invoiceSQL."\n\n-->";
		if( $g_Config->isDev && $debug ) {
			DumpInfo( $invoiceSQL );
			DumpInfo( htmlspecialchars($invoiceSQL) );
		}
	}
	$invoiceID = getInvoiceID($checkoutID);
	
	/// get the order number...
	if( $verb != "UPDATE" ) {
		$ocode = "W2G";
		$onum = getNextOrderNum( $ocode, $invoiceID, 0/*minimum is auto-retrieved*/, true/*isW2G*/ );
	}

	/// now update the invoice record for those fields...
	$SQL = "UPDATE invoice SET ";
	if( $verb != "UPDATE" ) {
		$SQL .= "orderCode = '".addslashes($ocode)."', ";
		$SQL .= "orderNum = '".$onum."', ";
	}
	$SQL .= "referrerID='".($_POST['i_referrerID']=="(none)"?0:$_POST['i_referrerID'])."', ";
	$SQL .= "fulfilled='".($_POST['i_fulfilled']=="Y"?"Y":"N")."', ";
	$SQL .= "ready='".($_POST['i_ready']=="Y"?"Y":"N")."', ";
	$SQL .= "scheduled='".($_POST['i_scheduled']=="Y"?"Y":"N")."', ";
	$SQL .= "auth='".($_POST['i_auth']=="Y"?"Y":"N")."', ";
	$SQL .= "paid='".($_POST['i_paid']=="Y"?"Y":"N")."', ";
	$SQL .= "installerPaid='".($_POST['i_installerPaid']=="Y"?"Y":"N")."', ";
	$SQL .= "waitForCallback='".($_POST['i_waitForCallback']=="Y"?"Y":"N")."', ";
	$SQL .= "onHold='".($_POST['i_onHold']=="Y"?"Y":"N")."', ";
	$SQL .= "waiting='".($_POST['i_wait']=="Y"?"Y":"N")."', ";
	$SQL .= "notServiced='".($_POST['i_notServiced']=="Y"?"Y":"N")."', ";
	$SQL .= "cancelled='".($_POST['i_cancelled']=="Y"?"Y":"N")."', ";
	$SQL .= "declined='".($_POST['i_declined']=="Y"?"Y":"N")."', ";
	$SQL .= "fraudulent='".($_POST['i_fraudulent']=="Y"?"Y":"N")."', ";
	//$SQL .= "edited='".($_POST['i_edited']=="Y"?"Y":"N")."', ";
	$SQL .= "hidden='".($_POST['i_hidden']=="Y"?"Y":"N")."', ";
	//$SQL .= "feedback='".($_POST['i_feedback']=="Y"?"Y":"N")."', ";
	$SQL .= "blink='".($_POST['i_blink']=="Y"?"Y":"N")."' ";
	$SQL .= " WHERE ID=".$invoiceID;
	echo "<!--\n\ninvoice SQL:\n".$SQL."\n\n-->";
	mysql_query($SQL);  // printArray($_POST); echo mysql_error()."<br>".$SQL;
	if( $g_Config->isDev && $debug ) DumpInfo( $SQL );
	if( $g_Config->isDev && $debug ) DumpInfo( htmlspecialchars($SQL) );
	
	/// special event message that posts when their order is complete...
	if( $_POST['i_installerPaid']=="Y" && $_POST['i_installerPaid_old']=="N" ) {
		if( intval($g_oNDB->getField("SELECT Max(ID) FROM invoiceEvents WHERE invoiceID='".$invoiceID."' AND subject='Order Complete'")) < 1 ) {  // don't repost
			$msg = $g_oNDB->getField(0,"SELECT event FROM messagePrefill WHERE subject='Order Complete'","");
			$g_oNDB->execute("INSERT INTO invoiceEvents SET invoiceID='".$invoiceID."', stamp=Now(), postedBy='system', subject='Order Complete', event=".$g_oNDB->escape($msg).", isVisible='Y'");
		}
	}

	/*// sync with main DB if new entry
	if( false && $verb!="UPDATE" ) {
		$sync =  invoiceSync($cartSQL, $checkoutSQL, $cartItemsSQL, $invoiceSQL);
		echo $sync!="" ? "<b>data synchronization error" : "";
	}/**/

	/// all done...
	echo "<p>invoiceID # <b>".$invoiceID."</b> successfully " . ($verb == "UPDATE" ? "updated" : "added") . "<br><br>\n";
	if( $verb != "UPDATE" ) {
		HandAuthForm( $invoiceID );
	}
	ShowItem( $invoiceID, $checkoutID );

} // SaveInvoice()

//-------------------------------------------------------------------------
// CancelLock:  Cancel Lock
//-------------------------------------------------------------------------
function CancelLock($invoiceID,$checkoutID){
	global $hDB;
	mysql_query( "UPDATE invoice SET is_locked='0', is_locked_by='' where ID=$invoiceID", $hDB );
	echo "<p>invoiceID # <b>".$invoiceID."</b> successfully cancel locked.<br><br>\n";
	ShowItem( $invoiceID, $checkoutID );
}


//-------------------------------------------------------------------------
// DuplicateInvoice:  Copy that invoice to a new one.
//-------------------------------------------------------------------------
function DuplicateInvoice( $InvID ) {

	global $g_Config, $g_oNDB;
	global $PHP_SELF, $site;

	// verify
	$InvID = intval($InvID);
	if( $InvID < 1 ) {
		exit( "Invoice not specified." );
		return;
	}
	
	// load
	$rInvoice = $g_oNDB->getRow( "SELECT * FROM `invoice` WHERE ID=".$InvID );
	if( !isset($rInvoice) || !is_array($rInvoice) || intval($rInvoice['ID']) != $InvID ) {
		exit( "Unable to find that invoice. (".$InvID.")" );
		return;
	}
	$rCartItem = $g_oNDB->getRow( "SELECT ID, productID FROM `cartItems` WHERE cartID=".intval($rInvoice['cartID'])." ORDER BY ID DESC LIMIT 1" );
	if( !isset($rCartItem) || !is_array($rCartItem) || intval($rCartItem['ID']) < 1 ) {
		exit( "Unable to find a product in the cart for that invoice. (".$rInvoice['cartID'].")" );
		return;
	}
	$rProduct = $g_oNDB->getRow( "SELECT ID FROM `product` WHERE ID=".intval($rCartItem['productID']) );
	if( !isset($rProduct) || !is_array($rProduct) || intval($rProduct['ID']) != $rCartItem['productID'] ) {
		exit( "Unable to load the product info from that invoice. (".$rCartItem['productID'].")" );
		return;
	}
	$rCheckout = $g_oNDB->getRow( "SELECT ID FROM `checkout` WHERE ID=".intval($rInvoice['checkoutID']) );
	if( !isset($rCheckout) || !is_array($rCheckout) || intval($rCheckout['ID']) != $rInvoice['checkoutID'] ) {
		exit( "Unable to load the checkout info from that invoice. (".$rCartItem['productID'].")" );
		return;
	}
	
	// duplicate everything from the ground up
	
	// cart	
	$sql = "INSERT INTO `cart`(stamp, randomKey, subtotal, ZIP, IP, session, nsLogID) ";
	$sql .= "SELECT Now(), '[duplicated]', subtotal, ZIP, IP, Concat('ref: ',ID), 0 FROM `cart` WHERE ID = ".$rInvoice['cartID'];
	$g_oNDB->execute( $sql );
	$dupe_cartID = $g_oNDB->getLastInsertID("cart");
	if( intval($dupe_cartID) < 1 ) {
		exit( "There has been an error with copying the cart." );
		return;
	}
	
	// item
	$sql = "INSERT INTO `cartItems`(cartID, productID, distributorID, itemPrice, quantity, parameters, partDetails, partnerGlassPayment, partnerLaborPayment) ";
	$sql .= "SELECT ".$dupe_cartID.", productID, distributorID, itemPrice, quantity, parameters, partDetails, partnerGlassPayment, partnerLaborPayment FROM `cartItems` WHERE ID = ".$rCartItem['ID'];
	$g_oNDB->execute( $sql );
	
	// checkout (non-ideal, ignored existing i_comments due to null issue when using concat)
	$sql = "INSERT INTO `checkout`(cartID, i_comments, s_Method, s_FirstName, s_LastName, s_Email, s_Company, s_Address, s_City, s_State, s_Country, s_Zip, s_Phone, s_Fax, s_VIN, s_Unit, b_SameAsShipping, b_FirstName, b_LastName, b_Email, b_Company, b_Address, b_City, b_State, b_Country, b_Zip, b_Phone, c_type, subtotal, shipping, tax, tax_old, discountCode, total, shopLabor, glassCost, profit, shipperNum, serviceType, paymentMethod, i_Name, i_Phone, i_Policy, i_Deductible, comments, shopComments, warehouseComments, referrer, agreeLowPrice, agreeFactors, shipWindshields, s_Warehouse, warehouseID, s_CrossStreet, s_InstallDate, invoiceID, s_InstallYear, installer, installerID) ";
	$sql .= "SELECT ".$dupe_cartID.", Concat(Date_Format(Now(), '[%Y-%m-%d]'), ' duplicated from #: ".$rInvoice['orderCode'].'-'.$rInvoice['orderNum']."\n') as `i_comments`, s_Method, s_FirstName, s_LastName, s_Email, s_Company, s_Address, s_City, s_State, s_Country, s_Zip, s_Phone, s_Fax, s_VIN, s_Unit, b_SameAsShipping, b_FirstName, b_LastName, b_Email, b_Company, b_Address, b_City, b_State, b_Country, b_Zip, b_Phone, c_type, subtotal, shipping, tax, tax_old, discountCode, total, shopLabor, glassCost, profit, shipperNum, serviceType, paymentMethod, i_Name, i_Phone, i_Policy, i_Deductible, comments, shopComments, warehouseComments, referrer, agreeLowPrice, agreeFactors, shipWindshields, s_Warehouse, warehouseID, s_CrossStreet, s_InstallDate, invoiceID, s_InstallYear, installer, installerID FROM `checkout` WHERE ID = ".$rInvoice['checkoutID'];
	$g_oNDB->execute( $sql );
	//echo $sql;
	$dupe_checkoutID = $g_oNDB->getLastInsertID("checkout");
	if( intval($dupe_checkoutID) < 1 ) {
		exit( "There has been an error with copying the checkout information." );
		return;
	}
	
	// pre-gen the order#
	$minOrderNum = intval($g_oNDB->getField("SELECT orderNumMin FROM affiliate WHERE ID=".(intval($rInvoice['affiliateID']) == 0 ? 108 : $rInvoice['affiliateID'] )));
	$newOrderNum = getNextOrderNum2b( $rInvoice['orderCode'], 0, $minOrderNum, intval($rInvoice['affiliateID']) == 0 );
	if( $newOrderNum < 0 ) {
		exit( "Could not generate a new order #, but the new checkout # ".$dupe_checkoutID." info should be on file." );
	}

	// invoice
	$sql = "INSERT INTO `invoice`(checkoutID, cartID, purchaseDate, isHandTicket, orderNum, orderCode, affiliateID, referrerID, customerKey, partnerID, partnerAnswer, randomCodeFull, randomCodeLabor, randomCodeDecline, installDate, paid, installerPaid, waitForCallback, declined, fulfilled, scheduled, auth, ready, onHold, waiting, notServiced, hidden, blink) ";
	$sql .= "SELECT ".$dupe_checkoutID.", ".$dupe_cartID.", Now(), 'Y', ".$newOrderNum.", orderCode, affiliateID, referrerID, customerKey, partnerID, partnerAnswer, randomCodeFull, randomCodeLabor, randomCodeDecline, installDate, paid, installerPaid, waitForCallback, declined, fulfilled, scheduled, auth, ready, onHold, waiting, notServiced, hidden, blink FROM `invoice` WHERE ID = ".$rInvoice['ID'];
	$g_oNDB->execute( $sql );
	$dupe_invoiceID = $g_oNDB->getLastInsertID("invoice");
	if( intval($dupe_invoiceID) < 1 ) {
		exit( "There has been an error with finalizing the copy of that invoice, but checkout ID # ".$dupe_checkoutID." should be on file." );
		return;
	}
	
	// done
	EditInvoice( $dupe_invoiceID, $dupe_checkoutID, "&raquo; Invoice duplicated!" );
	exit();
	return;

} // DuplicateInvoice()


///-------------------------------------------------------------------------
function getNextOrderNum2b( $ocode, $invoiceID=0, $minNum, $is_w2g ) {

	global $g_oNDB;
	
	/// get the next order number for this affiliate's code...
	$orderCode = $g_oNDB->escape($ocode);  // so the aff code will include 'tick' delimiters!
	if( $is_w2g ) {
		$minimum = intval(GetSetting("w2g_orderNumMin", 0, 0, 'master'));
	} else {
		$minimum = intval($minNum)>0 ? $minNum : 1;
	}
	$g_oNDB->execute( "INSERT INTO orderNums(stamp,refID,code,num) SELECT Now(), '0', ".$orderCode.", IF(Max(num)+1 > $minimum, Max(num)+1, $minimum) FROM orderNums WHERE code=".$orderCode );
	$orderNum = $g_oNDB->getField( 'num', "SELECT num FROM orderNums WHERE ID='".$g_oNDB->getLastInsertID()."'", -1 );

	/// returned an error...
	if( $orderNum < 0 ) {
		$g_oNDB->execute( "INSERT INTO `log` SET stamp=Now(), type='checkout-NextNum', event=".$g_oNDB->escape("Could not generate an order number for invoice: ".$invoiceID) );
		$orderNum = 0;
	}
	return $orderNum;
	
} // getNextOrderNum()


//-------------------------------------------------------------------------
// emailCustomer: 
//-------------------------------------------------------------------------
function emailCustomer( $invoiceID, $checkoutID ) {

	exit("emailCustomer() is DEPRECATED and is no longer functional; please use the printInvoice.php::EMAIL capture method");
	
	global $g_Config, $hDB, $site;
	$g_Config->settings['w2g_statusIntro'] = GetSetting("w2g_statusIntro");
	$g_Config->settings['w2g_guarantee'] = GetSetting("w2g_guarantee");
	
	$SQL = "SELECT c.s_Email, c.b_Email, c.b_FirstName, c.s_FirstName, c.b_LastName, c.s_LastName, i.ID, i.customerKey, i.orderNum, c.ID FROM invoice i, checkout c WHERE i.ID=" . $invoiceID . " AND i.checkoutID=" .  $checkoutID . " AND c.ID=" . $checkoutID;  // echo $SQL."<br>\n";
	$res = mysql_query( $SQL );
	$e = mysql_fetch_object( $res );
	$oMail = new Mail; // create the mail
	$email = "sales@windshieldstogo.com";
	$oMail->From( "$email" );
	if( $e->s_Email == $e->b_Email && !empty($e->b_Email) ) {
		$oMail->To( "$e->b_Email" );  // $oMail->To( "support@ilocke.com" );
	} else {
		if( empty($e->b_Email) ) {
			$oMail->To( "$e->s_Email" );  // $oMail->To( "support@ilocke.com" );
		} elseif( empty($e->s_Email) ) {
			$oMail->To( "$e->b_Email" );  // $oMail->Bcc( "support@ilocke.com" );
		} else {
			echo "No Email Address!";
		}
	}
	echo "<H1><a href='javascript: history.back();'>Back</a></H1>";

	// make fulfilled yes for this invoice if customer print view
	$hDB = dbConnect($_GET['site']);
	makeFulfilled($invoiceID);
	$message = "";			
	$message .= "<html><head><title>Printable Invoice</title></head>\n<body bgcolor='#ffffff' onload='window.focus();' >";
	// If you need to make any scheduling changes, your local shop's information is listed below (See Glass Installer).
	$message .= "<table width=600 border=0><tr><td><div align=left><font size=3><b>Thank you for your order your!</b></font><br>\n";
	$message .= "Your appointment has been sceduled. You can now view the status of your order online at any time. You can also send us a question or comment about your order.<br>\n";
	$message .= "<a href=\"http://www.windshieldstogo.com/status/\"><font size=3><b><u><nobr>http://www.windshieldstogo.com/status/</nobr></u></b></a></font	><br>\n";
	$message .= "You will be granted access by entering your Order Number and Customer Key.<br>\n";
	$message .= "Your <u>Order Number</u> is:&nbsp; <b>".$e->orderNum."</b><br>\n";
	$message .= "Your <u>	Customer Key</u> is:&nbsp; <b>".$e->customerKey."</b><br>\n";
	$message .= "<br>&nbsp;</div>\n</td></tr></table>\n";
	$message .= "<table cellpadding=0 cellspacing=0 border=0 width=600><tr valign=top><td><b>Windshields To Go USA</b><br>PO Box 3765<br>Santa Barbara CA 93130<br>Toll-Free: (800) 549-4470</td><td style='text-align: right;' align=right>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font face=verdana size=4><b>Order # " . $e->orderNum . "</font></b></td></tr></table>";
	$message .= "<br><p>";

	/// get the info...
	$SQL = "SELECT * FROM checkout WHERE ID=$checkoutID";
	$hCheckout = mysql_query($SQL , $hDB);
	if( !$hCheckout ) {
		?><script>alert("ERROR: There is no invoice with that number!");</script><?
	}

	$rCheckout = mysql_fetch_array($hCheckout,  MYSQL_ASSOC) or die("<blockquote><b>Invoice not found</b></blockquote>");
	$cartID = $rCheckout['cartID'];
	$hCartItems = mysql_query( "SELECT quantity,productID,parameters,part,moldingPart,year,make,model,style,price,installPrice, partDetails FROM cartItems LEFT JOIN product ON cartItems.productID=product.ID WHERE cartID=$cartID", $hDB);
	$rCartItem = mysql_fetch_array($hCartItems, MYSQL_ASSOC) or die("<blockquote><b>Invoice not found</b></blockquote>");

	/// check if installed
	if( $rCartItem['parameters'] == "inst" ) {
		$inst = "Yes";
		$hardware = "N/A";
	} else {
		$inst = "No";
		$hardware = $rCartItem['parameters']!="" ? $rCartItem['parameters'] : "none";
	}

	/// format date and time
	$date = preg_replace("/\s+/", " ", $rCheckout['s_InstallDate']);
	list($installDay,$installMonth,$installTime)= split (" ", $date, 3);
	if( !$installDay ) {  // null out bad dates
		$installTime = "";
		$installMonth = "";
		$installDay = "";
	}
	if( $rCheckout['i_Deductible'] != "" ) $deductible = '\$' . $rCheckout['i_Deductible'];  // only show dollar sign if deductible present

	// add the $rCheckout['installer'] informatino into the email

	/// show the data...
	$message .= "<table cellpadding=0 cellspacing=0 border=0 bordercolor=green width=600><tr valign=top>
		<td valign=top zstyle='border: #FF0000 1px dotted;'><table cellpadding=0 cellspacing=0 border=0 bordercolor=red width=300>
		<tr bgcolor='#E0E0E0' align=center><td colspan=2 style='padding: 5px;' zstyle='border: #00C000 1px dotted;'><b>Customer Information</b></td></tr>
		<tr valign=top><td style='text-align: right;' align=right><b>Name:&nbsp;<br>&nbsp;Address:</b>&nbsp;</td>
		<td width = 200".$rCheckout['s_FirstName']."&nbsp;".$rCheckout['s_LastName']."<br>".$rCheckout['s_Address']."<br>".$rCheckout['s_City'].",&nbsp;".$rCheckout['s_State']."&nbsp;&nbsp;&nbsp;".$rCheckout['s_Zip']."&nbsp;</td></tr>
		<tr><td height=2 colspan=2><spacer type=block width=1 height=1></td></tr>
		<tr><td style='text-align: right;' align=right><b>Email:</b>&nbsp;</td><td>" . $rCheckout['s_Email'] . "&nbsp;</td></tr>
		<tr><td style='text-align: right;' align=right><b>&nbsp;Company:</b>&nbsp;</td><td>" . $rCheckout['s_Company'] . "&nbsp;</td></tr>
		<tr><td style='text-align: right;' align=right><b>Phone:</b>&nbsp;</td><td>" . $rCheckout['s_Phone'] . "&nbsp;</td></tr>
		<tr><td style='text-align: right;' align=right><b>Fax:</b>&nbsp;</td><td>" . $rCheckout['s_Fax'] . "&nbsp;</td></tr>
		<tr><td height=4 colspan=2><spacer type=block width=1 height=1></td></tr>
		<tr><td style='text-align: right;' align=right nowrap><b>&nbsp;Cross Street:</b>&nbsp;</td><td>" . $rCheckout['s_CrossStreet'] . "&nbsp;</td></tr>
		<tr><td height=4 colspan=2><spacer type=block width=1 height=1></td></tr>
		<tr><td nowrap align=right><b>&nbsp;Requested Date:</b>&nbsp;</td><td>" . $installMonth . "&nbsp;" . $installDay . "&nbsp;" . $rCheckout['s_InstallYear'] . "</td></tr>
		<tr><td nowrap align=right><b>&nbsp;Requested Time:</b>&nbsp;</td><td>" . $installTime . "</td></tr></table></td>
	";
	$message .= "
		<td width=4>&nbsp;</td><td><table cellpadding=0 cellspacing=0 border=0 width=300><tr bgcolor='#E0E0E0' align=center><td colspan=2 style='padding: 5px;'><b>Billing Information</b></td></tr>
		 <tr valign=top><td style='text-align: right;' align=right><b>Name:&nbsp;<br>Address:</b>&nbsp;</td><td width = 200>" . $rCheckout['b_FirstName'] . "&nbsp;" . $rCheckout['b_LastName'] . "<br>" . $rCheckout['b_Address'] . "<br>" . $rCheckout['b_City'] . ",&nbsp;" . $rCheckout['b_State'] . "&nbsp;&nbsp;&nbsp;" . $rCheckout['b_Zip'] . "</td></tr>
		 <tr><td height=10 colspan=2><spacer type=block width=1 height=1></td></tr>
		 <tr><td style='text-align: right;' align=right><b>Email:</b>&nbsp;</td><td>" . $rCheckout['b_Email'] . "&nbsp;</td></tr>
		 <tr><td style='text-align: right;' align=right><b>&nbsp;Company:</b>&nbsp;</td><td>" . $rCheckout['b_Company'] . "&nbsp;</td></tr>
		 <tr><td style='text-align: right;' align=right><b>Phone:</b>&nbsp;</td><td>" . $rCheckout['b_Phone'] . "&nbsp;</td></tr>
		 <tr><td height=10 colspan=2><spacer type=block width=1 height=1></td></tr>
		 <tr><td style='text-align: right;' align=right nowrap><b>&nbsp;Payment:</b>&nbsp;</td><td>" . $rCheckout['c_type'] . "&nbsp;</tr>
		 <tr><td style='text-align: right;' align=right><b>Expires:</b>&nbsp;</td><td>" . $rCheckout['c_expmonth'] . "/" . $rCheckout['c_expyear'] . "&nbsp;</td></tr>
		 <tr><td height=28 colspan=2><spacer type=block width=1 height=1></td></tr>
		 </table></td>
	";
	$message .= "
			</tr>
			<tr><td height=4><spacer type=block width=1 height=1></td></tr>
			<td valign=top colspan=3 align=center>
			<table cellpadding=0 cellspacing=0 border=0 width=600>
			<tr bgcolor='#E0E0E0'><td colspan=5 align=center style='padding: 5px;'><b>Order Summary</b></td></tr>
			<tr><td style='text-align: right;' align=right width=150><b>Year:</b>&nbsp;</td><td width=150>" . $rCartItem['year'] . "&nbsp;</td><td rowspan=7 width=8><spacer type=block width=1 height=1></td><td style='text-align: right;' align=right><b>Model:</b>&nbsp;</td><td>" . $rCartItem['model'] . "&nbsp;</td></tr>
			<tr><td style='text-align: right;' align=right><b>Make:</b>&nbsp;</td><td>" . $rCartItem['make'] . "&nbsp;</td><td style='text-align: right;' align=right><b>Style:</b>&nbsp;</td><td>" . $rCartItem['style'] . "&nbsp;</td></tr>
			<tr><td height=20 colspan=5><spacer type=block width=1 height=1></td></tr>
			<tr><td style='text-align: right;' align=right><b>Installed:</b>&nbsp;<br><b>Hardware:</b>&nbsp;</td><td>" . $inst . "&nbsp;<br>".$hardware."</td><td style='text-align: right;' align=right><b>Part:</b>&nbsp;</td><td>" . $rCartItem['part'] . "&nbsp;&nbsp;</td><tr>
			<tr style='text-align: right;'><td style='text-align: right;' align=right><b>Quantity:</b>&nbsp;</td><td colspan=2>" . $rCartItem['quantity'] . "</td><td style='text-align: right;' align=right><b>Details:&nbsp;</b></td><td width=150>" . $rCartItem['partDetails'] . "&nbsp;&nbsp;</td></tr>
			<tr><td height=20 colspan=5><spacer type=block width=1 height=1></td></tr>
			<tr class=right align=right><td colspan=2 class=right align=right><b>Subtotal:</b>&nbsp;&nbsp;</td><td>$" . $rCheckout['subtotal'] . "&nbsp;</td><td rowspan=2 colspan=2>&nbsp;</td></tr>
			<tr class=right align=right><td colspan=2 class=right align=right><b>Shipping:</b>&nbsp;&nbsp;</td><td>$" . $rCheckout['shipping'] . "&nbsp;</td></tr>
			<tr class=right align=right><td colspan=2 class=right align=right><b>Total:</b>&nbsp;&nbsp;</td><td>$" . $rCheckout['total'] . "&nbsp;</td><td colspan=2 align=left><font size=-2 face=verdana>(includes any discounts)</td></tr>
			<tr><td height=16 colspan=5><spacer type=block width=1 height=1></td></tr>
	";
	//$message .=	"<tr valign=top><td style='text-align: right;' align=right><b>&nbsp;Glass Installer:&nbsp;</td><td colspan=4>" . $rCheckout['installer'] . "&nbsp;</td></tr>";
	$message .=	"<tr valign=top><td style='text-align: right;' align=right><b>&nbsp;Comments:&nbsp;</td><td colspan=4>" . $rCheckout['comments'] . "&nbsp;</td></tr>
			</table></td></tr><tr><td height=40><spacer type=block width=1 height=40></td></tr>
			<tr><td colspan=3>I HEREBY AUTHORIZE the above repair work to be done along with the necessary material.</td></tr>
			<tr><td colspan=3>SIGNATURE_____________________&nbsp;&nbsp;&nbsp;VIN______________&nbsp;&nbsp;&nbsp;LIC_______&nbsp;&nbsp;&nbsp;Miles_______<p>
				CONDITION OF SALE: I authorize my insurance company to pay the company named
				above. I authorize the above named company to endorse my signature on any
				insurance checks or drafts issued for glass replacement.  A FINANCE CHARGE
				of 1.5% per month or 18% annual may be added to all past-due accounts.  If
				collection is made, by suit or otherwise, I agree to pay interest at the
				above rate until the amount due is paid; also collection costs including
				reasonable attorney's fees, legal and administrative expenses.  
				<br><p>CUSTOMER SIGNATURE: ___________________________________________________
		<p></td></tr>
		<tr><td colspan=3><font face=verdana size=-2><b>Our Guarantee:</b><br><center><font face=arial size=-2>".$g_Config->settings['w2g_guarantee']."</font></center></td></tr>
	";
	// old, hard-coded guarantee: We guarantee our installation and the glass against any manufacturer's defects for as long as you own the vehicle. Rust or body damage VOID this guarantee.
	$message .=	"</table>";

	/// all done...
	$oMail->Subject( "Schedule Confirmation :: " . $site );	
	$oMail->isMIME( true );  // send in html format
	$oMail->Body( $message);  // set the body
	//$oMail->Priority(4);  // set the priority to Low ??
	$oMail->Send();  // send the mail
	echo "The schedule confirmation mail below has been sent:<br><pre>", $oMail->Get(), "</pre>";

} // emailCustomer()


///-------------------------------------------------------------------------
function ClearOldCCs() {

	global $g_Config, $g_oNDB, $PHP_SELF, $conf;

	/// be sure...
	$DaysOld = 30;
	if( $conf != "Y" ) {
		if( $conf=="N" ) exit ("Request cancelled.");
		echo "Really dump out credit card information for ALL orders more than ".$DaysOld." days old ??!<br>";
		echo "<a style='color: red; font-weight: bold;' href='".$PHP_SELF."?A=COCC&conf=N'>No</a> &nbsp;&nbsp;&middot;&nbsp;&nbsp; <a style='color: #009800;' href='".$PHP_SELF."?A=COCC&conf=Y'>YES</a><br>";
		exit;
	}
	
	/// clear out old numbers from the main database...
	$ID_SQL = "SELECT Max(checkoutID) FROM invoice WHERE purchaseDate < Date_Sub(Now(), INTERVAL ".($DaysOld+1)." DAY)";
	$cutoffID = intval($g_oNDB->getField($ID_SQL));
	$SQL = "UPDATE checkout SET c_num = ConCat('XX-',Right(c_num, 4)) WHERE ID < ".$cutoffID." AND Length(c_num) > 6 AND c_num NOT LIKE 'X%'";
	//echo $SQL;
	$g_oNDB->execute($SQL);
	$invID = $g_oNDB->getField("SELECT ID FROM invoice WHERE checkoutID=".$cutoffID);
	echo "<p>&gt;&gt; Credit card info in the main db has been abridged for all invoices before # ".$invID."<br>";
	
	/// and the c_cvv...
	$SQL = "UPDATE checkout SET c_cvv='' WHERE ID < ".$cutoffID;
	$g_oNDB->execute($SQL);
	echo "<p>&gt;&gt; CVV info in the main db has been removed for all invoices before # ".$invID."<br>";

	/// clear out old numbers from the backup database...
	$Backup_oNDB = new nDB( $g_Config->dbInfoI['database'], $g_Config->dbInfoI['user'], $g_Config->dbInfoI['password'], $g_Config->dbInfoI['server'], $NDB_Debugging );
	$cutoffID = intval($Backup_oNDB->getField($ID_SQL));
	$SQL = "UPDATE checkout SET c_num = ConCat('XX-',Right(c_num, 4)) WHERE ID < ".$cutoffID." AND Length(c_num) > 6 AND c_num NOT LIKE 'X%'";
	//echo $SQL."<br>\n";
	$Backup_oNDB->execute($SQL);
	$invID = $g_oNDB->getField("SELECT ID FROM invoice WHERE checkoutID=".$cutoffID);
	echo "<p>&gt;&gt; Credit card info in the backup db has been abridged for all invoices before # ".$invID."<br>";
	
	/// and the c_cvv...
	$SQL = "UPDATE checkout SET c_cvv='' WHERE ID < ".$cutoffID;
	//echo $SQL."<br>\n";
	$Backup_oNDB->execute($SQL);
	echo "<p>&gt;&gt; CVV info in the backup db has been removed for all invoices before # ".$invID."<br>";

	echo "<p>...done";


} // ClearOldCCs()


///-------------------------------------------------------------------------
function clean_phone( $phone ) {

	return preg_replace( "/[^0-9]/", "", trim($phone) );
	
} // clean_phone()
	

//-------------------------------------------------------------------------
// showHeader: common page leaderboard
//-------------------------------------------------------------------------
function showHeader() {

	global $PHP_SELF, $site, $altSite, $altQueryString, $g_oNDB;
	
	// get the number new
	$SQL = "SELECT Count(ID) FROM affiliate WHERE isNew='Y' AND isHidden='N'";
	$num = $g_oNDB->getField($SQL);
	
	/// page header...
	?>
	<html>
		<head>
			<link rel="stylesheet" type="text/css" href="../admin.css">
			<style>
				BODY{ margin: 5px; }
				BODY,TD{ color: #000080; text-align: left; }
				A,A:link,A:visited{ color: #2828B8; } A,A:link,A:visited,A:hover,A:active{ font-size: 11px; font-weight: normal; }
				div.bq{ margin-left: 40px; margin-right: 40px; }
				div.message{ margin: 0; padding: 0.25em 0.5em; font-size: 1.2em; color: #000; background: #FEFCE8; border: #D8D8D8 1px solid; border-radius: 3px; box-shadow: 2px 2px 3px #E8E8E8; display: inline-block; }
				div.message.err{ color: #C80000; }
				div.message.ok{ color: #009800; }
				.right{ text-align: right; }
				.tooltip { position: relative; display: inline-block; }
				.tooltip .tooltiptext { visibility: hidden; background-color: #FEFCE8; color: #000; text-align: center; border: #000 1px solid; border-radius: 5px; padding: 8px 0; position: absolute; z-index: 1; }
				.tooltip:hover .tooltiptext { text-align: left; font-size: 1.25em; visibility: visible; width: 35em; padding: 0.25em 0.5em; }
			</style>
			<script language="Javascript" src="windshield.js"></script>
		</head>
	<body bgcolor=white text="#000088"  LINK="#000088" VLINK="#ff0000" marginheight=5 marginwidth=5 topmargin=5 leftmargin=5>
	<?
	
	if( $num > 0 && $_SESSION['ADMIN_LEVEL'] >= 3 ) {
		echo '<div style="width: 50%; float: right; display: block; padding: 2px 4px;">';
		echo '<nobr><a href="../affiliates.php?A=L&N=100&new=Y" style="color: #00B800;"><span style="color: #00B800; background: #E0F4E4; font-size: 14px; font-weight: bold; padding: 2px 4px;">';
		echo '<blink>&nbsp; '.$num." new affiliate".($num==1 ? " has" : "s have")." signed up! &nbsp;</blink></span></a></nobr></div>\n";
	}
		
	?><font size=4><? echo $site; ?></font><span style='font-size: 4px;'><br><br></span><?


} // showHeader()


