<?php
// /elms/coordinator/assessments.php
declare(strict_types=1);

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

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

$PAGE_TITLE = 'Assessments & Projects';
$ACTIVE = 'assessments';

require_once APP_ROOT . '/includes/coordinator_auth.php';
require_once APP_ROOT . '/includes/db.php';
require_once APP_ROOT . '/includes/elms_notifications.php';

$db = null;
if (isset($mysqli) && $mysqli instanceof mysqli) {
    $db = $mysqli;
} elseif (isset($conn) && $conn instanceof mysqli) {
    $db = $conn;
}

if (!$db) {
    http_response_code(500);
    exit('Database connection not found.');
}

$db->set_charset('utf8mb4');

/* -------------------------------------------------------
   Basic helpers
------------------------------------------------------- */

function coass_h($value): string {
    return htmlspecialchars((string)$value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function coass_csrf_token(): string {
    if (empty($_SESSION['coass_csrf'])) {
        $_SESSION['coass_csrf'] = bin2hex(random_bytes(16));
    }
    return $_SESSION['coass_csrf'];
}

function coass_require_csrf(): void {
    if (!isset($_POST['csrf']) || !hash_equals($_SESSION['coass_csrf'] ?? '', (string)$_POST['csrf'])) {
        http_response_code(403);
        exit('CSRF validation failed');
    }
}

function coass_url(string $path = ''): string {
    if ($path === '') return '/elms/coordinator/assessments.php';
    if ($path[0] !== '/') $path = '/' . $path;
    return '/elms' . $path;
}

function coass_dt_or_null(?string $input): ?string {
    $input = trim((string)$input);
    if ($input === '') return null;

    $input = str_replace('T', ' ', $input);
    $ts = strtotime($input);

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

function coass_dt_input(?string $date): string {
    $date = trim((string)$date);
    if ($date === '' || $date === '0000-00-00 00:00:00') return '';
    return str_replace(' ', 'T', substr($date, 0, 16));
}

function coass_short(?string $text, int $limit = 100): string {
    $text = trim((string)$text);
    if ($text === '') return '';

    if (function_exists('mb_strlen') && mb_strlen($text, 'UTF-8') > $limit) {
        return mb_substr($text, 0, $limit, 'UTF-8') . '…';
    }

    if (!function_exists('mb_strlen') && strlen($text) > $limit) {
        return substr($text, 0, $limit) . '…';
    }

    return $text;
}

function coass_table_exists(mysqli $db, string $table): bool {
    $safe = $db->real_escape_string($table);
    $res = $db->query("SHOW TABLES LIKE '{$safe}'");
    $ok = $res && $res->num_rows > 0;
    if ($res) $res->free();
    return $ok;
}

function coass_col_exists(mysqli $db, string $table, string $col): bool {
    $safeTable = preg_replace('/[^a-zA-Z0-9_]/', '', $table);
    $safeCol = $db->real_escape_string($col);
    $res = $db->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeCol}'");
    $ok = $res && $res->num_rows > 0;
    if ($res) $res->free();
    return $ok;
}

function coass_first_col(mysqli $db, string $table, array $cols): ?string {
    if (!coass_table_exists($db, $table)) return null;

    foreach ($cols as $col) {
        if (coass_col_exists($db, $table, $col)) {
            return $col;
        }
    }

    return null;
}

function coass_public_file_url(?string $path): string {
    $path = trim((string)$path);
    if ($path === '') return '';

    if (preg_match('#^https?://#i', $path)) return $path;
    if (str_starts_with($path, '/elms/')) return $path;
    if (str_starts_with($path, '/uploads/')) return '/elms' . $path;
    if (str_starts_with($path, 'uploads/')) return '/elms/' . $path;

    return '/elms/' . ltrim($path, '/');
}

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

function coass_ensure_schema(mysqli $db): void {
    if (!coass_table_exists($db, 'lms_assessments')) {
        $db->query("
            CREATE TABLE lms_assessments (
                id INT AUTO_INCREMENT PRIMARY KEY,
                title VARCHAR(255) NOT NULL,
                description TEXT NULL,
                type ENUM('assignment','project') NOT NULL DEFAULT 'assignment',
                course_id INT NULL,
                module_id INT NULL,
                available_from DATETIME NULL,
                available_to DATETIME NULL,
                due_at DATETIME NULL,
                release_at DATETIME NULL,
                max_score INT NOT NULL DEFAULT 100,
                active TINYINT(1) NOT NULL DEFAULT 1,
                created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
            ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
        ");
    } else {
        if (!coass_col_exists($db, 'lms_assessments', 'description')) {
            $db->query("ALTER TABLE lms_assessments ADD COLUMN description TEXT NULL AFTER title");
        }
        if (!coass_col_exists($db, 'lms_assessments', 'type')) {
            $db->query("ALTER TABLE lms_assessments ADD COLUMN type ENUM('assignment','project') NOT NULL DEFAULT 'assignment'");
        }
        if (!coass_col_exists($db, 'lms_assessments', 'course_id')) {
            $db->query("ALTER TABLE lms_assessments ADD COLUMN course_id INT NULL");
        }
        if (!coass_col_exists($db, 'lms_assessments', 'module_id')) {
            $db->query("ALTER TABLE lms_assessments ADD COLUMN module_id INT NULL");
        }
        if (!coass_col_exists($db, 'lms_assessments', 'available_from')) {
            $db->query("ALTER TABLE lms_assessments ADD COLUMN available_from DATETIME NULL");
        }
        if (!coass_col_exists($db, 'lms_assessments', 'available_to')) {
            $db->query("ALTER TABLE lms_assessments ADD COLUMN available_to DATETIME NULL");
        }
        if (!coass_col_exists($db, 'lms_assessments', 'due_at')) {
            $db->query("ALTER TABLE lms_assessments ADD COLUMN due_at DATETIME NULL");
        }
        if (!coass_col_exists($db, 'lms_assessments', 'release_at')) {
            $db->query("ALTER TABLE lms_assessments ADD COLUMN release_at DATETIME NULL");
        }
        if (!coass_col_exists($db, 'lms_assessments', 'max_score')) {
            $db->query("ALTER TABLE lms_assessments ADD COLUMN max_score INT NOT NULL DEFAULT 100");
        }
        if (!coass_col_exists($db, 'lms_assessments', 'active')) {
            $db->query("ALTER TABLE lms_assessments ADD COLUMN active TINYINT(1) NOT NULL DEFAULT 1");
        }
    }

    $db->query("
        CREATE TABLE IF NOT EXISTS lms_assessment_batches (
            assessment_id INT NOT NULL,
            batch_id INT NOT NULL,
            PRIMARY KEY (assessment_id, batch_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    $db->query("
        CREATE TABLE IF NOT EXISTS lms_assessment_students (
            assessment_id INT NOT NULL,
            student_id INT NOT NULL,
            PRIMARY KEY (assessment_id, student_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    $db->query("
        CREATE TABLE IF NOT EXISTS lms_assessment_attachments (
            id INT AUTO_INCREMENT PRIMARY KEY,
            assessment_id INT NOT NULL,
            file_path VARCHAR(500) NOT NULL,
            uploaded_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            INDEX (assessment_id)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
    ");

    if (coass_table_exists($db, 'lms_submissions')) {
        if (!coass_col_exists($db, 'lms_submissions', 'workflow_status')) {
            $db->query("ALTER TABLE lms_submissions ADD COLUMN workflow_status VARCHAR(50) NOT NULL DEFAULT 'submitted'");
        }
        if (!coass_col_exists($db, 'lms_submissions', 'released_at')) {
            $db->query("ALTER TABLE lms_submissions ADD COLUMN released_at DATETIME NULL");
        }
        if (!coass_col_exists($db, 'lms_submissions', 'updated_at')) {
            $db->query("ALTER TABLE lms_submissions ADD COLUMN updated_at DATETIME NULL");
        }
    }
}

coass_ensure_schema($db);

/* -------------------------------------------------------
   Data helpers
------------------------------------------------------- */

function coass_courses(mysqli $db): array {
    if (!coass_table_exists($db, 'courses')) return [];

    $nameCol = coass_first_col($db, 'courses', ['course_name', 'name', 'title', 'label']) ?? 'id';

    $sql = "SELECT id, COALESCE(`{$nameCol}`, CONCAT('Course #', id)) AS label FROM courses ORDER BY id DESC";
    $res = $db->query($sql);

    $out = [];
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $out[(int)$row['id']] = (string)$row['label'];
        }
        $res->free();
    }

    return $out;
}

function coass_modules(mysqli $db, int $courseId = 0): array {
    if (!coass_table_exists($db, 'course_modules')) return [];

    $titleCol = coass_first_col($db, 'course_modules', ['title', 'module_name', 'name']) ?? 'id';
    $hasCourse = coass_col_exists($db, 'course_modules', 'course_id');

    $out = [];

    if ($courseId > 0 && $hasCourse) {
        $stmt = $db->prepare("SELECT id, COALESCE(`{$titleCol}`, CONCAT('Module #', id)) AS title FROM course_modules WHERE course_id = ? ORDER BY id ASC");
        $stmt->bind_param('i', $courseId);
        $stmt->execute();
        $res = $stmt->get_result();
    } else {
        $res = $db->query("SELECT id, COALESCE(`{$titleCol}`, CONCAT('Module #', id)) AS title FROM course_modules ORDER BY id ASC");
    }

    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $out[(int)$row['id']] = (string)$row['title'];
        }
        $res->free();
    }

    if (isset($stmt)) $stmt->close();

    return $out;
}

function coass_batches(mysqli $db, int $courseId = 0): array {
    if (!coass_table_exists($db, 'batches')) return [];

    $nameCol = coass_first_col($db, 'batches', ['batch_name', 'name', 'title', 'label']) ?? 'id';
    $hasCourse = coass_col_exists($db, 'batches', 'course_id');

    $out = [];

    if ($courseId > 0 && $hasCourse) {
        $stmt = $db->prepare("SELECT id, COALESCE(`{$nameCol}`, CONCAT('Batch #', id)) AS label FROM batches WHERE course_id = ? ORDER BY id DESC");
        $stmt->bind_param('i', $courseId);
        $stmt->execute();
        $res = $stmt->get_result();
    } else {
        $res = $db->query("SELECT id, COALESCE(`{$nameCol}`, CONCAT('Batch #', id)) AS label FROM batches ORDER BY id DESC");
    }

    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $out[(int)$row['id']] = (string)$row['label'];
        }
        $res->free();
    }

    if (isset($stmt)) $stmt->close();

    return $out;
}

function coass_students(mysqli $db, int $courseId = 0): array {
    if (!coass_table_exists($db, 'studentss')) return [];

    $nameCol = coass_first_col($db, 'studentss', ['full_name', 'name', 'student_name']) ?? 'id';
    $regCol = coass_first_col($db, 'studentss', ['center_reg_no', 'reference_no', 'reg_no']);
    $hasCourse = coass_col_exists($db, 'studentss', 'course_id');

    $select = "id, COALESCE(`{$nameCol}`, CONCAT('Student #', id)) AS name";
    if ($regCol) $select .= ", `{$regCol}` AS reg_no";

    if ($courseId > 0 && $hasCourse) {
        $stmt = $db->prepare("SELECT {$select} FROM studentss WHERE course_id = ? ORDER BY id DESC");
        $stmt->bind_param('i', $courseId);
        $stmt->execute();
        $res = $stmt->get_result();
    } else {
        $res = $db->query("SELECT {$select} FROM studentss ORDER BY id DESC");
    }

    $out = [];

    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $label = (string)$row['name'];
            if (!empty($row['reg_no'])) {
                $label .= ' • ' . $row['reg_no'];
            }
            $out[(int)$row['id']] = $label;
        }
        $res->free();
    }

    if (isset($stmt)) $stmt->close();

    return $out;
}

function coass_latest_attachment(mysqli $db, int $assessmentId): ?string {
    $stmt = $db->prepare("SELECT file_path FROM lms_assessment_attachments WHERE assessment_id = ? ORDER BY id DESC LIMIT 1");
    if (!$stmt) return null;

    $stmt->bind_param('i', $assessmentId);
    $stmt->execute();
    $stmt->bind_result($path);
    $ok = $stmt->fetch();
    $stmt->close();

    return $ok ? (string)$path : null;
}

function coass_save_attachment(mysqli $db, int $assessmentId, array $file): ?string {
    if (empty($file['name']) || !is_uploaded_file($file['tmp_name'])) return null;

    $uploadDir = APP_ROOT . '/uploads/assessments';

    if (!is_dir($uploadDir)) {
        @mkdir($uploadDir, 0775, true);
    }

    $original = (string)$file['name'];
    $ext = strtolower(pathinfo($original, PATHINFO_EXTENSION));
    $base = preg_replace('/[^A-Za-z0-9._-]+/', '_', pathinfo($original, PATHINFO_FILENAME));

    $safeName = date('Ymd_His') . '_ass' . $assessmentId . '_' . $base . ($ext ? '.' . $ext : '');
    $dest = rtrim($uploadDir, '/\\') . DIRECTORY_SEPARATOR . $safeName;

    if (!move_uploaded_file($file['tmp_name'], $dest)) {
        return null;
    }

    $publicPath = 'uploads/assessments/' . $safeName;

    $stmt = $db->prepare("INSERT INTO lms_assessment_attachments (assessment_id, file_path) VALUES (?, ?)");
    if ($stmt) {
        $stmt->bind_param('is', $assessmentId, $publicPath);
        $stmt->execute();
        $stmt->close();
    }

    return $publicPath;
}
function coass_notify_assigned_students(
    mysqli $db,
    int $assessmentId,
    string $assessmentTitle,
    array $batchIds,
    array $studentIds,
    bool $isUpdate = false
): int {
    if ($assessmentId <= 0) {
        return 0;
    }

    $notifyStudentIds = [];

    // Direct selected students
    foreach ($studentIds as $sid) {
        $sid = (int)$sid;
        if ($sid > 0) {
            $notifyStudentIds[$sid] = $sid;
        }
    }

    // Students from selected batches
    if ($batchIds && coass_table_exists($db, 'enrollments')) {
        $cleanBatchIds = array_values(array_unique(array_filter(array_map('intval', $batchIds))));

        if ($cleanBatchIds) {
            $batchList = implode(',', $cleanBatchIds);

            $res = $db->query("
                SELECT DISTINCT student_id
                FROM enrollments
                WHERE batch_id IN ({$batchList})
                  AND student_id IS NOT NULL
            ");

            if ($res) {
                while ($row = $res->fetch_assoc()) {
                    $sid = (int)($row['student_id'] ?? 0);
                    if ($sid > 0) {
                        $notifyStudentIds[$sid] = $sid;
                    }
                }

                $res->free();
            }
        }
    }

    if (!$notifyStudentIds) {
        return 0;
    }

    $title = $isUpdate ? 'Assessment Updated' : 'New Assessment';
    $message = $isUpdate
        ? 'An assessment has been updated: ' . $assessmentTitle
        : 'A new assessment has been assigned to you: ' . $assessmentTitle;

    $count = 0;

    foreach ($notifyStudentIds as $sid) {
        $ok = lms_notify(
            $db,
            'student',
            (int)$sid,
            $title,
            $message,
            '/elms/student/assessments/assessments.php',
            $isUpdate ? 'bi-pencil-square' : 'bi-clipboard-check',
            $isUpdate ? 'info' : 'success'
        );

        if ($ok) {
            $count++;
        }
    }

    return $count;
}

/* -------------------------------------------------------
   POST actions
------------------------------------------------------- */

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

    $op = (string)($_POST['op'] ?? '');

    if ($op === 'toggle') {
        $id = (int)($_POST['id'] ?? 0);
        $to = (int)($_POST['to'] ?? 0);

        $stmt = $db->prepare("UPDATE lms_assessments SET active = ? WHERE id = ?");
        $stmt->bind_param('ii', $to, $id);
        $stmt->execute();
        $stmt->close();

        header('Location: /elms/coordinator/assessments.php?msg=' . urlencode('Assessment status updated.'));
        exit;
    }

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

        $db->begin_transaction();

        try {
            $stmt = $db->prepare("DELETE FROM lms_assessment_batches WHERE assessment_id = ?");
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $stmt->close();

            $stmt = $db->prepare("DELETE FROM lms_assessment_students WHERE assessment_id = ?");
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $stmt->close();

            $stmt = $db->prepare("DELETE FROM lms_assessment_attachments WHERE assessment_id = ?");
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $stmt->close();

            $stmt = $db->prepare("DELETE FROM lms_assessments WHERE id = ?");
            $stmt->bind_param('i', $id);
            $stmt->execute();
            $stmt->close();

            $db->commit();

            header('Location: /elms/coordinator/assessments.php?msg=' . urlencode('Assessment deleted successfully.'));
            exit;
        } catch (Throwable $e) {
            $db->rollback();

            header('Location: /elms/coordinator/assessments.php?msg=' . urlencode('Delete failed.'));
            exit;
        }
    }

    if ($op === 'assessment_release_now') {
        $id = (int)($_POST['id'] ?? 0);

        $stmt = $db->prepare("UPDATE lms_assessments SET release_at = NOW() WHERE id = ?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $stmt->close();

        header('Location: /elms/coordinator/assessments.php?msg=' . urlencode('Assessment release date set to now.'));
        exit;
    }

    if ($op === 'assessment_clear_release') {
        $id = (int)($_POST['id'] ?? 0);

        $stmt = $db->prepare("UPDATE lms_assessments SET release_at = NULL WHERE id = ?");
        $stmt->bind_param('i', $id);
        $stmt->execute();
        $stmt->close();

        header('Location: /elms/coordinator/assessments.php?msg=' . urlencode('Assessment release date cleared.'));
        exit;
    }

    if ($op === 'release_results') {
        $id = (int)($_POST['id'] ?? 0);

        if (!coass_table_exists($db, 'lms_submissions')) {
            header('Location: /elms/coordinator/assessments.php?msg=' . urlencode('lms_submissions table not found.'));
            exit;
        }

        $sets = ["workflow_status = 'released'"];

        if (coass_col_exists($db, 'lms_submissions', 'released_at')) {
            $sets[] = "released_at = NOW()";
        }

        if (coass_col_exists($db, 'lms_submissions', 'updated_at')) {
            $sets[] = "updated_at = NOW()";
        }

        $sql = "
            UPDATE lms_submissions
            SET " . implode(', ', $sets) . "
            WHERE assessment_id = ?
              AND LOWER(COALESCE(workflow_status,'')) IN ('coord_approved','approved')
        ";

        // collect students before release
$releasedStudentRows = [];

$infoSql = "
    SELECT 
        s.student_id,
        COALESCE(a.title, CONCAT('Assessment #', s.assessment_id)) AS assessment_title
    FROM lms_submissions s
    LEFT JOIN lms_assessments a ON a.id = s.assessment_id
    WHERE s.assessment_id = ?
      AND LOWER(COALESCE(s.workflow_status,'')) IN ('coord_approved','approved')
";

$infoStmt = $db->prepare($infoSql);
if ($infoStmt) {
    $infoStmt->bind_param('i', $id);
    $infoStmt->execute();
    $infoRes = $infoStmt->get_result();

    while ($infoRow = $infoRes->fetch_assoc()) {
        $releasedStudentRows[] = $infoRow;
    }

    $infoStmt->close();
}

$stmt = $db->prepare($sql);
$stmt->bind_param('i', $id);
$stmt->execute();
$affected = $stmt->affected_rows;
$stmt->close();

$notifyCount = 0;

if ($affected > 0) {
    foreach ($releasedStudentRows as $row) {
        $sid = (int)($row['student_id'] ?? 0);
        $assessmentTitle = (string)($row['assessment_title'] ?? 'Assessment');

        if ($sid > 0) {
            $ok = lms_notify(
                $db,
                'student',
                $sid,
                'Result Released',
                'Your result for ' . $assessmentTitle . ' has been released.',
                '/elms/student/results.php',
                'bi-award',
                'success'
            );

            if ($ok) {
                $notifyCount++;
            }
        }
    }
}

header('Location: /elms/coordinator/assessments.php?msg=' . urlencode("Approved results released. Count: {$affected}. Notifications sent: {$notifyCount}"));
exit;
    }

    if ($op === 'save') {
        $editId = (int)($_POST['edit_id'] ?? 0);

        $title = trim((string)($_POST['title'] ?? ''));
        if ($title === '') $title = '(untitled)';

        $description = trim((string)($_POST['description'] ?? ''));
        $type = (string)($_POST['type'] ?? 'assignment');
        $type = $type === 'project' ? 'project' : 'assignment';

        $courseId = (int)($_POST['course_id'] ?? 0);
        $moduleId = (int)($_POST['module_id'] ?? 0);
        $maxScore = max(1, (int)($_POST['max_score'] ?? 100));

        $availableFrom = coass_dt_or_null($_POST['available_from'] ?? '');
        $availableTo = coass_dt_or_null($_POST['available_to'] ?? '');
        $dueAt = coass_dt_or_null($_POST['due_at'] ?? '');
        $releaseAt = coass_dt_or_null($_POST['release_at'] ?? '');

        $batchIds = array_values(array_unique(array_filter(array_map('intval', (array)($_POST['batch_ids'] ?? [])))));
        $studentIds = array_values(array_unique(array_filter(array_map('intval', (array)($_POST['student_ids'] ?? [])))));
        $batchesOnly = isset($_POST['batches_only']);

        if ($batchesOnly || $batchIds) {
            $studentIds = [];
        }

        if ($availableFrom && $availableTo && strtotime($availableFrom) > strtotime($availableTo)) {
            header('Location: /elms/coordinator/assessments.php?msg=' . urlencode('Available From must be before Available To.'));
            exit;
        }

        $db->begin_transaction();

        try {
            if ($editId > 0) {
                $sql = "
                    UPDATE lms_assessments
                    SET title = ?,
                        description = ?,
                        type = ?,
                        course_id = NULLIF(?,0),
                        module_id = NULLIF(?,0),
                        available_from = ?,
                        available_to = ?,
                        due_at = ?,
                        release_at = ?,
                        max_score = ?
                    WHERE id = ?
                ";

                $stmt = $db->prepare($sql);
                $stmt->bind_param(
                    'sssiissssii',
                    $title,
                    $description,
                    $type,
                    $courseId,
                    $moduleId,
                    $availableFrom,
                    $availableTo,
                    $dueAt,
                    $releaseAt,
                    $maxScore,
                    $editId
                );
                $stmt->execute();
                $stmt->close();

                $assessmentId = $editId;
            } else {
                $sql = "
                    INSERT INTO lms_assessments
                    (title, description, type, course_id, module_id, available_from, available_to, due_at, release_at, max_score)
                    VALUES (?, ?, ?, NULLIF(?,0), NULLIF(?,0), ?, ?, ?, ?, ?)
                ";

                $stmt = $db->prepare($sql);
                $stmt->bind_param(
                    'sssiissssi',
                    $title,
                    $description,
                    $type,
                    $courseId,
                    $moduleId,
                    $availableFrom,
                    $availableTo,
                    $dueAt,
                    $releaseAt,
                    $maxScore
                );
                $stmt->execute();
                $assessmentId = (int)$stmt->insert_id;
                $stmt->close();
            }

            $stmt = $db->prepare("DELETE FROM lms_assessment_batches WHERE assessment_id = ?");
            $stmt->bind_param('i', $assessmentId);
            $stmt->execute();
            $stmt->close();

            $stmt = $db->prepare("DELETE FROM lms_assessment_students WHERE assessment_id = ?");
            $stmt->bind_param('i', $assessmentId);
            $stmt->execute();
            $stmt->close();

            if ($batchIds) {
                $stmt = $db->prepare("INSERT INTO lms_assessment_batches (assessment_id, batch_id) VALUES (?, ?)");
                foreach ($batchIds as $batchId) {
                    $stmt->bind_param('ii', $assessmentId, $batchId);
                    $stmt->execute();
                }
                $stmt->close();
            }

            if ($studentIds) {
                $stmt = $db->prepare("INSERT INTO lms_assessment_students (assessment_id, student_id) VALUES (?, ?)");
                foreach ($studentIds as $studentId) {
                    $stmt->bind_param('ii', $assessmentId, $studentId);
                    $stmt->execute();
                }
                $stmt->close();
            }

            if (!empty($_FILES['brief']['name'])) {
                coass_save_attachment($db, $assessmentId, $_FILES['brief']);
            }

            $db->commit();

$notifyCount = coass_notify_assigned_students(
    $db,
    (int)$assessmentId,
    $title,
    $batchIds,
    $studentIds,
    $editId > 0
);

$msg = $editId > 0
    ? "Assessment updated successfully. Notifications sent: {$notifyCount}"
    : "Assessment created successfully. Notifications sent: {$notifyCount}";

header('Location: /elms/coordinator/assessments.php?msg=' . urlencode($msg));
exit;
        } catch (Throwable $e) {
            $db->rollback();

            header('Location: /elms/coordinator/assessments.php?msg=' . urlencode('Save failed: ' . $e->getMessage()));
            exit;
        }
    }
}

/* -------------------------------------------------------
   Load data
------------------------------------------------------- */

$filterCourse = (int)($_GET['course_id'] ?? 0);

$courses = coass_courses($db);
$modules = coass_modules($db, $filterCourse);
$batches = coass_batches($db, $filterCourse);
$students = coass_students($db, $filterCourse);

$editRow = null;
$selectedBatches = [];
$selectedStudents = [];

if (isset($_GET['edit'])) {
    $editId = (int)$_GET['edit'];

    $stmt = $db->prepare("SELECT * FROM lms_assessments WHERE id = ? LIMIT 1");
    $stmt->bind_param('i', $editId);
    $stmt->execute();
    $editRow = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    if ($editRow) {
        $filterCourse = (int)($editRow['course_id'] ?? $filterCourse);
        $modules = coass_modules($db, $filterCourse);
        $batches = coass_batches($db, $filterCourse);
        $students = coass_students($db, $filterCourse);

        $stmt = $db->prepare("SELECT batch_id FROM lms_assessment_batches WHERE assessment_id = ?");
        $stmt->bind_param('i', $editId);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $selectedBatches[] = (int)$row['batch_id'];
        }
        $stmt->close();

        $stmt = $db->prepare("SELECT student_id FROM lms_assessment_students WHERE assessment_id = ?");
        $stmt->bind_param('i', $editId);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $selectedStudents[] = (int)$row['student_id'];
        }
        $stmt->close();
    }
}

$courseNameCol = coass_first_col($db, 'courses', ['course_name', 'name', 'title', 'label']) ?? 'id';
$moduleNameCol = coass_first_col($db, 'course_modules', ['title', 'module_name', 'name']) ?? 'id';

$where = '';
if ($filterCourse > 0) {
    $where = "WHERE a.course_id = " . (int)$filterCourse;
}

$sql = "
    SELECT
        a.*,
        COALESCE(c.`{$courseNameCol}`, CONCAT('Course #', a.course_id)) AS course_label,
        COALESCE(cm.`{$moduleNameCol}`, CONCAT('Module #', a.module_id)) AS module_label,
        COUNT(DISTINCT sub.id) AS submission_count,
        SUM(CASE WHEN LOWER(COALESCE(sub.workflow_status,'')) IN ('coord_approved','approved') THEN 1 ELSE 0 END) AS approved_count,
        SUM(CASE WHEN LOWER(COALESCE(sub.workflow_status,'')) IN ('released','published') THEN 1 ELSE 0 END) AS released_count
    FROM lms_assessments a
    LEFT JOIN courses c ON c.id = a.course_id
    LEFT JOIN course_modules cm ON cm.id = a.module_id
    LEFT JOIN lms_submissions sub ON sub.assessment_id = a.id
    {$where}
    GROUP BY a.id
    ORDER BY a.id DESC
    LIMIT 150
";

$res = $db->query($sql);
$rows = $res ? $res->fetch_all(MYSQLI_ASSOC) : [];

if ($res) $res->free();

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

<style>
    :root {
        --co-bg: #f5f7fb;
        --co-card: #ffffff;
        --co-border: #d8dee9;
        --co-line: #edf0f5;
        --co-text: #111827;
        --co-muted: #6b7280;
        --co-primary: #1f4e79;
        --co-primary-soft: #eef6ff;
        --co-success: #16794c;
        --co-danger: #b42318;
        --co-warning: #9a6700;
    }

    body {
        background: var(--co-bg);
    }

    /* Page header - no luxury hero */
    .coass-hero {
        background: transparent;
        border: 0;
        box-shadow: none;
        padding: 0 0 14px 0;
        margin-bottom: 12px;
        border-radius: 0;
    }

    .coass-title {
        font-size: 22px;
        font-weight: 800;
        letter-spacing: -.02em;
        color: var(--co-text);
        margin: 0;
    }

    .coass-sub {
        color: var(--co-muted);
        font-size: 13px;
        margin-top: 4px;
    }

    .coass-hero .badge {
        background: #ffffff !important;
        color: var(--co-primary) !important;
        border: 1px solid var(--co-border);
        font-size: 12px;
        font-weight: 700;
    }

    .coass-hero .btn {
        height: 34px;
        padding: 6px 12px;
        font-size: 12px;
        border-radius: 8px !important;
    }

    /* Cards become compact panels */
    .coass-card {
        background: var(--co-card);
        border: 1px solid var(--co-border);
        border-radius: 10px;
        box-shadow: none;
        overflow: hidden;
        margin-bottom: 14px;
    }

    .coass-card-header {
        padding: 12px 16px;
        background: #fbfcfe;
        border-bottom: 1px solid var(--co-line);
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 12px;
    }

    .coass-card-header h5 {
        font-size: 15px;
        font-weight: 800;
        color: var(--co-text);
        margin-bottom: 2px !important;
    }

    .coass-card-header .text-muted {
        font-size: 12px;
    }

    .coass-card-body {
        padding: 16px;
    }

    /* Inner panels */
    .coass-panel {
        background: #fbfcfe;
        border: 1px solid var(--co-border);
        border-radius: 8px;
        padding: 14px;
        height: 100%;
    }

    .coass-panel-title {
        font-size: 11px;
        font-weight: 800;
        letter-spacing: .08em;
        color: var(--co-primary);
        text-transform: uppercase;
        margin-bottom: 12px;
        padding-bottom: 8px;
        border-bottom: 1px solid var(--co-line);
    }

    /* Form controls */
    .form-label {
        font-size: 12px;
        font-weight: 700;
        color: #374151;
        margin-bottom: 5px;
    }

    .form-control,
    .form-select {
        border-radius: 7px;
        border: 1px solid #cfd7e3;
        min-height: 36px;
        font-size: 13px;
        box-shadow: none !important;
        background-color: #fff;
    }

    .form-control:focus,
    .form-select:focus {
        border-color: var(--co-primary);
        box-shadow: 0 0 0 3px rgba(31, 78, 121, .08) !important;
    }

    textarea.form-control {
        min-height: 90px;
    }

    /* Batch / student selectors */
    .coass-picker {
        min-height: 165px;
        border-radius: 7px;
        font-size: 13px;
        background: #fff;
    }

    #batchSearch,
    #studentSearch {
        height: 36px;
        margin-bottom: 8px !important;
    }

    .form-check-label {
        color: #4b5563;
    }

    /* Buttons - more admin/ERP style */
    .btn {
        font-weight: 700;
    }

    .btn-eden {
        background: var(--co-primary) !important;
        border-color: var(--co-primary) !important;
        color: #fff !important;
    }

    .btn-eden:hover {
        background: #173c5d !important;
        border-color: #173c5d !important;
        color: #fff !important;
    }

    .rounded-pill {
        border-radius: 7px !important;
    }

    .btn-sm {
        font-size: 12px;
        padding: 5px 9px;
    }

    /* Sticky submit bar becomes simple footer */
    .coass-sticky {
        position: static;
        background: #f9fafb;
        backdrop-filter: none;
        border: 1px solid var(--co-border);
        box-shadow: none;
        border-radius: 8px;
        padding: 10px 12px;
        margin-top: 14px;
    }

    .coass-sticky .btn-eden {
        min-width: 150px;
    }

    /* Date pills - flatter */
    .coass-date {
        display: inline-flex;
        align-items: center;
        padding: 4px 8px;
        border-radius: 6px;
        font-size: 11px;
        font-weight: 700;
        margin: 2px 2px 2px 0;
        background: #eef2f7;
        color: #374151;
        border: 1px solid #e5e7eb;
    }

    .coass-date-danger {
        background: #fff1f0;
        color: var(--co-danger);
        border-color: #ffd4d0;
    }

    .coass-date-warning {
        background: #fff8e6;
        color: var(--co-warning);
        border-color: #ffe4a3;
    }

    .coass-date-success {
        background: #ecfdf3;
        color: var(--co-success);
        border-color: #bbf7d0;
    }

    /* Table - compact */
    .coass-table {
        font-size: 13px;
    }

    .coass-table thead th {
        background: #f3f6fa;
        color: #475569;
        font-size: 11px;
        font-weight: 800;
        text-transform: uppercase;
        letter-spacing: .04em;
        border-bottom: 1px solid var(--co-border);
        white-space: nowrap;
        padding: 10px 8px;
    }

    .coass-table tbody td {
        vertical-align: middle;
        border-color: var(--co-line);
        padding: 10px 8px;
    }

    .coass-table tbody tr:hover {
        background: #f8fbff;
    }

    .coass-table .fw-bold {
        font-weight: 800 !important;
        color: var(--co-text);
    }

    .coass-table .small {
        font-size: 11px;
    }

    .coass-table .badge {
        font-size: 11px;
        padding: 5px 8px;
        border-radius: 6px !important;
    }

    .coass-actions {
        display: flex;
        justify-content: flex-end;
        flex-wrap: wrap;
        gap: 5px;
        min-width: 230px;
    }

    .coass-actions .btn {
        border-radius: 6px !important;
    }

    .alert {
        border-radius: 8px !important;
        font-size: 13px;
    }

    /* Make create form visually shorter */
    .coass-card-body .row.g-3 {
        --bs-gutter-y: .75rem;
    }

    .coass-panel .mb-3 {
        margin-bottom: .65rem !important;
    }

    /* Cleaner mobile */
    @media (max-width: 992px) {
        .coass-card-header {
            flex-direction: column;
            align-items: flex-start;
        }

        .coass-actions {
            justify-content: flex-start;
            min-width: auto;
        }

        .coass-title {
            font-size: 20px;
        }

        .coass-card-body {
            padding: 12px;
        }
    }
</style>

<div class="coass-hero">
    <div class="d-flex flex-column flex-lg-row justify-content-between gap-3">
        <div>
            <h1 class="coass-title">Assessments & Projects</h1>
            <div class="coass-sub">
                Coordinator can create assessments, publish to batches/students, manage assessment release date, and release approved student results.
            </div>
        </div>

        <div class="d-flex flex-wrap gap-2">
            <span class="badge text-bg-danger rounded-pill px-3 py-2">
                <?= number_format(count($rows)) ?> Assessments
            </span>

            <a href="/elms/coordinator/submissions.php" class="btn btn-light border rounded-pill fw-bold">
                <i class="bi bi-inboxes me-1"></i> Submissions
            </a>

            <a href="/elms/coordinator/approval.php" class="btn btn-eden rounded-pill fw-bold">
                <i class="bi bi-send-check me-1"></i> Result Approval
            </a>
        </div>
    </div>
</div>

<?php if (isset($_GET['msg'])): ?>
    <div class="alert alert-info rounded-4">
        <i class="bi bi-info-circle me-1"></i>
        <?= coass_h($_GET['msg']) ?>
    </div>
<?php endif; ?>

<div class="coass-card">
    <div class="coass-card-header">
        <div>
            <h5 class="fw-bold mb-1">Filter Assessments</h5>
            <div class="text-muted small">Select a course to load related modules, batches, and students.</div>
        </div>
    </div>

    <div class="coass-card-body">
        <form method="get" class="row g-3 align-items-end">
            <div class="col-lg-8">
                <label class="form-label">Course</label>
                <select name="course_id" class="form-select" onchange="this.form.submit()">
                    <option value="0">All Courses</option>
                    <?php foreach ($courses as $id => $label): ?>
                        <option value="<?= (int)$id ?>" <?= $filterCourse === (int)$id ? 'selected' : '' ?>>
                            <?= coass_h($label) ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-lg-4">
                <a href="/elms/coordinator/assessments.php" class="btn btn-outline-secondary rounded-pill w-100">
                    Clear Filter
                </a>
            </div>
        </form>
    </div>
</div>

<div class="coass-card">
    <div class="coass-card-header">
        <div>
            <h5 class="fw-bold mb-1"><?= $editRow ? 'Edit Assessment' : 'Create New Assessment' ?></h5>
            <div class="text-muted small">Admin-style creation panel for coordinator portal.</div>
        </div>

        <?php if ($editRow): ?>
            <a href="/elms/coordinator/assessments.php" class="btn btn-outline-secondary rounded-pill">
                Cancel Edit
            </a>
        <?php endif; ?>
    </div>

    <div class="coass-card-body">
        <form method="post" enctype="multipart/form-data">
            <input type="hidden" name="csrf" value="<?= coass_h(coass_csrf_token()) ?>">
            <input type="hidden" name="op" value="save">
            <input type="hidden" name="edit_id" value="<?= (int)($editRow['id'] ?? 0) ?>">

            <div class="row g-3 mb-3">
                <div class="col-lg-6">
                    <div class="coass-panel">
                        <div class="coass-panel-title">
                            <i class="bi bi-diagram-3"></i> Course & Module
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Course</label>
                            <select name="course_id" class="form-select" onchange="location.href='/elms/coordinator/assessments.php?course_id='+this.value<?= $editRow ? "+'&edit=" . (int)$editRow['id'] . "'" : '' ?>;">
                                <option value="0">— Select Course —</option>
                                <?php $selectedCourse = (int)($editRow['course_id'] ?? $filterCourse); ?>
                                <?php foreach ($courses as $id => $label): ?>
                                    <option value="<?= (int)$id ?>" <?= $selectedCourse === (int)$id ? 'selected' : '' ?>>
                                        <?= coass_h($label) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div>
                            <label class="form-label">Module</label>
                            <select name="module_id" class="form-select">
                                <option value="0">— Select Module —</option>
                                <?php $selectedModule = (int)($editRow['module_id'] ?? 0); ?>
                                <?php foreach ($modules as $id => $label): ?>
                                    <option value="<?= (int)$id ?>" <?= $selectedModule === (int)$id ? 'selected' : '' ?>>
                                        <?= coass_h($label) ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="col-lg-6">
                    <div class="coass-panel">
                        <div class="coass-panel-title">
                            <i class="bi bi-file-earmark-text"></i> Assessment Details
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Title</label>
                            <input name="title" class="form-control" value="<?= coass_h($editRow['title'] ?? '') ?>" placeholder="Example: Final Project Brief">
                        </div>

                        <div class="row g-3 mb-3">
                            <div class="col-md-6">
                                <label class="form-label">Type</label>
                                <?php $type = (string)($editRow['type'] ?? 'assignment'); ?>
                                <select name="type" class="form-select">
                                    <option value="assignment" <?= $type === 'assignment' ? 'selected' : '' ?>>Assignment</option>
                                    <option value="project" <?= $type === 'project' ? 'selected' : '' ?>>Project</option>
                                </select>
                            </div>

                            <div class="col-md-6">
                                <label class="form-label">Max Score</label>
                                <input type="number" name="max_score" class="form-control" value="<?= (int)($editRow['max_score'] ?? 100) ?>">
                            </div>
                        </div>

                        <label class="form-label">Description</label>
                        <textarea name="description" rows="4" class="form-control" placeholder="Write assessment description..."><?= coass_h($editRow['description'] ?? '') ?></textarea>
                    </div>
                </div>
            </div>

            <div class="coass-panel mb-3">
                <div class="coass-panel-title">
                    <i class="bi bi-calendar-check"></i> Availability & Deadlines
                </div>

                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Available From</label>
                        <input type="datetime-local" name="available_from" class="form-control" value="<?= coass_h(coass_dt_input($editRow['available_from'] ?? null)) ?>">
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Available To</label>
                        <input type="datetime-local" name="available_to" class="form-control" value="<?= coass_h(coass_dt_input($editRow['available_to'] ?? null)) ?>">
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Due Deadline</label>
                        <input type="datetime-local" name="due_at" class="form-control" value="<?= coass_h(coass_dt_input($editRow['due_at'] ?? null)) ?>">
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Marks Release At</label>
                        <input type="datetime-local" name="release_at" class="form-control" value="<?= coass_h(coass_dt_input($editRow['release_at'] ?? null)) ?>">
                    </div>
                </div>
            </div>

            <div class="row g-3 mb-3">
                <div class="col-lg-6">
                    <div class="coass-panel">
                        <div class="coass-panel-title">
                            <i class="bi bi-people"></i> Publish to Batches
                        </div>

                        <input type="text" class="form-control mb-2" id="batchSearch" placeholder="Filter batches...">

                        <select name="batch_ids[]" id="batchSelect" class="form-select coass-picker" size="8" multiple>
                            <?php foreach ($batches as $id => $label): ?>
                                <option value="<?= (int)$id ?>" <?= in_array((int)$id, $selectedBatches, true) ? 'selected' : '' ?>>
                                    <?= coass_h($label) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>

                        <div class="form-check mt-3">
                            <input type="checkbox" name="batches_only" id="batchesOnly" class="form-check-input" <?= $selectedBatches && !$selectedStudents ? 'checked' : '' ?>>
                            <label class="form-check-label small" for="batchesOnly">
                                Publish only to selected batches. Individual students will be ignored.
                            </label>
                        </div>
                    </div>
                </div>

                <div class="col-lg-6">
                    <div class="coass-panel">
                        <div class="coass-panel-title">
                            <i class="bi bi-person-lines-fill"></i> Publish to Individual Students
                        </div>

                        <input type="text" class="form-control mb-2" id="studentSearch" placeholder="Filter students...">

                        <select name="student_ids[]" id="studentSelect" class="form-select coass-picker" size="8" multiple>
                            <?php foreach ($students as $id => $label): ?>
                                <option value="<?= (int)$id ?>" <?= in_array((int)$id, $selectedStudents, true) ? 'selected' : '' ?>>
                                    <?= coass_h($label) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>

                        <div class="small text-muted mt-3">
                            If any batch is selected or batches only is ticked, selected students are ignored.
                        </div>
                    </div>
                </div>
            </div>

            <div class="coass-panel mb-3">
                <div class="coass-panel-title">
                    <i class="bi bi-paperclip"></i> Attachment
                </div>

                <label class="form-label">Attach Brief / Project File</label>
                <input type="file" name="brief" class="form-control">

                <?php if (!empty($editRow['id'])): ?>
                    <?php $currentFile = coass_latest_attachment($db, (int)$editRow['id']); ?>
                    <?php if ($currentFile): ?>
                        <div class="small text-muted mt-2">
                            Current file:
                            <a href="<?= coass_h(coass_public_file_url($currentFile)) ?>" target="_blank">
                                <?= coass_h(basename($currentFile)) ?>
                            </a>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </div>

            <div class="coass-sticky d-flex justify-content-between align-items-center flex-wrap gap-2">
                <div class="small text-muted">
                    <?= $editRow ? 'Editing existing assessment.' : 'Ready to create new assessment.' ?>
                </div>

                <div class="d-flex gap-2">
                    <?php if ($editRow): ?>
                        <a href="/elms/coordinator/assessments.php" class="btn btn-outline-secondary rounded-pill">
                            Cancel
                        </a>
                    <?php endif; ?>

                    <button class="btn btn-eden rounded-pill fw-bold">
                        <i class="bi bi-check-circle me-1"></i>
                        <?= $editRow ? 'Update Assessment' : 'Create Assessment' ?>
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="coass-card">
    <div class="coass-card-header">
        <div>
            <h5 class="fw-bold mb-1">Assessment List</h5>
            <div class="text-muted small">Create, edit, release assessments and release approved results.</div>
        </div>
    </div>

    <div class="coass-card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle coass-table mb-0">
                <thead>
                    <tr>
                        <th>Assessment</th>
                        <th>Course</th>
                        <th>Window</th>
                        <th>Due</th>
                        <th>Assessment Release</th>
                        <th class="text-center">Submissions</th>
                        <th class="text-center">Approved</th>
                        <th class="text-center">Released</th>
                        <th>Active</th>
                        <th class="text-end">Action</th>
                    </tr>
                </thead>

                <tbody>
                    <?php if (!$rows): ?>
                        <tr>
                            <td colspan="10" class="text-center text-muted py-5">
                                <i class="bi bi-inbox fs-2 d-block mb-2"></i>
                                No assessments found.
                            </td>
                        </tr>
                    <?php endif; ?>

                    <?php foreach ($rows as $row): ?>
                        <?php
                            $isActive = (int)($row['active'] ?? 1) === 1;
                            $brief = coass_latest_attachment($db, (int)$row['id']);
                        ?>

                        <tr>
                            <td style="min-width:280px;">
                                <div class="fw-bold"><?= coass_h($row['title'] ?? 'Untitled') ?></div>

                                <div class="mt-1">
                                    <span class="badge text-bg-light border rounded-pill">
                                        <?= coass_h($row['type'] ?? 'assignment') ?>
                                    </span>

                                    <?php if (!empty($row['module_label'])): ?>
                                        <span class="badge text-bg-light border rounded-pill">
                                            <?= coass_h($row['module_label']) ?>
                                        </span>
                                    <?php endif; ?>
                                </div>

                                <?php if (!empty($row['description'])): ?>
                                    <div class="small text-muted mt-2">
                                        <?= coass_h(coass_short($row['description'], 120)) ?>
                                    </div>
                                <?php endif; ?>
                            </td>

                            <td><?= coass_h($row['course_label'] ?? '-') ?></td>

                            <td>
                                <?php if (!empty($row['available_from'])): ?>
                                    <span class="coass-date">From: <?= coass_h($row['available_from']) ?></span>
                                <?php else: ?>
                                    <span class="coass-date coass-date-warning">From: —</span>
                                <?php endif; ?>

                                <?php if (!empty($row['available_to'])): ?>
                                    <span class="coass-date">To: <?= coass_h($row['available_to']) ?></span>
                                <?php else: ?>
                                    <span class="coass-date coass-date-warning">To: —</span>
                                <?php endif; ?>
                            </td>

                            <td>
                                <?php if (!empty($row['due_at'])): ?>
                                    <span class="coass-date coass-date-danger"><?= coass_h($row['due_at']) ?></span>
                                <?php else: ?>
                                    <span class="coass-date coass-date-warning">—</span>
                                <?php endif; ?>
                            </td>

                            <td>
                                <?php if (!empty($row['release_at'])): ?>
                                    <span class="coass-date coass-date-success"><?= coass_h($row['release_at']) ?></span>
                                <?php else: ?>
                                    <span class="coass-date coass-date-warning">Not released</span>
                                <?php endif; ?>
                            </td>

                            <td class="text-center">
                                <span class="badge text-bg-danger rounded-pill">
                                    <?= (int)($row['submission_count'] ?? 0) ?>
                                </span>
                            </td>

                            <td class="text-center">
                                <span class="badge text-bg-info rounded-pill">
                                    <?= (int)($row['approved_count'] ?? 0) ?>
                                </span>
                            </td>

                            <td class="text-center">
                                <span class="badge text-bg-success rounded-pill">
                                    <?= (int)($row['released_count'] ?? 0) ?>
                                </span>
                            </td>

                            <td>
                                <form method="post" class="d-inline">
                                    <input type="hidden" name="csrf" value="<?= coass_h(coass_csrf_token()) ?>">
                                    <input type="hidden" name="op" value="toggle">
                                    <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                    <input type="hidden" name="to" value="<?= $isActive ? 0 : 1 ?>">

                                    <button class="badge bg-<?= $isActive ? 'success' : 'secondary' ?> border-0 rounded-pill px-3 py-2">
                                        <?= $isActive ? 'ON' : 'OFF' ?>
                                    </button>
                                </form>
                            </td>

                            <td>
                                <div class="coass-actions">
                                    <?php if ($brief): ?>
                                        <a href="<?= coass_h(coass_public_file_url($brief)) ?>" target="_blank" class="btn btn-sm btn-outline-secondary rounded-pill">
                                            Brief
                                        </a>
                                    <?php endif; ?>

                                    <a href="/elms/coordinator/assessments.php?edit=<?= (int)$row['id'] ?>&course_id=<?= (int)($row['course_id'] ?? 0) ?>" class="btn btn-sm btn-outline-primary rounded-pill">
                                        Edit
                                    </a>

                                    <?php if (empty($row['release_at'])): ?>
                                        <form method="post" class="d-inline" onsubmit="return confirm('Release this assessment now?');">
                                            <input type="hidden" name="csrf" value="<?= coass_h(coass_csrf_token()) ?>">
                                            <input type="hidden" name="op" value="assessment_release_now">
                                            <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                            <button class="btn btn-sm btn-outline-success rounded-pill">
                                                Release Now
                                            </button>
                                        </form>
                                    <?php else: ?>
                                        <form method="post" class="d-inline" onsubmit="return confirm('Clear assessment release date?');">
                                            <input type="hidden" name="csrf" value="<?= coass_h(coass_csrf_token()) ?>">
                                            <input type="hidden" name="op" value="assessment_clear_release">
                                            <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                            <button class="btn btn-sm btn-outline-secondary rounded-pill">
                                                Clear Release
                                            </button>
                                        </form>
                                    <?php endif; ?>

                                    <?php if ((int)($row['approved_count'] ?? 0) > 0): ?>
                                        <form method="post" class="d-inline" onsubmit="return confirm('Release all approved results for this assessment?');">
                                            <input type="hidden" name="csrf" value="<?= coass_h(coass_csrf_token()) ?>">
                                            <input type="hidden" name="op" value="release_results">
                                            <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                            <button class="btn btn-sm btn-success rounded-pill">
                                                Release Results
                                            </button>
                                        </form>
                                    <?php endif; ?>

                                    <form method="post" class="d-inline" onsubmit="return confirm('Delete this assessment?');">
                                        <input type="hidden" name="csrf" value="<?= coass_h(coass_csrf_token()) ?>">
                                        <input type="hidden" name="op" value="delete">
                                        <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                        <button class="btn btn-sm btn-outline-danger rounded-pill">
                                            Delete
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <div class="alert alert-light border rounded-4 mt-4 mb-0">
            <strong>Note:</strong>
            <code>Release Now</code> sets assessment <code>release_at</code>.
            <code>Release Results</code> changes approved submissions to <code>workflow_status = released</code>, so students can see results.
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    function attachSelectFilter(inputId, selectId) {
        const input = document.getElementById(inputId);
        const select = document.getElementById(selectId);

        if (!input || !select) return;

        const options = Array.from(select.options);

        input.addEventListener('input', function () {
            const q = input.value.toLowerCase().trim();

            select.innerHTML = '';

            options.forEach(option => {
                if (q === '' || option.text.toLowerCase().includes(q)) {
                    select.appendChild(option);
                }
            });
        });
    }

    attachSelectFilter('batchSearch', 'batchSelect');
    attachSelectFilter('studentSearch', 'studentSelect');

    const batchesOnly = document.getElementById('batchesOnly');
    const studentSelect = document.getElementById('studentSelect');

    function syncStudentDisable() {
        if (!batchesOnly || !studentSelect) return;

        if (batchesOnly.checked) {
            studentSelect.setAttribute('disabled', 'disabled');
        } else {
            studentSelect.removeAttribute('disabled');
        }
    }

    batchesOnly?.addEventListener('change', syncStudentDisable);
    syncStudentDisable();
});
</script>

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