<?php
$pageTitle = '课表';
$pageCss = '/css/schedule.css';
require_once '../includes/header.php';

// 获取学期时间配置（开学+放假截止）
$semesterStartDate = '';
$semesterEndDate = '';
$stmt2 = $db->query("SELECT key_name, value FROM settings WHERE group_name = 'semester'");
$semRows = $stmt2->fetchAll();
foreach ($semRows as $sr) {
    if ($sr['key_name'] === 'semester_start_date') $semesterStartDate = $sr['value'];
    if ($sr['key_name'] === 'semester_end_date') $semesterEndDate = $sr['value'];
}
if ($semesterStartDate) {
    $startTs = strtotime($semesterStartDate);
    $diffDays = floor((time() - $startTs) / 86400);
    $defaultWeek = max(1, ceil(($diffDays + 1) / 7));
    // 如果设置了放假截止日期且已超过，显示最后一周
    if ($semesterEndDate) {
        $endTs = strtotime($semesterEndDate);
        $totalWeeks = max(1, ceil(($endTs - $startTs) / (7 * 86400)));
        if (time() > $endTs) {
            $defaultWeek = min($totalWeeks, 25);
        }
    }
} else {
    $defaultWeek = 1;
}
// 计算学期总周数（用于周切换上限）
$maxWeek = 25;
if ($semesterStartDate && $semesterEndDate) {
    $maxWeek = max(1, ceil((strtotime($semesterEndDate) - strtotime($semesterStartDate)) / (7 * 86400)));
}

$currentWeek = isset($_GET['week']) ? (int)$_GET['week'] : $defaultWeek;
$todayWeekDay = date('w') == 0 ? 7 : date('w');

// 获取课节时间配置（从course_sections表）
$sectionTimes = [];
$stmt = $db->query("SELECT section_number, start_time, end_time FROM course_sections ORDER BY section_number");
$sectionRows = $stmt->fetchAll();
if (!empty($sectionRows)) {
    foreach ($sectionRows as $row) {
        $sectionTimes[(int)$row['section_number']] = [$row['start_time'], $row['end_time']];
    }
}
if (empty($sectionTimes)) {
    // 兜底默认12节
    $sectionTimes = [
        1  => ['08:00', '08:45'], 2  => ['08:55', '09:40'], 3  => ['10:00', '10:45'],
        4  => ['10:55', '11:40'], 5  => ['14:00', '14:45'], 6  => ['14:55', '15:40'],
        7  => ['16:00', '16:45'], 8  => ['16:55', '17:40'], 9  => ['19:00', '19:45'],
        10 => ['19:55', '20:40'], 11 => ['20:50', '21:35'], 12 => ['21:45', '22:30'],
    ];
}

// 从SESSION获取课表数据（不再从数据库读取）
$userId = $_SESSION['user_id'];
$syncedCourses = isset($_SESSION['course_data']) ? $_SESSION['course_data'] : [];
$customCourses = isset($_SESSION['custom_courses']) ? $_SESSION['custom_courses'] : [];

// 合并知岁OS同步课表 + 自定义课程
$courses = array_merge($syncedCourses, $customCourses);

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

// 按星期+起始节次构建课程映射 [week_day][start_section] = course
$courseMap = [];
foreach ($courses as $course) {
    if ($currentWeek >= $course['start_week'] && $currentWeek <= $course['end_week']) {
        $courseMap[$course['week_day']][$course['start_section']] = $course;
    }
}

// 课程颜色池
$colorPool = [
    ['#4F6EF7', '#EEF1FE'], ['#F7664F', '#FEECEA'], ['#36B37E', '#E3FCEF'],
    ['#FFAB00', '#FFF8E1'], ['#8B5CF6', '#F3EEFF'], ['#00B8D9', '#E0F7FA'],
    ['#EC4899', '#FDE7F0'], ['#6554C0', '#EAE6FF'], ['#FF5630', '#FFEBE6'],
    ['#00C853', '#E8F5E9'],
];

function getCourseColor($courseName, $colorPool) {
    $hash = crc32($courseName);
    $index = abs($hash) % count($colorPool);
    return $colorPool[$index];
}

// 本周日期
$weekDates = [];
$monday = strtotime('-' . ($todayWeekDay - 1) . ' days');
for ($i = 0; $i < 7; $i++) {
    $weekDates[$i + 1] = date('m/d', strtotime('+' . $i . ' days', $monday));
}

