<?php
require_once "config/db.php";

$msg = "";

if(isset($_POST['submit'])){

    $email = trim($_POST['email']);

    $stmt = $conn->prepare("SELECT * FROM users WHERE email=?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if($result->num_rows === 1){

        $token = bin2hex(random_bytes(32));
        $expire = date("Y-m-d H:i:s", strtotime("+1 hour"));

        $stmt = $conn->prepare("UPDATE users SET reset_token=?, reset_expire=? WHERE email=?");
        $stmt->bind_param("sss", $token, $expire, $email);
        $stmt->execute();

        $link = "https://billing.digitalvega.in/reset_password.php?token=$token";

        // SIMPLE EMAIL (you can replace with SMTP later)
        mail($email, "Password Reset", "Click here: $link");

        $msg = "Reset link sent to your email";

    } else {
        $msg = "Email not found";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
<title>Forgot Password</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body class="d-flex align-items-center justify-content-center" style="height:100vh;background:#f5f5f5;">

<div class="card p-4 shadow" style="width:350px;">

<h5 class="text-center mb-3">Forgot Password</h5>

<?php if($msg){ ?>
<div class="alert alert-info"><?= $msg ?></div>
<?php } ?>

<form method="POST">
<input type="email" name="email" class="form-control mb-3" placeholder="Enter Email" required>
<button class="btn btn-primary w-100" name="submit">Send Reset Link</button>
</form>

</div>

</body>
</html>
