<?php
session_start();
require_once '../../includes/db_connect.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_id = $_POST['user_id'];
    $input_code = $_POST['code'];

    $stmt = $conn->prepare("SELECT code, expires_at, used FROM Password_reset_codes 
                            WHERE user_id = ? ORDER BY created_at DESC LIMIT 1");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $code_row = $result->fetch_assoc();

    if (!$code_row || $code_row['used'] || new DateTime() > new DateTime($code_row['expires_at']) || !password_verify($input_code, $code_row['code'])) {
        $_SESSION['error'] = "유효하지 않거나 만료된 코드입니다.";
        header("Location: /Capstone/auth/enter-code.php?user_id=$user_id");
        exit;
    }

    $_SESSION['user_id'] = $user_id;
    header("Location: /Capstone/pages/user/reset-password.php");
    exit;
}
?>
