<?php

if( $_SERVER['REQUEST_METHOD'] == 'GET' ) {
	
	$user = help::get_user($_GET['e'] ?? null);
	
	$reset_page = help::url( PANEL_DIR ) . '/reset.php';

	if( !$user ) header("location: {$reset_page}?e=1");
	else {
		$data = help::get_json($user['_json']);
		if( ($data['reset_password'] ?? '') != ($_GET['k'] ?? null) ) header("location: {$reset_page}?e=2");
	};

} else {
 
	$user = help::get_user($_POST['email']);
	
	if( empty($_POST['password']) ) $msg = "New password is required";
	
	else if( strlen($_POST['password']) < 6 ) $msg = "Password should be at least 6 characters";
	
	else if( $_POST['password'] !=  $_POST['password-alt'] ) $msg = "Password does not match";
	
	else {
		
		$login_url = help::url( PANEL_DIR );
		
		$SQL = sQuery::update( 'tbl_users', array('pwd' => md5($_POST['password'])), "id={$user['id']}" );
		$status = $link->query( $SQL );
		$msg = $status ? "Password successfully updated! <br> You can <a href='{$login_url}'>login now</a>" : "Password not updated";
		
		if( $status ) {
			
			$mailer = new mailer();
			$mailer->addAddress($user['email']);
			$mailer->Subject = "Password Changed";
			$mailer->Body = "
				<section>
					Your password has been successfully updated. <br>
					You can login with your new password now <br>
					<a href='{$login_url}'>Login Now</a>
				</section>
			";
			
			$mailer->send();
			
		};
		
	};
	
}



