<?php
/**
 * 验证码辅助函数
 */

// 生成6位数字验证码
function generateVerifyCode() {
    return sprintf("%06d", mt_rand(0, 999999));
}

// 保存验证码到数据库
function saveVerifyCode($email, $code, $type = 'register') {
    global $db;
    
    // 删除该邮箱同类型的旧验证码
    $db->query("DELETE FROM email_verify_codes WHERE email = '$email' AND type = '$type' AND used = 0");
    
    // 设置5分钟过期
    $expired_at = date('Y-m-d H:i:s', strtotime('+5 minutes'));
    
    $db->query("INSERT INTO email_verify_codes (email, code, type, expired_at) 
                VALUES ('$email', '$code', '$type', '$expired_at')");
    
    return true;
}

// 验证验证码
function verifyCode($email, $code, $type = 'register') {
    global $db;
    
    $code = trim($code);
    $email = trim($email);
    
    if (empty($email) || empty($code)) {
        return ['valid' => false, 'message' => '邮箱和验证码不能为空'];
    }
    
    // 查询验证码
    $record = $db->fetchOne("SELECT * FROM email_verify_codes 
                              WHERE email = '$email' 
                              AND code = '$code' 
                              AND type = '$type' 
                              AND used = 0 
                              AND expired_at > NOW()");
    
    if (!$record) {
        return ['valid' => false, 'message' => '验证码错误或已过期'];
    }
    
    // 标记为已使用
    $db->query("UPDATE email_verify_codes SET used = 1 WHERE id = {$record['id']}");
    
    return ['valid' => true, 'message' => '验证成功'];
}

// 发送注册验证码
function sendRegisterCode($email) {
    global $db;
    
    // 检查邮箱是否已被注册
    $exist = $db->fetchOne("SELECT id FROM users WHERE email = '$email'");
    if ($exist) {
        return ['success' => false, 'message' => '该邮箱已被注册'];
    }
    
    $code = generateVerifyCode();
    saveVerifyCode($email, $code, 'register');
    
    if (sendVerifyCodeMail($email, $code, 'register')) {
        return ['success' => true, 'message' => '验证码已发送到您的邮箱'];
    } else {
        return ['success' => false, 'message' => '邮件发送失败，请检查SMTP配置'];
    }
}

// 发送登录验证码
function sendLoginCode($email) {
    global $db;
    
    // 检查邮箱是否存在
    $user = $db->fetchOne("SELECT id, email_verified FROM users WHERE email = '$email'");
    if (!$user) {
        return ['success' => false, 'message' => '该邮箱未注册'];
    }
    
    // 检查邮箱是否已验证（可选，可注释掉）
    // if ($user['email_verified'] != 1) {
    //     return ['success' => false, 'message' => '邮箱未验证，请先完成注册验证'];
    // }
    
    $code = generateVerifyCode();
    saveVerifyCode($email, $code, 'login');
    
    if (sendVerifyCodeMail($email, $code, 'login')) {
        return ['success' => true, 'message' => '验证码已发送到您的邮箱'];
    } else {
        return ['success' => false, 'message' => '邮件发送失败，请检查SMTP配置'];
    }
}

function completeRegisterWithCode($username, $password, $email, $code) {
    global $db;
    
    $verifyResult = verifyCode($email, $code, 'register');
    if (!$verifyResult['valid']) {
        return ['success' => false, 'message' => $verifyResult['message']];
    }
    
    $exist = $db->fetchOne("SELECT id FROM users WHERE username = '$username' OR email = '$email'");
    if ($exist) {
        return ['success' => false, 'message' => '用户名或邮箱已被注册'];
    }
    
    $hashed = password_hash($password, PASSWORD_DEFAULT);
    $db->query("INSERT INTO users (username, password, email, email_verified, role) 
                VALUES ('$username', '$hashed', '$email', 1, 'user')");
    
    $user_id = $db->insertId();
    
    $_SESSION['user_id'] = $user_id;
    $_SESSION['username'] = $username;
    $_SESSION['role'] = 'user';
    
    return ['success' => true, 'message' => '注册成功', 'user_id' => $user_id];
}
// 验证登录验证码并登录
function completeLoginWithCode($email, $code) {
    global $db;
    
    // 验证验证码
    $verifyResult = verifyCode($email, $code, 'login');
    if (!$verifyResult['valid']) {
        return ['success' => false, 'message' => $verifyResult['message']];
    }
    
    // 获取用户信息
    $user = $db->fetchOne("SELECT id, username, role, status FROM users WHERE email = '$email'");
    if (!$user || $user['status'] != 1) {
        return ['success' => false, 'message' => '账号不存在或已被禁用'];
    }
    
    // 登录用户
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['role'] = $user['role'];
    
    return ['success' => true, 'message' => '登录成功'];
}