<?php
// 会话安全配置增强
session_set_cookie_params([
    'httponly' => true,
    'samesite' => 'Lax',
    'secure' => isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on'
]);
session_start();

// 处理删除题目请求
if (isset($_POST['delete_question'])) {
    $questionId = filter_input(INPUT_POST, 'delete_question', FILTER_VALIDATE_INT);
    if ($questionId) {
        $allQuestions = readCsv(QUESTION_CSV);
        $header = ['id', '问题', '答案', '耗时(毫秒)', '总回答次数', '错误次数', '正确率', '第一次答题时间', '最近一次答题时间', '下次复习时间', '熟悉程度'];
        
        // 过滤掉要删除的题目
        $remainingQuestions = [];
        foreach ($allQuestions as $question) {
            if ((int)$question[0] != $questionId) {
                $remainingQuestions[] = $question;
            }
        }
        
        // 保存更新后的数据到1.csv
        saveCsv(QUESTION_CSV, $remainingQuestions, $header);
        
        // 重新生成ID序号
        regenerateQuestionIds();
        
        // 从当前组中移除已删除的题目
        if (!empty($_SESSION['current_group'])) {
            $newCurrentGroup = [];
            foreach ($_SESSION['current_group'] as $item) {
                if ((int)$item['data'][0] != $questionId) {
                    $newCurrentGroup[] = $item;
                }
            }
            $_SESSION['current_group'] = $newCurrentGroup;
            
            // 如果当前题目被删除，调整索引
            if ($_SESSION['current_question_index'] >= count($_SESSION['current_group'])) {
                $_SESSION['current_question_index'] = max(0, count($_SESSION['current_group']) - 1);
            }
        }
    }
    
    header("Location: index.php?" . time());
    exit();
}

// 处理重新开始（移到最前面，确保在任何输出之前执行）
if (isset($_POST['restart_all'])) {
    $_SESSION = [];
    session_destroy();
    header("Location: index.php?" . time()); // 添加时间戳防止缓存
    exit();
}

// 处理重来一组
if (isset($_POST['restart_group'])) {
    generateNewGroup();
    // 生成新的随机数参数防止缓存
    header("Location: index.php?" . time());
    exit();
}

// 集中初始化会话变量 - 新增last_question_id存储上一题ID
$defaultSession = [
    'done_questions' => [],
    'current_group' => [],
    'current_question_index' => 0,
    'start_time' => 0,
    'test_start_time' => 0,
    'paused' => false,
    'paused_time' => 0,
    'total_paused_time' => 0,
    'total_questions' => 0,
    'correct_answers' => 0,
    'last_result' => '',
    'last_question' => '',
    'last_question_id' => '', // 新增：存储上一题ID
    'last_correct_answer' => '',
    'show_stats' => false,
    'image_cache' => [] // 新增：图片缓存记录
];

foreach ($defaultSession as $key => $value) {
    if (!isset($_SESSION[$key])) {
        $_SESSION[$key] = $value;
    }
}

// 配置常量抽离，便于维护 - 明确指定1.csv作为题目文件
define('QUESTION_CSV', '1.csv');
define('WRONG_DIR', 'cw');
define('GROUP_SIZE', 50);
define('OPTION_COUNT', 4);
define('TOTAL_QUESTIONS_TO_COMPLETE', 50);
define('TIME_LOG_CSV', 'time.csv');
define('MAX_QUESTION_TIME', 300000); // 单次答题最大时间（5分钟=300000毫秒）
define('IMAGE_CACHE_TTL', 86400); // 图片缓存有效期：24小时

/**
 * 统一数据清洗函数
 */
function cleanString($str) {
    if (!is_string($str)) {
        $str = (string)$str;
    }
    $str = trim($str, " \t\n\r\0\x0B");
    $str = preg_replace('/\s+/', ' ', $str);
    $str = mb_convert_encoding($str, 'UTF-8', mb_detect_encoding($str));
    return $str;
}

/**
 * 从文本中提取图片URL
 */
function extractImageUrls($text) {
    $imageUrls = [];
    // 匹配img标签中的src属性
    preg_match_all('/<img[^>]+src=[\'"]([^\'"]+)[\'"]/i', $text, $matches);
    if (!empty($matches[1])) {
        $imageUrls = array_merge($imageUrls, $matches[1]);
    }
    // 匹配Markdown格式的图片
    preg_match_all('/!\[.*?\]\((.*?)\)/i', $text, $matches);
    if (!empty($matches[1])) {
        $imageUrls = array_merge($imageUrls, $matches[1]);
    }
    return array_unique($imageUrls);
}

/**
 * 预加载图片并更新缓存记录
 */
function preloadImages($questions) {
    $imageUrls = [];
    foreach ($questions as $question) {
        // 从问题和答案中提取图片URL
        $questionText = is_array($question) && isset($question['data'][1]) ? $question['data'][1] : '';
        $answerText = is_array($question) && isset($question['data'][2]) ? $question['data'][2] : '';
        
        $imageUrls = array_merge(
            $imageUrls,
            extractImageUrls($questionText),
            extractImageUrls($answerText)
        );
    }
    
    $imageUrls = array_unique($imageUrls);
    $currentTime = time();
    $validImages = [];
    
    // 过滤已过期的缓存
    foreach ($_SESSION['image_cache'] as $url => $timestamp) {
        if ($currentTime - $timestamp < IMAGE_CACHE_TTL) {
            $validImages[$url] = $timestamp;
        }
    }
    
    // 添加新图片到缓存记录
    foreach ($imageUrls as $url) {
        if (!isset($validImages[$url])) {
            $validImages[$url] = $currentTime;
        }
    }
    
    $_SESSION['image_cache'] = $validImages;
    return array_keys($validImages);
}

/**
 * 格式化毫秒数为易读的时间格式
 */
function formatTime($milliseconds, $showHours = false) {
    $seconds = (int)($milliseconds / 1000);
    $hours = (int)($seconds / 3600);
    $minutes = (int)(($seconds % 3600) / 60);
    $seconds = $seconds % 60;
    $ms = $milliseconds % 1000;
    
    $parts = [];
    
    if ($hours > 0 || $showHours) {
        $parts[] = $hours . '小时';
    }
    
    if ($minutes > 0 || count($parts) > 0 || $seconds > 0) {
        $parts[] = $minutes . '分';
    }
    
    $parts[] = $seconds . '.' . str_pad((int)($ms / 100), 1, '0', STR_PAD_LEFT) . '秒';
    
    return implode('', $parts);
}

/**
 * 读取时间日志并计算统计信息
 */
function getTimeStats() {
    $today = date('Y-m-d');
    $totalMillisecondsToday = 0;
    $totalMillisecondsAllTime = 0;
    
    if (file_exists(TIME_LOG_CSV)) {
        if (($handle = fopen(TIME_LOG_CSV, "r")) !== FALSE) {
            $isFirstRow = true;
            while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
                if ($isFirstRow) {
                    $isFirstRow = false;
                    continue;
                }
                
                if (isset($row[0], $row[3]) && is_numeric($row[3])) {
                    $logDate = $row[0];
                    $duration = (int)$row[3]; // 毫秒
                    
                    $totalMillisecondsAllTime += $duration;
                    
                    if ($logDate === $today) {
                        $totalMillisecondsToday += $duration;
                    }
                }
            }
            fclose($handle);
        }
    }
    
    return [
        'today' => $totalMillisecondsToday,
        'all_time' => $totalMillisecondsAllTime
    ];
}

