<?php
include 'db.php';

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    header('Location: forgot_password.php');
    exit();
}

$email = normalizeEmailAddress($_POST['email'] ?? '');
$token = preg_replace('/\D+/', '', (string) ($_POST['token'] ?? ''));
$new_pass = $_POST['new_pass'] ?? '';
$confirm = $_POST['confirm_pass'] ?? '';

if ($email === '' || $token === '' || !isValidEmailAddress($email)) {
    echo "<script>alert('Maklumat reset kata laluan tidak sah.'); window.history.back();</script>";
    exit();
}

if ($new_pass !== $confirm) {
    echo "<script>alert('Kata laluan tidak sepadan.'); window.history.back();</script>";
    exit();
}

$stmt = mysqli_prepare($conn, "SELECT token, expires_at FROM password_resets WHERE email = ? ORDER BY created_at DESC LIMIT 1");
if (!$stmt) {
    echo "<script>alert('Ralat sistem. Sila cuba lagi.'); window.history.back();</script>";
    exit();
}

mysqli_stmt_bind_param($stmt, "s", $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

if (!$row = mysqli_fetch_assoc($result)) {
    echo "<script>alert('Tiada permintaan reset dijumpai.'); window.history.back();</script>";
    exit();
}

if (strtotime($row['expires_at']) <= time()) {
    $cleanup = mysqli_prepare($conn, "DELETE FROM password_resets WHERE email = ?");
    if ($cleanup) {
        mysqli_stmt_bind_param($cleanup, "s", $email);
        mysqli_stmt_execute($cleanup);
    }

    echo "<script>alert('Token telah tamat tempoh. Sila buat permintaan token baharu.'); window.history.back();</script>";
    exit();
}

if (!hash_equals((string) $row['token'], (string) $token)) {
    echo "<script>alert('Token salah. Sila semak semula token 6 digit yang dihantar ke emel anda.'); window.history.back();</script>";
    exit();
}

$hash = password_hash($new_pass, PASSWORD_DEFAULT);

$update = mysqli_prepare($conn, "UPDATE users SET password = ? WHERE LOWER(email) = ?");
if (!$update) {
    echo "<script>alert('Ralat sistem semasa mengemas kini kata laluan.'); window.history.back();</script>";
    exit();
}

mysqli_stmt_bind_param($update, "ss", $hash, $email);
mysqli_stmt_execute($update);

if (mysqli_stmt_affected_rows($update) < 0) {
    echo "<script>alert('Kata laluan gagal dikemaskini. Sila cuba lagi.'); window.history.back();</script>";
    exit();
}

$del = mysqli_prepare($conn, "DELETE FROM password_resets WHERE email = ?");
if ($del) {
    mysqli_stmt_bind_param($del, "s", $email);
    mysqli_stmt_execute($del);
}

echo "<script>alert('Kata laluan berjaya ditukar. Sila log masuk dengan kata laluan baru.'); window.location='login.php';</script>";
exit();
