<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../includes/db.php';
require_once '../includes/helpers.php';

$message = '';
$message_type = 'info';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    
    $token = bin2hex(random_bytes(16));
    $token_hash = hash("sha256", $token);
    $expiry_time = date("Y-m-d H:i:s", time() + 60 * 15); // 15 minute expiry

    $stmt = $conn->prepare("UPDATE admins SET reset_token_hash = ?, reset_token_expires_at = ? WHERE email = ?");
    $stmt->bind_param("sss", $token_hash, $expiry_time, $email);
    $stmt->execute();

    if ($stmt->affected_rows > 0) {
        $reset_link = "https://" . $_SERVER["HTTP_HOST"] . "/admin/reset-password.php?token=$token";
        $subject = "Admin Password Reset Request";
        $body = "<p>Click the link below to reset your admin password. The link is valid for 15 minutes.</p><p><a href='$reset_link'>$reset_link</a></p>";
        send_email($email, $subject, $body);
    }
    $stmt->close();
    
    $message = "If an account with that email exists, a password reset link has been sent.";
}
?>
<!DOCTYPE html>
<html lang="en" data-bs-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Admin Forgot Password</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style> body { background-color: var(--bs-body-bg); } </style>
</head>
<body>
    <div class="container"><div class="row justify-content-center align-items-center vh-100"><div class="col-md-6 col-lg-4">
        <div class="text-center mb-4"><h1 class="h3">Reset Admin Password</h1></div>
        <div class="card shadow-sm border-0"><div class="card-body p-4">
            <?php if ($message): ?>
                <div class="alert alert-<?php echo $message_type; ?>"><?php echo $message; ?></div>
            <?php endif; ?>
            <form method="POST">
                <div class="mb-3"><label for="email" class="form-label">Your Admin Email</label><input type="email" class="form-control" id="email" name="email" required autofocus></div>
                <div class="d-grid"><button type="submit" class="btn btn-primary">Send Reset Link</button></div>
            </form>
        </div>
        <div class="text-center mt-3"><a href="index.php" class="text-muted small">← Back to Login</a></div>
    </div></div></div>
</body>
</html>
