<?php
// /elms/lecturer/reports.php
declare(strict_types=1);

$PAGE_TITLE = 'Reports';
$ACTIVE = 'reports';

require_once __DIR__ . '/../includes/lecturer_auth.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');

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

function lr_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 lr_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 lr_first_col(mysqli $db, string $table, array $cols): ?string {
    if (!lr_table_exists($db, $table)) return null;

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

    return null;
}

function lr_grade(float $score, float $maxScore = 100): string {
    if ($maxScore <= 0) $maxScore = 100;
    $pct = ($score / $maxScore) * 100;

    if ($pct >= 75) return 'A';
    if ($pct >= 65) return 'B';
    if ($pct >= 55) return 'C';
    if ($pct >= 40) return 'S';
    return 'F';
}

function lr_grade_badge(string $grade): string {
    return match ($grade) {
        'A' => 'text-bg-success',
        'B' => 'text-bg-primary',
        'C' => 'text-bg-info',
        'S' => 'text-bg-warning',
        default => 'text-bg-danger',
    };
}

function lr_status_badge(string $status): string {
    $status = strtolower(trim($status));

    return match ($status) {
        'submitted', 'pending' => 'text-bg-warning',
        'needs_correction' => 'text-bg-danger',
        'graded_provisional' => 'text-bg-primary',
        'under_review', 'coord_review', 'coordinator_review', 'admin_review' => 'text-bg-info',
        'coord_approved', 'approved' => 'text-bg-success',
        'released', 'published' => 'text-bg-success',
        default => 'text-bg-light border text-dark',
    };
}

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

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

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

    $rows = [];

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

    return $rows;
}

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

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

    if ($courseId > 0 && $hasCourse) {
        $stmt = $db->prepare("
            SELECT id, COALESCE(`{$nameCol}`, CONCAT('Batch #', id)) AS label
            FROM batches
            WHERE course_id = ?
            ORDER BY label ASC
        ");
        $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 label ASC
        ");
    }

    $rows = [];

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

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

    return $rows;
}