// 读取CSV数据并缓存到会话中
function readCsv($filename) {
    $cacheKey = 'csv_' . md5($filename);
    $fileMtime = filemtime($filename);
    $cacheMtimeKey = $cacheKey . '_mtime';
    
    if (isset($_SESSION[$cacheKey]) && isset($_SESSION[$cacheMtimeKey]) && $_SESSION[$cacheMtimeKey] === $fileMtime) {
        return $_SESSION[$cacheKey];
    }
    
    $data = [];
    $isFirstRow = true;
    
    if (($handle = fopen($filename, "r")) !== FALSE) {
        while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
            if ($isFirstRow) {
                $isFirstRow = false;
                continue;
            }
            
            foreach ($row as &$col) {
                $col = cleanString($col);
            }
            unset($col);
            
            // 确保数组有足够的元素，包含时间列、下次复习时间列和熟悉程度列
            while (count($row) < 11) {
                $row[] = '';
            }
            
            // 处理原有列
            if (!isset($row[4]) || !is_numeric($row[4])) {
                $row[4] = 0;
            } else {
                $row[4] = (int)$row[4];
            }
            
            if (!isset($row[5]) || !is_numeric($row[5])) {
                $row[5] = 0;
            } else {
                $row[5] = (int)$row[5];
            }
            
            if (!isset($row[6]) || !is_numeric($row[6])) {
                $total = $row[4];
                $errors = $row[5];
                $correct = $total - $errors;
                $row[6] = $total > 0 ? round(($correct / $total) * 100, 1) : 0;
            } else {
                $row[6] = (float)$row[6];
            }
            
            // 确保耗时为数字类型（毫秒）
            if (!isset($row[3]) || !is_numeric($row[3])) {
                $row[3] = 0;
            } else {
                $row[3] = (float)$row[3];
            }
            
            // 确保熟悉程度为数字类型
            if (!isset($row[10]) || !is_numeric($row[10])) {
                $row[10] = 0;
            } else {
                $row[10] = (int)$row[10];
            }
            
            $data[] = $row;
        }
        fclose($handle);
    }
    
    if (empty($data) && !file_exists($filename)) {
        // 包含时间列标题、下次复习时间列和熟悉程度列
        $header = ['id', '问题', '答案', '耗时(毫秒)', '总回答次数', '错误次数', '正确率', '第一次答题时间', '最近一次答题时间', '下次复习时间', '熟悉程度'];
        $handle = fopen($filename, "w");
        fputcsv($handle, $header);
        fclose($handle);
    }
    
    $_SESSION[$cacheKey] = $data;
    $_SESSION[$cacheMtimeKey] = $fileMtime;
    return $data;
}

// 保存CSV数据 - 确保数据写入正确的文件
function saveCsv($filename, $data, $header) {
    $handle = fopen($filename, "w");
    if ($handle === false) {
        error_log("无法打开文件进行写入: " . $filename);
        return false;
    }
    
    fputcsv($handle, $header);
    
    foreach ($data as $row) {
        fputcsv($handle, $row);
    }
    fclose($handle);
    
    $cacheKey = 'csv_' . md5($filename);
    $cacheMtimeKey = $cacheKey . '_mtime';
    $_SESSION[$cacheKey] = $data;
    $_SESSION[$cacheMtimeKey] = filemtime($filename);
    return true;
}

// 重新生成CSV文件中的ID序号
function regenerateQuestionIds() {
    $allQuestions = readCsv(QUESTION_CSV);
    $header = ['id', '问题', '答案', '耗时(毫秒)', '总回答次数', '错误次数', '正确率', '第一次答题时间', '最近一次答题时间', '下次复习时间', '熟悉程度'];
    
    // 重新生成ID，从1开始递增
    foreach ($allQuestions as $index => &$question) {
        $question[0] = $index + 1;
    }
    unset($question); // 解除引用
    
    // 保存更新后的数据到1.csv
    return saveCsv(QUESTION_CSV, $allQuestions, $header);
}

// 保存学习时间记录到CSV文件
function logStudyTime($startTime, $endTime, $totalMilliseconds, $totalQuestions, $correctAnswers) {
    $filename = TIME_LOG_CSV;
    $existingLogs = [];
    $header = ['日期', '开始时间', '结束时间', '总时长(毫秒)', '总时长(时分秒)', '总题数', '正确题数', '正确率(%)'];
    
    if (file_exists($filename)) {
        $existingLogs = readCsv($filename);
    }
    
    $accuracy = $totalQuestions > 0 ? round(($correctAnswers / $totalQuestions) * 100, 2) : 0;
    
    $date = date('Y-m-d', $endTime);
    $startTimeFormatted = date('H:i:s', $startTime);
    $endTimeFormatted = date('H:i:s', $endTime);
    $formattedTime = formatTime($totalMilliseconds);
    
    $newLog = [
        $date,
        $startTimeFormatted,
        $endTimeFormatted,
        $totalMilliseconds,
        $formattedTime,
        $totalQuestions,
        $correctAnswers,
        $accuracy
    ];
    
    $existingLogs[] = $newLog;
    
    return saveCsv($filename, $existingLogs, $header);
}

// 添加错题到cw文件夹的当日文件中
function addToWrongAnswers($question) {
    $dir = WRONG_DIR;
    if (!is_dir($dir)) {
        mkdir($dir, 0755, true);
    }
    
    $filename = $dir . '/' . date('md') . '.csv';
    $existingQuestions = [];
    if (file_exists($filename)) {
        $existingQuestions = readCsv($filename);
    }
    
    $questionText = cleanString($question[1]);
    $questionMap = array_column($existingQuestions, null, 1);
    if (!isset($questionMap[$questionText])) {
        $existingQuestions[] = $question;
        // 错题文件保持原有结构
        $header = ['id', '问题', '答案', '耗时(毫秒)', '总回答次数', '错误次数', '正确率'];
        saveCsv($filename, $existingQuestions, $header);
    }
}

// 获取未做过的题目
function getUnansweredQuestions($allQuestions) {
    $unanswered = [];
    foreach ($allQuestions as $index => $question) {
        if ((int)$question[4] == 0) {
            $unanswered[] = [
                'index' => $index,
                'data' => $question
            ];
        }
    }
    return $unanswered;
}

