<?php

use Mtc\Shop\Basket\Protx;

if(SAGEPAY_TOKEN == true && !empty($member->sagepay_token)){
    $strPurchaseURL = PROTX_URL_TOKEN;
}
else{
    $strPurchaseURL = SAGEPAY_URL_PURCHASE;
}

$basket->ProtxTx();
$strVendorTxCode = config('site.tnx_prefix') . $basket->protx;

// Gather customer details from the session
$strCustomerEMail = $basket->info['email'];
$strBillingFirstnames = $basket->address['billing']['firstname'];
$strBillingSurname = $basket->address['billing']['lastname'];
$strBillingAddress1 = $basket->address['billing']['address1'];
$strBillingAddress2 = $basket->address['billing']['address2'];
$strBillingCity = $basket->address['billing']['city'];
$strBillingPostCode = $basket->address['billing']['postcode'];
$strBillingCountry = $basket->address['billing']['country'];
$strBillingState = $basket->address['billing']['state'];
$strBillingPhone = $basket->info['contact_no'];
$bIsDeliverySame = false;
$strDeliveryFirstnames = $basket->address['shipping']['firstname'];
$strDeliverySurname = $basket->address['shipping']['lastname'];
$strDeliveryAddress1 = $basket->address['shipping']['address1'];
$strDeliveryAddress2 = $basket->address['shipping']['address2'];
$strDeliveryCity = $basket->address['shipping']['city'];
$strDeliveryPostCode = $basket->address['shipping']['postcode'];
$strDeliveryCountry = $basket->address['shipping']['country'];
$strDeliveryState = $basket->address['shipping']['state'];
$strDeliveryPhone = $basket->info['contact_no'];

/* Now to build the Sage Pay Server POST.  For more details see the Sage Pay Server Protocol 2.23
 * * NB: Fields potentially containing non ASCII characters are URLEncoded when included in the POST */
$strPost = "VPSProtocol=" . $strProtocol;
$strPost = $strPost . "&TxType=" . $strTransactionType; //PAYMENT by default.  You can change this in the includes file
$strPost = $strPost . "&Vendor=" . $strVendorName;
$strPost = $strPost . "&VendorTxCode=" . $strVendorTxCode; //As generated above
$strPost = $strPost . "&VendorEMail=" . SAGEPAY_EMAIL;

// Optional: If you are a Sage Pay Partner and wish to flag the transactions with your unique partner id, it should be passed here
if (strlen($strPartnerID) > 0)
    $strPost = $strPost . "&ReferrerID=" . URLEncode($strPartnerID);  //You can change this in the includes file

$strPost = $strPost . "&Amount=" . number_format($basket->cost_total, 2); //Formatted to 2 decimal places with leading digit but no commas or currency symbols **
$strPost = $strPost . "&Currency=" . $strCurrency;

//Up to 100 chars of free format description
$strPost = $strPost . "&Description=" . config('app.name') . " Online Order";

/* The Notification URL is the page to which Sage Pay Server calls back when a transaction completes
 * * You can change this for each transaction, perhaps passing a session ID or state flag if you wish */
$strPost = $strPost . "&NotificationURL=" . $strYourSiteFQDN . "shop/checkout/server/payment-notification.php";

?>
<script>
    console.log('<?= $strYourSiteFQDN . "shop/checkout/server/payment-notification.php" ?>')
</script>
<?php

// Billing Details:
$strPost = $strPost . "&BillingFirstnames=" . $strBillingFirstnames;
$strPost = $strPost . "&BillingSurname=" . $strBillingSurname;
$strPost = $strPost . "&BillingAddress1=" . $strBillingAddress1;
if (strlen($strBillingAddress2) > 0)
    $strPost = $strPost . "&BillingAddress2=" . $strBillingAddress2;
$strPost = $strPost . "&BillingCity=" . $strBillingCity;
$strPost = $strPost . "&BillingPostCode=" . $strBillingPostCode;
$strPost = $strPost . "&BillingCountry=" . $strBillingCountry;
if (strlen($strBillingState && $strBillingCountry == "US") > 0)
    $strPost = $strPost . "&BillingState=" . $strBillingState;
if (strlen($strBillingPhone) > 0)
    $strPost = $strPost . "&BillingPhone=" . $strBillingPhone;

