<?php
require_once __DIR__ . '/db.php';

if (isset($_SESSION['user_id'])) {
    header('Location: dashboard.php');
    exit();
}

$emel = trim($_POST['emel'] ?? '');
$ic = trim($_POST['ic'] ?? '');
$normalizedIc = preg_replace('/[\s-]+/', '', $ic);

if ($emel === '' || $ic === '') {
    header('Location: forgot_password.php?error=invalid_input');
    exit();
}

$stmt = $conn->prepare("
    SELECT id, nama, ic, emel, approval_status, account_status
    FROM users
    WHERE emel = ?
      AND (ic = ? OR REPLACE(REPLACE(ic, '-', ''), ' ', '') = ?)
    LIMIT 1
");
$stmt->bind_param('sss', $emel, $ic, $normalizedIc);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    header('Location: forgot_password.php?error=not_found');
    exit();
}

if (($user['approval_status'] ?? '') !== 'active' || ($user['account_status'] ?? '') !== 'active') {
    header('Location: forgot_password.php?error=inactive_account');
    exit();
}

$code = (string) random_int(100000, 999999);
$codeHash = password_hash($code, PASSWORD_DEFAULT);
$expiresAt = date('Y-m-d H:i:s', time() + (15 * 60));
$userId = (int) $user['id'];

$conn->begin_transaction();

$cleanup = $conn->prepare("UPDATE password_reset_codes SET used_at = NOW() WHERE user_id = ? AND used_at IS NULL");
$cleanup->bind_param('i', $userId);
$cleanup->execute();

$insert = $conn->prepare("
    INSERT INTO password_reset_codes (user_id, emel, ic, code_hash, expires_at)
    VALUES (?, ?, ?, ?, ?)
");
$storedIc = (string) $user['ic'];
$insert->bind_param('issss', $userId, $emel, $storedIc, $codeHash, $expiresAt);
$insert->execute();
$resetCodeId = (int) $conn->insert_id;

$conn->commit();

if (!send_password_reset_code($emel, (string) $user['nama'], $code)) {
    $markFailed = $conn->prepare("UPDATE password_reset_codes SET used_at = NOW() WHERE id = ?");
    $markFailed->bind_param('i', $resetCodeId);
    $markFailed->execute();

    header('Location: forgot_password.php?error=mail_failed');
    exit();
}

$_SESSION['password_reset_user_id'] = $userId;
$_SESSION['password_reset_code_id'] = $resetCodeId;
$_SESSION['password_reset_email'] = $emel;

header('Location: verify_reset_code.php?success=code_sent');
exit();
