<?php
require_once dirname(__DIR__) . '/config.php';

header('Content-Type: application/json');

$email = trim($_POST['email'] ?? '');
$code = trim($_POST['code'] ?? '');
$password = $_POST['password'] ?? '';
$confirm_password = $_POST['confirm_password'] ?? '';

if (empty($email) || empty($code) || empty($password)) {
    echo json_encode(['success' => false, 'message' => '请填写完整信息']);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['success' => false, 'message' => '邮箱格式不正确']);
    exit;
}

if (strlen($password) < 6) {
    echo json_encode(['success' => false, 'message' => '密码至少6位']);
    exit;
}

if ($password !== $confirm_password) {
    echo json_encode(['success' => false, 'message' => '两次密码不一致']);
    exit;
}

// 验证验证码
$record = $db->fetchOne("SELECT * FROM email_verify_codes 
                         WHERE email = '$email' 
                         AND code = '$code' 
                         AND type = 'reset' 
                         AND used = 0 
                         AND expired_at > NOW()");

if (!$record) {
    echo json_encode(['success' => false, 'message' => '验证码错误或已过期']);
    exit;
}

// 更新密码
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$db->query("UPDATE users SET password = '$hashed_password' WHERE email = '$email'");

// 标记验证码为已使用
$db->query("UPDATE email_verify_codes SET used = 1 WHERE id = {$record['id']}");

echo json_encode(['success' => true, 'message' => '密码重置成功，请登录']);