<?php
require_once "/var/www/html/track/tools/FlowApi.class.php";
require_once "/var/www/html/track/func/fn_st_flow_common.php";

date_default_timezone_set('America/Santiago');

$ms = mysqli_connect($gsValues["DB_HOSTNAME"], $gsValues["DB_USERNAME"], $gsValues["DB_PASSWORD"], $gsValues["DB_NAME"], $gsValues["DB_PORT"]);
mysqli_set_charset($ms, "UTF8");

if (mysqli_connect_errno($ms)) {
	error(500, "Error de conexión: ".mysqli_connect_error($ms));
}

$jsonData 	  	  = json_decode(file_get_contents("php://input")) ?? error(
											500,
											json_encode([
												"status" => 500,
												"message" => "No data given"
											]));

$signature = $jsonData->signature;

$decodedSignature = shortDecode($signature);

$signatureData 	  = [
	"email"   => $decodedSignature[0],
	"plate_number" => $decodedSignature[1],
	"plan_id" => $decodedSignature[2],
	"name" => $decodedSignature[3],
	"period" => $decodedSignature[4],
	"period_type" => $decodedSignature[5],
	"price" => $decodedSignature[6]
];

$user = getUserByEmail($ms, $signatureData["email"]);

$data = [
	$user["id"],
	$signatureData["plate_number"],
	$signatureData["plan_id"],
	$signatureData["period"],
	$signatureData["period_type"],
];

$concatenatedData = implode($encryptionSeparator, $data);

$encodedData = shortEncode($concatenatedData);

$optional = [
	"Firma" => $encodedData
];

//Prepara el arreglo de datos
$params = [
	"commerceOrder"   => $user["id"].date("ymdHis"),
	"subject" 		  => $signatureData["name"],
	"currency" 		  => "CLP",
	"amount" 		  => $signatureData["price"],
	"email" 		  => $signatureData["email"],
	"paymentMethod"   => 9,
	"urlConfirmation" => Config::get("BASEURL") ."/func/fn_st_flow_confirm.php",
	"urlReturn" 	  => Config::get("BASEURL") ."/inc/inc_st_flow_redirect.php",
	"optional" 		  => json_encode($optional)
];
//Define el metodo a usar
$serviceName = "payment/create";

try {
	// Instancia la clase FlowApi
	$flowApi = new FlowApi();
	// Ejecuta el servicio
	$response = $flowApi->send($serviceName, $params, "POST");
	//Prepara url para redireccionar el browser del pagador
	$redirect = $response["url"] . "?token=" . $response["token"];

	$payment = getPaymentByToken($response["token"]);
	
	insertPayment($ms, $payment);

    mysqli_close($ms);
	
	echo json_encode([
		"status" => 200,
		"message" => $redirect
	]);
} catch (Exception $e) {
	error(500, json_encode([
		"status" => 500,
		"message" => $e->getCode() . " - " . $e->getMessage()
	]));
}
