<?php
session_start();
require 'db.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';

$errors = [];
$success = '';
$step = 1;

// Handle email submission to generate token
if (isset($_POST['generate_token'])) {
    $email = trim($_POST['email']);

    if (empty($email)) {
        $errors[] = "Email is required";
    } else {
        $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->bind_param("s", $email);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            $stmt->bind_result($user_id);
            $stmt->fetch();

            $token = mt_rand(100000, 999999); // 6-digit token
            $expires = date("Y-m-d H:i:s", strtotime("+1 hour"));

            $stmt2 = $conn->prepare("UPDATE users SET reset_token=?, reset_expires=? WHERE id=?");
            $stmt2->bind_param("ssi", $token, $expires, $user_id);
            $stmt2->execute();
            $stmt2->close();

            $_SESSION['reset_email'] = $email;
            $step = 2; // Show token + password reset form

            // Send email with PHPMailer
            $mail = new PHPMailer(true);
            try {
                //Server settings
                $mail->isSMTP();
                $mail->Host = 'smtp.gmail.com';  // replace with your SMTP server
                $mail->SMTPAuth = true;
                $mail->Username = 'youremail@gmail.com'; // your email
                $mail->Password = 'yourpassword'; // your email password or app password
                $mail->SMTPSecure = 'tls';
                $mail->Port = 587;

                //Recipients
                $mail->setFrom('youremail@gmail.com', 'Tbils Property');
                $mail->addAddress($email);

                //Content
                $mail->isHTML(true);
                $mail->Subject = 'Password Reset Token';
                $mail->Body    = "Your password reset token is: <b>$token</b>. It expires in 1 hour.";

                $mail->send();
                $success = "Password reset token sent to your email! Please enter it below to reset your password.";
            } catch (Exception $e) {
                $errors[] = "Token generated but email could not be sent. Mailer Error: {$mail->ErrorInfo}";
            }

        } else {
            $errors[] = "No user found with this email";
        }
        $stmt->close();
    }
}

// Handle token + new password submission
if (isset($_POST['reset_password'])) {
    $email = $_SESSION['reset_email'] ?? '';
    $token_input = trim($_POST['token']);
    $new_password = trim($_POST['new_password']);
    $confirm_password = trim($_POST['confirm_password']);

    if (empty($token_input) || empty($new_password) || empty($confirm_password)) {
        $errors[] = "All fields are required";
    } elseif ($new_password !== $confirm_password) {
        $errors[] = "Passwords do not match";
    } else {
        $stmt = $conn->prepare("SELECT id, reset_expires FROM users WHERE email=? AND reset_token=?");
        $stmt->bind_param("ss", $email, $token_input);
        $stmt->execute();
        $stmt->store_result();

        if ($stmt->num_rows > 0) {
            $stmt->bind_result($user_id, $expires);
            $stmt->fetch();
            $stmt->close();

            if (strtotime($expires) < time()) {
                $errors[] = "Token has expired. Please generate a new one.";
                $step = 1;
            } else {
                $stmt2 = $conn->prepare("UPDATE users SET password=?, reset_token=NULL, reset_expires=NULL WHERE id=?");
                $stmt2->bind_param("si", $new_password, $user_id);
                $stmt2->execute();
                $stmt2->close();

                $success = "Password successfully reset! You can now login.";
                unset($_SESSION['reset_email']);
                $step = 1;
            }
        } else {
            $errors[] = "Invalid token.";
            $step = 2;
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Forgot Password - Tbils Property</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">

<div class="container d-flex justify-content-center align-items-center" style="min-height: 80vh;">
    <div class="card shadow-lg p-4" style="width: 100%; max-width: 400px;">
        <div class="text-center mb-4">
            <img src="assets/img/logo.png" width="70" height="70" class="d-block mx-auto mb-2" alt="Logo"/>
        </div>

        <h3 class="text-center mb-4 fw-bold">Forgot Password</h3>

        <?php if (!empty($errors)): ?>
            <div class="alert alert-danger">
                <ul class="mb-0">
                    <?php foreach ($errors as $error) echo "<li>$error</li>"; ?>
                </ul>
            </div>
        <?php endif; ?>

        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo $success; ?></div>
        <?php endif; ?>

        <?php if ($step === 1): ?>
            <form action="" method="POST">
                <div class="mb-3">
                    <label>Email</label>
                    <input type="email" class="form-control" name="email" required>
                </div>
                <button class="btn btn-primary w-100 py-2" name="generate_token" style="background-color:#000">Generate Reset Token</button>
            </form>
        <?php else: ?>
            <form action="" method="POST">
                <div class="mb-3">
                    <label>Enter Token</label>
                    <input type="text" class="form-control" name="token" required>
                </div>
                <div class="mb-3">
                    <label>New Password</label>
                    <input type="password" class="form-control" name="new_password" required>
                </div>
                <div class="mb-3">
                    <label>Confirm New Password</label>
                    <input type="password" class="form-control" name="confirm_password" required>
                </div>
                <button class="btn btn-primary w-100 py-2" name="reset_password" style="background-color:#000">Reset Password</button>
            </form>
        <?php endif; ?>

        <p class="text-center mt-3"><a href="login.php">Back to Login</a></p>
    </div>
</div>

</body>
</html>
