<?php
session_start();
require_once '../config.php';
// 引入等级计算核心逻辑
require_once 'level_check.php';

// 1. 检查登录
if (!isset($_SESSION['user_logged_in']) || $_SESSION['user_logged_in'] !== true) {
    header('Location: index.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$today = date('Y-m-d');
$today_start = $today . ' 00:00:00';
$today_end = $today . ' 23:59:59';

// 2. 获取客户端信息
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['HTTP_CLIENT_IP'] ?? $_SERVER['REMOTE_ADDR'];
if (strpos($ip, ',') !== false) {
    $ips = explode(',', $ip);
    $ip = trim($ips[0]);
}
$ip = filter_var($ip, FILTER_VALIDATE_IP) ? $ip : '0.0.0.0';

// 页面跳转模式，使用后端生成的弱指纹
$fingerprint = md5($_SERVER['HTTP_USER_AGENT'] . $_SERVER['HTTP_ACCEPT_LANGUAGE']);
$ua = $_SERVER['HTTP_USER_AGENT'];

// 3. 获取用户信息
$stmt = mysqli_prepare($conn, "SELECT username, qq, coins FROM users WHERE id = ?");
mysqli_stmt_bind_param($stmt, "i", $user_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$user = mysqli_fetch_assoc($result);

if (!$user) {
    die("用户不存在");
}

$qq = $user['qq'];
$msg = '';
$success = false;
$new_level = false; // 用于存储升级信息

// --- 签到逻辑开始 ---

// 检测 1: 用户是否已签到
$stmt = mysqli_prepare($conn, "SELECT id FROM check_in_logs WHERE user_id = ? AND create_time BETWEEN ? AND ?");
mysqli_stmt_bind_param($stmt, "iss", $user_id, $today_start, $today_end);
mysqli_stmt_execute($stmt);
$res_check = mysqli_stmt_get_result($stmt);

if ($res_check->num_rows > 0) {
    $msg = '您今天已经签到过了，无需重复签到。';
} else {
    // 检测 2: QQ号限制 (必须绑定QQ才能签到)
    if (empty($qq)) {
        $msg = '请先绑定QQ号后再签到。';
    } else {
        // 检测该QQ号是否今日已签到 (防止一人多号)
        $stmt = mysqli_prepare($conn, "SELECT id FROM check_in_logs WHERE qq = ? AND create_time BETWEEN ? AND ?");
        mysqli_stmt_bind_param($stmt, "sss", $qq, $today_start, $today_end);
        mysqli_stmt_execute($stmt);
        if (mysqli_stmt_get_result($stmt)->num_rows > 0) {
            $msg = '该QQ号关联的账号今日已签到！';
        }
    }

    // 检测 3: IP地址限制 (防止同网多号)
    if (empty($msg)) {
        $stmt = mysqli_prepare($conn, "SELECT id FROM check_in_logs WHERE ip_address = ? AND create_time BETWEEN ? AND ?");
        mysqli_stmt_bind_param($stmt, "sss", $ip, $today_start, $today_end);
        mysqli_stmt_execute($stmt);
        if (mysqli_stmt_get_result($stmt)->num_rows > 0) {
            $msg = '当前网络环境今日已签到！';
        }
    }

    // 检测 4: 设备指纹限制 (防止同设备多号)
    if (empty($msg)) {
        $stmt = mysqli_prepare($conn, "SELECT id FROM check_in_logs WHERE fingerprint = ? AND create_time BETWEEN ? AND ?");
        mysqli_stmt_bind_param($stmt, "sss", $fingerprint, $today_start, $today_end);
        mysqli_stmt_execute($stmt);
        if (mysqli_stmt_get_result($stmt)->num_rows > 0) {
            $msg = '当前设备今日已签到！';
        }
    }

    // --- 全部检测通过，发放奖励 ---
    if (empty($msg)) {
        
        // 奖励设置：2 个小马币
        $reward_coins = 2; 

        mysqli_begin_transaction($conn);
        try {
            // 1. 增加小马币并更新签到时间
            $new_coins = $user['coins'] + $reward_coins;
            $update_user = mysqli_prepare($conn, "UPDATE users SET coins = ?, last_check_in = ? WHERE id = ?");
            mysqli_stmt_bind_param($update_user, "isi", $new_coins, $today, $user_id);
            mysqli_stmt_execute($update_user);

            // 2. 记录签到日志
            $insert_log = mysqli_prepare($conn, "INSERT INTO check_in_logs (user_id, qq, ip_address, fingerprint, user_agent, coins_awarded, create_time) VALUES (?, ?, ?, ?, ?, ?, NOW())");
            mysqli_stmt_bind_param($insert_log, "issssi", $user_id, $qq, $ip, $fingerprint, $ua, $reward_coins);
            mysqli_stmt_execute($insert_log);

            // 3. 写入收益详情日志
            $log_desc = '每日签到奖励';
            $stmt_coin_log = mysqli_prepare($conn, "INSERT INTO coin_logs (user_id, change_amount, balance_after, type, description) VALUES (?, ?, ?, 'checkin', ?)");
            mysqli_stmt_bind_param($stmt_coin_log, "iiis", $user_id, $reward_coins, $new_coins, $log_desc);
            mysqli_stmt_execute($stmt_coin_log);

            mysqli_commit($conn);
            
            $msg = "签到成功！获得 {$reward_coins} 个小马币";
            $success = true;

            // --- 检测并处理升级 ---
            // 签到增加了累积量，检查是否升级
            $new_level = checkAndUpdateLevel($user_id, $conn);

        } catch (Exception $e) {
            mysqli_rollback($conn);
            $msg = '系统错误，请稍后重试: ' . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>签到处理中...</title>
    <style>
        body { background: #f4f6f9; font-family: sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; }
        .process-box { background: white; padding: 40px; border-radius: 10px; text-align: center; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .icon { font-size: 50px; margin-bottom: 20px; }
        .title { font-size: 20px; margin-bottom: 10px; font-weight: bold; }
        .message { color: #666; margin-bottom: 20px; line-height: 1.5; }
        .level-up { color: #ff4757; font-weight: bold; margin-top: 10px; display: block; animation: flash 1s infinite; }
        .btn-back { padding: 10px 30px; background: #007bff; color: white; border: none; border-radius: 20px; cursor: pointer; text-decoration: none; display: inline-block; }
        @keyframes flash { 0% { opacity: 1; } 50% { opacity: 0.5; } 100% { opacity: 1; } }
    </style>
</head>
<body>
    <div class="process-box">
        <div class="icon"><?php echo $success ? '✅' : '⚠️'; ?></div>
        <div class="title"><?php echo $success ? '签到成功' : '签到失败'; ?></div>
        <div class="message">
            <?php echo $msg; ?>
            <?php if ($new_level): ?>
                <span class="level-up">🎉 恭喜！等级提升至 V<?php echo $new_level; ?></span>
            <?php endif; ?>
        </div>
        <a href="home.php" class="btn-back">返回个人中心</a>
    </div>
    
    <script>
        // 3秒后自动跳转
        setTimeout(function() {
            window.location.href = 'home.php';
        }, 3000);
    </script>
</body>
</html>
