<?php

	include('../../_global.php');
	
	if (!isset($_SESSION["upsell_completed"])) {
		$_SESSION["upsell_completed"] = true;
	} else {
		if ($_SESSION["upsell_completed"] === true) {
			// Don't let customer attempt to purchase upsell again.
			//header('Location: '.$configs->path.'confirmation.php?customerId='.$_POST["customer_id"]."&upsell=false");
			//return;
		}
	}

	// New upsell steps change
	//Check for upsell step
	if (!empty($_POST["u_step"])) {
		$upsellStep = $_POST["u_step"];
	} else {
		//Array location of 1st upsell
		$upsellStep = 0;
	}

	if (!empty($_POST["__next_upsell"])) {
		$nextUpsell = $_POST["__next_upsell"];
	} else {
		//Array location of 1st upsell
		$nextUpsell = 'confirmation';
	}
	// New upsell steps change

	
	if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
		http_response_code(404);
		exit();
	}
		
	if ($_POST["add_upsell"] === "false") {
		header('Location: '.$configs->path.'confirmation.php?customerId='.$_POST["customer_id"]."&upsell=false");
		return;
	}
	
	$resp = $konnektive->get_order($_SESSION["orderId"]);
		
	if (is_null($resp)) {
		echo "No order associated with customer.";
		return;
	}
	
	// 3DS
	if ($configs->threeds_enabled) {
		if (isset($_POST["cavv"]) && $_POST["cavv"] !== "") {
			$data["cavv"] = $_POST["cavv"];
			$data["xid"] = $_POST["ds_trans_id"];
			$data["eci"] = $_POST["eci"];
		}
	}
	
	// Set product ID
	$upsell_product_id = $configs->affiliates[$_SESSION["affid"]]->upsells[$upsellStep];
	if (isset($_SESSION["scrub"]) && $_SESSION["scrub"] === true) {
		$upsell_product_id = $configs->affiliates[$_SESSION["affid"]]->upsells_sc[$upsellStep];
	}
	
	$resp = $konnektive->import_upsale(array(
		"orderId" 	=> $_SESSION["orderId"],
		"productId" => $upsell_product_id
	));
	
	$resp = json_decode($resp);
	
	$url = 'Location: ' . $configs->path . $nextUpsell .'.php?customerId='. $_POST["customer_id"] . "&upsell=true";
	
	if ($resp->result === "SUCCESS") {
		$_SESSION["upsells"][] = $configs->upsells[$upsellStep];
		$_SESSION["total"] = $_SESSION["total"] + $configs->upsells[$upsellStep]["full_price"];
		$_SESSION["added_upsell"] = true;
		header($url);
	} else {
		
		$_SESSION["added_upsell"] = false;
		header($url);
	}

	exit(0);
	