<?php
// /elms/admin/reports/student_full_report.php
// FULL replacement code
declare(strict_types=1);

define('APP_ROOT', dirname(__DIR__, 2));

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

$mysqli = $mysqli ?? ($conn ?? null);
if (!$mysqli instanceof mysqli) {
    http_response_code(500);
    exit('Database connection not found.');
}
$mysqli->set_charset('utf8mb4');

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

function sfr_table_exists(mysqli $db, string $table): bool {
    $st = $db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? LIMIT 1");
    if (!$st) return false;
    $st->bind_param('s', $table);
    $st->execute();
    return (bool)$st->get_result()->fetch_row();
}

function sfr_col_exists(mysqli $db, string $table, string $col): bool {
    if (!sfr_table_exists($db, $table)) return false;
    $st = $db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ? AND COLUMN_NAME = ? LIMIT 1");
    if (!$st) return false;
    $st->bind_param('ss', $table, $col);
    $st->execute();
    return (bool)$st->get_result()->fetch_row();
}

function sfr_first_col(mysqli $db, string $table, array $cols): string {
    foreach ($cols as $c) {
        if (sfr_col_exists($db, $table, $c)) return $c;
    }
    return '';
}

function sfr_table(mysqli $db, array $tables): string {
    foreach ($tables as $t) {
        if (sfr_table_exists($db, $t)) return $t;
    }
    return '';
}

function sfr_num($v): float {
    if ($v === null || $v === '') return 0.0;
    if (is_numeric($v)) return (float)$v;
    return 0.0;
}

function sfr_value_from_json($json, array $keys): string {
    if (!$json) return '';
    $arr = json_decode((string)$json, true);
    if (!is_array($arr)) return '';
    foreach ($keys as $k) {
        if (isset($arr[$k]) && $arr[$k] !== '') return (string)$arr[$k];
    }
    return '';
}

$studentTable     = sfr_table($mysqli, ['studentss', 'students']);
$quizAttemptTable = sfr_table($mysqli, ['lms_quiz_attempts', 'quiz_attempts']);
$quizTable        = sfr_table($mysqli, ['lms_quizzes', 'quizzes']);
$questionTable    = sfr_table($mysqli, ['lms_quiz_questions', 'quiz_questions']);
$submissionTable  = sfr_table($mysqli, ['lms_submissions', 'submissions']);
$assessmentTable  = sfr_table($mysqli, ['lms_assessments', 'assessments']);
$batchTable       = sfr_table($mysqli, ['batches']);
$courseTable      = sfr_table($mysqli, ['courses']);

$studentId = isset($_GET['student_id']) ? (int)$_GET['student_id'] : 0;
$q = trim((string)($_GET['q'] ?? ''));

$students = [];
$student = null;
$quizRows = [];
$assessmentRows = [];

$studentName = $studentReg = $studentRef = $studentNic = $studentBatch = $studentCourse = '';

$sidCol = $nameCol = $regCol = $refCol = $nicCol = $batchCol = $courseCol = '';

