<?php
$pageTitle = '自定义课程';
$pageCss = '/css/custom.css';
require_once '../includes/header.php';

// 处理表单提交
$userId = $_SESSION['user_id'];
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add' || $action === 'edit') {
        $courseName = trim($_POST['course_name'] ?? '');
        $teacherName = trim($_POST['teacher_name'] ?? '');
        $location = trim($_POST['location'] ?? '');
        $weekDay = (int)($_POST['week_day'] ?? 0);
        $startSection = (int)($_POST['start_section'] ?? 0);
        $endSection = (int)($_POST['end_section'] ?? 0);
        $startWeek = (int)($_POST['start_week'] ?? 1);
        $endWeek = (int)($_POST['end_week'] ?? 18);
        
        if (empty($courseName) || empty($weekDay) || empty($startSection) || empty($endSection)) {
            $message = '请填写完整信息';
        } else {
            // 从SESSION读取自定义课程
            $customCourses = isset($_SESSION['custom_courses']) ? $_SESSION['custom_courses'] : [];
            
            if ($action === 'add') {
                // 生成唯一ID
                $maxId = 0;
                foreach ($customCourses as $c) {
                    if ($c['id'] > $maxId) $maxId = $c['id'];
                }
                $newId = $maxId + 1;
                // 同时检查synced courses的ID避免冲突
                $syncedCourses = isset($_SESSION['course_data']) ? $_SESSION['course_data'] : [];
                foreach ($syncedCourses as $c) {
                    if ($c['id'] > $maxId) $maxId = $c['id'];
                }
                $newId = $maxId + 1;
                // 使用更大的ID范围避免冲突（自定义课程ID从1000开始）
                $newId = max($newId, 1000);
                foreach ($customCourses as $c) {
                    if ($c['id'] >= $newId) $newId = $c['id'] + 1;
                }

                $customCourses[] = [
                    'id' => $newId,
                    'course_name' => $courseName,
                    'teacher_name' => $teacherName,
                    'location' => $location,
                    'week_day' => $weekDay,
                    'start_section' => $startSection,
                    'end_section' => $endSection,
                    'start_week' => $startWeek,
                    'end_week' => $endWeek,
                    'semester' => '',
                    'academic_year' => '',
                    'is_custom' => true,
                ];
                $_SESSION['custom_courses'] = $customCourses;
                $message = '课程添加成功';
            } elseif ($action === 'edit') {
                $courseId = (int)$_POST['course_id'];
                foreach ($customCourses as $i => $c) {
                    if ($c['id'] == $courseId) {
                        $customCourses[$i] = [
                            'id' => $courseId,
                            'course_name' => $courseName,
                            'teacher_name' => $teacherName,
                            'location' => $location,
                            'week_day' => $weekDay,
                            'start_section' => $startSection,
                            'end_section' => $endSection,
                            'start_week' => $startWeek,
                            'end_week' => $endWeek,
                            'semester' => $c['semester'] ?? '',
                            'academic_year' => $c['academic_year'] ?? '',
                            'is_custom' => true,
                        ];
                        break;
                    }
                }
                $_SESSION['custom_courses'] = $customCourses;
                $message = '课程修改成功';
            }
        }
    } elseif ($action === 'delete') {
        $courseId = (int)$_POST['course_id'];
        $customCourses = isset($_SESSION['custom_courses']) ? $_SESSION['custom_courses'] : [];
        $_SESSION['custom_courses'] = array_values(array_filter($customCourses, function($c) use ($courseId) {
            return $c['id'] != $courseId;
        }));
        $message = '课程删除成功';
    }
}

// 获取用户自定义课程列表（从SESSION读取）
$courses = isset($_SESSION['custom_courses']) ? $_SESSION['custom_courses'] : [];
?>

<!-- 自定义课程头部 -->
<div class="custom-header">
    <span class="header-title">自定义课程</span>
</div>

<?php if ($message): ?>
<div class="toast"><?php echo htmlspecialchars($message); ?></div>
<?php endif; ?>

