<?php
include 'db.php';

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

$email = normalizeEmailAddress($_POST['email'] ?? '');
$ic_number_input = trim($_POST['ic_number'] ?? '');
$ic_number = normalizeIcNumber($ic_number_input);

if ($email === '' || $ic_number === '' || !isValidEmailAddress($email)) {
    echo "<script>alert('Maklumat tidak sah. Sila gunakan emel berdaftar dan nombor kad pengenalan yang betul.'); window.history.back();</script>";
    exit();
}

$stmt = mysqli_prepare($conn, "SELECT id, fullname FROM users WHERE LOWER(email) = ? AND REPLACE(REPLACE(ic_number, '-', ''), ' ', '') = ? LIMIT 1");
if (!$stmt) {
    echo "<script>alert('Ralat sistem. Sila cuba lagi.'); window.history.back();</script>";
    exit();
}

mysqli_stmt_bind_param($stmt, "ss", $email, $ic_number);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$user = $result ? mysqli_fetch_assoc($result) : null;

if (!$user) {
    echo "<script>alert('Emel atau No. Kad Pengenalan tidak sepadan dalam sistem.'); window.history.back();</script>";
    exit();
}
$recipient_name = trim((string) ($user['fullname'] ?? ''));

$token = str_pad((string) random_int(0, 999999), 6, '0', STR_PAD_LEFT);
$expires = date('Y-m-d H:i:s', strtotime('+' . getPasswordResetExpiryMinutes() . ' minutes'));

$cleanup = mysqli_prepare($conn, "DELETE FROM password_resets WHERE email = ? OR expires_at < NOW()");
if ($cleanup) {
    mysqli_stmt_bind_param($cleanup, "s", $email);
    mysqli_stmt_execute($cleanup);
}

$insert = mysqli_prepare($conn, "INSERT INTO password_resets (email, token, expires_at) VALUES (?, ?, ?)");
if (!$insert) {
    echo "<script>alert('Ralat sistem semasa menyediakan token reset.'); window.history.back();</script>";
    exit();
}

mysqli_stmt_bind_param($insert, "sss", $email, $token, $expires);
mysqli_stmt_execute($insert);

if (mysqli_stmt_affected_rows($insert) < 1) {
    echo "<script>alert('Token reset gagal dijana. Sila cuba lagi.'); window.history.back();</script>";
    exit();
}

$mail_result = sendPasswordResetTokenEmail($email, $token, $expires, $recipient_name);
if (!$mail_result['success']) {
    $rollback = mysqli_prepare($conn, "DELETE FROM password_resets WHERE email = ? AND token = ?");
    if ($rollback) {
        mysqli_stmt_bind_param($rollback, "ss", $email, $token);
        mysqli_stmt_execute($rollback);
    }

    $mail_error = trim((string) ($mail_result['message'] ?? ''));
    $alert_message = 'Token tidak dapat dihantar ke emel anda.';
    if ($mail_error !== '') {
        $alert_message .= "\\n\\nPunca: " . $mail_error;
    }
    $alert_message .= "\\n\\nSila semak mail_config.php dan tetapan SMTP/App Password emel penghantar.";

    echo "<script>alert(" . json_encode($alert_message, JSON_UNESCAPED_UNICODE) . "); window.history.back();</script>";
    exit();
}

echo "<script>alert('Token reset telah dihantar ke emel anda. Sila semak inbox atau fail spam.'); window.location='reset_password.php?email=" . urlencode($email) . "';</script>";
exit();