if ($studentTable !== '') {
    $sidCol    = sfr_first_col($mysqli, $studentTable, ['id', 'student_id']);
    $nameCol   = sfr_first_col($mysqli, $studentTable, ['full_name', 'student_name', 'name', 'first_name']);
    $regCol    = sfr_first_col($mysqli, $studentTable, ['reg_no', 'registration_no', 'center_reg_no', 'student_no', 'course_reg_no']);
    $refCol    = sfr_first_col($mysqli, $studentTable, ['reference_no', 'ref_no', 'nec_no', 'student_ref', 'ref']);
$nicCol = sfr_first_col($mysqli, $studentTable, [
    'nic_passport',
    'nic',
    'nic_no',
    'nic_number',
    'national_id',
    'identity_no',
    'id_no',
    'passport_no'
]);    $batchCol  = sfr_first_col($mysqli, $studentTable, ['batch_id']);
    $courseCol = sfr_first_col($mysqli, $studentTable, ['course_id']);

    if ($q !== '' && $sidCol !== '') {
        $where = [];
        $params = [];
        $types = '';

        foreach ([$nameCol, $regCol, $refCol, $nicCol] as $c) {
            if ($c !== '') {
                $where[] = "`$c` LIKE ?";
                $params[] = '%' . $q . '%';
                $types .= 's';
            }
        }

        if ($where) {
            $sql = "SELECT * FROM `$studentTable` WHERE " . implode(' OR ', $where) . " ORDER BY `$sidCol` DESC LIMIT 25";
            $st = $mysqli->prepare($sql);
            if ($st) {
                $st->bind_param($types, ...$params);
                $st->execute();
                $students = $st->get_result()->fetch_all(MYSQLI_ASSOC);
            }
        }
    }

    if ($studentId > 0 && $sidCol !== '') {
        $st = $mysqli->prepare("SELECT * FROM `$studentTable` WHERE `$sidCol` = ? LIMIT 1");
        if ($st) {
            $st->bind_param('i', $studentId);
            $st->execute();
            $student = $st->get_result()->fetch_assoc() ?: null;
        }
    }

    if ($student) {
        $studentName = $nameCol ? (string)($student[$nameCol] ?? '') : 'Student';
        $studentReg  = $regCol ? (string)($student[$regCol] ?? '') : '';
        $studentRef  = $refCol ? (string)($student[$refCol] ?? '') : '';
        $studentNic  = $nicCol ? (string)($student[$nicCol] ?? '') : '';

        if ($studentBatch === '' && $batchTable && $batchCol && !empty($student[$batchCol])) {
            $bLabel = sfr_first_col($mysqli, $batchTable, ['batch_name', 'name', 'code', 'batch_code', 'title']);
            if ($bLabel) {
                $bid = (int)$student[$batchCol];
                $st = $mysqli->prepare("SELECT `$bLabel` AS label FROM `$batchTable` WHERE id = ? LIMIT 1");
                if ($st) {
                    $st->bind_param('i', $bid);
                    $st->execute();
                    $x = $st->get_result()->fetch_assoc();
                    $studentBatch = (string)($x['label'] ?? '');
                }
            }
        }

        if ($studentCourse === '' && $courseTable && $courseCol && !empty($student[$courseCol])) {
            $cLabel = sfr_first_col($mysqli, $courseTable, ['course_name', 'name', 'title', 'code']);
            if ($cLabel) {
                $cid = (int)$student[$courseCol];
                $st = $mysqli->prepare("SELECT `$cLabel` AS label FROM `$courseTable` WHERE id = ? LIMIT 1");
                if ($st) {
                    $st->bind_param('i', $cid);
                    $st->execute();
                    $x = $st->get_result()->fetch_assoc();
                    $studentCourse = (string)($x['label'] ?? '');
                }
            }
        }

        if ($quizAttemptTable) {
            $qaStudent = sfr_first_col($mysqli, $quizAttemptTable, ['student_id', 'user_id']);
            $qaQuiz    = sfr_first_col($mysqli, $quizAttemptTable, ['quiz_id', 'lms_quiz_id']);
            $qaScore   = sfr_first_col($mysqli, $quizAttemptTable, ['score', 'marks', 'obtained_marks', 'correct_count', 'points']);
            $qaTotal   = sfr_first_col($mysqli, $quizAttemptTable, ['total', 'total_marks', 'max_score', 'max_marks', 'out_of', 'question_count']);
            $qaPercent = sfr_first_col($mysqli, $quizAttemptTable, ['percent', 'percentage']);
            $qaDate    = sfr_first_col($mysqli, $quizAttemptTable, ['finished_at', 'attempted_at', 'submitted_at', 'created_at', 'updated_at', 'date_taken']);
            $qaStatus  = sfr_first_col($mysqli, $quizAttemptTable, ['passed', 'status', 'result', 'pass_status']);

            $qtTitle = $quizTable ? sfr_first_col($mysqli, $quizTable, ['title', 'quiz_title', 'name']) : '';

            $select = "qa.*";
            $join = "";

            if ($quizTable && $qaQuiz && $qtTitle) {
                $select .= ", q.`$qtTitle` AS quiz_title";
                $join .= " LEFT JOIN `$quizTable` q ON q.id = qa.`$qaQuiz`";
            }

            if ($qaStudent) {
                $order = $qaDate ? "qa.`$qaDate` DESC" : "qa.id DESC";
                $st = $mysqli->prepare("SELECT $select FROM `$quizAttemptTable` qa $join WHERE qa.`$qaStudent` = ? ORDER BY $order, qa.id DESC LIMIT 300");
                if ($st) {
                    $st->bind_param('i', $studentId);
                    $st->execute();
                    $all = $st->get_result()->fetch_all(MYSQLI_ASSOC);

                    $seen = [];
                    foreach ($all as $r) {
                        $key = $qaQuiz && isset($r[$qaQuiz]) ? 'q_' . $r[$qaQuiz] : 'row_' . ($r['id'] ?? uniqid());
                        if (isset($seen[$key])) continue;
                        $seen[$key] = true;

                        $quizId = $qaQuiz ? (int)($r[$qaQuiz] ?? 0) : 0;
                        $score = $qaScore ? sfr_num($r[$qaScore] ?? 0) : 0;
                        $total = $qaTotal ? sfr_num($r[$qaTotal] ?? 0) : 0;

                        if ($total <= 0 && $questionTable && $quizId > 0) {
                            $qQuizCol = sfr_first_col($mysqli, $questionTable, ['quiz_id', 'lms_quiz_id']);
                            $qPointCol = sfr_first_col($mysqli, $questionTable, ['points', 'mark', 'marks', 'score']);
                            if ($qQuizCol) {
                                if ($qPointCol) {
                                    $st2 = $mysqli->prepare("SELECT COALESCE(SUM(`$qPointCol`),0) AS t FROM `$questionTable` WHERE `$qQuizCol` = ?");
                                } else {
                                    $st2 = $mysqli->prepare("SELECT COUNT(*) AS t FROM `$questionTable` WHERE `$qQuizCol` = ?");
                                }
                                if ($st2) {
                                    $st2->bind_param('i', $quizId);
                                    $st2->execute();
                                    $x = $st2->get_result()->fetch_assoc();
                                    $total = sfr_num($x['t'] ?? 0);
                                }
                            }
                        }

                        $percent = $qaPercent && isset($r[$qaPercent]) && is_numeric($r[$qaPercent])
                            ? round((float)$r[$qaPercent], 2)
                            : ($total > 0 ? round(($score / $total) * 100, 2) : 0);

                        $statusRaw = $qaStatus ? strtolower((string)($r[$qaStatus] ?? '')) : '';
                        $pf = ($statusRaw === '1' || $statusRaw === 'pass' || $statusRaw === 'passed')
                            ? 'Pass'
                            : (($statusRaw === '0' || str_contains($statusRaw, 'fail')) ? 'Fail' : ($percent >= 50 ? 'Pass' : 'Fail'));

                        $quizRows[] = [
                            'title'   => $r['quiz_title'] ?? ($quizId ? 'Quiz #' . $quizId : 'Quiz'),
                            'score'   => $score,
                            'total'   => $total,
                            'percent' => $percent,
                            'status'  => $pf,
                            'date'    => $qaDate ? ($r[$qaDate] ?? '') : '',
                        ];
                    }
                }
            }
        }

        if ($submissionTable) {
            $sStudent    = sfr_first_col($mysqli, $submissionTable, ['student_id', 'user_id']);
            $sAssessment = sfr_first_col($mysqli, $submissionTable, ['assessment_id', 'lms_assessment_id']);
$sScore = sfr_first_col($mysqli, $submissionTable, [
    'final_score',
    'provisional_score',
    'score',
    'marks',
    'mark',
    'marks_obtained',
    'obtained_marks',
    'awarded_marks',
    'total_score',
    'grade',
    'percentage',
    'percent'
]);            $sStatus     = sfr_first_col($mysqli, $submissionTable, ['workflow_status', 'status', 'submission_status']);
            $sFeedback   = sfr_first_col($mysqli, $submissionTable, ['feedback', 'lecturer_feedback', 'remarks', 'comment']);
            $sDate       = sfr_first_col($mysqli, $submissionTable, ['released_at', 'marked_at', 'updated_at', 'submitted_at', 'created_at']);
            $sBatch      = sfr_first_col($mysqli, $submissionTable, ['batch_id']);
            $sJson       = sfr_first_col($mysqli, $submissionTable, ['payload', 'meta', 'data', 'result_json', 'marking_json']);

            $aTitle  = $assessmentTable ? sfr_first_col($mysqli, $assessmentTable, ['title', 'assessment_title', 'name']) : '';
            $aBatch  = $assessmentTable ? sfr_first_col($mysqli, $assessmentTable, ['batch_id']) : '';
            $aCourse = $assessmentTable ? sfr_first_col($mysqli, $assessmentTable, ['course_id']) : '';

            $select = "s.*";
            $join = "";

            if ($assessmentTable && $sAssessment && $aTitle) {
                $select .= ", a.`$aTitle` AS assessment_title";
                $join .= " LEFT JOIN `$assessmentTable` a ON a.id = s.`$sAssessment`";
            }

            if ($batchTable) {
                $bLabel = sfr_first_col($mysqli, $batchTable, ['batch_name', 'name', 'code', 'batch_code', 'title']);
                $batchSource = $sBatch ? "s.`$sBatch`" : (($aBatch && $assessmentTable) ? "a.`$aBatch`" : "");
                if ($bLabel && $batchSource) {
                    $select .= ", b.`$bLabel` AS batch_title";
                    $join .= " LEFT JOIN `$batchTable` b ON b.id = $batchSource";
                }
            }

            if ($courseTable && $studentCourse === '' && $assessmentTable && $aCourse) {
                $cLabel = sfr_first_col($mysqli, $courseTable, ['course_name', 'name', 'title', 'code']);
                if ($cLabel) {
                    $select .= ", c.`$cLabel` AS course_title";
                    $join .= " LEFT JOIN `$courseTable` c ON c.id = a.`$aCourse`";
                }
            }

            if ($sStudent) {
                $order = $sDate ? "s.`$sDate` DESC" : "s.id DESC";
                $st = $mysqli->prepare("SELECT $select FROM `$submissionTable` s $join WHERE s.`$sStudent` = ? ORDER BY $order, s.id DESC LIMIT 300");
                if ($st) {
                    $st->bind_param('i', $studentId);
                    $st->execute();
                    $all = $st->get_result()->fetch_all(MYSQLI_ASSOC);

                    $seen = [];
                    foreach ($all as $r) {
                        $key = $sAssessment && isset($r[$sAssessment]) ? 'a_' . $r[$sAssessment] : 'row_' . ($r['id'] ?? uniqid());
                        if (isset($seen[$key])) continue;
                        $seen[$key] = true;

                        $scoreVal = $sScore ? (string)($r[$sScore] ?? '') : '';
                        if ($scoreVal === '' && $sJson) {
                            $scoreVal = sfr_value_from_json($r[$sJson] ?? '', ['score', 'marks', 'mark', 'final_score', 'total_score', 'percentage', 'percent']);
                        }

                        $batchVal = (string)($r['batch_title'] ?? '');
                        if ($studentBatch === '' && $batchVal !== '') $studentBatch = $batchVal;

                        if ($studentCourse === '' && isset($r['course_title']) && $r['course_title'] !== '') {
                            $studentCourse = (string)$r['course_title'];
                        }

                        $assessmentRows[] = [
                            'title'    => $r['assessment_title'] ?? (($sAssessment && isset($r[$sAssessment])) ? 'Assessment #' . $r[$sAssessment] : 'Assessment'),
                            'batch'    => $batchVal,
                            'score'    => $scoreVal,
                            'status'   => $sStatus ? ($r[$sStatus] ?? '') : '',
                            'feedback' => $sFeedback ? ($r[$sFeedback] ?? '') : '',
                            'date'     => $sDate ? ($r[$sDate] ?? '') : '',
                        ];
                    }
                }
            }
        }
    }
}

