<?php
	 require_once "/var/www/html/track/config.php";
	require_once "/var/www/html/track/func/fn_st_flow_common.php";
	include_once "/var/www/html/track/lng/spanish/lng_main.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));
	}

	$signature 	  	  = $_GET["signature"];
	$decodedSignature = shortDecode($signature); 

	$email 		  	  = $decodedSignature[0];
	$plate_number 	  = $decodedSignature[1];

	$plans 		  	  = getPlans($ms); 
?>
<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Plan GPS</title>

	<style>
		:root {
			--clr-light: #f7f7f7;
			--clr-highlight: #0097D5;
			--clr-gray: #CCCCCC;
		}
		
		a {
			cursor: pointer;
			color: inherit;
			text-decoration: inherit;
		}

		.main {
			text-align: center;
			padding: 2em 0;
			background-color: var(--clr-light);
			height: 100vh;

			font-family: Helvetica, sans-serif;

		}

		.logo {
			max-width: 25%;
			margin: 0 auto;
		}

		.title {
			margin-top: 1rem;
			margin-bottom: 2.25rem;
			font-size: 1.5rem;
		}

		.title > b {
			color: var(--clr-highlight);
		}

		/* .plans {} */

		.plans__list {
			width: 80%;
			
			margin: 0 auto;
			padding: 2em;
			
			display: grid;

			grid-template-columns: 4fr 2fr 2fr 1fr;
			grid-auto-rows: 3em;

			gap: .5em 0;

			text-align: start;
			background-color: #f5f5f5;
			border: 2px solid var(--clr-gray);
			border-radius: .5em;
		}

		.plans__data,
		.plans__header {
			display: flex;
			justify-content: start;
			align-items: center;
		}
		
		.plans__header {
			font-weight: 900;

			border-bottom: 4px solid var(--clr-highlight);
		}

		.plans__data {
			border-bottom: 2px solid var(--clr-gray);
			padding: .5em 0 1em;
		}

		.plans__data--comprar > a {
			margin: 0 auto;
			padding: .5em 1.2em;
			background-color: var(--clr-highlight);
			color: #f5f5f5;
			border-radius: 1em;
			text-decoration: none;

			transition: opacity ease-in-out .5s;
		}

		.plans__data--comprar > a:hover {
			opacity: .8;
		}

		.plans__data--last-row { border-bottom: none; }

		.modal {
			display: none;

			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);

			border: 4px solid var(--clr-highlight);
			background-color: var(--clr-light);

			border-radius: .5em;

			padding: 2em;
		}

		.modal__body {
			text-align: center;
		}
	</style>
</head>
<body>

	<article data-modal class="modal">
		<section class="modal__body">
			<h2>Cargando compra del plan...</h2>
			<p>Sera redirigido a la brevedad.</p>
		</section>
	</article>

    <main class="main">
		<figure class="logo">
			<img src="https://www.gpsimple.cl/track/img/logo.png" width="100%">
		</figure>
		<br />
		<section class="title">
			Hola,
			<br />
			Escoja un plan para renovar el GPS de
			<br />
			su vehiculo de patente: &nbsp;<b><?php echo $plate_number?></b>&nbsp;
		</section>
		<section class="plans">
			<article class="plans__list">
				<span class="plans__header plans__header--nombre">NOMBRE</span>
				<span class="plans__header plans__header--periodo">PERIODO</span>
				<span class="plans__header plans__header--precio">PRECIO</span>
				<span class="plans__header"></span>
				<?php
					foreach ($plans as $i => $plan) {

						/* 
						0 email
						1 plate_number
						2 plan_id
						3 name
						4 period
						5 period_type
						6 price
						*/
						
						$planPayload 	   = [
							$email,
							$plate_number,
							$plan["plan_id"],
							$plan["name"],
							$plan["period"],
							$plan["period_type"],
							$plan["price"]
						];

						$planPayloadString = implode($encryptionSeparator, $planPayload);

						$planSignature	   = shortEncode($planPayloadString);

						$periodType		   = $la[strtoupper($plan["period_type"])] ?? $plan["period_type"];
						
						$last_row 		   = $i === (count($plans) - 1) ? 'plans__data--last-row' : '';

						echo "
							<span class='plans__data plans__data--nombre {$last_row}'>{$plan['name']}</span>
							<span class='plans__data plans__data--periodo {$last_row}'>{$plan['period']} {$periodType}</span>
							<span class='plans__data plans__data--precio {$last_row}'>$ {$plan['price']}</span>
							<span class='plans__data plans__data--comprar {$last_row}'><a data-plan-signature='{$planSignature}'>Comprar</a></span>
						";
					}
				?>
			</article>
		</section>
    </main>

	<script>
		const buyBtns = document.querySelectorAll("[data-plan-signature]");
		const modal = document.querySelector("[data-modal]");

                    	const buyPlan = async e => {
                    		e.preventDefault();

                			modal.style.display = "block";

            			try {
                				const { status, message } = await fetch(
                					'/track/func/fn_st_flow_payment.php',
                					{
                						method: "POST",
                						body: JSON.stringify({signature: e.target.getAttribute("data-plan-signature")})
                					}
                				).then(res => res.json());

                				if (status === 200) {
                					return open(message, "_self");
                				}
                    
                				if (status === 500) {
                					return alert(message);
                				}
                                
                			} catch (error) {
                				console.trace(error);
                			} finally {
                				modal.style.display = "none"
                			}
                		};
                        

                		buyBtns.forEach(btn => {
                			btn.onclick = buyPlan;
                		});
	</script>
</body>

</html>