<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

function curPageURL() {
	$pageURL = 'http';
	if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
	$pageURL .= "://";
	if ($_SERVER["SERVER_PORT"] != "80") {
		$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
	} else {
		$pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
	}
	return $pageURL;
}
function curServerURL() {
	$pageURL = 'http';
	if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
	$pageURL .= "://";
	// if ($_SERVER["SERVER_PORT"] != "80") {
	// 	$pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"];
	// } else {
	// 	$pageURL .= $_SERVER["SERVER_NAME"];
	// }
	$pageURL .= $_SERVER["SERVER_NAME"];
	return $pageURL;
}

if (!isset($_GET['access_token'])) {
	echo json_encode([]);
	return;
} else {
	//access token has been set
	$access_token = $_GET['access_token'];
	include 'conf/conn.php';

	$query = "select * from `orders` where `paypal id`='$access_token'";
	// echo $query;
	$result = mysqli_query($conn, $query);
	if ($result) {
		$row = mysqli_fetch_assoc($result);
		// echo "record found";
		require_once 'vendor/autoload.php';
		\Stripe\Stripe::setApiKey(STRIPE_SECRET_KEY);
		try {
			// See https://stripe.com/docs/api/checkout/sessions/create
			// for additional parameters to pass.
			// {CHECKOUT_SESSION_ID} is a string literal; do not change it!
			// the actual Session ID is returned in the query parameter when your customer
			// is redirected to the success page.
			$success_url = curServerURL() . '/stripesuccess.php?session_id={CHECKOUT_SESSION_ID}';
			$cancel_url = curServerURL() . '/stripecancel.php';
			// echo $success_url;
			$checkout_session = \Stripe\Checkout\Session::create([
				'success_url' => $success_url,
				'cancel_url' => $cancel_url,
				'payment_method_types' => ['card'],
				'mode' => 'payment',
				'line_items' => [[
					'price_data' => [
						'currency' => 'hkd',
						'product_data' => [
							'name' => $row['bought_items'],
						],
						'unit_amount' => $row['amount'] * 100,
					],
					'quantity' => 1,
				]],

			]);
		} catch (Exception $e) {
			var_dump($e);
			// return $response->withJson([
			// 	'error' => [
			// 		'message' => $e->getError()->message,
			// 	],
			// ], 400);
		}

// echo "Session";
		// echo "<br>";
		// var_dump($checkout_session);

		//Insert into Stripe and Payment Record
		$output_session = $checkout_session['id'];
		$query2 = "INSERT into `stripe_payment`  (`paypal_id`, `stripe_session_id`) VALUES ('$access_token','$output_session')";
		// echo $query;
		$result = mysqli_query($conn, $query2);

		// echo $query;

		//End Insert into Stripe and Payment Record

		echo json_encode(['sessionId' => $checkout_session['id']]);
	} else {
		// echo "record not found";
		echo json_encode([]);
		return;
	}
	//end access token has been set
} //else

?>