$quizTotal = count($quizRows);
$quizAvg = $quizTotal ? round(array_sum(array_column($quizRows, 'percent')) / $quizTotal, 2) : 0;
$assTotal = count($assessmentRows);

$assScores = [];
foreach ($assessmentRows as $ar) {
    if (is_numeric($ar['score'])) $assScores[] = (float)$ar['score'];
}
$assAvg = $assScores ? round(array_sum($assScores) / count($assScores), 2) : 0;

$passCount = 0;
$failCount = 0;

foreach ($quizRows as $qr) {
    ($qr['status'] === 'Pass') ? $passCount++ : $failCount++;
}
foreach ($assessmentRows as $ar) {
    if (is_numeric($ar['score'])) {
        ((float)$ar['score'] >= 50) ? $passCount++ : $failCount++;
    }
}

if (isset($_GET['export']) && $_GET['export'] === 'csv' && $student) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=student_full_report_' . $studentId . '.csv');
    $out = fopen('php://output', 'w');

    fputcsv($out, ['Student Full Report']);
    fputcsv($out, ['Name', $studentName]);
    fputcsv($out, ['Reg No', $studentReg]);
    fputcsv($out, ['Reference No', $studentRef]);
    fputcsv($out, ['NIC', $studentNic]);
    fputcsv($out, ['Batch', $studentBatch]);
    fputcsv($out, ['Course', $studentCourse]);
    fputcsv($out, []);

    fputcsv($out, ['Quiz Report']);
    fputcsv($out, ['Title', 'Score', 'Total', '%', 'Pass/Fail', 'Attempted Date']);
    foreach ($quizRows as $r) {
        fputcsv($out, [$r['title'], $r['score'], $r['total'], $r['percent'], $r['status'], $r['date']]);
    }

    fputcsv($out, []);
    fputcsv($out, ['Assessment Report']);
    fputcsv($out, ['Title', 'Batch', 'Score', 'Workflow Status', 'Feedback', 'Last Action Date']);
    foreach ($assessmentRows as $r) {
        fputcsv($out, [$r['title'], $r['batch'], $r['score'], $r['status'], $r['feedback'], $r['date']]);
    }

    fclose($out);
    exit;
}

