<?php 
include 'includes/header.php'; 
include 'includes/sidebar.php'; 

$teacher_id = $_SESSION['teacher_id'];
$id = $_GET['id'] ?? null;

$stmt = $pdo->prepare("SELECT * FROM class_notices WHERE id = ? AND teacher_id = ?");
$stmt->execute([$id, $teacher_id]);
$data = $stmt->fetch();

if (!$data) { die("Notice not found!"); }

$courses = $pdo->prepare("SELECT id, title FROM courses WHERE teacher_id = ? OR 1=1 AND status='active'");
$courses->execute([$teacher_id]);
$course_list = $courses->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $pdo->prepare("UPDATE class_notices SET course_id=?, title=?, content=? WHERE id=?")
        ->execute([$_POST['course_id'], $_POST['title'], $_POST['content'], $id]);
    header("Location: class_notices.php?msg=updated");
    exit;
}
?>

<div class="main-content">
    <div class="dashboard-header d-flex justify-content-between align-items-center">
        <div class="d-flex align-items-center"><button class="btn btn-light d-lg-none me-3" id="sidebarToggle"><i class="fas fa-bars"></i></button><h4 class="mb-0 fw-bold">Edit Class Notice</h4></div>
        <a href="class_notices.php" class="btn btn-light border rounded-pill px-4 fw-bold">Back</a>
    </div>

    <div class="row justify-content-center">
        <div class="col-xl-7">
            <div class="form-card" style="border-top-color: var(--theme-gold);">
                <form method="POST">
                    <div class="mb-4">
                        <label class="form-label">Course</label>
                        <select name="course_id" class="form-select" required>
                            <?php foreach($course_list as $c): ?>
                                <option value="<?= $c['id'] ?>" <?= $data['course_id'] == $c['id'] ? 'selected' : '' ?>><?= $c['title'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-4"><label class="form-label">Title</label><input type="text" name="title" class="form-control" value="<?= $data['title'] ?>" required></div>
                    <div class="mb-4"><label class="form-label">Content</label><textarea name="content" class="form-control" rows="6" required><?= $data['content'] ?></textarea></div>
                    <div class="text-center mt-4"><button type="submit" class="btn-submit" style="background:var(--theme-green)">Update Notice</button></div>
                </form>
            </div>
        </div>
    </div>
</div>
<?php include 'includes/footer.php'; ?>