// 生成新的题目组
function generateNewGroup() {
    $allQuestions = readCsv(QUESTION_CSV);
    $unanswered = getUnansweredQuestions($allQuestions);
    
    if (count($unanswered) < GROUP_SIZE) {
        $selected = $unanswered;
        $needMore = GROUP_SIZE - count($unanswered);
        
        // 筛选已答题并排除近2分钟内回答过的题目
        $answered = [];
        $tenMinutesAgo = time() - 120; // 2分钟前的时间戳
        foreach ($allQuestions as $index => $question) {
            if ((int)$question[4] > 0) {
                // 检查最近一次答题时间是否在2分钟内
                $lastAnswerTime = isset($question[8]) && !empty($question[8]) ? strtotime($question[8]) : 0;
                if ($lastAnswerTime < $tenMinutesAgo) {
                    $answered[] = [
                        'index' => $index,
                        'data' => $question
                    ];
                }
            }
        }
        
        // 先按总回答次数升序排序（最少的在前），次数相同则按耗时降序排序
        usort($answered, function($a, $b) {
            if ($a['data'][4] != $b['data'][4]) {
                return $a['data'][4] - $b['data'][4];
            }
            // 次数相同，按耗时（毫秒）降序排序
            return $b['data'][3] - $a['data'][3];
        });
        
        // 取前10题回答次数最少的题目
        $leastAnswered = array_slice($answered, 0, 10);
        $remainingAnswered = array_slice($answered, 10);
        
        // 剩余已回答题目按错误率从高到低排序，错误率相同时按最近答题时间升序
        usort($remainingAnswered, function($a, $b) {
            $errorRateA = 100 - $a['data'][6];
            $errorRateB = 100 - $b['data'][6];
            
            if ($errorRateA != $errorRateB) {
                return $errorRateB - $errorRateA;
            }
            
            // 错误率相同时，按最近答题时间升序（优先选择久未答题的题目）
            $timeA = isset($a['data'][8]) && !empty($a['data'][8]) ? strtotime($a['data'][8]) : 0;
            $timeB = isset($b['data'][8]) && !empty($b['data'][8]) ? strtotime($b['data'][8]) : 0;
            return $timeA - $timeB;
        });
        
        // 合并并取需要的数量
        $candidates = array_merge($leastAnswered, $remainingAnswered);
        $additional = array_slice($candidates, 0, $needMore);
        
        $selected = array_merge($selected, $additional);
    } else {
        $selected = array_slice($unanswered, 0, GROUP_SIZE);
    }
    
    shuffle($selected);
    
    $group = [];
    foreach ($selected as $item) {
        $group[] = [
            'index' => $item['index'],
            'data' => $item['data']
        ];
    }
    
    $_SESSION['current_group'] = $group;
    $_SESSION['current_question_index'] = 0;
    
    // 预加载当前组题目的图片
    preloadImages($group);
}

// 处理统计按钮点击
if (isset($_POST['show_stats'])) {
    // 切换统计显示状态
    $_SESSION['show_stats'] = !$_SESSION['show_stats'];
    
    // 重新生成ID序号
    regenerateQuestionIds();
    
    header("Location: index.php?" . time()); // 添加时间戳防止缓存
    exit();
}

// 处理用户对题目的掌握程度提交
if (isset($_POST['mastery_level']) && !$_SESSION['paused']) {
    $masteryLevel = filter_input(INPUT_POST, 'mastery_level', FILTER_SANITIZE_STRING);
    $allQuestions = readCsv(QUESTION_CSV);
    $currentGroup = $_SESSION['current_group'];
    $currentIndex = $_SESSION['current_question_index'];
    
    if (empty($currentGroup) || !isset($currentGroup[$currentIndex])) {
        generateNewGroup();
        header("Location: index.php?" . time()); // 添加时间戳防止缓存
        exit();
    }
    
    $currentQuestion = $currentGroup[$currentIndex];
    $questionDataIndex = $currentQuestion['index'];
    
    // 保存当前问题ID作为上一题ID，用于结果显示
    $_SESSION['last_question_id'] = $currentQuestion['data'][0];
    
    $correctAnswer = cleanString($currentQuestion['data'][2]);
    $_SESSION['last_question'] = $currentQuestion['data'][1];
    $_SESSION['last_correct_answer'] = $correctAnswer;
    
    // 根据按钮点击设置结果、下次复习时间和熟悉程度
    $currentTime = time();
    $familiarityLevel = 0; // 1-4，忘记1、模糊2、认识3、熟悉4
    
    switch ($masteryLevel) {
        case 'forget':
            $nextReviewTime = date('Y-m-d H:i:s', $currentTime + 3 * 60); // 3分钟
            $_SESSION['last_result'] = "forget";
            $familiarityLevel = 1;
            break;
        case 'vague':
            $nextReviewTime = date('Y-m-d H:i:s', $currentTime + 5 * 60); // 5分钟
            $_SESSION['last_result'] = "vague";
            $familiarityLevel = 2;
            break;
        case 'know':
            $nextReviewTime = date('Y-m-d H:i:s', $currentTime + 10 * 60); // 10分钟
            $_SESSION['last_result'] = "know";
            $_SESSION['correct_answers']++;
            $familiarityLevel = 3;
            break;
        case 'familiar':
            $nextReviewTime = date('Y-m-d H:i:s', $currentTime + 60 * 60); // 60分钟
            $_SESSION['last_result'] = "familiar";
            $_SESSION['correct_answers']++;
            $familiarityLevel = 4;
            break;
    }
    
    // 计算耗时（毫秒）并应用5分钟上限
    $endTime = microtime(true) * 1000; // 毫秒级时间戳
    $timeSpent = $endTime - ($_SESSION['start_time'] * 1000) - ($_SESSION['paused_time'] * 1000);
    $timeSpent = min($timeSpent, MAX_QUESTION_TIME);
    
    // 获取当前时间，用于记录答题时间
    $currentDateTime = date('Y-m-d H:i:s');
    
    // 更新统计数据
    $_SESSION['total_questions']++;
    
    // 记录原始总回答次数，用于判断是否是第一次答题
    $originalAttempts = (int)$allQuestions[$questionDataIndex][4];
    
    // 更新题目统计数据
    $allQuestions[$questionDataIndex][4] = $originalAttempts + 1;
    
    // 除了"认识"和"熟悉"之外都算作错误
    if ($masteryLevel != 'know' && $masteryLevel != 'familiar') {
        $allQuestions[$questionDataIndex][5] = (int)$allQuestions[$questionDataIndex][5] + 1;
    }
    
    $totalAttempts = $allQuestions[$questionDataIndex][4];
    $wrongAttempts = $allQuestions[$questionDataIndex][5];
    $correctAttempts = $totalAttempts - $wrongAttempts;
    $allQuestions[$questionDataIndex][6] = $totalAttempts > 0 ? round(($correctAttempts / $totalAttempts) * 100, 1) : 0;
    
    $allQuestions[$questionDataIndex][3] = $timeSpent; // 保存处理后的耗时（毫秒）
    
    // 处理第一次答题时间和最近一次答题时间
    if ($originalAttempts == 0) {
        // 第一次答题，同时设置第一次和最近一次时间
        $allQuestions[$questionDataIndex][7] = $currentDateTime; // 第8列：第一次答题时间
        $allQuestions[$questionDataIndex][8] = $currentDateTime; // 第9列：最近一次答题时间
    } else {
        // 不是第一次答题，只更新最近一次时间
        $allQuestions[$questionDataIndex][8] = $currentDateTime; // 第9列：最近一次答题时间
    }
    
    // 设置下次复习时间（第10列索引）
    $allQuestions[$questionDataIndex][9] = $nextReviewTime;
    
    // 设置熟悉程度（第11列索引）
    $allQuestions[$questionDataIndex][10] = $familiarityLevel;
    
    // 更新表头，包含下次复习时间列和熟悉程度列
    $header = ['id', '问题', '答案', '耗时(毫秒)', '总回答次数', '错误次数', '正确率', '第一次答题时间', '最近一次答题时间', '下次复习时间', '熟悉程度'];
    saveCsv(QUESTION_CSV, $allQuestions, $header);
    
    // 非"认识"和"熟悉"的都加入错题
    if ($masteryLevel != 'know' && $masteryLevel != 'familiar') {
        addToWrongAnswers($currentQuestion['data']);
    }
    
    $_SESSION['current_question_index']++;
    if ($_SESSION['current_question_index'] >= count($currentGroup)) {
        generateNewGroup();
    }
    
    $_SESSION['start_time'] = time();
    $_SESSION['paused_time'] = 0;
    
    header("Location: index.php?" . time()); // 添加时间戳防止缓存
    exit();
}

