<?php
// /elms/admin/announcements/index.php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

define('APP_ROOT', dirname(__DIR__, 2)); // .../elms

$PAGE_TITLE = 'Announcements';
$ACTIVE = 'announcements';

require_once APP_ROOT . '/includes/admin_auth.php';
require_once APP_ROOT . '/includes/db.php';

$helpers = APP_ROOT . '/includes/helpers.php';
if (is_file($helpers)) {
    require_once $helpers;
}

if (!isset($mysqli) || !($mysqli instanceof mysqli)) {
    if (isset($conn) && $conn instanceof mysqli) {
        $mysqli = $conn;
    }
}

if (!isset($mysqli) || !($mysqli instanceof mysqli)) {
    http_response_code(500);
    echo 'Database connection not initialized.';
    exit;
}

@$mysqli->set_charset('utf8mb4');

/* ---------------- Helpers ---------------- */

if (!function_exists('esc')) {
    function esc($s): string
    {
        return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

if (!function_exists('table_exists')) {
    function table_exists(mysqli $db, string $table): bool
    {
        $table = $db->real_escape_string($table);

        if ($rs = $db->query("SHOW TABLES LIKE '{$table}'")) {
            $ok = $rs->num_rows > 0;
            $rs->free();
            return $ok;
        }

        return false;
    }
}

if (!function_exists('col_exists')) {
    function col_exists(mysqli $db, string $table, string $column): bool
    {
        $table = $db->real_escape_string($table);
        $column = $db->real_escape_string($column);

        if ($rs = $db->query("SHOW COLUMNS FROM `{$table}` LIKE '{$column}'")) {
            $ok = $rs->num_rows > 0;
            $rs->free();
            return $ok;
        }

        return false;
    }
}

if (!function_exists('label_col')) {
    function label_col(mysqli $db, string $table, array $candidates): string
    {
        if (!table_exists($db, $table)) {
            return 'id';
        }

        if ($rs = $db->query("SHOW COLUMNS FROM `{$table}`")) {
            $cols = [];

            while ($row = $rs->fetch_assoc()) {
                $cols[] = $row['Field'];
            }

            $rs->free();

            foreach ($candidates as $column) {
                if (in_array($column, $cols, true)) {
                    return $column;
                }
            }
        }

        return 'id';
    }
}

if (!function_exists('dt_from_input')) {
    function dt_from_input(?string $value): ?string
    {
        $value = trim((string)$value);

        if ($value === '') {
            return null;
        }

        $time = strtotime($value);

        if ($time === false) {
            return null;
        }

        return date('Y-m-d H:i:s', $time);
    }
}

if (!function_exists('format_dt')) {
    function format_dt($value): string
    {
        $value = trim((string)$value);

        if ($value === '' || $value === '0000-00-00' || $value === '0000-00-00 00:00:00') {
            return '—';
        }

        $time = strtotime($value);

        return $time ? date('d M Y, h:i A', $time) : $value;
    }
}

if (!function_exists('scope_badge_class')) {
    function scope_badge_class(string $scope): string
    {
        return match (strtolower($scope)) {
            'system' => 'bg-primary',
            'course' => 'bg-success',
            'batch' => 'bg-warning text-dark',
            default => 'bg-secondary',
        };
    }
}

/* ---------------- Schema ensure ---------------- */

if (!table_exists($mysqli, 'lms_announcements')) {
    $mysqli->query("
        CREATE TABLE lms_announcements (
            id INT AUTO_INCREMENT PRIMARY KEY,
            scope_type VARCHAR(30) NOT NULL DEFAULT 'system',
            scope_id INT NULL,
            title VARCHAR(255) NOT NULL,
            body TEXT NOT NULL,
            publish_at DATETIME NULL,
            expire_at DATETIME NULL,
            pinned TINYINT(1) NOT NULL DEFAULT 0,
            created_by INT NULL,
            created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX(scope_type),
            INDEX(scope_id),
            INDEX(pinned),
            INDEX(publish_at)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");
} else {
    if (!col_exists($mysqli, 'lms_announcements', 'scope_type')) {
        $mysqli->query("ALTER TABLE lms_announcements ADD scope_type VARCHAR(30) NOT NULL DEFAULT 'system'");
    }

    if (!col_exists($mysqli, 'lms_announcements', 'scope_id')) {
        $mysqli->query("ALTER TABLE lms_announcements ADD scope_id INT NULL");
    }

    if (!col_exists($mysqli, 'lms_announcements', 'title')) {
        $mysqli->query("ALTER TABLE lms_announcements ADD title VARCHAR(255) NOT NULL");
    }

    if (!col_exists($mysqli, 'lms_announcements', 'body')) {
        $mysqli->query("ALTER TABLE lms_announcements ADD body TEXT NOT NULL");
    }

    if (!col_exists($mysqli, 'lms_announcements', 'publish_at')) {
        $mysqli->query("ALTER TABLE lms_announcements ADD publish_at DATETIME NULL");
    }

    if (!col_exists($mysqli, 'lms_announcements', 'expire_at')) {
        $mysqli->query("ALTER TABLE lms_announcements ADD expire_at DATETIME NULL");
    }

    if (!col_exists($mysqli, 'lms_announcements', 'pinned')) {
        $mysqli->query("ALTER TABLE lms_announcements ADD pinned TINYINT(1) NOT NULL DEFAULT 0");
    }

    if (!col_exists($mysqli, 'lms_announcements', 'created_by')) {
        $mysqli->query("ALTER TABLE lms_announcements ADD created_by INT NULL");
    }

    if (!col_exists($mysqli, 'lms_announcements', 'created_at')) {
        $mysqli->query("ALTER TABLE lms_announcements ADD created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP");
    }
}

/* ---------------- CSRF ---------------- */

if (empty($_SESSION['csrf_announcement'])) {
    $_SESSION['csrf_announcement'] = bin2hex(random_bytes(16));
}

function check_announcement_csrf(): void
{
    $token = (string)($_POST['csrf'] ?? '');

    if (!hash_equals((string)($_SESSION['csrf_announcement'] ?? ''), $token)) {
        http_response_code(403);
        exit('CSRF validation failed.');
    }
}

/* ---------------- Data sources ---------------- */

$courses = [];
$courseLabelCol = null;

if (table_exists($mysqli, 'courses')) {
    $courseLabelCol = label_col($mysqli, 'courses', ['course_name', 'name', 'title', 'label']);

    if ($rs = $mysqli->query("
        SELECT id, `$courseLabelCol` AS label
        FROM courses
        ORDER BY label ASC
    ")) {
        while ($row = $rs->fetch_assoc()) {
            $courses[(int)$row['id']] = (string)$row['label'];
        }

        $rs->free();
    }
}

$course_id = (int)($_GET['course_id'] ?? 0);
$batches = [];
$batchLabelCol = null;

if (table_exists($mysqli, 'batches')) {
    $batchLabelCol = label_col($mysqli, 'batches', ['batch_name', 'batch_code', 'name', 'title', 'label']);

    $where = '';
    $types = '';
    $params = [];

    if ($course_id > 0 && col_exists($mysqli, 'batches', 'course_id')) {
        $where = 'WHERE course_id = ?';
        $types = 'i';
        $params[] = $course_id;
    }

    $sql = "
        SELECT id, `$batchLabelCol` AS label
        FROM batches
        $where
        ORDER BY id DESC
        LIMIT 300
    ";

    $stmt = $mysqli->prepare($sql);

    if ($stmt) {
        if ($types !== '') {
            $stmt->bind_param($types, ...$params);
        }

        $stmt->execute();
        $rs = $stmt->get_result();

        while ($row = $rs->fetch_assoc()) {
            $batches[(int)$row['id']] = (string)$row['label'];
        }

        $stmt->close();
    }
}

/* ---------------- Actions ---------------- */

$msg = '';
$action = (string)($_POST['action'] ?? '');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    check_announcement_csrf();

    if ($action === 'create') {
        $scope_type = strtolower(trim((string)($_POST['scope_type'] ?? 'system')));

        if (!in_array($scope_type, ['system', 'course', 'batch'], true)) {
            $scope_type = 'system';
        }

        $scope_id = null;

        if ($scope_type === 'course') {
            $scope_id = (int)($_POST['scope_course'] ?? 0);
        } elseif ($scope_type === 'batch') {
            $scope_id = (int)($_POST['scope_id'] ?? 0);
        }

        if ($scope_type !== 'system' && (!$scope_id || $scope_id <= 0)) {
            $msg = '<div class="alert alert-danger border-0 rounded-4 shadow-sm py-2">
                        Please select a valid ' . esc($scope_type) . '.
                    </div>';
        } else {
            $title = trim((string)($_POST['title'] ?? ''));
            $body = trim((string)($_POST['body'] ?? ''));
            $publish_at = dt_from_input($_POST['publish_at'] ?? '');
            $expire_at = dt_from_input($_POST['expire_at'] ?? '');
            $pinned = isset($_POST['pinned']) ? 1 : 0;
            $created_by = (int)(admin_id() ?: ($_SESSION['user_id'] ?? 0));

            if ($title === '' || $body === '') {
                $msg = '<div class="alert alert-danger border-0 rounded-4 shadow-sm py-2">
                            Title and body are required.
                        </div>';
            } elseif ($publish_at && $expire_at && strtotime($publish_at) > strtotime($expire_at)) {
                $msg = '<div class="alert alert-danger border-0 rounded-4 shadow-sm py-2">
                            Publish date must be before expire date.
                        </div>';
            } else {
                $stmt = $mysqli->prepare("
                    INSERT INTO lms_announcements
                    (scope_type, scope_id, title, body, publish_at, expire_at, pinned, created_by)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                ");

                if ($stmt) {
                    $stmt->bind_param(
                        'sissssii',
                        $scope_type,
                        $scope_id,
                        $title,
                        $body,
                        $publish_at,
                        $expire_at,
                        $pinned,
                        $created_by
                    );

                    $stmt->execute();
                    $stmt->close();
                    $announcementLink = '/elms/student/notifications.php';

if (table_exists($mysqli, 'lms_notifications') && table_exists($mysqli, 'studentss')) {
    $studentsSql = "SELECT id FROM studentss";

    if (
        $scope_type === 'course'
        && $scope_id > 0
        && table_exists($mysqli, 'enrollments')
        && table_exists($mysqli, 'batches')
    ) {
        $studentsSql = "
            SELECT DISTINCT e.student_id AS id
            FROM enrollments e
            INNER JOIN batches b ON b.id = e.batch_id
            WHERE b.course_id = {$scope_id}
        ";
    }

    if (
        $scope_type === 'batch'
        && $scope_id > 0
        && table_exists($mysqli, 'enrollments')
    ) {
        $studentsSql = "
            SELECT DISTINCT student_id AS id
            FROM enrollments
            WHERE batch_id = {$scope_id}
        ";
    }

    if ($studentRows = $mysqli->query($studentsSql)) {
        while ($stu = $studentRows->fetch_assoc()) {
            $sid = (int)($stu['id'] ?? 0);
            if ($sid <= 0) {
                continue;
            }

            $nt = $mysqli->prepare("
                INSERT INTO lms_notifications
                (user_type, user_id, title, message, link_url, icon, type, is_read, created_at)
                VALUES (?, ?, ?, ?, ?, ?, ?, 0, NOW())
            ");

            if ($nt) {
                $userType = 'student';
                $icon = 'bi-megaphone';
                $type = 'announcement';

                $nt->bind_param(
                    'sisssss',
                    $userType,
                    $sid,
                    $title,
                    $body,
                    $announcementLink,
                    $icon,
                    $type
                );

                $nt->execute();
                $nt->close();
            }
        }
    }
}
                    $msg = '<div class="alert alert-success border-0 rounded-4 shadow-sm py-2">
                                Announcement created successfully.
                            </div>';
                } else {
                    $msg = '<div class="alert alert-danger border-0 rounded-4 shadow-sm py-2">
                                Failed to create announcement.
                            </div>';
                }
            }
        }
    }

    if ($action === 'pin' || $action === 'unpin') {
        $id = (int)($_POST['id'] ?? 0);

        if ($id > 0) {
            $pinned = $action === 'pin' ? 1 : 0;

            $stmt = $mysqli->prepare("
                UPDATE lms_announcements
                SET pinned = ?
                WHERE id = ?
            ");

            if ($stmt) {
                $stmt->bind_param('ii', $pinned, $id);
                $stmt->execute();
                $stmt->close();

                $msg = '<div class="alert alert-success border-0 rounded-4 shadow-sm py-2">
                            Announcement ' . ($pinned ? 'pinned' : 'unpinned') . '.
                        </div>';
            }
        }
    }

    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);

        if ($id > 0) {
            $stmt = $mysqli->prepare("
                DELETE FROM lms_announcements
                WHERE id = ?
            ");

            if ($stmt) {
                $stmt->bind_param('i', $id);
                $stmt->execute();
                $stmt->close();

                $msg = '<div class="alert alert-warning border-0 rounded-4 shadow-sm py-2">
                            Announcement deleted.
                        </div>';
            }
        }
    }
}

/* ---------------- Recent rows ---------------- */

$rows = [];

try {
    $res = $mysqli->query("
        SELECT 
            id,
            scope_type,
            scope_id,
            title,
            body,
            publish_at,
            expire_at,
            pinned,
            created_at
        FROM lms_announcements
        ORDER BY pinned DESC, publish_at DESC, id DESC
        LIMIT 100
    ");

    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $rows[] = $row;
        }

        $res->free();
    }
} catch (Throwable $e) {
    $rows = [];
}

$total = count($rows);
$pinnedCount = 0;
$activeCount = 0;
$now = time();

foreach ($rows as $row) {
    if ((int)($row['pinned'] ?? 0) === 1) {
        $pinnedCount++;
    }

    $publish = !empty($row['publish_at']) ? strtotime((string)$row['publish_at']) : null;
    $expire = !empty($row['expire_at']) ? strtotime((string)$row['expire_at']) : null;

    $isPublished = (!$publish || $publish <= $now) && (!$expire || $expire >= $now);

    if ($isPublished) {
        $activeCount++;
    }
}

/* ---------------- Layout ---------------- */

require_once APP_ROOT . '/includes/admin_layout_top.php';
?>

<style>
    .ann-hero {
        background: linear-gradient(135deg, #eff6ff 0%, #f8fafc 48%, #eef2ff 100%);
        border: 1px solid #dbeafe;
        border-radius: 22px;
        padding: 22px;
        box-shadow: 0 10px 28px rgba(15, 23, 42, .06);
    }

    .ann-chip {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 7px 11px;
        border-radius: 999px;
        background: #fff;
        border: 1px solid #e5e7eb;
        color: #475569;
        font-size: 12px;
        font-weight: 700;
    }

    .ann-card {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 20px;
        box-shadow: 0 8px 24px rgba(15, 23, 42, .055);
        overflow: hidden;
    }

    .ann-card-header {
        padding: 18px 20px;
        border-bottom: 1px solid #e5e7eb;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 14px;
        flex-wrap: wrap;
    }

    .ann-card-body {
        padding: 20px;
    }

    .ann-table thead th {
        background: #f8fafc;
        color: #64748b;
        font-size: 12px;
        text-transform: uppercase;
        letter-spacing: .04em;
        white-space: nowrap;
    }

    .scope-help {
        font-size: 12px;
        color: #64748b;
    }

    .announcement-title {
        font-weight: 800;
        color: #111827;
    }

    .announcement-body-preview {
        font-size: 13px;
        color: #64748b;
        max-width: 480px;
    }
</style>

<?php if ($msg): ?>
    <?= $msg ?>
<?php endif; ?>

<div class="ann-hero mb-4">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
        <div>
            <h4 class="fw-bold mb-1">Announcements</h4>
            <div class="text-muted">
                Create and manage system, course, and batch announcements.
            </div>
        </div>

        <div class="d-flex flex-wrap gap-2">
            <span class="ann-chip">
                <i class="bi bi-megaphone text-primary"></i>
                <?= number_format($total) ?> Recent
            </span>

            <span class="ann-chip">
                <i class="bi bi-pin-angle text-warning"></i>
                <?= number_format($pinnedCount) ?> Pinned
            </span>

            <span class="ann-chip">
                <i class="bi bi-broadcast text-success"></i>
                <?= number_format($activeCount) ?> Active
            </span>
        </div>
    </div>
</div>

<div class="ann-card mb-4">
    <div class="ann-card-header">
        <div>
            <h5 class="mb-0 fw-bold">Create Announcement</h5>
            <div class="text-muted small">Choose where the announcement should appear.</div>
        </div>
    </div>

    <div class="ann-card-body">
        <form method="post" class="row g-3">
            <input type="hidden" name="action" value="create">
            <input type="hidden" name="csrf" value="<?= esc($_SESSION['csrf_announcement']) ?>">

            <div class="col-lg-3 col-md-6">
                <label class="form-label fw-semibold">Scope</label>
                <select name="scope_type" class="form-select" id="scope_select" onchange="toggleScope();">
                    <option value="system">System</option>
                    <option value="course">Course</option>
                    <option value="batch">Batch</option>
                </select>
                <div class="scope-help mt-1">System = all users</div>
            </div>

            <div class="col-lg-4 col-md-6" id="course_wrap" style="display:none;">
                <label class="form-label fw-semibold">Course</label>
                <select name="scope_course" class="form-select" id="scope_course">
                    <option value="">Select course...</option>

                    <?php foreach ($courses as $cid => $ctitle): ?>
                        <option value="<?= (int)$cid ?>" <?= $cid === $course_id ? 'selected' : '' ?>>
                            <?= esc($ctitle) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <div class="scope-help mt-1">Required for course or batch announcements</div>
            </div>

            <div class="col-lg-5 col-md-12" id="batch_wrap" style="display:none;">
                <label class="form-label fw-semibold">Batch</label>
                <select name="scope_id" class="form-select" id="scope_batch">
                    <option value="">Select batch...</option>

                    <?php foreach ($batches as $bid => $bcode): ?>
                        <option value="<?= (int)$bid ?>">
                            <?= esc($bcode) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
                <div class="scope-help mt-1">
                    Select course first, then choose related batch.
                </div>
            </div>

            <div class="col-12">
                <label class="form-label fw-semibold">Title</label>
                <input name="title" class="form-control" required placeholder="Example: Final project submission deadline">
            </div>

            <div class="col-12">
                <label class="form-label fw-semibold">Body</label>
                <textarea name="body" class="form-control" rows="4" required placeholder="Write the announcement message..."></textarea>
            </div>

            <div class="col-lg-3 col-md-6">
                <label class="form-label fw-semibold">Publish At</label>
                <input type="datetime-local" name="publish_at" class="form-control">
            </div>

            <div class="col-lg-3 col-md-6">
                <label class="form-label fw-semibold">Expire At</label>
                <input type="datetime-local" name="expire_at" class="form-control">
            </div>

            <div class="col-lg-3 col-md-6 d-flex align-items-end">
                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" name="pinned" id="pin">
                    <label class="form-check-label fw-semibold" for="pin">
                        Pin announcement
                    </label>
                </div>
            </div>

            <div class="col-lg-3 col-md-6 d-flex align-items-end justify-content-lg-end">
                <button class="btn btn-admin-primary w-100">
                    <i class="bi bi-plus-circle me-1"></i>
                    Create Announcement
                </button>
            </div>
        </form>
    </div>
</div>

<div class="ann-card">
    <div class="ann-card-header">
        <div>
            <h5 class="mb-0 fw-bold">Recent Announcements</h5>
            <div class="text-muted small">Latest 100 announcements</div>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table ann-table table-hover align-middle mb-0">
            <thead>
                <tr>
                    <th style="width:80px;">#</th>
                    <th>Scope</th>
                    <th>Announcement</th>
                    <th>Publish</th>
                    <th>Expire</th>
                    <th>Pinned</th>
                    <th class="text-end">Actions</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$rows): ?>
                    <tr>
                        <td colspan="7" class="text-center text-muted py-4">
                            No announcements yet.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($rows as $row): ?>
                        <?php
                            $scope = (string)($row['scope_type'] ?? 'system');
                            $scopeId = (int)($row['scope_id'] ?? 0);
                            $pinned = (int)($row['pinned'] ?? 0) === 1;
                            $bodyPreview = trim((string)($row['body'] ?? ''));

                            if (function_exists('mb_strlen') && mb_strlen($bodyPreview, 'UTF-8') > 110) {
                                $bodyPreview = mb_substr($bodyPreview, 0, 110, 'UTF-8') . '...';
                            } elseif (strlen($bodyPreview) > 110) {
                                $bodyPreview = substr($bodyPreview, 0, 110) . '...';
                            }
                        ?>

                        <tr>
                            <td class="fw-semibold">
                                <?= (int)$row['id'] ?>
                            </td>

                            <td>
                                <span class="badge <?= esc(scope_badge_class($scope)) ?>">
                                    <?= esc(ucfirst($scope)) ?>
                                    <?= $scopeId ? ' #' . $scopeId : '' ?>
                                </span>
                            </td>

                            <td>
                                <div class="announcement-title">
                                    <?= esc($row['title']) ?>
                                </div>

                                <?php if ($bodyPreview !== ''): ?>
                                    <div class="announcement-body-preview mt-1">
                                        <?= esc($bodyPreview) ?>
                                    </div>
                                <?php endif; ?>
                            </td>

                            <td>
                                <?= esc(format_dt($row['publish_at'] ?? '')) ?>
                            </td>

                            <td>
                                <?= esc(format_dt($row['expire_at'] ?? '')) ?>
                            </td>

                            <td>
                                <?php if ($pinned): ?>
                                    <span class="badge bg-warning text-dark">
                                        <i class="bi bi-pin-angle me-1"></i>
                                        Yes
                                    </span>
                                <?php else: ?>
                                    <span class="badge bg-secondary">No</span>
                                <?php endif; ?>
                            </td>

                            <td class="text-end">
                                <div class="d-flex justify-content-end flex-wrap gap-2">
                                    <form method="post" class="d-inline">
                                        <input type="hidden" name="csrf" value="<?= esc($_SESSION['csrf_announcement']) ?>">
                                        <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                        <input type="hidden" name="action" value="<?= $pinned ? 'unpin' : 'pin' ?>">

                                        <button class="btn btn-sm btn-outline-secondary rounded-pill">
                                            <?= $pinned ? 'Unpin' : 'Pin' ?>
                                        </button>
                                    </form>

                                    <form method="post" class="d-inline" onsubmit="return confirm('Delete announcement?')">
                                        <input type="hidden" name="csrf" value="<?= esc($_SESSION['csrf_announcement']) ?>">
                                        <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                        <input type="hidden" name="action" value="delete">

                                        <button class="btn btn-sm btn-outline-danger rounded-pill">
                                            Delete
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
(function() {
    const scopeSelect = document.getElementById('scope_select');
    const courseWrap = document.getElementById('course_wrap');
    const batchWrap = document.getElementById('batch_wrap');
    const courseSelect = document.getElementById('scope_course');

    function toggleScope() {
        const value = scopeSelect ? scopeSelect.value : 'system';

        if (courseWrap) {
            courseWrap.style.display = (value === 'course' || value === 'batch') ? '' : 'none';
        }

        if (batchWrap) {
            batchWrap.style.display = (value === 'batch') ? '' : 'none';
        }
    }

    if (scopeSelect) {
        scopeSelect.addEventListener('change', toggleScope);
    }

    if (courseSelect) {
        courseSelect.addEventListener('change', function() {
            const scope = scopeSelect ? scopeSelect.value : 'system';

            if (scope === 'batch') {
                const courseId = this.value || 0;
                window.location.href = '?course_id=' + encodeURIComponent(courseId);
            }
        });
    }

    toggleScope();
})();
</script>

<?php require_once APP_ROOT . '/includes/admin_layout_bottom.php'; ?>