$PAGE_TITLE = 'Student Full Report';
$ACTIVE = 'reports';

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

<style>
.sfr-wrap{width:100%;max-width:none;margin:0;padding:0 18px 28px}
.sfr-card{background:#fff;border:1px solid #dbe3ef;border-radius:16px;box-shadow:0 8px 22px rgba(15,23,42,.035)}
.sfr-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap;margin:0 0 14px}
.sfr-title{font-size:24px;font-weight:900;color:#0f172a;margin:0}
.sfr-sub{color:#64748b;margin:4px 0 0;font-size:13px}
.sfr-search{padding:16px;margin-bottom:14px!important}
.sfr-search .form-control-lg,.sfr-search .btn-lg{height:44px;font-size:15px;border-radius:8px}
.sfr-profile{display:grid;grid-template-columns:repeat(6,1fr);gap:8px;padding:10px;margin-bottom:14px}
.sfr-info{background:#fff;border:1px solid #dbe3ef;border-radius:12px;padding:13px 14px;min-height:58px}
.sfr-info small{display:block;color:#475569;font-weight:800;font-size:11px;margin-bottom:6px}
.sfr-info b{color:#020617;font-size:14px;font-weight:900}
.sfr-grid{display:grid;grid-template-columns:repeat(6,1fr);gap:8px;margin:0 0 14px}
.sfr-kpi{padding:16px 15px;border-radius:14px;background:#fff;border:1px solid #dbe3ef;box-shadow:0 8px 20px rgba(15,23,42,.035);min-height:78px}
.sfr-kpi .num{font-size:25px;line-height:1;font-weight:950;color:#020617;margin-bottom:8px}
.sfr-kpi .lbl{font-size:13px;color:#334155;font-weight:700}
.sfr-table-card{padding:16px;margin-bottom:14px}
.sfr-table-card h5{font-size:18px;margin-bottom:12px!important}
.sfr-table-card .table{margin-bottom:0}
.sfr-table-card .table thead th{font-size:11px;text-transform:uppercase;letter-spacing:.04em;color:#475569;background:#f8fafc;border-bottom:1px solid #dbe3ef;padding:10px 8px}
.sfr-table-card .table tbody td{padding:12px 8px;vertical-align:middle;border-bottom:1px solid #e5e7eb}
.badge-soft-success{background:#dcfce7;color:#166534}
.badge-soft-danger{background:#fee2e2;color:#991b1b}
.badge-soft-secondary{background:#e5e7eb;color:#374151}
.badge-soft-success,.badge-soft-danger,.badge-soft-secondary{padding:5px 10px;border-radius:999px;font-size:11px;font-weight:800}
@media(max-width:1200px){.sfr-profile,.sfr-grid{grid-template-columns:repeat(3,1fr)}}
@media(max-width:650px){.sfr-wrap{padding:0 10px 18px}.sfr-profile,.sfr-grid{grid-template-columns:1fr}}
</style>

<div class="sfr-wrap">
    <div class="sfr-head">
        <div>
            <h1 class="sfr-title">Student Full Report</h1>
            <p class="sfr-sub">Quiz attempts, assessment submissions, scores and workflow summary.</p>
        </div>
        <?php if ($student): ?>
            <a class="btn btn-success" href="?student_id=<?= (int)$studentId ?>&export=csv">Export CSV</a>
        <?php endif; ?>
    </div>

    <div class="sfr-card sfr-search mb-3">
        <form method="get" class="row g-2 align-items-end">
            <div class="col-lg-9">
                <label class="form-label fw-bold">Search Student</label>
                <input type="text" name="q" value="<?= h($q) ?>" class="form-control form-control-lg"
                       placeholder="Search by name, NEC / reference no, reg no, NIC">
            </div>
            <div class="col-lg-3 d-grid">
                <button class="btn btn-primary btn-lg">Search</button>
            </div>
        </form>

        <?php if ($q !== ''): ?>
            <div class="table-responsive mt-3">
                <table class="table table-hover align-middle mb-0">
                    <thead>
                    <tr>
                        <th>Name</th>
                        <th>Reg No</th>
                        <th>Reference No</th>
                        <th>NIC</th>
                        <th class="text-end">Action</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php if (!$students): ?>
                        <tr><td colspan="5" class="text-center text-muted py-4">No students found.</td></tr>
                    <?php else: ?>
                        <?php foreach ($students as $s): ?>
                            <?php $sid = (int)($s[$sidCol] ?? 0); ?>
                            <tr>
                                <td class="fw-bold"><?= h($nameCol ? ($s[$nameCol] ?? '') : '') ?></td>
                                <td><?= h($regCol ? ($s[$regCol] ?? '') : '') ?></td>
                                <td><?= h($refCol ? ($s[$refCol] ?? '') : '') ?></td>
                                <td><?= h($nicCol ? ($s[$nicCol] ?? '') : '-') ?></td>
                                <td class="text-end">
                                    <a class="btn btn-sm btn-dark" href="?student_id=<?= $sid ?>">Open Report</a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>

    <?php if (!$student): ?>
        <div class="alert alert-info">Search and select a student to view the full report.</div>
    <?php else: ?>

        <div class="sfr-card sfr-profile">
            <div class="sfr-info"><small>Name</small><b><?= h($studentName ?: '-') ?></b></div>
            <div class="sfr-info"><small>Reg No</small><b><?= h($studentReg ?: '-') ?></b></div>
            <div class="sfr-info"><small>Reference No</small><b><?= h($studentRef ?: '-') ?></b></div>
            <div class="sfr-info"><small>NIC</small><b><?= h($studentNic ?: '-') ?></b></div>
            <div class="sfr-info"><small>Batch</small><b><?= h($studentBatch ?: '-') ?></b></div>
            <div class="sfr-info"><small>Course</small><b><?= h($studentCourse ?: '-') ?></b></div>
        </div>

        <div class="sfr-grid">
            <div class="sfr-kpi"><div class="num"><?= (int)$quizTotal ?></div><div class="lbl">Total Quizzes</div></div>
            <div class="sfr-kpi"><div class="num"><?= h($quizAvg) ?>%</div><div class="lbl">Average Quiz %</div></div>
            <div class="sfr-kpi"><div class="num"><?= (int)$assTotal ?></div><div class="lbl">Total Assessments</div></div>
<div class="sfr-kpi">
    <div class="num"><?= $assAvg > 0 ? h(number_format($assAvg, 1)) : '0' ?></div>
    <div class="lbl">Average Assessment Score</div>
</div>            <div class="sfr-kpi"><div class="num"><?= (int)$passCount ?></div><div class="lbl">Pass Count</div></div>
            <div class="sfr-kpi"><div class="num"><?= (int)$failCount ?></div><div class="lbl">Fail Count</div></div>
        </div>

        <div class="sfr-card sfr-table-card">
            <h5 class="fw-bold mb-3">Quiz Report - Latest Attempts</h5>
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead>
                    <tr>
                        <th>Title</th>
                        <th>Score</th>
                        <th>Total</th>
                        <th>%</th>
                        <th>Pass/Fail</th>
                        <th>Attempted Date</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php if (!$quizRows): ?>
                        <tr><td colspan="6" class="text-center text-muted py-4">No quiz attempts found.</td></tr>
                    <?php else: ?>
                        <?php foreach ($quizRows as $r): ?>
                            <tr>
                                <td class="fw-bold"><?= h($r['title']) ?></td>
                                <td><?= h($r['score']) ?></td>
                                <td><?= h($r['total']) ?></td>
                                <td><?= h($r['percent']) ?>%</td>
                                <td>
                                    <span class="badge <?= $r['status'] === 'Pass' ? 'badge-soft-success' : 'badge-soft-danger' ?>">
                                        <?= h($r['status']) ?>
                                    </span>
                                </td>
                                <td><?= h($r['date'] ?: '-') ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="sfr-card sfr-table-card">
            <h5 class="fw-bold mb-3">Assessment Report - Latest Submissions</h5>
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead>
                    <tr>
                        <th>Title</th>
                        <th>Batch</th>
                        <th>Score</th>
                        <th>Workflow Status</th>
                        <th>Feedback</th>
                        <th>Last Action Date</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php if (!$assessmentRows): ?>
                        <tr><td colspan="6" class="text-center text-muted py-4">No assessment submissions found.</td></tr>
                    <?php else: ?>
                        <?php foreach ($assessmentRows as $r): ?>
                            <tr>
                                <td class="fw-bold"><?= h($r['title']) ?></td>
                                <td><?= h($r['batch'] ?: '-') ?></td>
                                <td><?= h($r['score'] !== '' ? $r['score'] : '-') ?></td>
                                <td><span class="badge badge-soft-secondary"><?= h($r['status'] ?: '-') ?></span></td>
                                <td><?= h($r['feedback'] ?: '-') ?></td>
                                <td><?= h($r['date'] ?: '-') ?></td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

    <?php endif; ?>
</div>

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