<?php
$pageTitle = '成绩';
$pageCss = '/css/grades.css';
require_once '../includes/header.php';

$userId = $_SESSION['user_id'];

// 从SESSION获取成绩数据（不再从数据库读取）
$grades = isset($_SESSION['score_data']) ? $_SESSION['score_data'] : [];

// 计算总学分和GPA
$totalCredits = 0;
$totalGpa = 0;
$gpa = 0;

foreach ($grades as $grade) {
    $totalCredits += $grade['credit'];
    $totalGpa += $grade['grade_point'] * $grade['credit'];
}
$gpa = $totalCredits > 0 ? round($totalGpa / $totalCredits, 2) : 0;

// 按学期分组
$gradesBySemester = [];
foreach ($grades as $grade) {
    $key = $grade['academic_year'] . ' ' . $grade['semester'];
    $gradesBySemester[$key][] = $grade;
}

// 检查数据是否过期（超过7天）
$syncTime = $_SESSION['score_sync_time'] ?? '';
$isExpired = false;
$daysSinceSync = 0;
if ($syncTime) {
    $daysSinceSync = floor((time() - strtotime($syncTime)) / 86400);
    if ($daysSinceSync > 7) {
        $isExpired = true;
    }
}
?>

<!-- 数据过期提示 -->
<?php if ($isExpired): ?>
<div class="sync-expire-banner">
    <i class="fas fa-exclamation-triangle"></i>
    <span>成绩数据已<?php echo $daysSinceSync; ?>天未更新，请重新同步知岁OS获取最新数据</span>
    <button class="expire-sync-btn" onclick="syncData('score')">立即更新</button>
</div>
<?php endif; ?>

<!-- 页面头部 -->
<div class="page-header-simple">
    <div class="header-left">
        <div class="header-title">成绩</div>
        <div class="header-stats">
            <div class="stat-item">
                <span class="stat-value"><?php echo $gpa; ?></span>
                <span class="stat-label">GPA</span>
            </div>
            <div class="stat-divider"></div>
            <div class="stat-item">
                <span class="stat-value"><?php echo $totalCredits; ?></span>
                <span class="stat-label">总学分</span>
            </div>
        </div>
    </div>
    <div class="sync-btn" onclick="syncData('score')">
        <i class="fas fa-cloud-download-alt"></i> 同步
    </div>
</div>

<!-- 成绩列表 -->
<div class="data-content">
    <?php if (empty($gradesBySemester)): ?>
    <div class="empty-state">
        <i class="fas fa-graduation-cap"></i>
        <p>暂无成绩数据</p>
        <div class="empty-hint">点击"同步"按钮从知岁OS获取成绩数据</div>
    </div>
    <?php else: ?>
        <?php foreach ($gradesBySemester as $semester => $semesterGrades): ?>
        <div class="semester-section">
            <div class="semester-title"><?php echo htmlspecialchars($semester); ?></div>
            <div class="grade-table">
                <div class="table-header">
                    <div class="col-course">课程</div>
                    <div class="col-credit">学分</div>
                    <div class="col-gpa">绩点</div>
                    <div class="col-score">成绩</div>
                </div>
                <?php foreach ($semesterGrades as $grade): ?>
                <?php
                $scoreClass = 'score-pass';
                $scoreVal = $grade['score'];
                if (is_numeric($scoreVal)) {
                    if ($scoreVal >= 90) $scoreClass = 'score-excellent';
                    elseif ($scoreVal >= 80) $scoreClass = 'score-good';
                } else {
                    // 文字成绩：优→excellent, 良→good, 中/合格→pass, 不及格→fail
                    $textGrade = strtolower(trim($scoreVal));
                    if (in_array($textGrade, ['优', '优秀', 'a', 'a+'])) $scoreClass = 'score-excellent';
                    elseif (in_array($textGrade, ['良', '良好', 'b', 'b+'])) $scoreClass = 'score-good';
                    elseif (in_array($textGrade, ['中', '中等', '合格', '及格', 'c', 'pass'])) $scoreClass = 'score-pass';
                    elseif (in_array($textGrade, ['不及格', '不合格', '差', 'f', 'fail'])) $scoreClass = 'score-fail';
                }
                ?>
                <div class="table-row">
                    <div class="col-course">
                        <div class="course-name"><?php echo htmlspecialchars($grade['course_name']); ?></div>
                    </div>
                    <div class="col-credit"><?php echo $grade['credit']; ?></div>
                    <div class="col-gpa"><?php echo $grade['grade_point']; ?></div>
                    <div class="col-score">
                        <span class="score-value <?php echo $scoreClass; ?>"><?php echo $grade['score']; ?></span>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endforeach; ?>
    <?php endif; ?>
</div>

<!-- 底部导航 -->
<div class="bottom-nav">
    <div class="nav-item" onclick="location.href='../index.php'">
        <div class="nav-icon"><i class="fas fa-home"></i></div>
        <div class="nav-name">大厅</div>
    </div>
    <div class="nav-item" onclick="location.href='schedule.php'">
        <div class="nav-icon"><i class="fas fa-calendar-alt"></i></div>
        <div class="nav-name">课表</div>
    </div>
    <div class="nav-item" onclick="location.href='profile.php'">
        <div class="nav-icon"><i class="fas fa-user"></i></div>
        <div class="nav-name">我的</div>
    </div>
</div>

<script>
function syncData(type) {
    location.href = '<?php echo SITE_URL; ?>/pages/zsos-import.php?type=' + (type || 'score');
}
</script>

<?php require_once '../includes/footer.php'; ?>
