<?php
session_start();
require_once 'db.php';

$success = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email']);

    try {
        // Check user exists
        $stmt = $conn->prepare("SELECT id FROM users WHERE email = :email LIMIT 1");
        $stmt->bindValue(':email', $email, PDO::PARAM_STR);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($user) {
            $user_id = $user['id'];
            $token = bin2hex(random_bytes(32));
            $expires = date("Y-m-d H:i:s", strtotime("+1 hour"));

            // Delete old reset requests
            $stmtDel = $conn->prepare("DELETE FROM password_resets WHERE user_id = :uid");
            $stmtDel->bindValue(':uid', $user_id, PDO::PARAM_INT);
            $stmtDel->execute();

            // Insert new token
            $stmtInsert = $conn->prepare("INSERT INTO password_resets (user_id, token, expires_at) VALUES (:uid, :token, :expires)");
            $stmtInsert->bindValue(':uid', $user_id, PDO::PARAM_INT);
            $stmtInsert->bindValue(':token', $token, PDO::PARAM_STR);
            $stmtInsert->bindValue(':expires', $expires, PDO::PARAM_STR);
            $stmtInsert->execute();

            $resetLink = "https://savannahsystems.co.ke/Bella/reset-password.php?token=$token";

            $subject = "Password Reset Request - Taji Yetu";
            $message = "Hello,\n\nWe received a request to reset your password.\n\n";
            $message .= "Click the link below to reset it (valid for 1 hour):\n$resetLink\n\n";
            $message .= "If you did not request this, please ignore this email.\n\nBest Regards,\nTaji Yetu Team";

            $headers  = "From: Taji Yetu <no-reply@savannahsystems.co.ke>\r\n";
            $headers .= "Reply-To: no-reply@savannahsystems.co.ke\r\n";
            $headers .= "X-Mailer: PHP/" . phpversion();

            if (mail($email, $subject, $message, $headers)) {
                $success = "✅ A reset link has been sent to your email.";
            } else {
                $error = "❌ Failed to send email. Please try again later.";
            }
        } else {
            $error = "❌ No account found with that email.";
        }
    } catch (Exception $e) {
        $error = "❌ Server error: " . $e->getMessage();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Forgot Password - Taji Yetu</title>
<link rel="icon" href="images/taji-yetu.png" type="image/png">
<style>
body {
    font-family: 'Inter', sans-serif;
    display:flex; justify-content:center; align-items:center;
    height:100vh; background:#000; color:#fff; margin:0; overflow:hidden;
}
canvas#bg {
    position: fixed;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: #000;
    z-index: -1;
}
.container {
    background: rgba(0,0,0,0.85);
    padding: 30px;
    border-radius: 12px;
    width: 100%;
    max-width: 400px;
    box-shadow: 0 0 15px rgba(255,255,255,0.2);
    animation: fadeIn 1.2s ease;
}
@keyframes fadeIn {
    from { opacity: 0; transform: translateY(40px); }
    to { opacity: 1; transform: translateY(0); }
}
h2 {
    text-align: center;
    margin-bottom: 20px;
}
input {
    width: 100%;
    padding: 10px;
    margin-bottom: 20px;
    border-radius: 6px;
    border: none;
    background: #111;
    color: #fff;
}
input:focus {
    outline: none;
    box-shadow: 0 0 5px #fff;
}
button {
    width: 100%;
    padding: 12px;
    border: none;
    border-radius: 8px;
    background: #fff;
    color: #000;
    font-weight: bold;
    cursor: pointer;
    transition: 0.3s;
}
button:hover {
    background: #000;
    color: #fff;
    transform: scale(1.05);
    box-shadow: 0 0 10px #fff;
}
.error {
    color: #ff8080;
    margin-bottom: 15px;
    text-align: center;
}
.success {
    color: #80ff80;
    margin-bottom: 15px;
    text-align: center;
}
a {
    color: #fff;
    text-decoration: none;
}
a:hover {
    text-decoration: underline;
    color: #ccc;
}
@media (max-width: 600px) {
    .container {
        padding: 20px;
        margin: 10px;
    }
}
</style>
</head>
<body>
<canvas id="bg"></canvas>

<div class="container">
<h2>Forgot Password</h2>

<?php if($error) echo "<div class='error'>$error</div>"; ?>
<?php if($success) echo "<div class='success'>$success</div>"; ?>

<form method="POST">
    <input type="email" name="email" placeholder="Enter your email" required>
    <button type="submit">Send Reset Link</button>
</form>

<p style="text-align:center;">Back to <a href="login.php">Login</a></p>
</div>

<script>
const canvas = document.getElementById('bg');
const ctx = canvas.getContext('2d');
let particles = [];

function resize() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
}
window.addEventListener('resize', resize);
resize();

for (let i = 0; i < 80; i++) {
  particles.push({
    x: Math.random() * canvas.width,
    y: Math.random() * canvas.height,
    size: Math.random() * 2 + 1
  });
}

function animate() {
  ctx.fillStyle = "#000";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "white";
  particles.forEach(p => {
    ctx.beginPath();
    ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2);
    ctx.fill();
    p.y -= 0.3;
    if (p.y < 0) p.y = canvas.height;
  });
  requestAnimationFrame(animate);
}
animate();
</script>
</body>
</html>