function lr_assessments(mysqli $db, int $courseId = 0): array {
    if (!lr_table_exists($db, 'lms_assessments')) return [];

    if ($courseId > 0 && lr_col_exists($db, 'lms_assessments', 'course_id')) {
        $stmt = $db->prepare("
            SELECT id, COALESCE(title, CONCAT('Assessment #', id)) AS title
            FROM lms_assessments
            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(title, CONCAT('Assessment #', id)) AS title
            FROM lms_assessments
            ORDER BY id DESC
        ");
    }

    $rows = [];

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

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

    return $rows;
}

/*
|--------------------------------------------------------------------------
| Filters
|--------------------------------------------------------------------------
*/

$filterCourse = (int)($_GET['course_id'] ?? 0);
$filterBatch = (int)($_GET['batch_id'] ?? 0);
$filterAssessment = (int)($_GET['assessment_id'] ?? 0);
$filterStatus = strtolower(trim((string)($_GET['status'] ?? 'all')));

$allowedStatuses = [
    'all',
    'submitted',
    'needs_correction',
    'graded_provisional',
    'under_review',
    'coord_approved',
    'released'
];

if (!in_array($filterStatus, $allowedStatuses, true)) {
    $filterStatus = 'all';
}

$courses = lr_courses($db);
$batches = lr_batches($db, $filterCourse);
$assessments = lr_assessments($db, $filterCourse);

/*
|--------------------------------------------------------------------------
| Main data
|--------------------------------------------------------------------------
*/

$summary = [
    'submitted' => 0,
    'needs_correction' => 0,
    'graded_provisional' => 0,
    'under_review' => 0,
    'coord_approved' => 0,
    'released' => 0,
    'total' => 0,
];

$assessmentProgress = [];
$studentRows = [];

if (lr_table_exists($db, 'lms_submissions') && lr_table_exists($db, 'lms_assessments')) {
    $studentTable = lr_table_exists($db, 'studentss') ? 'studentss' : (lr_table_exists($db, 'students') ? 'students' : null);

    $studentNameCol = $studentTable ? (lr_first_col($db, $studentTable, ['full_name', 'name', 'student_name']) ?? 'id') : null;
    $studentRegCol = $studentTable ? lr_first_col($db, $studentTable, ['center_reg_no', 'reference_no', 'reg_no']) : null;

    $courseNameCol = lr_first_col($db, 'courses', ['course_name', 'name', 'title', 'label']) ?? 'id';
    $batchNameCol = lr_first_col($db, 'batches', ['batch_name', 'name', 'title', 'label']) ?? 'id';

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

    if ($filterCourse > 0) {
        $where[] = "a.course_id = ?";
        $types .= 'i';
        $params[] = $filterCourse;
    }

    if ($filterAssessment > 0) {
        $where[] = "s.assessment_id = ?";
        $types .= 'i';
        $params[] = $filterAssessment;
    }

    if ($filterBatch > 0 && lr_col_exists($db, 'lms_submissions', 'batch_id')) {
        $where[] = "s.batch_id = ?";
        $types .= 'i';
        $params[] = $filterBatch;
    }

    if ($filterStatus !== 'all') {
        if ($filterStatus === 'under_review') {
            $where[] = "LOWER(COALESCE(s.workflow_status,'')) IN ('under_review','coord_review','coordinator_review','admin_review')";
        } elseif ($filterStatus === 'coord_approved') {
            $where[] = "LOWER(COALESCE(s.workflow_status,'')) IN ('coord_approved','approved')";
        } elseif ($filterStatus === 'released') {
            $where[] = "LOWER(COALESCE(s.workflow_status,'')) IN ('released','published')";
        } else {
            $where[] = "LOWER(COALESCE(s.workflow_status,'')) = ?";
            $types .= 's';
            $params[] = $filterStatus;
        }
    }

    $whereSql = "WHERE " . implode(" AND ", $where);

    $studentJoin = '';
    $studentNameExpr = "CONCAT('Student #', s.student_id)";
    $studentRegExpr = "'' AS reg_no";

    if ($studentTable && $studentNameCol) {
        $studentJoin = "LEFT JOIN {$studentTable} st ON st.id = s.student_id";
        $studentNameExpr = "COALESCE(st.`{$studentNameCol}`, CONCAT('Student #', s.student_id))";

        if ($studentRegCol) {
            $studentRegExpr = "st.`{$studentRegCol}` AS reg_no";
        }
    }

    $sql = "
        SELECT
            s.id,
            s.student_id,
            s.assessment_id,
            s.batch_id,
            s.final_score,
            s.lecturer_feedback,
            s.workflow_status,
            s.submitted_at,
            s.graded_at,
            s.released_at,

            {$studentNameExpr} AS student_name,
            {$studentRegExpr},

            COALESCE(a.title, CONCAT('Assessment #', s.assessment_id)) AS assessment_title,
            COALESCE(a.max_score, 100) AS max_score,
            COALESCE(c.`{$courseNameCol}`, CONCAT('Course #', a.course_id)) AS course_name,
            COALESCE(b.`{$batchNameCol}`, CONCAT('Batch #', s.batch_id)) AS batch_name
        FROM lms_submissions s
        INNER JOIN lms_assessments a ON a.id = s.assessment_id
        LEFT JOIN courses c ON c.id = a.course_id
        LEFT JOIN batches b ON b.id = s.batch_id
        {$studentJoin}
        {$whereSql}
        ORDER BY s.id DESC
        LIMIT 500
    ";

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

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

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

        while ($row = $res->fetch_assoc()) {
            $wf = strtolower(trim((string)($row['workflow_status'] ?? 'submitted')));

            if (in_array($wf, ['submitted', 'pending', ''], true)) {
                $summary['submitted']++;
            } elseif ($wf === 'needs_correction') {
                $summary['needs_correction']++;
            } elseif ($wf === 'graded_provisional') {
                $summary['graded_provisional']++;
            } elseif (in_array($wf, ['under_review', 'coord_review', 'coordinator_review', 'admin_review'], true)) {
                $summary['under_review']++;
            } elseif (in_array($wf, ['coord_approved', 'approved'], true)) {
                $summary['coord_approved']++;
            } elseif (in_array($wf, ['released', 'published'], true)) {
                $summary['released']++;
            }

            $summary['total']++;

            $score = (float)($row['final_score'] ?? 0);
            $max = (float)($row['max_score'] ?? 100);
            $row['percent'] = ($max > 0 && $row['final_score'] !== null && $row['final_score'] !== '') ? round(($score / $max) * 100, 1) : null;
            $row['grade'] = $row['percent'] !== null ? lr_grade($score, $max) : '-';

            $studentRows[] = $row;
        }

        $stmt->close();
    }

    /*
    |--------------------------------------------------------------------------
    | Assessment-wise progress
    |--------------------------------------------------------------------------
    */

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

    if ($filterCourse > 0) {
        $where[] = "a.course_id = ?";
        $types .= 'i';
        $params[] = $filterCourse;
    }

    if ($filterAssessment > 0) {
        $where[] = "a.id = ?";
        $types .= 'i';
        $params[] = $filterAssessment;
    }

    if ($filterBatch > 0 && lr_col_exists($db, 'lms_submissions', 'batch_id')) {
        $where[] = "s.batch_id = ?";
        $types .= 'i';
        $params[] = $filterBatch;
    }

    $whereSql = "WHERE " . implode(" AND ", $where);

    $sql = "
        SELECT
            a.id AS assessment_id,
            COALESCE(a.title, CONCAT('Assessment #', a.id)) AS assessment_title,
            COALESCE(a.max_score, 100) AS max_score,
            COALESCE(c.`{$courseNameCol}`, CONCAT('Course #', a.course_id)) AS course_name,

            COUNT(s.id) AS total_submissions,
            SUM(CASE WHEN LOWER(COALESCE(s.workflow_status,'')) IN ('submitted','pending','') THEN 1 ELSE 0 END) AS pending_marking,
            SUM(CASE WHEN LOWER(COALESCE(s.workflow_status,'')) = 'needs_correction' THEN 1 ELSE 0 END) AS needs_correction,
            SUM(CASE WHEN LOWER(COALESCE(s.workflow_status,'')) IN ('graded_provisional','under_review','coord_review','coordinator_review','admin_review','coord_approved','approved','released','published') THEN 1 ELSE 0 END) AS marked_count,
            SUM(CASE WHEN LOWER(COALESCE(s.workflow_status,'')) IN ('under_review','coord_review','coordinator_review','admin_review') THEN 1 ELSE 0 END) AS under_review,
            SUM(CASE WHEN LOWER(COALESCE(s.workflow_status,'')) IN ('released','published') THEN 1 ELSE 0 END) AS released_count,
            AVG(CASE WHEN s.final_score IS NOT NULL THEN s.final_score END) AS avg_score
        FROM lms_assessments a
        LEFT JOIN lms_submissions s ON s.assessment_id = a.id
        LEFT JOIN courses c ON c.id = a.course_id
        {$whereSql}
        GROUP BY a.id
        ORDER BY a.id DESC
        LIMIT 200
    ";

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

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

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

        while ($row = $res->fetch_assoc()) {
            $total = (int)($row['total_submissions'] ?? 0);
            $marked = (int)($row['marked_count'] ?? 0);
            $row['marking_pct'] = $total > 0 ? round(($marked / $total) * 100, 1) : 0;
            $assessmentProgress[] = $row;
        }

        $stmt->close();
    }
}

