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

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

$userId = (int) ($_SESSION['password_reset_user_id'] ?? 0);
$resetCodeId = (int) ($_SESSION['password_reset_code_id'] ?? 0);
$verificationCode = trim($_POST['verification_code'] ?? '');

if ($userId <= 0 || $resetCodeId <= 0) {
    header('Location: forgot_password.php');
    exit();
}

if (!preg_match('/^\d{6}$/', $verificationCode)) {
    header('Location: verify_reset_code.php?error=invalid_input');
    exit();
}

$stmt = $conn->prepare("
    SELECT id, code_hash, expires_at, used_at
    FROM password_reset_codes
    WHERE id = ? AND user_id = ?
    LIMIT 1
");
$stmt->bind_param('ii', $resetCodeId, $userId);
$stmt->execute();
$resetCode = $stmt->get_result()->fetch_assoc();

if (!$resetCode || !empty($resetCode['used_at'])) {
    header('Location: forgot_password.php');
    exit();
}

if (strtotime((string) $resetCode['expires_at']) < time()) {
    $expireStmt = $conn->prepare("UPDATE password_reset_codes SET used_at = NOW() WHERE id = ?");
    $expireStmt->bind_param('i', $resetCodeId);
    $expireStmt->execute();

    unset($_SESSION['password_reset_user_id'], $_SESSION['password_reset_code_id'], $_SESSION['password_reset_email']);
    header('Location: forgot_password.php?error=expired');
    exit();
}

if (!password_verify($verificationCode, (string) $resetCode['code_hash'])) {
    header('Location: verify_reset_code.php?error=invalid_code');
    exit();
}

$_SESSION['password_reset_verified_user_id'] = $userId;
$_SESSION['password_reset_verified_code_id'] = $resetCodeId;

header('Location: reset_password.php');
exit();
