<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/session.php';
require_once __DIR__ . '/includes/Database.php';
require_once __DIR__ . '/includes/SecurityGuard.php';
require_once __DIR__ . '/includes/Notifier.php';

use KawalCloud\Database;
use KawalCloud\Notifier;
use KawalCloud\SecurityGuard;

SecurityGuard::applySecurityHeaders(false);
header('Referrer-Policy: no-referrer');

if (!empty($_SESSION['kw_logged_in'])) {
    header('Location: ./');
    exit;
}

function e(?string $s): string
{
    return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

$pdo = Database::getConnection();
$csrf = SecurityGuard::getCsrfToken();
$sent = false;
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $identifier = trim((string)($_POST['identifier'] ?? ''));
    $ip = SecurityGuard::getClientIp();

    if (!SecurityGuard::verifyCsrfToken([], true)) {
        $error = 'Sesi formulir kedaluwarsa. Muat ulang halaman lalu coba lagi.';
    } elseif ($identifier === '' || strlen($identifier) > 150) {
        $error = 'Masukkan username atau email Anda.';
    } else {
        $rlIp  = SecurityGuard::checkRateLimit($pdo, 'forgot_ip_' . $ip, 5, 3600);
        $rlAcc = SecurityGuard::checkRateLimit($pdo, 'forgot_acc_' . hash('sha256', strtolower($identifier)), 3, 3600);

        if (!$rlIp['allowed'] || !$rlAcc['allowed']) {
            $error = 'Terlalu banyak permintaan. Coba lagi dalam beberapa menit.';
        } else {
            // Respons SELALU sama (tidak membocorkan apakah akun ada atau tidak)
            $sent = true;

            $stmt = $pdo->prepare("
                SELECT id, username, email FROM users
                WHERE (username = :u OR LOWER(email) = LOWER(:u)) AND is_active = 1
                ORDER BY id ASC LIMIT 3
            ");
            $stmt->execute([':u' => $identifier]);
            $users = $stmt->fetchAll();

            $appUrl = rtrim((string)(getenv('APP_URL') ?: ''), '/');
            foreach ($users as $u) {
                if ($appUrl === '' || !filter_var($u['email'], FILTER_VALIDATE_EMAIL)) {
                    Database::audit('password.reset_email_skipped', 'user_id=' . (int)$u['id'] . ($appUrl === '' ? ' (APP_URL kosong)' : ' (email tidak valid)'), 0);
                    continue;
                }

                // Batalkan token lama yang belum dipakai, buat token baru (hanya hash yang disimpan)
                $pdo->prepare("UPDATE password_resets SET used_at = CURRENT_TIMESTAMP WHERE user_id = :id AND used_at IS NULL")
                    ->execute([':id' => $u['id']]);
                $token = bin2hex(random_bytes(32));
                $pdo->prepare("
                    INSERT INTO password_resets (user_id, token_hash, expires_at)
                    VALUES (:id, :h, :exp)
                ")->execute([
                    ':id'  => $u['id'],
                    ':h'   => hash('sha256', $token),
                    ':exp' => date('Y-m-d H:i:s', time() + 1800),
                ]);

                $link = $appUrl . '/reset?token=' . $token;
                $html = '<p>Halo <strong>' . e($u['username']) . '</strong>,</p>'
                    . '<p>Kami menerima permintaan reset password untuk akun KawalCloud Anda. '
                    . 'Klik tautan berikut (berlaku <strong>30 menit</strong>, hanya satu kali pakai):</p>'
                    . '<p><a href="' . e($link) . '">' . e($link) . '</a></p>'
                    . '<p>Jika Anda tidak meminta ini, abaikan email ini. Password Anda tidak berubah.</p>';

                $notifier = new Notifier(Database::getSettings(1));
                $res = $notifier->sendEmail('Reset Password KawalCloud', $html, $u['email']);
                Database::audit($res['ok'] ?? false ? 'password.reset_email_sent' : 'password.reset_email_failed', 'user_id=' . (int)$u['id'], 0);
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="referrer" content="no-referrer">
    <title>Lupa Password — KawalCloud</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>tailwind.config = { darkMode: 'class' };</script>
<?php include __DIR__ . '/includes/head_icons.php'; ?>
</head>
<body class="min-h-screen bg-[#09090b] text-zinc-200 flex items-center justify-center p-4">
<div class="w-full max-w-[400px] bg-[#121215] border border-zinc-800 rounded-lg p-6">
    <h1 class="text-lg font-semibold mb-1">Lupa Password</h1>
    <p class="text-xs text-zinc-400 mb-5">Masukkan username atau email akun Anda. Kami akan mengirim tautan untuk membuat password baru.</p>

    <?php if ($error !== ''): ?>
        <div class="mb-4 p-3 rounded-md bg-rose-950/40 border border-rose-900/60 text-xs text-rose-300"><?= e($error) ?></div>
    <?php endif; ?>

    <?php if ($sent): ?>
        <div class="p-3 rounded-md bg-emerald-950/40 border border-emerald-900/60 text-xs text-emerald-300 leading-relaxed">
            Jika akun tersebut terdaftar, tautan reset password telah dikirim ke email terkait. Periksa kotak masuk (dan folder spam).
        </div>
    <?php else: ?>
        <form method="POST" action="forgot" class="space-y-4">
            <input type="hidden" name="csrf_token" value="<?= e($csrf) ?>">
            <div>
                <label class="block text-xs font-medium mb-1.5">Username atau Email</label>
                <input type="text" name="identifier" required autofocus maxlength="150"
                       class="w-full px-3 py-2 rounded-md bg-[#09090B] border border-zinc-800 text-xs font-mono focus:outline-none focus:border-zinc-400">
            </div>
            <button type="submit" class="w-full py-2 rounded-md bg-zinc-100 hover:bg-white text-zinc-950 font-semibold text-xs">Kirim Tautan Reset</button>
        </form>
    <?php endif; ?>

    <div class="mt-5 text-center text-[11px]"><a href="login" class="text-emerald-400 hover:underline">← Kembali ke Login</a></div>
</div>
</body>
</html>
