<?php

$_POST = help::sanitize($_POST);


if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	
	if( empty($_POST['email']) ): $msg = "Email field cannot be empty";
	
	else:
		
		$user = help::get_user($_POST['email']);

		if( empty($user) ): $msg = "The email account was not found";
		
		else:
			
			$data = help::get_json($user['_json']);
			$data['reset_password'] = md5(help::keygen(10, false));
			
			$SQL = sQuery::update( 'tbl_users', array("_json" => json_encode($data)), "id={$user['id']}" );
			$link->query( $SQL );
			
			$reset_link = help::url( PANEL_DIR ) . "/confirm.php?k={$data['reset_password']}&e={$user['email']}";
			
			$mailer = new mailer();
			$mailer->addAddress($user['email']);
			$mailer->Subject = "Password Reset";
			$mailer->Body = "
				<section>
					<div>We received your request to reset your password. Please click the link below to confirm the reset process</div>
					<div><a href='{$reset_link}'>Click here to reset password</a></div>
				</section>
			";
			
			if( $mailer->send() ) $msg = "We have sent you a link to reset your password";
			else $msg = "Something went wrong! Please try again";

		endif;
			
	endif;
	
} else {
	
	$error = (int)($_GET['e'] ?? null); 
	if( $error ) {
		if( $error === 1 ) $msg = "Email account is missing! <br> Please try again";
		elseif( $error == 2 ) $msg = "The reset link is not valid";
	};
	
}
      	
