<?php

if( !empty($__user['actwo']) ):
	
	$json = help::get_json($__user['_json']);
	
	$verified = $error = null;
	
	if( isset($_POST['resend']) ) {
		unset($_POST['resend']);
		unset($_POST['otp']);
	};
	
	if( !isset($_POST['otp']) ) {
	
		$key = strtolower(help::keygen(5, false));
		$json['transfer_email_otp'] = $key;
		
		$SQL = sQuery::update( 'tbl_users', array( '_json' => json_encode($json) ), "id = {$__user['id']}" );
		$save_otp = $link->query( $SQL );
		
		$mailer = new mailer();
		$mailer->addAddress($__user['email']);
		$mailer->Subject = "Transfer OTP";
		$mailer->Body = "
			<section>
				<div>You are just one step away from completing your transfer. Please enter the code below to proceed</div>
				<div><h3 style='text-align: center; padding: 6px; background-color: lightgray;'>{$json['transfer_email_otp']}</h3></div>
			</section>
		";
		
		$sent = $mailer->send();
	
	} else {
		$verified = ($json['transfer_email_otp'] == $_POST['otp']);
		if( !$verified ) $error = "OTP is incorrect";
	};
	
	### [ verification ]
	
	if( !$verified ):
	
		events::addListener('@header', function() {
			echo "<style>
				.resend {
					border: none;
					background-color: transparent;
					color: var(--info);
					padding: 0;
					margin: 0;
					line-height: 0;
				}
			</style>";
		});
		
		template::get_header();

?>

			<div class='row'>
				<div class='col-md-7 m-auto'>
				
					<div class='card'>
						<div class='card-body'>
							
							<?php template::alert( $error, $verified ); ?>
							
							<div class='alert alert-info text-center'>
								Please enter the OTP code sent to your email
							</div>
							
							<form method='post'>

								<?php 
									foreach( $_POST as $key => $value ): 
										if( $key == 'data' ) continue;
								?>
									<input type='hidden' name='<?php echo $key; ?>' value='<?php echo $value; ?>'>
								<?php endforeach; ?>	

								<div class='form-group text-right'>
									<input type='text' name='otp' placeholder='Enter OTP' class='form-control form-control-lg mb-1' autocomplete='false'>
									<button type='submit' class='resend' name='resend' value='1'>
										<i class='fas fa-envelope'></i> Resent OTP
									</button>
								</div>
								
								<input type='hidden' name='data' value='<?php echo base64_encode( json_encode($data) ); ?>'>
								
								<div class='form-group'>
									<button class='btn btn-primary btn-block'> Confirm </button>
								</div>
								
							</form>
							
						</div>
					</div>
					
				</div>
			</div>
			
<?php 
	
		template::get_footer();

		exit;
	
	endif;
	
	### [ end verification ];
	
endif;