// 处理答案编辑和保存（修复保存功能）
if (isset($_POST['save_answer']) || isset($_POST['auto_save'])) {
    // 使用更可靠的方式获取POST数据
    $newAnswer = isset($_POST['new_answer']) ? cleanString($_POST['new_answer']) : '';
    $allQuestions = readCsv(QUESTION_CSV);
    $currentGroup = $_SESSION['current_group'];
    $currentIndex = $_SESSION['current_question_index'];
    
    if (empty($currentGroup) || !isset($currentGroup[$currentIndex])) {
        generateNewGroup();
        // 如果是自动保存，不跳转页面
        if (!isset($_POST['auto_save'])) {
            header("Location: index.php?" . time()); // 添加时间戳防止缓存
        }
        exit();
    }
    
    $currentQuestion = $currentGroup[$currentIndex];
    $questionDataIndex = $currentQuestion['index'];
    
    // 验证问题数据索引是否有效
    if (isset($allQuestions[$questionDataIndex])) {
        // 更新答案
        $allQuestions[$questionDataIndex][2] = $newAnswer;
        
        // 保存更新到1.csv
        $header = ['id', '问题', '答案', '耗时(毫秒)', '总回答次数', '错误次数', '正确率', '第一次答题时间', '最近一次答题时间', '下次复习时间', '熟悉程度'];
        $saveSuccess = saveCsv(QUESTION_CSV, $allQuestions, $header);
        
        // 更新当前组中的答案
        if ($saveSuccess) {
            $_SESSION['current_group'][$currentIndex]['data'][2] = $newAnswer;
            // 如果答案中包含新图片，更新图片缓存
            $newImages = extractImageUrls($newAnswer);
            if (!empty($newImages)) {
                preloadImages([$currentQuestion]);
            }
        }
    }
    
    // 如果是自动保存请求，返回JSON响应而不跳转
    if (isset($_POST['auto_save'])) {
        header('Content-Type: application/json');
        echo json_encode(['status' => 'success', 'message' => '自动保存成功']);
        exit();
    }
    
    header("Location: index.php?" . time()); // 添加时间戳防止缓存
    exit();
}

// 检查是否完成指定数量的题目
if ($_SESSION['total_questions'] >= TOTAL_QUESTIONS_TO_COMPLETE) {
    $end_time = time();
    $total_time = ($end_time - $_SESSION['test_start_time'] - $_SESSION['total_paused_time']) * 1000; // 转换为毫秒
    
    logStudyTime(
        $_SESSION['test_start_time'],
        $end_time,
        $total_time,
        $_SESSION['total_questions'],
        $_SESSION['correct_answers']
    );
    
    $timeStats = getTimeStats();
    
    $formatted_time = formatTime($total_time);
    $today_time = formatTime($timeStats['today']);
    $all_time = formatTime($timeStats['all_time'], true);
    
    $dir = WRONG_DIR;
    $filename = $dir . '/' . date('md') . '.csv';
    $wrongQuestions = file_exists($filename) ? readCsv($filename) : [];
    
    // 重新计算正确率，确保正确
    $accuracy = $_SESSION['total_questions'] > 0 
        ? round(($_SESSION['correct_answers'] / $_SESSION['total_questions']) * 100, 2) 
        : 0;
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>琦哥3500测试</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        /* 图片容器和图片样式优化 */
        .image-container {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 15px 0;
            padding: 10px;
            background-color: #f9f9f9;
            border-radius: 8px;
            overflow: hidden;
        }
        
        img {
            max-width: 100%;
            max-height: 600px;
            width: auto;
            height: auto;
            object-fit: contain;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            cursor: zoom-in;
        }
        
        img:hover {
            transform: scale(1.02);
        }
        
        img.loaded {
            opacity: 1;
        }
        
        /* 图片查看器样式 */
        .image-viewer {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.9);
            z-index: 1000;
            justify-content: center;
            align-items: center;
            cursor: zoom-out;
        }
        
        .image-viewer img {
            max-width: 90%;
            max-height: 90%;
            cursor: default;
        }
        
        /* 图片预加载容器 */
        .preload-container {
            display: none;
            position: absolute;
            top: -9999px;
            left: -9999px;
        }
        
        .summary {
            background-color: #f5f5f5;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
        }
        .wrong-questions {
            background-color: #fff0f0;
            padding: 20px;
            border-radius: 8px;
        }
        .question-item {
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
            display: flex;
            align-items: flex-start;
            gap: 15px;
            position: relative; /* 添加相对定位 */
        }
        .question-stats {
            background-color: #ffeeba;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 0.9em;
            min-width: 80px;
        }
        .stat-item {
            margin: 3px 0;
            font-weight: bold;
        }
        .correct-rate {
            color: #28a745;
        }
        .wrong-count {
            color: #dc3545;
        }
        button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 1em;
        }
        button:hover {
            background-color: #45a049;
        }
        .progress-container {
            margin: 20px 0;
        }
        .progress-bar {
            height: 20px;
            background-color: #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
            margin-bottom: 5px;
        }
        .progress-fill {
            height: 100%;
            background-color: #4CAF50;
            width: <?php echo ($_SESSION['total_questions'] / TOTAL_QUESTIONS_TO_COMPLETE) * 100; ?>%;
            transition: width 0.3s ease;
        }
        .stats-row {
            display: flex;
            justify-content: space-between;
            font-size: 0.9em;
            color: #666;
            margin-bottom: 15px;
        }
        .progress-text {
            text-align: left;
        }
        .accuracy-text {
            text-align: right;
        }
        .time-stat {
            color: #1565C0;
            font-weight: bold;
        }
        .time-summary {
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px dashed #ccc;
        }
        /* 删除按钮样式 */
        .delete-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            background-color: #ff4444;
            color: white;
            border: none;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            font-size: 16px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0;
            line-height: 1;
        }
        .delete-btn:hover {
            background-color: #cc0000;
        }
    </style>
</head>
<body>
    <!-- 图片查看器 -->
    <div class="image-viewer" id="imageViewer">
        <img id="viewerImage" src="" alt="大图查看">
    </div>
    
    <!-- 图片预加载容器 -->
    <div class="preload-container" id="preloadContainer"></div>
    
    <h1>测试完成！</h1>
    
    <div class="summary">
        <h2>测试总结</h2>
        <p>总题数：<?php echo $_SESSION['total_questions']; ?>题</p>
        <p>正确题数：<?php echo $_SESSION['correct_answers']; ?>题</p>
        <p>正确率：<?php echo $accuracy; ?>%</p>
        <p>本次学习花费时间：<span class="time-stat"><?php echo $formatted_time; ?></span></p>
        <button type="button" class="scroll-btn" onclick="window.scrollTo({top: document.body.scrollHeight, behavior: 'smooth'})">
    跳转到页底
