<?php
$pageTitle = '空教室';
$pageCss = '/css/classroom.css';
require_once '../includes/header.php';

$userId = $_SESSION['user_id'];

// 从SESSION获取空教室数据（不再从数据库读取）
$classroomRawData = isset($_SESSION['classroom_data']) ? $_SESSION['classroom_data'] : [];

// 获取今天是星期几
$weekDay = date('w') == 0 ? 7 : date('w');
$dayNames = ['一', '二', '三', '四', '五', '六', '日'];

// 解析SESSION数据为页面需要的格式
$classroomData = [];
$buildings = [];
foreach ($classroomRawData as $building => $rooms) {
    if (!is_array($rooms)) continue;
    $buildings[] = $building;
    foreach ($rooms as $room) {
        $roomName = $room['name'] ?? '';
        $status = $room['status'] ?? [];
        if (empty($roomName)) continue;

        // 生成12节的状态数组
        $sectionStatus = array_fill(0, 12, 0); // 0=空闲
        if (!empty($status)) {
            foreach ($status as $i => $s) {
                if ($i < 12) {
                    $sectionStatus[$i] = intval($s);
                }
            }
        }

        // 计算空闲节数
        $freeCount = count(array_filter($sectionStatus, function($v) { return $v === 0; }));

        $classroomData[$building][] = [
            'name' => $roomName,
            'capacity' => $room['capacity'] ?? 0,
            'status' => $sectionStatus,
            'freeCount' => $freeCount,
        ];
    }
}

$hasData = !empty($classroomData);

// 检查数据是否过期（超过7天）
$syncTime = $_SESSION['classroom_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('classroom')">立即更新</button>
</div>
<?php endif; ?>

<!-- 页面头部 -->
<div class="page-header">
    <div class="header-title">空教室</div>
    <div class="header-sub">周<?php echo $dayNames[$weekDay - 1]; ?> · <?php echo $hasData ? count($buildings) . '栋教学楼' : '暂无数据'; ?></div>
    <div class="sync-btn" onclick="syncData('classroom')">
        <i class="fas fa-cloud-download-alt"></i> 同步
    </div>
</div>

<!-- 数据展示 -->
<?php if (!$hasData): ?>
<div class="empty-state">
    <i class="fas fa-chalkboard"></i>
    <p>暂无空教室数据</p>
    <div class="empty-hint">点击"同步"按钮从知岁OS获取数据</div>
</div>
<?php else: ?>
<div class="classroom-content">
    <?php foreach ($classroomData as $building => $rooms): ?>
    <div class="building-section">
        <div class="building-title">
            <i class="fas fa-building"></i>
            <?php echo htmlspecialchars($building); ?>
            <span class="building-count"><?php echo count($rooms); ?>间</span>
        </div>
        <div class="room-grid">
            <?php foreach ($rooms as $room): ?>
            <div class="room-card <?php echo $room['freeCount'] > 0 ? 'has-free' : 'all-busy'; ?>">
                <div class="room-name"><?php echo htmlspecialchars($room['name']); ?></div>
                <?php if ($room['capacity'] > 0): ?>
                <div class="room-capacity"><?php echo $room['capacity']; ?>人</div>
                <?php endif; ?>
                <div class="room-status">
                    <?php foreach ($room['status'] as $i => $s): ?>
                    <div class="section-dot <?php echo $s === 0 ? 'free' : 'busy'; ?>" title="第<?php echo $i + 1; ?>节"></div>
                    <?php endforeach; ?>
                </div>
                <div class="room-free-count">
                    <?php echo $room['freeCount']; ?>/12节空闲
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- 节次对照条 -->
<div class="section-legend">
    <?php for ($i = 1; $i <= 12; $i++): ?>
    <div class="legend-item">
        <span class="legend-num"><?php echo $i; ?></span>
    </div>
    <?php endfor; ?>
</div>
<?php endif; ?>

<!-- 底部导航 -->
<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 || 'classroom');
}
</script>

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