<?php
$pageTitle = '首页';
$pageCss = '/css/index.css';
require_once 'includes/header.php';

// 获取首页弹窗公告
$homePopups = [];
$stmt = $db->prepare("SELECT * FROM popups WHERE is_active = 1 AND show_pages = 'home' AND (start_time IS NULL OR start_time <= NOW()) AND (end_time IS NULL OR end_time >= NOW()) ORDER BY sort_order DESC");
$stmt->execute();
$homePopups = $stmt->fetchAll();

// 获取功能分类和功能列表

// 获取所有分类
$categories = $db->query("SELECT * FROM function_categories ORDER BY sort_order")->fetchAll();

// 获取时间API数据
$timeInfo = '';
$timeJson = @file_get_contents('http://shanhe.kim/api/za/rsdjs.php');
if ($timeJson) {
    $timeData = json_decode($timeJson, true);
    if ($timeData && $timeData['code'] === 200) {
        $timeInfo = $timeData['hour'];
    }
}
if (empty($timeInfo)) {
    $timeInfo = date('H') . '小时' . date('i') . '分钟';
}

// 从SESSION获取课表数据（与课表页同步）
$userId = $_SESSION['user_id'];
$syncedCourses = isset($_SESSION['course_data']) ? $_SESSION['course_data'] : [];
$customCourses = isset($_SESSION['custom_courses']) ? $_SESSION['custom_courses'] : [];
$allCourses = array_merge($syncedCourses, $customCourses);

// 获取今日课表
$todayCourses = [];
$today = date('w'); // 0-6, 0是周日
$today = $today == 0 ? 7 : $today;

// 获取开学时间计算当前周数
$semesterStartDate = '';
$stmt2 = $db->query("SELECT value FROM settings WHERE group_name = 'semester' AND key_name = 'semester_start_date'");
$semRow = $stmt2->fetch();
if ($semRow && $semRow['value']) {
    $semesterStartDate = $semRow['value'];
    $startTs = strtotime($semesterStartDate);
    $diffDays = floor((time() - $startTs) / 86400);
    $currentWeek = max(1, ceil(($diffDays + 1) / 7));
} else {
    $currentWeek = 1;
}

// 从SESSION数据中筛选今日课表
foreach ($allCourses as $course) {
    if ($course['week_day'] == $today && $currentWeek >= $course['start_week'] && $currentWeek <= $course['end_week']) {
        $todayCourses[] = $course;
    }
}
// 按起始节次排序
usort($todayCourses, function($a, $b) { return $a['start_section'] - $b['start_section']; });
?>



<!-- 主要内容 -->
<div class="main-content">
    <!-- 日期和课表卡片 -->
    <div class="schedule-card">
        <div class="date-header">
            <div class="date"><?php echo date('d/F', time()); ?></div>
            <div style="display:flex;align-items:center;gap:12px;">
                <span style="font-size:12px;color:#9ca3af;cursor:pointer;" onclick="syncData('course')">同步课表</span>
                <div class="collapse-btn" id="collapseBtn" onclick="toggleCourseList()">展开</div>
            </div>
        </div>
        <div class="schedule-title">今日课表</div>
        <div class="schedule-subtitle" id="time-subtitle"><?php echo htmlspecialchars($timeInfo); ?></div>
        <?php if (!empty($todayCourses)): ?>
        <div class="course-list" id="courseList">
            <?php foreach ($todayCourses as $i => $course): ?>
            <div class="course-item" style="<?php echo $i > 0 ? 'display:none;' : ''; ?>" data-index="<?php echo $i; ?>">
                <div class="course-time">第<?php echo $course['start_section']; ?>-<?php echo $course['end_section']; ?>节</div>
                <div class="course-name"><?php echo htmlspecialchars($course['course_name']); ?></div>
                <div class="course-location"><?php echo htmlspecialchars($course['location']); ?></div>
            </div>
            <?php endforeach; ?>
        </div>
        <div class="view-more" onclick="location.href='pages/schedule.php'">点击查看更多课程 ></div>
        <?php else: ?>
        <div class="course-list" style="text-align: center; padding: 20px; color: #9ca3af;">
            <div style="font-size:14px;margin-bottom:8px;">今日暂无课程</div>
            <div style="font-size:12px;color:#3b82f6;cursor:pointer;" onclick="syncData('course')">点击同步课表数据</div>
        </div>
        <?php endif; ?>
    </div>

    <?php foreach ($categories as $category): ?>
    <!-- 功能分类 -->
    <div class="section-title"><?php echo htmlspecialchars($category['name']); ?></div>
    <div class="function-grid">
        <div class="grid-4">
            <?php
            $stmt = $db->prepare("SELECT * FROM functions WHERE category_id = ? ORDER BY sort_order");
            $stmt->execute([$category['id']]);
            $functions = $stmt->fetchAll();
            
            foreach ($functions as $function):
                // 判断是外部链接还是内部页面
                if ($function['is_external'] && !empty($function['external_url'])) {
                    $url = $function['external_url'];
                    $target = 'target="_blank"';
                } elseif (!empty($function['page_url'])) {
                    $url = SITE_URL . '/' . $function['page_url'];
                    $target = '';
                } else {
                    $url = 'javascript:void(0)';
                    $target = '';
                }
            ?>
            <div class="grid-item" onclick="location.href='<?php echo $url; ?>'" <?php echo $target; ?>>
                <div class="icon-box">
                    <i class="fas <?php echo $function['icon']; ?>"></i>
                </div>
                <div class="grid-item-name"><?php echo htmlspecialchars($function['name']); ?></div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endforeach; ?>

    <!-- 品牌标识 -->
    <div class="brand">
        一课
    </div>