</button>

        <div class="time-summary">
            <h3>学习时间统计</h3>
            <p>今日学习时长：<span class="time-stat"><?php echo $today_time; ?></span></p>
            <p>累积学习时长：<span class="time-stat"><?php echo $all_time; ?></span></p>
        </div>

    </div>
    
    <div class="wrong-questions">
        <h2>错误题目列表 (共<?php echo count($wrongQuestions); ?>题)</h2>
        <?php foreach ($wrongQuestions as $index => $question): ?>
            <div class="question-item">
                <!-- 删除按钮 -->
                <button class="delete-btn" onclick="confirmDelete(<?php echo htmlspecialchars($question[0]); ?>)">×</button>
                
                <div class="question-stats">
                    <div class="stat-item">回答: <?php echo isset($question[4]) ? (int)$question[4] : 0; ?>次</div>
                    <div class="stat-item wrong-count">错误: <?php echo isset($question[5]) ? (int)$question[5] : 0; ?>次</div>
                    <div class="stat-item correct-rate">正确率: <?php echo isset($question[6]) ? (float)$question[6] : 0; ?>%</div>
                    <div class="stat-item">耗时: <?php echo isset($question[3]) ? formatTime((float)$question[3]) : 0; ?></div>
                </div>
                <div class="question-content">
                    <p><strong>问题 ID: <?php echo htmlspecialchars($question[0]); ?>：</strong><?php echo $question[1]; ?></p>
                    <div class="image-container">
                        <?php echo htmlspecialchars($question[2]); ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    
    <form method="post">
        <button type="submit" name="restart_all">重新开始</button>
    </form>
    
    <!-- 总进度条 -->
    <div class="progress-container">
        <div class="progress-bar">
            <div class="progress-fill"></div>
        </div>
        <div class="stats-row">
            <div class="progress-text">
                <?php echo $_SESSION['total_questions'] . "/" . TOTAL_QUESTIONS_TO_COMPLETE . "题 (" . 
                    round(($_SESSION['total_questions'] / TOTAL_QUESTIONS_TO_COMPLETE) * 100) . "%)"; ?>
            </div>
            <div class="accuracy-text">
                <?php 
                echo "正确率：" . $_SESSION['correct_answers'] . " / " . $_SESSION['total_questions'] . "题 (" . $accuracy . "%)"; 
                ?>
            </div>
        </div>
    </div>
    
    <script>
        // 图片查看器功能
        const imageViewer = document.getElementById('imageViewer');
        const viewerImage = document.getElementById('viewerImage');
        let currentImageSrc = '';
        
        // 点击图片查看大图
        document.addEventListener('click', function(e) {
            if (e.target.tagName === 'IMG' && !e.target.closest('.image-viewer')) {
                currentImageSrc = e.target.src;
                viewerImage.src = currentImageSrc;
                imageViewer.style.display = 'flex';
                document.body.style.overflow = 'hidden'; // 防止背景滚动
            } else if (e.target === imageViewer) {
                // 点击背景关闭查看器
                imageViewer.style.display = 'none';
                document.body.style.overflow = 'auto'; // 恢复滚动
            }
        });
        
        // 按ESC键关闭图片查看器
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && imageViewer.style.display === 'flex') {
                imageViewer.style.display = 'none';
                document.body.style.overflow = 'auto';
            }
        });
        
        // 图片加载完成后添加loaded类
        document.addEventListener('DOMContentLoaded', function() {
            const images = document.querySelectorAll('img:not(.preloaded)');
            images.forEach(img => {
                img.addEventListener('load', function() {
                    this.classList.add('loaded');
                });
                
                // 如果图片已经缓存，手动触发load事件
                if (img.complete) {
                    img.classList.add('loaded');
                }
            });
            
            // 预加载下一组可能的图片
            <?php if (!empty($_SESSION['image_cache'])): ?>
            const preloadContainer = document.getElementById('preloadContainer');
            const imageUrls = <?php echo json_encode(array_keys($_SESSION['image_cache'])); ?>;
            
            imageUrls.forEach(url => {
                // 只预加载尚未在页面中加载的图片
                if (!document.querySelector(`img[src="${url}"]`)) {
                    const img = new Image();
                    img.src = url;
                    img.classList.add('preloaded');
                    preloadContainer.appendChild(img);
                }
            });
            <?php endif; ?>
        });
        
        // 确认删除函数
        function confirmDelete(questionId) {
            if (confirm(`确定要删除问题 ID: ${questionId} 吗？此操作将同时从1.csv中删除该题目，且不可恢复。`)) {
                // 创建表单并提交删除请求
                const form = document.createElement('form');
                form.method = 'post';
                form.action = '';
                form.innerHTML = `<input type="hidden" name="delete_question" value="${questionId}">`;
                document.body.appendChild(form);
                form.submit();
            }
        }
    </script>
</body>
</html>
<?php
    exit();
}

// 如果没有当前组，生成新组
if (empty($_SESSION['current_group'])) {
    generateNewGroup();
    if ($_SESSION['test_start_time'] == 0) {
        $_SESSION['test_start_time'] = time();
    }
}

// 获取当前题目
$currentGroup = $_SESSION['current_group'];
$currentIndex = $_SESSION['current_question_index'];

if (!isset($currentGroup[$currentIndex])) {
    $_SESSION['current_question_index'] = 0;
    $currentIndex = 0;
}

$currentQuestion = $currentGroup[$currentIndex];

// 计算总进度百分比和正确率
$progressPercentage = ($_SESSION['total_questions'] / TOTAL_QUESTIONS_TO_COMPLETE) * 100;
$accuracy = 0;
if ($_SESSION['total_questions'] > 0) {
    $accuracy = round(($_SESSION['correct_answers'] / $_SESSION['total_questions']) * 100, 2);
}

// 初始化开始时间
if ($_SESSION['start_time'] == 0) {
    $_SESSION['start_time'] = time();
    if ($_SESSION['test_start_time'] == 0) {
        $_SESSION['test_start_time'] = time();
    }
}

// 获取正确答案
$allQuestions = readCsv(QUESTION_CSV);
$correctAnswerClean = cleanString($currentQuestion['data'][2]);

// 计算统计信息
$totalQuestionsInSystem = count($allQuestions);
$answeredCount = 0;
$completedQuestions = 0;

foreach ($allQuestions as $question) {
    $answerCount = (int)$question[4];
    $answeredCount += $answerCount;
    
    if ($answerCount > 0) {
        $completedQuestions++;
    }
}

$unansweredCount = $totalQuestionsInSystem - $completedQuestions;
$accuracyRanges = [
    '100%' => 0,
    '80%-99%' => 0,
    '60%-79%' => 0,
    '40%-59%' => 0,
    '20%-39%' => 0,
    '<20%' => 0,
    '未回答' => 0
];

foreach ($allQuestions as $question) {
    $answerCount = (int)$question[4];
    $accuracyVal = isset($question[6]) ? (float)$question[6] : 0;
    
    if ($answerCount == 0) {
        $accuracyRanges['未回答']++;
        continue;
    }
    
    if ($accuracyVal == 100) {
        $accuracyRanges['100%']++;
    } elseif ($accuracyVal >= 80) {
        $accuracyRanges['80%-99%']++;
    } elseif ($accuracyVal >= 60) {
        $accuracyRanges['60%-79%']++;
    } elseif ($accuracyVal >= 40) {
        $accuracyRanges['40%-59%']++;
    } elseif ($accuracyVal >= 20) {
        $accuracyRanges['20%-39%']++;
    } else {
        $accuracyRanges['<20%']++;
    }
}

