<?php 

session_start();
$errors = [];
$user_id = "";
include('includes/config.php');
require 'mail.php';



if (isset($_POST['reset-password'])) {

  $email = $_POST['email'];
  //$email = trim($email," ");
  // ensure that the user exists on our system
  $query = "SELECT Useremail FROM users WHERE Useremail='$email'";
  $results = mysqli_query($con, $query);
  
  //$results = $db->runQuery($query);

  if (empty($email)) {
    array_push($errors, "Your email is required");
  }else if(mysqli_num_rows($results) <= 0) {
    array_push($errors, "Sorry, no user exists on our system with that email");
  }
  // generate a unique random token of length 100
  $token = bin2hex(random_bytes(50));

  if (count($errors) == 0) {
    // store token in the password-reset database table against the user's email
    $sql = "INSERT INTO user_password_reset(email, token) VALUES ('$email', '$token')";


    $results = mysqli_query($con, $sql);


    // Send email to user with the token in a link they can click on
   // $to = $email;
    $subject = "Reset Your Password ";
    //$body.=" By ".$uname." Please have a look into Application at <a href=".$website_url."/templates/Forms/viewform.php?id='".$form_id."'>".$website_url."/templates/Forms/viewform.php?id='".$form_id."'</a>."
    $body=" Hi there, click on this link to reset your password  <a href=".$website_url."/new_password.php?token=$token>"."  Reset Password</a>";
   // $headers = "From: komal@hastishah.com";
    //mail($to, $subject, $msg, $headers);
    //send_mail($to, $subject, $msg, $headers);
    forgot_mail($email,$subject,$body);
    header('location: pending.php?email=' . $email);
  }
}


// ENTER A NEW PASSWORD
if (isset($_POST['new_password'])) {
  // echo '<pre>';
  // print_r($_POST);

  $new_pass = mysqli_real_escape_string($con, $_POST['new_pass']);

  $new_pass_c = mysqli_real_escape_string($con, $_POST['new_pass_c']);

  // Grab to token that came from the email link
  $token = $_GET['token'];

  if (empty($new_pass) || empty($new_pass_c)) array_push($errors, "Password is required");
  if ($new_pass !== $new_pass_c) array_push($errors, "Password do not match");
  if (count($errors) == 0) {
    // select email address of user from the password_reset table 
    $sql = "SELECT email FROM user_password_reset WHERE token='$token' LIMIT 1";
    $results = mysqli_query($con, $sql);
    $email = mysqli_fetch_assoc($results)['email'];
   

    if ($email) {
      $new_pass = md5($new_pass);
      $sql = "UPDATE users SET password='$new_pass' WHERE email='$email'";
      $results = mysqli_query($con, $sql);
      header('location: index.php');
    }
  }
}
?>