</div>

<?php if (!empty($homePopups)): ?>
<!-- 首页弹窗公告 -->
<div id="popupOverlay" style="position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(0,0,0,0.5);z-index:9999;display:flex;align-items:center;justify-content:center;">
    <?php foreach ($homePopups as $popup): ?>
    <div class="popup-card" style="background:white;border-radius:16px;max-width:340px;width:90%;overflow:hidden;">
        <?php if ($popup['popup_type'] == 2 && $popup['image']): ?>
        <!-- 图片弹窗 -->
        <div style="width:100%;"><img src="<?php echo htmlspecialchars($popup['image']); ?>" style="width:100%;display:block;"></div>
        <?php else: ?>
        <!-- 公告弹窗 -->
        <div style="padding:24px;">
            <div style="font-size:16px;font-weight:600;color:#1f2937;margin-bottom:12px;"><?php echo htmlspecialchars($popup['title']); ?></div>
            <div style="font-size:14px;color:#6b7280;line-height:1.8;"><?php echo htmlspecialchars($popup['content']); ?></div>
        </div>
        <?php endif; ?>
        <div style="padding:12px 24px;text-align:right;border-top:1px solid #f3f4f6;">
            <button onclick="closePopup()" style="padding:8px 16px;background:#374151;color:white;border-radius:8px;font-size:14px;cursor:pointer;border:none;">知道了</button>
        </div>
    </div>
    <?php break; // 只显示第一个弹窗 ?>
    <?php endforeach; ?>
</div>

<script>
function closePopup() {
    document.getElementById('popupOverlay').style.display = 'none';
}
</script>
<?php endif; ?>

<!-- 底部导航 -->
<div class="bottom-nav">
    <div class="nav-item active">
        <div class="nav-icon">
            <i class="fas fa-home"></i>
        </div>
        <div class="nav-name">大厅</div>
    </div>
    <div class="nav-item" onclick="location.href='<?php echo SITE_URL; ?>/pages/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='<?php echo SITE_URL; ?>/pages/profile.php'">
        <div class="nav-icon">
            <i class="fas fa-user"></i>
        </div>
        <div class="nav-name">我的</div>
    </div>
</div>

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

<script>
var courseExpanded = false;
function toggleCourseList() {
    var btn = document.getElementById('collapseBtn');
    var items = document.querySelectorAll('.course-item[data-index]');
    courseExpanded = !courseExpanded;
    items.forEach(function(item) {
        if (item.getAttribute('data-index') === '0') return;
        item.style.display = courseExpanded ? 'block' : 'none';
    });
    btn.textContent = courseExpanded ? '收起' : '展开';
}

function updateTimeSubtitle() {
    fetch('<?php echo SITE_URL; ?>/api/time.php')
        .then(function(res) { return res.json(); })
        .then(function(data) {
            if (data.code === 200) {
                var el = document.getElementById('time-subtitle');
                if (el) {
                    el.textContent = '今天已过去' + data.hour;
                }
            }
        })
        .catch(function() {});
}
setInterval(updateTimeSubtitle, 60000);

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