<?php

// include 'map.php';
include_once 'header.php';

// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
// error_reporting(E_ALL);
/*********************/
/********** Map ***********/
/*********************/

$forgotid = isset($_GET['data'])?encryptDecrypt($_GET['data'], 'd' ):'0';




/*********************/
/********** Forgot Password ***********/
/*********************/

$forgotun_err = '';
$successmsg = '';

if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Check if username is empty
    if(empty(trim($_POST["username"]))){
        $forgotun_err = "Please enter email.";
    } else if (!filter_var($_POST["username"], FILTER_VALIDATE_EMAIL)) {
      $forgotun_err = "invalid email address";
   }else{
        $username = trim($_POST["username"]);

    }
    // Validate credentials
    // print_r($_POST["username"]);
    if(empty($forgotun_err)){

        // Prepare a select statement
        $sql = "SELECT id, username, password, zip_code, city, state  FROM users WHERE email = ?";

        if($stmt = $mysqli->prepare($sql)){
            // Bind variables to the prepared statement as parameters
            $stmt->bind_param("s", $param_username);

            // Set parameters
            $param_username = $username;

            // Attempt to execute the prepared statement
            if($stmt->execute()){
                // Store result
                $stmt->store_result();
                
                // Check if username exists, if yes then verify password
                if($stmt->num_rows == 1){
                  $sqlsurveyState = "SELECT * FROM users WHERE email = '".$_POST["username"]."'";
                    $Statequery = mysqli_query($mysqli,$sqlsurveyState);
                    $row = mysqli_fetch_assoc($Statequery);
                    $id = $row['id'];
                  $mail->addAddress($username);

                  $mail->isHTML(true);
                  $mail->Subject = "STRESS TRACKER-Forgot Password";
                  $forgoturl = $baseurl.'forgotpassword.php?data='.encryptDecrypt($id, 'e' );
                  $mail->Body = '<table style="font-family:Verdana,sans-serif;font-size:13px;border:2px solid #242424;line-height:18px;border-radius:4px;overflow:hidden;max-width:600px" border="0" width="600px" cellspacing="0" cellpadding="0" align="center"><tbody><tr style="background:#ffffff"><td style="padding:10px;margin:10px 0px 0px 10px;text-align:left;margin-top:5px;display:block" colspan="2"><a><br><img src="'.$baseurl.'Stress_Tracker_Logo.png" alt="Stress Tracker" width="60px"><br></a></td></tr><tr style="background:#242424;margin-top:5px;display:block;width:100%">
                    <td style="padding:5px 20px;text-align:left" colspan="2"><p style="font-size:16px;color:#ffffff;margin:0px;padding:6px 0px">Stress Tracker Forgot Password</p>
                    </td></tr><tr><td style="padding:10px 20px 20px 20px;width:100%"><p style="font-weight:normal;text-align:left;line-height:26px;font-size:14px;color:#000">Hello '.$row['username'].',</p><p style="font-weight:normal;text-align:left;line-height:26px;font-size:14px;color:#3b3b3b">You are receiving this email because we have received a reset password request from your account. Please click on the <a href='.$forgoturl.'>Link</a> to reset your password.<br>If you did not request to reset the password, you can safely ignore this email.</p><p style="font-weight:bold;text-align:left;color:#242424;margin:0px">Thanks,</p>
                        <p style="font-weight:bold;text-align:left;color:#242424;margin:0px">Stress Tracker Team</p>
                      </td></tr></tbody></table>';
                ?>
                
                <?php

                  if($mail->send())
                  {
                    $successmsg = "Email has been sent for reset password.";
                    $username = '';
                  }
                  else
                  {
                      echo "Could not be sent";
                      echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
                  }

                } else{
                    // Display an error message if username doesn't exist
                    $forgotun_err = "No account found with that email.";
                }
            } else{
                $forgotun_err =  "Oops! Something went wrong. Please try again later.";
            }

            // Close statement
            $stmt->close();
            // unset $data;
        }
    }
    // Close connection
    $mysqli->close(); 
}
/*********************/
/********** Forgot Password ***********/
/*********************/


