<?php

$RESEND_OTP = ($_SESSION['OTP_RK'] ?? TRUE) == ($_GET['r'] ?? NULL);

if( empty($_SESSION['otp_hash']) || empty(trim($__user['otp_hash'])) || $RESEND_OTP ):

	$_SESSION['otp_hash'] = help::CREATE_OTP('Confirm Login', $__user['email'], function($OTP) use($link, $__user) {
		
		$SQL = sQuery::update( 'tbl_users', array(
			"otp_hash" => md5($OTP)
		), "email = '{$__user['email']}'");
		
		$IP = $_SERVER['REMOTE_ADDR'];
		
		$MSG = "
			<section>
				A device with the IP {$IP} is trying to login in to your account. If this is you, please confirm by entering the PIN
			</section>
			<section>
				<div style='text-align: center; font-weight: bold;'>{$OTP}</div>
			</section>
		";
		
		return $link->query( $SQL ) ? $MSG : NULL;
		
	});

endif;

### ///

if( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
	
	if( md5($_POST['otp']) != $__user['otp_hash'] ) $msg = "OTP is wrong";
	
	else {
		
		$_SESSION['otp_hash'] = $__user['otp_hash'];
		
		header("location: " . help::url( PANEL_DIR ) . "/home.php");
		
		exit;
		
	};
	
} else if( $RESEND_OTP ) $msg = "New OTP has been sent";

###

// OTP_RK = OTP Resent KEY;

$_SESSION['OTP_RK'] = help::generate_number(3);