$avgScore = 0;
$scoreCount = 0;

foreach ($studentRows as $row) {
    if ($row['percent'] !== null) {
        $avgScore += (float)$row['percent'];
        $scoreCount++;
    }
}

$avgScore = $scoreCount > 0 ? round($avgScore / $scoreCount, 1) : 0;

require_once __DIR__ . '/../includes/lecturer_layout_top.php';
?>

<style>
    .lr-head {
        border: 1px solid #e5e7eb;
        background:
            radial-gradient(circle at top right, rgba(37, 99, 235, .13), transparent 28%),
            linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
        border-radius: 20px;
        padding: 22px;
        margin-bottom: 18px;
    }

    .lr-title {
        font-size: 26px;
        font-weight: 950;
        letter-spacing: -.03em;
        margin: 0;
        color: #0f172a;
    }

    .lr-sub {
        color: #64748b;
        margin-top: 4px;
    }

    .lr-card {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 18px;
        box-shadow: 0 10px 28px rgba(15,23,42,.055);
        overflow: hidden;
    }

    .lr-card-head {
        padding: 15px 18px;
        border-bottom: 1px solid #eef2f7;
        background: #fbfcfe;
        display: flex;
        justify-content: space-between;
        gap: 12px;
        align-items: center;
        flex-wrap: wrap;
    }

    .lr-card-body {
        padding: 18px;
    }

    .lr-kpi {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 16px;
        padding: 15px;
        height: 100%;
    }

    .lr-kpi-label {
        color: #64748b;
        font-size: 12px;
        font-weight: 800;
        text-transform: uppercase;
        letter-spacing: .04em;
    }

    .lr-kpi-value {
        font-size: 28px;
        font-weight: 950;
        line-height: 1.1;
        margin-top: 4px;
        color: #0f172a;
    }

    .lr-kpi-icon {
        font-size: 24px;
        color: #2563eb;
        opacity: .95;
    }

    .lr-filter {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 18px;
        padding: 16px;
        margin-bottom: 18px;
    }

    .table-lr th {
        background: #f8fafc;
        color: #475569;
        font-size: 11px;
        text-transform: uppercase;
        letter-spacing: .04em;
        white-space: nowrap;
    }

    .table-lr td {
        vertical-align: middle;
        font-size: 13px;
    }

    .progress-thin {
        height: 8px;
        border-radius: 999px;
    }