// Delivery Details:
$strPost = $strPost . "&DeliveryFirstnames=" . $strDeliveryFirstnames;
$strPost = $strPost . "&DeliverySurname=" . $strDeliverySurname;
$strPost = $strPost . "&DeliveryAddress1=" . $strDeliveryAddress1;
if (strlen($strBillingAddress2) > 0)
    $strPost = $strPost . "&DeliveryAddress2=" . $strDeliveryAddress2;
$strPost = $strPost . "&DeliveryCity=" . $strDeliveryCity;
$strPost = $strPost . "&DeliveryPostCode=" . $strDeliveryPostCode;
$strPost = $strPost . "&DeliveryCountry=" . $strDeliveryCountry;
if (strlen($strDeliveryState && $strDeliveryCountry == "US") > 0)
    $strPost = $strPost . "&DeliveryState=" . $strDeliveryState;
if (strlen($strDeliveryPhone) > 0)
    $strPost = $strPost . "&DeliveryPhone=" . $strDeliveryPhone;

// Set other optionals
$strPost = $strPost . "&CustomerEMail=" . urlencode($strCustomerEMail);
//$strPost=$strPost . "&Basket=" . urlencode($strBasket); //As created above

/** For charities registered for Gift Aid, set to 1 to display the Gift Aid check box on the payment pages * */
$strPost = $strPost . "&AllowGiftAid=0";

/* Allow fine control over AVS/CV2 checks and rules by changing this value. 0 is Default
 * * It can be changed dynamically, per transaction, if you wish.  See the Sage Pay Server Protocol document */

if(SAGEPAY_TOKEN == true){
	if(!empty($member->sagepay_token)){
        /* If token is already created do not perform 3D-Secure checks */
        $strPost=$strPost . "&Apply3DSecure=2";
    }else{
        if(DEV_MODE==true){
            $strPost=$strPost . "&Apply3DSecure=2";
        }else{
            $strPost=$strPost . "&Apply3DSecure=0";
        }
    }

	if(!empty($member->sagepay_token)){
	    $strPost=$strPost . "&Token=" . $member->sagepay_token;
	    $strPost=$strPost . "&StoreToken=1";
	}else{
	    if($_REQUEST[save_card]!="no"){
	        $strPost=$strPost . "&CreateToken=1" ;
	    }
	}
} else {
    if(DEV_MODE) {
        $strPost = $strPost . '&Apply3DSecure=2';
    }
	if ($strTransactionType !== "AUTHENTICATE")
    	$strPost = $strPost . "&ApplyAVSCV2=0";

	/* Allow fine control over 3D-Secure checks and rules by changing this value. 0 is Default **
	 * * It can be changed dynamically, per transaction, if you wish.  See the Sage Pay Server Protocol document */
	$strPost = $strPost . "&Apply3DSecure=0";
}


// Optional setting for Profile can be used to set a simpler payment page. See protocol guide for more info. **
$strPost = $strPost . "&Profile=LOW"; //NORMAL is default setting. Can also be set to LOW for the simpler payment page version.

/* The full transaction registration POST has now been built **
 * * Send the post to the target URL
 * * if anything goes wrong with the connection process:
 * * - $arrResponse["Status"] will be 'FAIL';
 * * - $arrResponse["StatusDetail"] will be set to describe the problem
 * * Data is posted to strPurchaseURL which is set depending on whether you are using SIMULATOR, TEST or LIVE */

/*
 * Initial comment:
 * Lets update the SEcurity Key into basket_protx
 * - This is more reliable, and associates a key with a protx id rather than a basket_id
 * - Since a basket can have multiple protx_id's if the customer starts the payment process / goes back / reinstanciates a payment process
 *
 * 2015-01-27 GB:
 * The problem with the above is protx_id is a fiction and so far basket_id was being used instead.
 *
 * We should be using VPSTxId for indexing SecurityKeys or T30788 will strike back.
 *
 * When deploying on legacy sites run this on both staging and live:
 * ALTER TABLE `basket_protx` ADD COLUMN `VPSTxId` VARCHAR(50) NOT NULL AFTER `secKey` ADD UNIQUE INDEX `VPSTxId_UNIQUE` (`VPSTxId` ASC);
 */
$arrResponse = requestPost($strPurchaseURL, $strPost);

Protx::query()
    ->where('id', $basket->protx)
    ->update([
        'secKey' => $arrResponse['SecurityKey'],
        'VPSTxId' => $arrResponse['VPSTxId'],
    ]);
