<?php
// File: auth/reset_password.php
require_once '../config/db.php';

// Bagian 1: Form Permintaan Token Reset
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['email'])) {
    $email = $_POST['email'];

    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user) {
        $token = bin2hex(random_bytes(16));
        $expires = date('Y-m-d H:i:s', strtotime('+1 hour'));

        $stmt = $pdo->prepare("INSERT INTO reset_tokens (user_id, token, expires_at) VALUES (?, ?, ?)");
        $stmt->execute([$user['id'], $token, $expires]);

        echo "<div class='form-container'>";
        echo "<h3>Token berhasil dibuat!</h3>";
        echo "<p>Salin link berikut dan buka di browser:</p>";
        echo "<a href='reset_password.php?token=$token'>reset_password.php?token=$token</a>";
        echo "</div>";
        exit;
    } else {
        echo "<div class='form-container'><p>Email tidak ditemukan.</p></div>";
    }
}

// Bagian 2: Form Ganti Password Jika Token Valid
if (isset($_GET['token'])) {
    $token = $_GET['token'];

    $stmt = $pdo->prepare("SELECT user_id FROM reset_tokens WHERE token = ? AND expires_at > NOW()");
    $stmt->execute([$token]);
    $row = $stmt->fetch();

    if (!$row) {
        exit("<div class='form-container'><p>Token tidak valid atau sudah kadaluarsa.</p></div>");
    }

    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['new_password'])) {
        $new = $_POST['new_password'];
        $hash = password_hash($new, PASSWORD_BCRYPT);

        $pdo->prepare("UPDATE users SET password = ? WHERE id = ?")->execute([$hash, $row['user_id']]);
        $pdo->prepare("DELETE FROM reset_tokens WHERE token = ?")->execute([$token]);

        echo "<div class='form-container'><p>Password berhasil direset. Silakan <a href='login.php'>login</a>.</p></div>";
        exit;
    }
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Reset Password Baru</title>
    <link rel="stylesheet" href="../style.css">
</head>
<body>
<div class="form-container">
    <h2>Reset Password Baru</h2>
    <form method="POST">
        <input type="password" name="new_password" placeholder="Password baru" required>
        <button type="submit">Reset Sekarang</button>
    </form>
</div>
</body>
</html>
<?php
    exit;
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Lupa Password | KOMFAK</title>
    <link rel="stylesheet" href="../style.css">
</head>
<body>
<div class="form-container">
    <h2>Lupa Password</h2>
    <form method="POST">
        <input type="email" name="email" placeholder="Masukkan email" required>
        <button type="submit">Kirim Token Reset</button>
    </form>
</div>
</body>
</html>