<!-- 添加课程表单 -->
<div class="form-container">
    <div class="form-title">添加课程</div>
    <form method="POST" action="">
        <input type="hidden" name="action" value="add">
        
        <div class="form-group">
            <label class="form-label">课程名称 *</label>
            <input type="text" class="form-input" name="course_name" required placeholder="请输入课程名称">
        </div>
        
        <div class="form-group">
            <label class="form-label">任课老师</label>
            <input type="text" class="form-input" name="teacher_name" placeholder="请输入任课老师">
        </div>
        
        <div class="form-group">
            <label class="form-label">上课地点</label>
            <input type="text" class="form-input" name="location" placeholder="请输入上课地点">
        </div>
        
        <div class="form-row">
            <div class="form-group">
                <label class="form-label">星期 *</label>
                <select class="form-select" name="week_day" required>
                    <option value="">请选择</option>
                    <?php for ($i = 1; $i <= 7; $i++): ?>
                    <option value="<?php echo $i; ?>">周<?php echo ['一', '二', '三', '四', '五', '六', '日'][$i - 1]; ?></option>
                    <?php endfor; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label">开始节次 *</label>
                <select class="form-select" name="start_section" required>
                    <option value="">请选择</option>
                    <?php for ($i = 1; $i <= 13; $i++): ?>
                    <option value="<?php echo $i; ?>">第<?php echo $i; ?>节</option>
                    <?php endfor; ?>
                </select>
            </div>
            
            <div class="form-group">
                <label class="form-label">结束节次 *</label>
                <select class="form-select" name="end_section" required>
                    <option value="">请选择</option>
                    <?php for ($i = 1; $i <= 13; $i++): ?>
                    <option value="<?php echo $i; ?>">第<?php echo $i; ?>节</option>
                    <?php endfor; ?>
                </select>
            </div>
        </div>
        
        <div class="form-row">
            <div class="form-group">
                <label class="form-label">开始周次</label>
                <input type="number" class="form-input" name="start_week" value="1" min="1" max="18">
            </div>
            
            <div class="form-group">
                <label class="form-label">结束周次</label>
                <input type="number" class="form-input" name="end_week" value="18" min="1" max="18">
            </div>
        </div>
        
        <div class="btn-group">
            <button type="button" class="btn btn-secondary" onclick="resetForm()">重置</button>
            <button type="submit" class="btn btn-primary">添加课程</button>
        </div>
    </form>
</div>

<!-- 课程列表 -->
<?php if (!empty($courses)): ?>
<div class="course-list">
    <div class="list-title">我的自定义课程</div>
    <?php foreach ($courses as $course): ?>
    <div class="course-item">
        <div class="course-header">
            <div class="course-name"><?php echo htmlspecialchars($course['course_name']); ?></div>
            <div class="course-actions">
                <button class="action-btn edit-btn" onclick="editCourse(<?php echo $course['id']; ?>)">编辑</button>
                <button class="action-btn delete-btn" onclick="deleteCourse(<?php echo $course['id']; ?>)">删除</button>
            </div>
        </div>
        <div class="course-detail">
            <span>老师:</span><?php echo htmlspecialchars($course['teacher_name'] ?: '未设置'); ?><br>
            <span>地点:</span><?php echo htmlspecialchars($course['location'] ?: '未设置'); ?><br>
            <span>时间:</span>周<?php echo ['一', '二', '三', '四', '五', '六', '日'][$course['week_day'] - 1]; ?>
            第<?php echo $course['start_section']; ?>-<?php echo $course['end_section']; ?>节
            (第<?php echo $course['start_week']; ?>-<?php echo $course['end_week']; ?>周)
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<script>
function resetForm() {
    document.querySelector('form').reset();
}

function editCourse(id) {
    // 使用AJAX方式编辑（避免需要单独的编辑页面）
    var courses = <?php echo json_encode($courses, JSON_UNESCAPED_UNICODE); ?>;
    var course = null;
    for (var i = 0; i < courses.length; i++) {
        if (courses[i].id == id) { course = courses[i]; break; }
    }
    if (!course) return;

    // 填充表单
    var form = document.querySelector('form');
    form.querySelector('[name="action"]').value = 'edit';
    // 动态添加course_id隐藏字段
    var idInput = form.querySelector('[name="course_id"]');
    if (!idInput) {
        idInput = document.createElement('input');
        idInput.type = 'hidden';
        idInput.name = 'course_id';
        form.appendChild(idInput);
    }
    idInput.value = id;

    form.querySelector('[name="course_name"]').value = course.course_name;
    form.querySelector('[name="teacher_name"]').value = course.teacher_name || '';
    form.querySelector('[name="location"]').value = course.location || '';
    form.querySelector('[name="week_day"]').value = course.week_day;
    form.querySelector('[name="start_section"]').value = course.start_section;
    form.querySelector('[name="end_section"]').value = course.end_section;
    form.querySelector('[name="start_week"]').value = course.start_week;
    form.querySelector('[name="end_week"]').value = course.end_week;

    // 更改提交按钮文字
    var submitBtn = form.querySelector('.btn-primary');
    submitBtn.textContent = '保存修改';
}

function deleteCourse(id) {
    if (confirm('确定要删除这门课程吗？')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="course_id" value="${id}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}
</script>

<!-- 底部导航 -->
<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>

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