// 为每个课程块计算颜色和跨度信息
$courseBlocks = [];
foreach ($courseMap as $day => $dayCourses) {
    foreach ($dayCourses as $startSec => $course) {
        $colors = getCourseColor($course['course_name'], $colorPool);
        $span = $course['end_section'] - $course['start_section'] + 1;
        $courseBlocks[$day][$startSec] = [
            'id' => $course['id'],
            'name' => $course['course_name'],
            'location' => $course['location'] ?: '',
            'teacher' => $course['teacher_name'] ?: '',
            'start' => $course['start_section'],
            'end' => $course['end_section'],
            'span' => $span,
            'c1' => $colors[0],
            'c2' => $colors[1],
        ];
    }
}

// 跟踪哪些格子被课程占用 [day][section] = true
$occupied = [];
foreach ($courseBlocks as $day => $blocks) {
    foreach ($blocks as $block) {
        for ($s = $block['start']; $s <= $block['end']; $s++) {
            $occupied[$day][$s] = 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('course')">立即更新</button>
</div>
<?php endif; ?>

<!-- 顶部栏：周切换 + 更多 -->
<div class="top-bar">
    <div class="week-nav">
        <i class="fas fa-chevron-left" onclick="changeWeek(<?php echo max(1, $currentWeek - 1); ?>)"></i>
        <span class="week-label" onclick="changeWeek()">第<?php echo $currentWeek; ?>周</span>
        <i class="fas fa-chevron-right" onclick="changeWeek(<?php echo min($maxWeek, $currentWeek + 1); ?>)"></i>
    </div>
    <div class="top-actions">
        <i class="fas fa-sync-alt" onclick="syncData('course')" title="同步课表"></i>
        <i class="fas fa-plus" onclick="location.href='custom.php'" title="自定义课程"></i>
        <i class="fas fa-ellipsis-v" onclick="toggleMenu()" title="更多"></i>
    </div>
</div>

<!-- 更多菜单 -->
<div class="floating-menu" id="floatingMenu">
    <div class="menu-item" onclick="syncData('course');toggleMenu();">
        <i class="fas fa-cloud-download-alt"></i>
        <span>同步课表</span>
    </div>
    <div class="menu-item" onclick="changeWeek();toggleMenu();">
        <i class="fas fa-calendar-week"></i>
        <span>跳转周次</span>
    </div>
    <div class="menu-item" onclick="location.href='custom.php'">
        <i class="fas fa-plus-circle"></i>
        <span>自定义课程</span>
    </div>
</div>

<!-- 课表网格 -->
<div class="timetable-wrapper">
    <?php if (empty($courses)): ?>
    <!-- 空数据提示横幅 -->
    <div class="empty-grid-tip" style="text-align:center;padding:16px 20px;background:#fef3c7;border-radius:8px;margin-bottom:12px;font-size:14px;color:#92400e;">
        <i class="fas fa-info-circle" style="margin-right:4px;"></i>
        暂无课表数据，请点击右上角同步按钮导入
    </div>
    <?php endif; ?>
    <!-- 星期头 -->
    <div class="timetable-header">
        <div class="th-corner"></div>
        <?php for ($day = 1; $day <= 7; $day++): ?>
        <div class="th-day <?php echo $day == $todayWeekDay ? 'today' : ''; ?>">
            <div class="th-day-name">周<?php echo ['一','二','三','四','五','六','日'][$day-1]; ?></div>
            <div class="th-date"><?php echo $weekDates[$day]; ?></div>
        </div>
        <?php endfor; ?>
    </div>

    <!-- 课表网格主体：8列(1节次+7天) x 12行(节次) -->
    <div class="timetable-grid">
        <?php for ($sec = 1; $sec <= 12; $sec++): ?>
            <!-- 左侧节次 -->
            <div class="sec-cell" style="grid-row: <?php echo $sec; ?>; grid-column: 1;">
                <span class="sec-num"><?php echo $sec; ?></span>
                <span class="sec-time-start"><?php echo $sectionTimes[$sec][0]; ?></span>
                <span class="sec-time-end"><?php echo $sectionTimes[$sec][1]; ?></span>
            </div>

            <!-- 7天格子 -->
            <?php for ($day = 1; $day <= 7; $day++): ?>
                <?php if (isset($courseBlocks[$day][$sec])): ?>
                    <!-- 课程色块：跨行显示 -->
                    <div class="course-block"
                         style="grid-row: <?php echo $sec; ?> / span <?php echo $courseBlocks[$day][$sec]['span']; ?>; grid-column: <?php echo $day + 1; ?>; --c1: <?php echo $courseBlocks[$day][$sec]['c1']; ?>; --c2: <?php echo $courseBlocks[$day][$sec]['c2']; ?>; --span: <?php echo $courseBlocks[$day][$sec]['span']; ?>;"
                         onclick="showCourseDetail(<?php echo $courseBlocks[$day][$sec]['id']; ?>)">
                        <div class="cb-name"><?php echo htmlspecialchars($courseBlocks[$day][$sec]['name']); ?></div>
                        <?php if ($courseBlocks[$day][$sec]['location']): ?>
                        <div class="cb-location">@<?php echo htmlspecialchars($courseBlocks[$day][$sec]['location']); ?></div>
                        <?php endif; ?>
                        <?php if ($courseBlocks[$day][$sec]['teacher'] && $courseBlocks[$day][$sec]['span'] >= 2): ?>
                        <div class="cb-teacher"><?php echo htmlspecialchars($courseBlocks[$day][$sec]['teacher']); ?></div>
                        <?php endif; ?>
                    </div>
                <?php elseif (!isset($occupied[$day][$sec])): ?>
                    <!-- 空格子 -->
                    <div class="grid-cell"
                         style="grid-row: <?php echo $sec; ?>; grid-column: <?php echo $day + 1; ?>"></div>
                <?php endif; ?>
            <?php endfor; ?>
        <?php endfor; ?>
    </div>
</div>

<!-- 课程详情弹窗 -->
<div class="course-modal" id="courseModal" onclick="closeCourseModal(event)">
    <div class="course-modal-content" id="courseModalContent"></div>
</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 active">
        <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>
var courseData = <?php echo json_encode(array_column($courses, null, 'id'), JSON_UNESCAPED_UNICODE); ?>;

function toggleMenu() {
    document.getElementById('floatingMenu').classList.toggle('show');
}

document.addEventListener('click', function(e) {
    var menu = document.getElementById('floatingMenu');
    var btn = document.querySelector('.fa-ellipsis-v');
    if (btn && !menu.contains(e.target) && e.target !== btn && !btn.contains(e.target)) {
        menu.classList.remove('show');
    }
});

var maxWeek = <?php echo $maxWeek; ?>;
function changeWeek(week) {
    if (week === undefined) {
        week = prompt('请输入周次 (1-' + maxWeek + '):', '<?php echo $currentWeek; ?>');
        if (!week) return;
    }
    week = parseInt(week);
    if (week >= 1 && week <= maxWeek) {
        location.href = '<?php echo SITE_URL; ?>/pages/schedule.php?week=' + week;
    }
}

function showCourseDetail(id) {
    var c = courseData[id];
    if (!c) return;
    var weekDayNames = ['','周一','周二','周三','周四','周五','周六','周日'];
    var html = '<div class="cmd-header">' +
        '<div class="cmd-name">' + c.course_name + '</div>' +
        '<i class="fas fa-times cmd-close" onclick="closeCourseModal()"></i>' +
        '</div>' +
        '<div class="cmd-body">' +
        '<div class="cmd-row"><i class="fas fa-user-tie"></i><span>' + (c.teacher_name || '未设置') + '</span></div>' +
        '<div class="cmd-row"><i class="fas fa-map-marker-alt"></i><span>' + (c.location || '未设置') + '</span></div>' +
        '<div class="cmd-row"><i class="fas fa-clock"></i><span>第' + c.start_section + '-' + c.end_section + '节</span></div>' +
        '<div class="cmd-row"><i class="fas fa-calendar-week"></i><span>' + weekDayNames[c.week_day] + '，第' + c.start_week + '-' + c.end_week + '周</span></div>' +
        '</div>';
    document.getElementById('courseModalContent').innerHTML = html;
    document.getElementById('courseModal').classList.add('show');
}

function closeCourseModal(e) {
    if (e && e.target !== document.getElementById('courseModal') && !e.target.classList.contains('cmd-close')) return;
    document.getElementById('courseModal').classList.remove('show');
}

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

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