?>
<!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 {
            font-family: Arial, sans-serif;
            max-width: 1000px;
            margin: 0 auto;
            padding: 20px;
            line-height: 1.6;
        }
        /* 图片容器和图片样式优化 */
        .image-container {
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 15px 0;
            padding: 10px;
            background-color: #f9f9f9;
            border-radius: 8px;
            overflow: hidden;
        }
        
        img {
            max-width: 100%;
            max-height: 600px;
            width: auto;
            height: auto;
            object-fit: contain;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            cursor: zoom-in;
        }
        
        img:hover {
            transform: scale(1.02);
        }
        
        img.loaded {
            opacity: 1;
        }
        
        /* 图片查看器样式 */
        .image-viewer {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.9);
            z-index: 1000;
            justify-content: center;
            align-items: center;
            cursor: zoom-out;
        }
        
        .image-viewer img {
            max-width: 90%;
            max-height: 90%;
            cursor: default;
        }
        
        /* 图片预加载容器 */
        .preload-container {
            display: none;
            position: absolute;
            top: -9999px;
            left: -9999px;
        }
        
        .question-container {
            background-color: #f5f5f5;
            padding: 5px;
            border-radius: 8px;
            margin-bottom: 5px;
            min-height: 10px;
            text-align: center;
            position: relative; /* 添加相对定位 */
            display: flex;
            align-items: center;
        }
        
        .question-navigation {
            margin-right: 1.5px;
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .nav-btn {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #e0e0e0;
            border: none;
            font-size: 1.2em;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s;
        }
        
        .nav-btn:hover {
            background-color: #ccc;
            transform: scale(1.1);
        }
        
        .question-content {
            display: inline-block;
            text-align: left;
            max-width: 100%;
            flex: 1;
        }
        .question-content h3 {
            font-size: 1.0em;
            margin: 0 0 8px 0;
        }

        .question-content p {
            font-size: 1.8em;
            margin: 0;
            line-height: 1.4;
        }
        .answer-container {
            margin: 15px 0;
            padding: 15px;
            background-color: #f9f9f9;
            border-radius: 6px;
            max-width: 800px;
            margin-left: auto;
            margin-right: auto;
        }
        .answer-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        .answer-input {
            width: 100%;
            padding: 12px;
            margin: 10px 0 0 0;
            font-size: 1.2em;
            border: 1px solid #ddd;
            border-radius: 4px;
            min-height: 80px;
            box-sizing: border-box;
            white-space: pre-wrap;
            word-wrap: break-word;
            resize: none;
            overflow: hidden;
        }
        .save-btn {
            background-color: #4CAF50;
            color: white;
            border: none;
            padding: 8px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 0.9em;
        }
        .save-status {
            margin-left: 10px;
            font-size: 0.9em;
            color: #666;
        }
        .controls {
            margin: 20px 0;
            display: flex;
            gap: 10px;
            justify-content: center;
            flex-wrap: wrap;
        }
        .result {
            padding: 15px;
            margin: 20px 0;
            border-radius: 4px;
            font-weight: bold;
            text-align: left;
            overflow: hidden;
        }
        .forget {
            background-color: #f2dede;
            color: #a94442;
        }
        .vague {
            background-color: #fcf8e3;
            color: #8a6d3b;
        }
        .know {
            background-color: #dff0d8;
            color: #3c763d;
        }
        .familiar {
            background-color: #d9edf7;
            color: #31708f;
        }
        .control-btn {
            background-color: #428bca;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 1em;
            flex: 1;
            min-width: 120px;
            max-width: 200px;
        }
        .forget-btn {
            background-color: #d9534f;
        }
        .forget-btn:hover {
            background-color: #c9302c;
        }
        .vague-btn {
            background-color: #f0ad4e;
        }
        .vague-btn:hover {
            background-color: #ec971f;
        }
        .know-btn {
            background-color: #5cb85c;
        }
        .know-btn:hover {
            background-color: #449d44;
        }
        .familiar-btn {
            background-color: #337ab7;
        }
        .familiar-btn:hover {
            background-color: #286090;
        }
        .stats-btn {
            background-color: #5cb85c;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 1em;
        }
        .stats-btn:hover {
            background-color: #449d44;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        .restart-btn {
            background-color: #f0ad4e;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 1em;
        }
        .restart-btn:hover {
            background-color: #ec971f;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        form {
            display: inline;
            flex: 1;
            min-width: 120px;
            max-width: 200px;
        }
        .stats-row {
            display: flex;
            justify-content: space-between;
            font-size: 0.9em;
            color: #666;
            margin-bottom: 15px;
        }
        .progress-text {
            text-align: left;
        }
        .accuracy-text {
            text-align: right;
        }
        .progress-container {
            margin: 20px 0;
        }
        .progress-bar {
            height: 20px;
            background-color: #e0e0e0;
            border-radius: 10px;
            overflow: hidden;
        }
        .progress-fill {
            height: 100%;
            background-color: #4CAF50;
            width: <?php echo $progressPercentage; ?>%;
            transition: width 0.3s ease;
        }
        .result-symbol {
            font-size: 1.2em;
            margin-right: 8px;
        }
        .stats-container {
            background-color: #e8f4f8;
            padding: 15px;
            border-radius: 6px;
            margin: 15px 0;
            border: 1px solid #bce8f1;
            display: <?php echo $_SESSION['show_stats'] ? 'block' : 'none'; ?>;
        }
        .stats-item {
            margin: 8px 0;
            font-size: 1em;
        }
        /* 按钮工具栏样式 */
        .button-toolbar {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin: 15px 0;
            flex-wrap: wrap;
        }
        .button-toolbar form {
            flex: 1;
            min-width: 120px;
            max-width: 200px;
        }
        .button-toolbar button {
            width: 100%;
            padding: 10px;
            font-size: 1em;
            border-radius: 6px;
            border: none;
            color: white;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        /* 删除按钮样式 */
        .delete-btn {
            position: absolute;
            top: 10px;
            right: 10px;
            background-color: #ff4444;
            color: white;
            border: none;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            font-size: 16px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0;
            line-height: 1;
        }
        .delete-btn:hover {
            background-color: #cc0000;
        }
    </style>
</head>
<body>
    <!-- 图片查看器 -->
    <div class="image-viewer" id="imageViewer">
        <img id="viewerImage" src="" alt="大图查看">
    </div>
    
    <!-- 图片预加载容器 -->
    <div class="preload-container" id="preloadContainer"></div>
    
    <div class="question-container">
        <!-- 问题容器左侧的上下箭头按钮 -->
        <div class="question-navigation">
            <form method="post">
                <button type="submit" name="mastery_level" value="vague" class="nav-btn" title="模糊（上键）">↑</button>
            </form>
            <form method="post">
                <button type="submit" name="mastery_level" value="know" class="nav-btn" title="认识（下键）">↓</button>
            </form>
        </div>
        
        <button class="delete-btn" onclick="confirmDelete(<?php echo htmlspecialchars($currentQuestion['data'][0]); ?>)">×</button>
        
        <div class="question-content">
            <!-- 显示当前题目的ID -->
            <h3>问题 <?php echo htmlspecialchars($currentQuestion['data'][0]); ?></h3>
            <div class="image-container">
                <p><?php echo $currentQuestion['data'][1]; ?></p>
            </div>
        </div>
    </div>
    
    <div class="answer-container">
        <div class="answer-header">
            <h3>正确答案：</h3>
            <div style="display: flex; align-items: center;">
    
    <div class="button-toolbar">
 
    </div>

<span class="save-status" id="saveStatus"></span>

<form method="post">
    <button type="submit" name="restart_group" class="action-btn restart-btn">重来</button>
</form>

<form method="post">
    <button type="submit" name="show_stats" class="action-btn stats-btn">统计</button>
</form>
<button type="submit" name="save_answer" class="action-btn save-btn" form="answerForm">保存答案</button>

            </div>
        </div>
    <!-- 四个按钮移到页面最顶端 -->
    <div class="controls">
        <form method="post" id="forgetForm">
            <button type="submit" name="mastery_level" value="forget" class="control-btn forget-btn">忘记（←键）</button>
        </form>
        <form method="post" id="vagueForm">
            <button type="submit" name="mastery_level" value="vague" class="control-btn vague-btn">模糊（↑键）</button>
        </form>
        <form method="post" id="knowForm">
            <button type="submit" name="mastery_level" value="know" class="control-btn know-btn">认识（↓键）</button>
        </form>
        <form method="post" id="familiarForm">
            <button type="submit" name="mastery_level" value="familiar" class="control-btn familiar-btn">熟悉（→键）</button>
        </form>
    </div>
    

        <form method="post" id="answerForm">
            <textarea name="new_answer" class="answer-input" id="answerText"><?php echo htmlspecialchars($correctAnswerClean); ?></textarea>
        </form>
    </div>
    
    <!-- 统计信息显示区域 -->
    <div class="stats-container">
        <h3>题目统计信息</h3>
        <div class="stats-item">
            <strong>系统总题数：</strong><?php echo $totalQuestionsInSystem; ?>题
        </div>
        <div class="stats-item">
            <strong>剩余未做题数：</strong><?php echo $unansweredCount; ?>题
        </div>
        <div class="stats-item">
            <strong>累积做题次数：</strong><?php echo $answeredCount; ?>次
        </div>
        <div class="stats-item">
            <strong>已完成题目：</strong><?php echo $completedQuestions; ?>题
        </div>
<form method="post">
    <button type="submit" formmethod="get" formaction="data.php" class="action-btn forget-btn">分析</button>
</form>

        <div class="stats-section">
            <h3>正确率分布</h3>
            <div class="progress-visualization" style="max-width: 600px; margin: 0 auto;">
                <?php 
                $total = array_sum($accuracyRanges);
                $colors = [
                    '100%' => '#2ECC71',
                    '80%-99%' => '#58D68D',
                    '60%-79%' => '#F4D03F',
                    '40%-59%' => '#F5B041',
                    '20%-39%' => '#F39C12',
                    '<20%' => '#E74C3C',
                    '未回答' => '#3498DB'
                ];
                ?>
                
                <?php foreach ($accuracyRanges as $range => $count): ?>
                <?php if ($total > 0) $percentage = min(100, max(0, ($count / $total) * 100)); else $percentage = 0; ?>
                <div class="range-item" style="margin-bottom: 10px;">
                    <div class="range-label" style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                        <span style="font-weight: bold;"><?php echo $range; ?></span>
                        <span><?php echo $count; ?>题 (<?php echo round($percentage); ?>%)</span>
                    </div>
                    <div class="range-bar-container" style="height: 24px; background-color: #f5f5f5; border-radius: 12px; overflow: hidden; box-shadow: inset 0 1px 3px rgba(0,0,0,0.1);">
                        <div class="range-bar" style="height: 100%; width: <?php echo $percentage; ?>%; background-color: <?php echo $colors[$range]; ?>; transition: width 0.5s ease; box-shadow: 0 1px 2px rgba(0,0,0,0.1);"></div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <div class="chart-legend" style="display: flex; flex-wrap: wrap; justify-content: center; gap: 15px; margin: 15px 0; padding: 10px; background-color: #f9f9f9; border-radius: 8px;">
            <?php foreach ($accuracyRanges as $range => $count): ?>
            <div style="display: flex; align-items: center;">
                <span style="display: inline-block; width: 15px; height: 15px; background-color: <?php echo $colors[$range]; ?>; margin-right: 5px; border-radius: 3px;"></span>
                <span style="font-size: 0.9em;"><?php echo $range; ?></span>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    
    <!-- 自动调整文本框高度的脚本 -->
    <script>
        // 自动调整文本框高度以显示全部内容
        function autoAdjustTextareaHeight(textarea) {
            // 临时设置高度为auto以获取正确的scrollHeight
            textarea.style.height = 'auto';
            // 设置高度为scrollHeight，确保所有内容可见
            textarea.style.height = (textarea.scrollHeight) + 'px';
        }
        
        // 获取答案编辑框元素
        const answerTextarea = document.getElementById('answerText');
        
        // 初始化时调整高度
        if (answerTextarea) {
            autoAdjustTextareaHeight(answerTextarea);
            
            // 监听输入事件，实时调整高度
            answerTextarea.addEventListener('input', function() {
                autoAdjustTextareaHeight(this);
                resetAutoSaveTimer(); // 内容变化时重置自动保存计时器
            });
            
            // 监听窗口大小变化，重新调整高度
            window.addEventListener('resize', function() {
                autoAdjustTextareaHeight(answerTextarea);
            });
        }
        
        // 自动调整结果展示区高度
        function adjustResultDisplay() {
            const resultDiv = document.querySelector('.result');
            if (resultDiv) {
                // 移除固定高度限制，让内容决定高度
                resultDiv.style.height = 'auto';
            }
        }
        
        // 页面加载完成后调整结果展示区
        window.addEventListener('load', adjustResultDisplay);
    </script>
    
    <!-- 自动保存功能脚本 -->
    <script>
        let autoSaveTimer;
        let secondsRemaining = 5;
        const saveStatus = document.getElementById('saveStatus');
        const answerTextarea = document.getElementById('answerText');
        let lastSavedContent = answerTextarea.value; // 记录最后保存的内容
        
        // 更新保存状态显示
        function updateSaveStatus(message, isSuccess = false) {
            saveStatus.textContent = message;
            saveStatus.style.color = isSuccess ? '#28a745' : '#666';
        }
        
        // 重置自动保存计时器
        function resetAutoSaveTimer() {
            clearTimeout(autoSaveTimer);
            secondsRemaining = 5;
            updateSaveStatus(`自动保存将在${secondsRemaining}秒后触发`);
            
            // 每秒更新倒计时
            const countdownInterval = setInterval(() => {
                secondsRemaining--;
                if (secondsRemaining <= 0) {
                    clearInterval(countdownInterval);
                    autoSave();
                } else {
                    updateSaveStatus(`自动保存将在${secondsRemaining}秒后触发`);
                }
            }, 1000);
        }
        
        // 执行自动保存
        function autoSave() {
            // 只有内容发生变化时才保存
            if (answerTextarea.value === lastSavedContent) {
                updateSaveStatus('内容未变化，无需保存');
                resetAutoSaveTimer(); // 重置计时器，继续监控变化
                return;
            }
            
            updateSaveStatus('正在保存...');
            
            // 创建FormData对象
            const formData = new FormData();
            formData.append('new_answer', answerTextarea.value);
            formData.append('auto_save', '1');
            
            // 发送POST请求
            fetch('', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.status === 'success') {
                    lastSavedContent = answerTextarea.value;
                    updateSaveStatus('已自动保存', true);
                    
                    // 提取新图片并预加载
                    const newImages = extractImageUrls(answerTextarea.value);
                    if (newImages.length > 0) {
                        preloadImages(newImages);
                    }
                } else {
                    updateSaveStatus('保存失败，请手动保存');
                }
                // 无论成功失败，都重置计时器
                setTimeout(resetAutoSaveTimer, 1000);
            })
            .catch(error => {
                console.error('自动保存出错:', error);
                updateSaveStatus('保存失败，请手动保存');
                setTimeout(resetAutoSaveTimer, 1000);
            });
        }
        
        // 从文本中提取图片URL
        function extractImageUrls(text) {
            const imageUrls = [];
            // 匹配img标签中的src属性
            const imgTagRegex = /<img[^>]+src=[\'"]([^\'"]+)[\'"]/gi;
            let match;
            while ((match = imgTagRegex.exec(text)) !== null) {
                imageUrls.push(match[1]);
            }
            
            // 匹配Markdown格式的图片
            const mdRegex = /!\[.*?\]\((.*?)\)/gi;
            while ((match = mdRegex.exec(text)) !== null) {
                imageUrls.push(match[1]);
            }
            
            return [...new Set(imageUrls)]; // 去重
        }
        
        // 预加载图片
        function preloadImages(urls) {
            const preloadContainer = document.getElementById('preloadContainer');
            
            urls.forEach(url => {
                // 检查是否已预加载
                if (!document.querySelector(`.preloaded[src="${url}"]`) && 
                    !document.querySelector(`img[src="${url}"]`)) {
                    
                    const img = new Image();
                    img.src = url;
                    img.classList.add('preloaded');
                    preloadContainer.appendChild(img);
                }
            });
        }
        
        // 手动保存成功后更新状态
        document.getElementById('answerForm').addEventListener('submit', function(e) {
            // 只在表单通过正常提交方式提交时触发（不是自动保存）
            if (!e.submitter || e.submitter.name !== 'auto_save') {
                lastSavedContent = answerTextarea.value;
                // 提取新图片并预加载
                const newImages = extractImageUrls(answerTextarea.value);
                if (newImages.length > 0) {
                    preloadImages(newImages);
                }
            }
        });
        
        // 初始化自动保存计时器
        resetAutoSaveTimer();
    </script>
    
    <script>
        // 图片查看器功能
        const imageViewer = document.getElementById('imageViewer');
        const viewerImage = document.getElementById('viewerImage');
        let currentImageSrc = '';
        
        // 点击图片查看大图
        document.addEventListener('click', function(e) {
            if (e.target.tagName === 'IMG' && !e.target.closest('.image-viewer')) {
                currentImageSrc = e.target.src;
                viewerImage.src = currentImageSrc;
                imageViewer.style.display = 'flex';
                document.body.style.overflow = 'hidden'; // 防止背景滚动
            } else if (e.target === imageViewer) {
                // 点击背景关闭查看器
                imageViewer.style.display = 'none';
                document.body.style.overflow = 'auto'; // 恢复滚动
            }
        });
        
        // 按ESC键关闭图片查看器
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && imageViewer.style.display === 'flex') {
                imageViewer.style.display = 'none';
                document.body.style.overflow = 'auto';
            }
        });
        
        // 确认删除函数 - 明确提示将从1.csv中删除
        function confirmDelete(questionId) {
            if (confirm(`确定要删除问题 ID: ${questionId} 吗？此操作将同时从1.csv中删除该题目，且不可恢复。`)) {
                // 创建表单并提交删除请求
                const form = document.createElement('form');
                form.method = 'post';
                form.action = '';
                form.innerHTML = `<input type="hidden" name="delete_question" value="${questionId}">`;
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        // 键盘操作功能：左-忘记，上-模糊，下-认识，右-熟悉
        document.addEventListener('keydown', function(e) {
            // 当文本框被聚焦时不触发键盘导航，避免影响输入
            if (document.activeElement.tagName === 'TEXTAREA') {
                return;
            }
            
            switch(e.key) {
                case 'ArrowLeft':
                    document.getElementById('forgetForm').submit();
                    break;
                case 'ArrowUp':
                    document.getElementById('vagueForm').submit();
                    break;
                case 'ArrowDown':
                    document.getElementById('knowForm').submit();
                    break;
                case 'ArrowRight':
                    document.getElementById('familiarForm').submit();
                    break;
            }
        });
        
        document.addEventListener('DOMContentLoaded', function() {
            // 图片加载完成后添加loaded类
            const images = document.querySelectorAll('img:not(.preloaded)');
            images.forEach(img => {
                img.addEventListener('load', function() {
                    this.classList.add('loaded');
                });
                
                // 如果图片已经缓存，手动触发load事件
                if (img.complete) {
                    img.classList.add('loaded');
                }
            });
            
            // 预加载当前组中其他题目的图片
            <?php if (!empty($_SESSION['image_cache'])): ?>
            const imageUrls = <?php echo json_encode(array_keys($_SESSION['image_cache'])); ?>;
            preloadImages(imageUrls);
            <?php endif; ?>
            
            const accuracyData = {
                '100%': <?php echo $accuracyRanges['100%']; ?>,
                '80%-99%': <?php echo $accuracyRanges['80%-99%']; ?>,
                '60%-79%': <?php echo $accuracyRanges['60%-79%']; ?>,
                '40%-59%': <?php echo $accuracyRanges['40%-59%']; ?>,
                '20%-39%': <?php echo $accuracyRanges['20%-39%']; ?>,
                '<20%': <?php echo $accuracyRanges['<20%']; ?>,
                '未回答': <?php echo $accuracyRanges['未回答']; ?>
            };

            const labels = Object.keys(accuracyData);
            const data = Object.values(accuracyData);
            const backgroundColors = [
                '#FF6384',
                '#36A2EB',
                '#FFCE56',
                '#4BC0C0',
                '#9966FF',
                '#C9CBCF',
                '#FF9F40'
            ];

            // 添加缺失的canvas元素
            const statsContainer = document.querySelector('.stats-container');
            const canvas = document.createElement('canvas');
            canvas.id = 'accuracyChart';
            canvas.height = 200;
            statsContainer.appendChild(canvas);
            
            const ctx = document.getElementById('accuracyChart').getContext('2d');
            
            new Chart(ctx, {
                type: 'pie',
                data: {
                    labels: labels,
                    datasets: [{
                        data: data,
                        backgroundColor: backgroundColors,
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.raw || 0;
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = total > 0 ? Math.round((value / total) * 100) : 0;
                                    return `${label}: ${value}题 (${percentage}%)`;
                                }
                            }
                        }
                    },
                    animation: {
                        animateRotate: true,
                        animateScale: true
                    }
                }
            });
        });
    </script>
    
    <!-- 总进度条移到页面最下方 -->
    <div class="progress-container">
        <div class="progress-bar">
            <div class="progress-fill"></div>
        </div>
        <div class="stats-row">
            <div class="progress-text">
                <?php echo $_SESSION['total_questions'] . "/" . TOTAL_QUESTIONS_TO_COMPLETE . "题 (" . 
                    round($progressPercentage) . "%)"; ?>
            </div>
            <div class="accuracy-text">
                <?php 
                echo "正确率：" . $_SESSION['correct_answers'] . " / " . $_SESSION['total_questions'] . "题 (" . $accuracy . "%)"; 
                ?>
            </div>
        </div>
    </div>
</body>
</html>
