<?php
/**
 * 验证验证码并完成注册/登录 API
 * 请求方式：POST
 */

require_once dirname(__DIR__) . '/config.php';
require_once dirname(__DIR__) . '/includes/verify_code_helper.php';
require_once dirname(__DIR__) . '/includes/functions.php';

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

// 只接受 POST 请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => '请求方式错误']);
    exit;
}

// 获取参数
$type = $_POST['type'] ?? '';
$email = trim($_POST['email'] ?? '');
$code = trim($_POST['code'] ?? '');

// 注册相关参数
$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';
$confirm_password = $_POST['confirm_password'] ?? '';

// 登录相关参数
$login_email = trim($_POST['login_email'] ?? '');
$login_code = trim($_POST['login_code'] ?? '');

if ($type === 'register') {
    // ========== 注册验证 ==========
    if (empty($username) || empty($password) || empty($email) || empty($code)) {
        echo json_encode(['success' => false, 'message' => '请填写完整信息']);
        exit;
    }
    
    if (strlen($username) < 3 || strlen($username) > 20) {
        echo json_encode(['success' => false, 'message' => '用户名3-20个字符']);
        exit;
    }
    
    if (strlen($password) < 6) {
        echo json_encode(['success' => false, 'message' => '密码至少6位']);
        exit;
    }
    
    if ($password !== $confirm_password) {
        echo json_encode(['success' => false, 'message' => '两次密码不一致']);
        exit;
    }
    
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['success' => false, 'message' => '邮箱格式不正确']);
        exit;
    }
    
    $result = completeRegisterWithCode($username, $password, $email, $code);
    echo json_encode($result);
    
} elseif ($type === 'login') {
    // ========== 登录验证 ==========
    if (empty($login_email) || empty($login_code)) {
        echo json_encode(['success' => false, 'message' => '请输入邮箱和验证码']);
        exit;
    }
    
    if (!filter_var($login_email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['success' => false, 'message' => '邮箱格式不正确']);
        exit;
    }
    
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    
    // 检查登录失败限制
    $limit = checkLoginLimit($ip);
    if ($limit['locked']) {
        echo json_encode(['success' => false, 'message' => $limit['message']]);
        exit;
    }
    
    $result = completeLoginWithCode($login_email, $login_code);
    
    // ========== 登录成功后添加提醒和日志 ==========
    if ($result['success']) {
        // 登录成功，清除失败记录
        clearLoginFail($ip);
        
        // 获取用户信息
        $user = $db->fetchOne("SELECT * FROM users WHERE email = '$login_email'");
        if ($user && !empty($user['email']) && ($user['email_notify'] ?? 1)) {
            $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
            $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
            $login_time = date('Y-m-d H:i:s');
            
            // 获取IP位置
            function getIpLocation($ip) {
                if ($ip == '127.0.0.1' || $ip == 'localhost') return '本地';
                $url = "https://v2.xxapi.cn/api/ip?ip=" . urlencode($ip);
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 3);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $response = curl_exec($ch);
                curl_close($ch);
                $data = json_decode($response, true);
                if ($data && $data['code'] == 200 && !empty($data['data']['address'])) {
                    return $data['data']['address'];
                }
                return '未知位置';
            }
            
            // 获取设备类型（使用增强函数）
            $device_info = getDetailedDeviceInfo($user_agent);
            $device = $device_info['full'];
            $city = getIpLocation($ip);
            
            // 引入邮件函数
            require_once dirname(__DIR__) . '/includes/mail_helper.php';
            sendLoginAlert($user, $ip, $city, $device, $login_time);
        }
        
        // 记录登录日志
        $db->query("INSERT INTO user_login_log (user_id, ip, city, device, user_agent) 
                    VALUES ({$user['id']}, '$ip', '$city', '$device', '" . addslashes($user_agent) . "')");
    } else {
        // 登录失败，记录失败次数
        $fail_result = recordLoginFail($ip, $login_email);
        $result['message'] = $fail_result['message'];
    }
    
    echo json_encode($result);
    
} else {
    echo json_encode(['success' => false, 'message' => '请求类型错误']);
    exit;
}
?>