<?php
require 'phpmailr/PHPMailer.php';
require 'phpmailr/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;

// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Retrieve the submitted email address
  $email = $_POST['email'];
require_once '../config.php';
  // Validate the email address (e.g., format and existence in the database)
  // Example code using PDO (PHP Data Objects) for database interaction
  $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_password);

  // Prepare the SQL statement to check if the email exists in the database
  $stmt = $pdo->prepare("SELECT * FROM users WHERE username = :email");
  $stmt->execute(['email' => $email]);

  // Fetch the user record
  $user = $stmt->fetch();

  // Check if the user exists
  if (!$user) {
    // Display an error message or redirect to an error page
    // ...
  }

  // Generate a unique and secure password reset token
  $token = bin2hex(random_bytes(32));

  // Calculate the expiration time (e.g., 1 hour from now)
  $expiration = date('Y-m-d H:i:s', strtotime('+1 hour'));

  // Store the token and its expiration time in the database for the user
  // Prepare the SQL statement to update the user record with the token and expiration time
  $stmt = $pdo->prepare("UPDATE users SET reset_token = :token, token_expiration = :expiration WHERE username = :email");
  $stmt->execute(['token' => $token, 'expiration' => $expiration, 'email' => $email]);

  // Send the password reset email to the user's email address
  $resetLink = "https://ceseasiamissions.org/portal/reset_password.php?token=" . $token;
  //$emailBody = "Click the following link to reset your password: $resetLink";
  $emailBody = "Hello, " . $user['name'] . "!\n\n";
$emailBody .= "We received a request to reset your password. To proceed with the password reset, please click the link below:\n\n";
$emailBody .= "$resetLink\n\n";
$emailBody .= "If you didn't request a password reset, you can safely ignore this email. Your current password will remain unchanged.\n\n";
$emailBody .= "Thank you,\n";
$emailBody .= "CE SE Asia Missions Support Team";
  $emailSubject = "Password Reset for Your CE SE Asia Missions Account";
  // Create a new PHPMailer instance
$mail = new PHPMailer();

// Enable SMTP debugging (optional)
$mail->SMTPDebug = SMTP::DEBUG_OFF; // Set to SMTP::DEBUG_SERVER for detailed debug output
$mail->Debugoutput = 'html';

// Set the SMTP credentials and server settings
$mail->isSMTP();
$mail->Host = 'smtp-relay.brevo.com';
$mail->SMTPAuth = true;
$mail->Username = 'admin@ceseasiamissions.org';
$mail->Password = '7ZkYPVJbjdGAraLT';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;

// Set the email content and attributes
$mail->setFrom('admin@ceseasiamissions.org', 'Christ Embassy South-East Asia Intl Missions');
$mail->addAddress($email);
$mail->Subject = $emailSubject;
$mail->Body = $emailBody;
$mail->CharSet = 'UTF-8';

// Send the email
if ($mail->send()) {
  echo 'Email sent successfully!';
} else {
  echo 'Email could not be sent. Error: ' . $mail->ErrorInfo;
}
  //mail($email, "Password Reset", $emailBody);

  // Redirect the user to a confirmation page
  header("Location: reset_password_confirmation.php");
  exit();
}


?>
<?php
// Check if the token is provided in the query string
if (isset($_GET['token'])) {
  $token = $_GET['token'];
require_once '../config.php';
  // Validate the token and retrieve the associated user from the database
  // Example code using PDO (PHP Data Objects) for database interaction
  $pdo = new PDO("mysql:host=$db_host;dbname=$db_name", $db_user, $db_password);

  // Prepare the SQL statement to retrieve the user based on the token
  $stmt = $pdo->prepare("SELECT * FROM users WHERE reset_token = :token");
  $stmt->execute(['token' => $token]);

  // Fetch the user record
  $user = $stmt->fetch();

  // Check if the user exists and the token is valid
  if (!$user || $user['token_expiration'] < date('Y-m-d H:i:s')) {
    // Display an error message or redirect to an error page
    echo "Invalid token or expired";
    // ...
  }
} else {
  // Display an error message or redirect to an error page
  // ...
}
?>

<?php
if ($user && $user['token_expiration'] >= date('Y-m-d H:i:s')) {
// Token is valid, proceed with password reset logic
// ...
// Display the password reset form
?>


<!DOCTYPE html>
<html>
<head>
  <title>Reset Password</title>
</head>
<body>
  <h2>Reset Your Password</h2>
  <form method="post" action="process_reset_password.php">
    <input type="hidden" name="token" value="<?php echo $token; ?>">
    <div>
      <label for="new_password">New Password:</label>
      <input type="password" id="new_password" name="new_password" required>
    </div>
    <div>
      <label for="confirm_password">Confirm Password:</label>
      <input type="password" id="confirm_password" name="confirm_password" required>
    </div>
    <div>
      <button type="submit">Reset Password</button>
    </div>
  </form>
</body>
</html>
<?php

} else {
      // Invalid token or expired, display an error message or redirect to an error page
      echo "Invalid or expired token.";
    }
