<?php
require_once __DIR__ . '/../includes/security.php';
secureSessionStart();
// File: admin/forgot_password.php
require_once '../includes/db_connect.php';

$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $username = $_POST['username'];
    
    // Cek user
    $stmt = $pdo->prepare("SELECT id FROM admin_users WHERE username = ?");
    $stmt->execute([$username]);
    $user = $stmt->fetch();

    if ($user) {
        // Generate Token Simpel
        $token = bin2hex(random_bytes(16));
        $expiry = date('Y-m-d H:i:s', strtotime('+1 hour'));
        
        // Simpan ke DB
        $update = $pdo->prepare("UPDATE admin_users SET reset_token = ?, reset_expiry = ? WHERE id = ?");
        $update->execute([$token, $expiry, $user['id']]);
        
        // Di sistem real, ini kirim email. Di sini kita simulasi aja.
        $msg = "<div class='bg-green-100 text-green-700 p-4 rounded mb-4 text-sm'>
            <strong>Permintaan Diterima!</strong><br>
            Hubungi Tim IT dan berikan username Anda. Tim IT akan mereset password melalui database atau memberikan link reset khusus.
            <br><span class='text-xs text-gray-500 mt-2 block'>(Dev Note: Token tersimpan di DB: $token)</span>
        </div>";
    } else {
        $msg = "<div class='bg-red-100 text-red-700 p-3 rounded mb-4'>Username tidak ditemukan!</div>";
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <title>Lupa Password</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 h-screen flex items-center justify-center">
    <div class="bg-white p-8 rounded-xl shadow-lg w-96">
        <h2 class="text-2xl font-bold mb-2 text-center text-gray-800">Reset Password</h2>
        <p class="text-center text-gray-500 text-sm mb-6">Masukkan username Anda</p>
        
        <?= $msg ?>
        
        <form method="POST">
            <div class="mb-6">
                <label class="block text-gray-700 text-sm font-bold mb-2">Username</label>
                <input type="text" name="username" class="w-full p-2.5 border rounded focus:ring-2 focus:ring-blue-500 focus:outline-none" required>
            </div>
            <button type="submit" class="w-full bg-blue-600 text-white font-bold py-2.5 px-4 rounded hover:bg-blue-700 transition">Kirim Permintaan</button>
        </form>
        <div class="text-center mt-4">
            <a href="login.php" class="text-sm text-gray-500 hover:text-gray-800">Kembali ke Login</a>
        </div>
    </div>
</body>
</html>