<?php
include '../functions/pagename.php';
include '../functions/'.$session;
Session::checkSession_log();
include '../config.php';
try {
function test_input($data) { //filter value function
    $db = new database();
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    $data = mysqli_real_escape_string($db->link, $data);
    return $data;
}

function RandomString($length = 20) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

$reset_token_check = false;
$resetpass_btn = false;

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  if(isset($_POST['resetpass-btn'])){
    $email = test_input($_POST['email']);
    $reset_error = true;
    $reset_error_status = 'Something is wrong! Can not send mail.';
	$reset_token  = RandomString(20);
	
	if($user_email == $email ){
            $token_update_query = "UPDATE evp_options
												SET option_value = CASE option_name
													WHEN 'reset_pass_token' THEN '$reset_token'
												END
												WHERE option_name IN ('reset_pass_token')";
            $token_update_read = $db->update($token_update_query);
            if ($token_update_read) {
				$reset_error_status = "Password reset link sent to $email";
				$sendmail = new SendMail;
				$sendmail->notify_user_account_updates($user_name,$user_email,$reset_token,'password_reset');
                $reset_error = false;
                $message = 'Request Sent';
                $submessage = "Password reset request mail sent to $email";
            }
    }
    if($reset_error){
      $resetpass_btn = true;
    }else{
      $action_cat = 'token';
      Session::set("action_cat", $action_cat);
      Session::set("action_message", $message);
      Session::set("action_submessage", $submessage);
      header("Location: ".$login_page);
    }
  }elseif(isset($_POST['changepass-btn'])) {
    $email = test_input($_POST['email']);
    $token = test_input($_POST['token']);
    $user_id = test_input($_POST['user_id']);
    $new_pass = test_input($_POST['new_pass']);
    $con_pass = test_input($_POST['con_pass']);
    $reset_error = true;
    $reset_error_status = 'Something is wrong! Please try again';
    if($new_pass == $con_pass){
            if(!empty($reset_pass_token)){
              $new_pass = md5($new_pass);
              $token_update_query = "UPDATE evp_options
												SET option_value = CASE option_name
													WHEN 'password' THEN '$new_pass'
												END
												WHERE option_name IN ('password')";
              $token_update_read = $db->update($token_update_query);
              if ($token_update_read) {
                  $reset_error = false;
                  $message = 'Password change successful';
                  $submessage = "Please login now";
				  $token_update_reset_query = "UPDATE evp_options
												SET option_value = CASE option_name
													WHEN 'reset_pass_token' THEN null
												END
												WHERE option_name IN ('reset_pass_token')";
				  $db->update($token_update_reset_query);
              }
            }
    }else{
      $reset_error_status = 'Confirm password do not match!';
      $reset_token_check = true;
      $confirm_token = $token;
      $confirm_email = $email;
      $current_user_id = $user_id;
    }
    if($reset_error){
      $resetpass_btn = true;
    }else{
      $action_cat = 'token';
      Session::set("action_cat", $action_cat);
      Session::set("action_message", $message);
      Session::set("action_submessage", $submessage);
      header("Location: ".$login_page);
    }
  }
}elseif(isset($_GET['resettoken']) && isset($_GET['email'])){
  $confirm_token = test_input($_GET['resettoken']);
  $confirm_email = test_input($_GET['email']);
    if(($confirm_token == $reset_pass_token) && ($confirm_email == $user_email)){
      $current_user_id = $user_id;
      $reset_token_check = true;
    }
}
} 
catch (Exception $e) { ?> 
    <script>
        alert('<?php echo $e->getMessage();?>');
    </script>
<?php } ?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">
  <title><?php _e('Forgot Password');?></title>
                         <!-- Google Font -->
                        <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
                        <!-- CSS -->
						<link rel="stylesheet" type="text/css" href="../assets/vendors/styles/core.min.css">   <!-- style css -->
						<link rel="stylesheet" type="text/css" href="../assets/vendors/styles/style.css">
						<link rel="stylesheet" type="text/css" href="../assets/styles/theme.css">   <!-- style css -->
						<!--Load Scripts-->
						<script src="../assets/scripts/jquery.min.js"></script>
						<script src="//cdn.jsdelivr.net/npm/sweetalert2@10"></script>

</head>
<body class="bg-gradient-primary">
  <div class="container">
    <!-- Password Reset - Outer Row -->
    <div class="access_box row justify-content-center">
      <div class="col-xl-10 col-lg-12 col-md-9">
        <div class="card o-hidden border-0 shadow-lg my-5">
          <div class="card-body p-0">
            <!-- Nested Row within Card Body -->
            <div class="row">
              <div class="col-lg-6 d-none d-lg-block text-center m-auto"> <img src="../assets/app-img/evp_fpass.jpg" alt="..." class="img-thumbnail"> </div>
              <div class="col-lg-6">
                <div class="p-5">
                  <?php if($reset_token_check){ ?>
                    <div class="text-center">
                      <h1 class="h4 text-gray-900 mb-4"><?php _e('Change Password');?></h1>
                    </div>
                    <form class="user" action="<?php echo $forgot_password_page;?>" method="post">
                      <input required hidden type="email" name="email" value="<?php echo $confirm_email;?>">
                      <input required hidden type="text" name="token" value="<?php echo $confirm_token;?>">
                      <input required hidden type="text" name="user_id" value="<?php echo $current_user_id;?>">
                      <div class="form-group">
                        <input type="password" name="new_pass" class="form-control form-control-user" id="exampleInputEmail" aria-describedby="emailHelp" placeholder="<?php _e('Enter New Password');?>...">
                      </div>
                      <div class="form-group">
                        <input type="password" name="con_pass" class="form-control form-control-user" id="exampleInputEmail" aria-describedby="emailHelp" placeholder="<?php _e('Confirm Password');?>...">
                      </div>
                      <?php if($resetpass_btn){
                        echo '<p class="text-danger">'.$reset_error_status.'</p>';
                      }?>
                      <button type="submit" name="changepass-btn" class="btn btn-primary btn-user btn-block"><?php _e('Save');?></button>
                    </form>
                  <?php }else{ ?>
                    <div class="text-center">
                      <h1 class="h4 text-gray-900 mb-2"><?php _e('Forgot Your Password');?>?</h1>
                      <p class="mb-4"><?php _e("We get it, stuff happens. Just enter your email address below and we'll send you a link to reset your password");?>!</p>
                    </div>
                    <form class="user" action="<?php echo $forgot_password_page;?>" method="post">
                      <div class="form-group">
                        <input type="email" name="email" class="form-control form-control-user" id="exampleInputEmail" aria-describedby="emailHelp" placeholder="<?php _e('Enter Email Address');?>...">
                      </div>
                      <?php if($resetpass_btn){
                        echo '<p class="text-danger">'.$reset_error_status.'</p>';
                      }?>
                      <button type="submit" name="resetpass-btn" class="btn btn-primary btn-user btn-block">
                        <?php _e('Reset Password');?>
                      </button>
                    </form>
                  <?php }?>

                  <hr>
                  <div class="text-center">
                    <a class="small" href="<?php echo $login_page;?>"><?php _e('Already have an account? Login');?>!</a>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

</body>
</html>