?>
<section class="reset-password">
<div class="container-fluid">
  <div class="row justify-content-center">
        <div class="col-lg-4 col-md-6">
          <div class="st-index-right">
            <div class="st-login">
              <?php if(isset($forgotid) && $forgotid > 0) { ?>
              <div class="form-title"> <h2>RESET PASSWORD</h2></div>
              <form method="post" id="reset-password" autocomplete="off">
                <input type="hidden" name="forgotid" id="forgotid" value="<?php echo $forgotid; ?>">
                <div class="row">
                  <div class="col-md-12">
                    <div class="form-group ">              
                      <input type="password" class="form-control" name="password" id="password" placeholder="PASSWORD" value="">
                      <span class="help-block" id="error-password"></span>
                    </div>
                  </div>
                  <div class="col-md-12">
                    <div class="form-group ">              
                      <input type="password" class="form-control" name="cpassword" id="cpassword" placeholder="CONFIRM PASSWORD" value="">
                      <span class="help-block" id="error-cpassword"></span>
                    </div>
                  </div>                  
                  <div class="col-md-12">
                    <div class="form-group text-center">              
                      <input type="button" class="btn btn-primary"  value="SAVE"  class="btn btn-primary">
                    </div>
                  </div>
                </div>
              </form>
              <?php
            }else{
            ?>
           <div class="form-title"> <h2>FORGOT PASSWORD</h2></div>
            <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" id="user-mail-form" method="post" autocomplete="off">
                <div class="row">
                  <div class="col-md-12">
                    <div class="form-group  <?php echo (!empty($forgotun_err)) ? 'has-error' : ''; ?>">              
                      <input type="text" class="form-control" name="username" placeholder="EMAIL ADDRES" value="<?php echo $username; ?>">
                      <span class="help-block"><?php echo $forgotun_err; ?></span>
                    </div>
                  </div>
                  <div class="col-md-12">
                    <div class="form-group ">              
                      <h6 style="color: #008140;"><?php echo $successmsg; ?></h6>
                    </div>
                  </div>
                  <div class="col-md-12">
                    <div class="form-group text-center">              
                      <input type="submit" class="btn btn-primary"  value="RESET PASSWORD"  class="btn btn-primary">
                    </div>
                  </div>
                </div>
              </form>
            <?php
              }
            ?>
            </div>
          </div>
        </div>
    </div>
</div>
</section>

<?php
include_once 'footer.php';
?>
<!-- <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://api.mapbox.com/mapbox-gl-js/v2.0.0/mapbox-gl.js"></script>
<link href="https://api.mapbox.com/mapbox-gl-js/v2.0.0/mapbox-gl.css" rel="stylesheet" /> -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" ></script>
<script type="text/javascript">
   

  $(document).on("click", "form#reset-password", function () {
    // alert("44");
    $("#error-password").html('');
    $("#error-cpassword").html('');
    var password = $("#password").val();
    var confirmPassword = $("#cpassword").val();
    var forgotid = $('#forgotid').val();
    var flag = 1;
    if (password == '') {
      $("#error-password").html("This field is required.");
      flag = 0;
    }else if(password.length  < 6){
      $("#error-password").html("Your password must be 6 characters.");
      flag = 0;
    }

    if (confirmPassword == '') {
      $("#error-cpassword").html("This field is required.");
      flag = 0;
    }else if(confirmPassword.length  < 6){
      $("#error-cpassword").html("Your password must be 6 characters.");
      flag = 0;
    }
    if (password != confirmPassword){
        $("#error-cpassword").html("Passwords does not match!");
      flag = 0;
    }
    // alert(flag);
    if(flag == 0){
      return false;
    }else{
      $.ajax({
          url:"ajaxQry.php",    //the page containing php script
          type: "post",    //request type,
          dataType : 'json',
          data: {action: "Reset_password", password: password,forgotid:forgotid},
          success:function(result){
            if(result == 'yes'){
            // $('.st-index-right').html('<h5>successfully change password. please click here: <a href="<?php echo $baseurl; ?>">Login</a></h5>');
            window.location.href = '<?php echo $baseurl; ?>';
            }
          }
        });
    }
  });
</script>