</style>

<div class="lr-head">
    <div class="d-flex flex-column flex-lg-row justify-content-between gap-3">
        <div>
            <h1 class="lr-title">Lecturer Reports</h1>
            <div class="lr-sub">
                Marking summary, assessment progress, student marks, workflow status, and performance overview.
            </div>
        </div>

        <div class="d-flex flex-wrap gap-2">
            <a href="#assessment-progress" class="btn btn-light border rounded-pill fw-bold">
                Assessment Progress
            </a>
            <a href="#student-performance" class="btn btn-primary rounded-pill fw-bold">
                Student Marks
            </a>
        </div>
    </div>
</div>

<div class="lr-filter">
    <form method="get" class="row g-3 align-items-end">
        <div class="col-lg-3">
            <label class="form-label fw-bold">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' : '' ?>>
                        <?= h($label) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-lg-3">
            <label class="form-label fw-bold">Batch</label>
            <select name="batch_id" class="form-select">
                <option value="0">All Batches</option>
                <?php foreach ($batches as $id => $label): ?>
                    <option value="<?= (int)$id ?>" <?= $filterBatch === (int)$id ? 'selected' : '' ?>>
                        <?= h($label) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-lg-3">
            <label class="form-label fw-bold">Assessment</label>
            <select name="assessment_id" class="form-select">
                <option value="0">All Assessments</option>
                <?php foreach ($assessments as $id => $label): ?>
                    <option value="<?= (int)$id ?>" <?= $filterAssessment === (int)$id ? 'selected' : '' ?>>
                        <?= h($label) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-lg-2">
            <label class="form-label fw-bold">Status</label>
            <select name="status" class="form-select">
                <option value="all" <?= $filterStatus === 'all' ? 'selected' : '' ?>>All</option>
                <option value="submitted" <?= $filterStatus === 'submitted' ? 'selected' : '' ?>>Submitted</option>
                <option value="needs_correction" <?= $filterStatus === 'needs_correction' ? 'selected' : '' ?>>Needs Correction</option>
                <option value="graded_provisional" <?= $filterStatus === 'graded_provisional' ? 'selected' : '' ?>>Provisional</option>
                <option value="under_review" <?= $filterStatus === 'under_review' ? 'selected' : '' ?>>Under Review</option>
                <option value="coord_approved" <?= $filterStatus === 'coord_approved' ? 'selected' : '' ?>>Approved</option>
                <option value="released" <?= $filterStatus === 'released' ? 'selected' : '' ?>>Released</option>
            </select>
        </div>

        <div class="col-lg-1 d-grid">
            <button class="btn btn-primary rounded-pill fw-bold">
                Go
            </button>
        </div>

        <div class="col-12">
            <a href="/elms/lecturer/reports.php" class="btn btn-sm btn-outline-secondary rounded-pill">
                Clear Filters
            </a>
        </div>
    </form>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="lr-kpi">
            <div class="d-flex justify-content-between">
                <div>
                    <div class="lr-kpi-label">Total Items</div>
                    <div class="lr-kpi-value"><?= number_format($summary['total']) ?></div>
                </div>
                <i class="bi bi-list-check lr-kpi-icon"></i>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="lr-kpi">
            <div class="d-flex justify-content-between">
                <div>
                    <div class="lr-kpi-label">Pending Marking</div>
                    <div class="lr-kpi-value text-warning"><?= number_format($summary['submitted']) ?></div>
                </div>
                <i class="bi bi-clock-history lr-kpi-icon"></i>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="lr-kpi">
            <div class="d-flex justify-content-between">
                <div>
                    <div class="lr-kpi-label">Under Review</div>
                    <div class="lr-kpi-value text-info"><?= number_format($summary['under_review']) ?></div>
                </div>
                <i class="bi bi-hourglass-split lr-kpi-icon"></i>
            </div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="lr-kpi">
            <div class="d-flex justify-content-between">
                <div>
                    <div class="lr-kpi-label">Released</div>
                    <div class="lr-kpi-value text-success"><?= number_format($summary['released']) ?></div>
                </div>
                <i class="bi bi-award lr-kpi-icon"></i>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="lr-kpi">
            <div class="lr-kpi-label">Needs Correction</div>
            <div class="lr-kpi-value text-danger"><?= number_format($summary['needs_correction']) ?></div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="lr-kpi">
            <div class="lr-kpi-label">Provisional</div>
            <div class="lr-kpi-value text-primary"><?= number_format($summary['graded_provisional']) ?></div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="lr-kpi">
            <div class="lr-kpi-label">Approved</div>
            <div class="lr-kpi-value text-success"><?= number_format($summary['coord_approved']) ?></div>
        </div>
    </div>

    <div class="col-md-3">
        <div class="lr-kpi">
            <div class="lr-kpi-label">Average Score</div>
            <div class="lr-kpi-value text-primary"><?= number_format($avgScore, 1) ?>%</div>
        </div>
    </div>
</div>

<div class="lr-card mb-4" id="assessment-progress">
    <div class="lr-card-head">
        <div>
            <h5 class="fw-bold mb-1">Assessment-wise Marking Progress</h5>
            <div class="text-muted small">Total submissions, marked count, pending count, average score and release count.</div>
        </div>

        <span class="badge text-bg-primary rounded-pill">
            <?= number_format(count($assessmentProgress)) ?> assessments
        </span>
    </div>

    <div class="table-responsive">
        <table class="table table-hover align-middle table-lr mb-0">
            <thead>
                <tr>
                    <th>Assessment</th>
                    <th>Course</th>
                    <th class="text-center">Total</th>
                    <th class="text-center">Pending</th>
                    <th class="text-center">Marked</th>
                    <th class="text-center">Review</th>
                    <th class="text-center">Released</th>
                    <th class="text-center">Average</th>
                    <th style="min-width:170px;">Progress</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$assessmentProgress): ?>
                    <tr>
                        <td colspan="9" class="text-center text-muted py-5">
                            <i class="bi bi-inbox fs-2 d-block mb-2"></i>
                            No assessment progress found.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($assessmentProgress as $row): ?>
                        <?php $pct = (float)($row['marking_pct'] ?? 0); ?>
                        <tr>
                            <td>
                                <div class="fw-bold"><?= h($row['assessment_title'] ?? '-') ?></div>
                                <div class="small text-muted">ID: <?= (int)$row['assessment_id'] ?></div>
                            </td>

                            <td><?= h($row['course_name'] ?? '-') ?></td>

                            <td class="text-center">
                                <span class="badge text-bg-light border"><?= (int)$row['total_submissions'] ?></span>
                            </td>

                            <td class="text-center">
                                <span class="badge text-bg-warning"><?= (int)$row['pending_marking'] ?></span>
                            </td>

                            <td class="text-center">
                                <span class="badge text-bg-primary"><?= (int)$row['marked_count'] ?></span>
                            </td>

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

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

                            <td class="text-center">
                                <?php if ($row['avg_score'] !== null): ?>
                                    <?= number_format((float)$row['avg_score'], 1) ?>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>

                            <td>
                                <div class="d-flex justify-content-between small mb-1">
                                    <span><?= number_format($pct, 1) ?>%</span>
                                    <span><?= (int)$row['marked_count'] ?>/<?= (int)$row['total_submissions'] ?></span>
                                </div>
                                <div class="progress progress-thin">
                                    <div class="progress-bar bg-primary" style="width: <?= min(100, max(0, $pct)) ?>%"></div>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="lr-card" id="student-performance">
    <div class="lr-card-head">
        <div>
            <h5 class="fw-bold mb-1">Student Marks & Workflow Table</h5>
            <div class="text-muted small">Student name, assessment, marks, workflow status, feedback and submitted date.</div>
        </div>

        <span class="badge text-bg-success rounded-pill">
            <?= number_format(count($studentRows)) ?> records
        </span>
    </div>

    <div class="table-responsive">
        <table class="table table-hover align-middle table-lr mb-0">
            <thead>
                <tr>
                    <th>Student</th>
                    <th>Reg No</th>
                    <th>Course</th>
                    <th>Batch</th>
                    <th>Assessment</th>
                    <th class="text-center">Marks</th>
                    <th class="text-center">%</th>
                    <th class="text-center">Grade</th>
                    <th>Status</th>
                    <th>Feedback</th>
                    <th>Submitted</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$studentRows): ?>
                    <tr>
                        <td colspan="11" class="text-center text-muted py-5">
                            <i class="bi bi-people fs-2 d-block mb-2"></i>
                            No student report records found.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($studentRows as $row): ?>
                        <?php
                            $wf = strtolower((string)($row['workflow_status'] ?? 'submitted'));
                            $grade = (string)($row['grade'] ?? '-');
                        ?>
                        <tr>
                            <td>
                                <div class="fw-bold"><?= h($row['student_name'] ?? '-') ?></div>
                                <div class="small text-muted">ID: <?= (int)$row['student_id'] ?></div>
                            </td>

                            <td><?= h($row['reg_no'] ?? '-') ?></td>

                            <td><?= h($row['course_name'] ?? '-') ?></td>

                            <td>
                                <?php if (!empty($row['batch_id'])): ?>
                                    <?= h($row['batch_name'] ?? ('Batch #' . (int)$row['batch_id'])) ?>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>

                            <td>
                                <div class="fw-semibold"><?= h($row['assessment_title'] ?? '-') ?></div>
                                <div class="small text-muted">Assessment ID: <?= (int)$row['assessment_id'] ?></div>
                            </td>

                            <td class="text-center">
                                <?php if ($row['final_score'] !== null && $row['final_score'] !== ''): ?>
                                    <span class="fw-bold"><?= h((string)$row['final_score']) ?> / <?= h((string)$row['max_score']) ?></span>
                                <?php else: ?>
                                    <span class="text-muted">Not marked</span>
                                <?php endif; ?>
                            </td>

                            <td class="text-center">
                                <?php if ($row['percent'] !== null): ?>
                                    <?= number_format((float)$row['percent'], 1) ?>%
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>

                            <td class="text-center">
                                <?php if ($grade !== '-'): ?>
                                    <span class="badge <?= h(lr_grade_badge($grade)) ?>"><?= h($grade) ?></span>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>

                            <td>
                                <span class="badge <?= h(lr_status_badge($wf)) ?>">
                                    <?= h($wf !== '' ? ucwords(str_replace('_', ' ', $wf)) : 'Submitted') ?>
                                </span>
                            </td>

                            <td style="max-width:240px;">
                                <div class="small text-muted text-truncate">
                                    <?= h($row['lecturer_feedback'] ?? '') ?>
                                </div>
                            </td>

                            <td class="small text-muted">
                                <?php if (!empty($row['submitted_at'])): ?>
                                    <?= h(date('Y-m-d H:i', strtotime((string)$row['submitted_at']))) ?>
                                <?php else: ?>
                                    —
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/lecturer_layout_bottom.php'; ?>