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

$PAGE_TITLE = 'Dashboard';
$ACTIVE = 'dashboard';

require_once __DIR__ . '/../includes/admin_auth.php';

/*
|--------------------------------------------------------------------------
| DB
|--------------------------------------------------------------------------
*/

$db = null;

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

if (!$db instanceof mysqli) {
    http_response_code(500);
    exit('Database connection failed.');
}

$db->set_charset('utf8mb4');

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

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

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

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

    return null;
}

function ad_count(mysqli $db, string $table): int {
    if (!ad_tbl($db, $table)) return 0;

    $safe = preg_replace('/[^a-zA-Z0-9_]/', '', $table);
    $res = $db->query("SELECT COUNT(*) AS c FROM `{$safe}`");

    if (!$res) return 0;

    $row = $res->fetch_assoc();
    $res->free();

    return (int)($row['c'] ?? 0);
}

function ad_count_where(mysqli $db, string $table, string $where): int {
    if (!ad_tbl($db, $table)) return 0;

    $safe = preg_replace('/[^a-zA-Z0-9_]/', '', $table);
    $res = $db->query("SELECT COUNT(*) AS c FROM `{$safe}` WHERE {$where}");

    if (!$res) return 0;

    $row = $res->fetch_assoc();
    $res->free();

    return (int)($row['c'] ?? 0);
}

function ad_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 ad_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 ad_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',
    };
}

/*
|--------------------------------------------------------------------------
| Core counts
|--------------------------------------------------------------------------
*/

$totalLearners = ad_count($db, 'studentss');

$totalCourses     = ad_count($db, 'courses');
$totalBatches     = ad_count($db, 'batches');
$totalModules     = ad_count($db, 'course_modules');
$totalLecturers   = ad_count($db, 'lecturers');
$totalAssessments = ad_count($db, 'lms_assessments');
$totalSubmissions = ad_count($db, 'lms_submissions');

$activeBatches = 0;
if (ad_tbl($db, 'batches') && ad_col($db, 'batches', 'status')) {
    $activeBatches = ad_count_where($db, 'batches', "LOWER(COALESCE(status,'')) IN ('active','1','open','ongoing')");
} else {
    $activeBatches = $totalBatches;
}

$activeAssessments = 0;
if (ad_tbl($db, 'lms_assessments')) {
    if (ad_col($db, 'lms_assessments', 'active')) {
        $activeAssessments = ad_count_where($db, 'lms_assessments', "active = 1");
    } elseif (ad_col($db, 'lms_assessments', 'is_active')) {
        $activeAssessments = ad_count_where($db, 'lms_assessments', "is_active = 1");
    } else {
        $activeAssessments = $totalAssessments;
    }
}

/*
|--------------------------------------------------------------------------
| Workflow counts
|--------------------------------------------------------------------------
*/

$pendingLecturerMarking = 0;
$needsCorrection = 0;
$provisional = 0;
$underReview = 0;
$approvedNotReleased = 0;
$releasedResults = 0;

if (ad_tbl($db, 'lms_submissions') && ad_col($db, 'lms_submissions', 'workflow_status')) {
    $pendingLecturerMarking = ad_count_where($db, 'lms_submissions', "LOWER(COALESCE(workflow_status,'')) IN ('submitted','pending','')");
    $needsCorrection        = ad_count_where($db, 'lms_submissions', "LOWER(COALESCE(workflow_status,'')) = 'needs_correction'");
    $provisional            = ad_count_where($db, 'lms_submissions', "LOWER(COALESCE(workflow_status,'')) = 'graded_provisional'");
    $underReview            = ad_count_where($db, 'lms_submissions', "LOWER(COALESCE(workflow_status,'')) IN ('under_review','coord_review','coordinator_review','admin_review')");
    $approvedNotReleased    = ad_count_where($db, 'lms_submissions', "LOWER(COALESCE(workflow_status,'')) IN ('coord_approved','approved')");
    $releasedResults        = ad_count_where($db, 'lms_submissions', "LOWER(COALESCE(workflow_status,'')) IN ('released','published')");
}

/*
|--------------------------------------------------------------------------
| Workflow breakdown
|--------------------------------------------------------------------------
*/

$workflowBreakdown = [];

if (ad_tbl($db, 'lms_submissions') && ad_col($db, 'lms_submissions', 'workflow_status')) {
    $res = $db->query("
        SELECT 
            LOWER(COALESCE(NULLIF(workflow_status,''), 'submitted')) AS status,
            COUNT(*) AS total
        FROM lms_submissions
        GROUP BY LOWER(COALESCE(NULLIF(workflow_status,''), 'submitted'))
        ORDER BY total DESC
    ");

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

/*
|--------------------------------------------------------------------------
| Recent submissions
|--------------------------------------------------------------------------
*/

$recentSubmissions = [];

if (ad_tbl($db, 'lms_submissions')) {
    $studentTable = ad_tbl($db, 'studentss') ? 'studentss' : (ad_tbl($db, 'students') ? 'students' : null);
    $studentNameCol = $studentTable ? (ad_first_col($db, $studentTable, ['full_name', 'name', 'student_name']) ?? 'id') : null;
    $regCol = $studentTable ? ad_first_col($db, $studentTable, ['center_reg_no', 'reference_no', 'reg_no']) : null;

    $studentJoin = '';
    $studentNameExpr = "CONCAT('Student #', s.student_id)";
    $regExpr = "'' 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 ($regCol) {
            $regExpr = "st.`{$regCol}` AS reg_no";
        }
    }

    $assessmentJoin = '';
    $assessmentExpr = "CONCAT('Assessment #', s.assessment_id)";
    $maxScoreExpr = "100 AS max_score";

    if (ad_tbl($db, 'lms_assessments')) {
        $assessmentJoin = "LEFT JOIN lms_assessments a ON a.id = s.assessment_id";
        $assessmentExpr = "COALESCE(a.title, CONCAT('Assessment #', s.assessment_id))";
        $maxScoreExpr = ad_col($db, 'lms_assessments', 'max_score') ? "COALESCE(a.max_score, 100) AS max_score" : "100 AS max_score";
    }

    $submittedExpr = ad_col($db, 'lms_submissions', 'submitted_at') ? "s.submitted_at" : "NULL AS submitted_at";
    $workflowExpr = ad_col($db, 'lms_submissions', 'workflow_status') ? "s.workflow_status" : "'submitted' AS workflow_status";
    $scoreExpr = ad_col($db, 'lms_submissions', 'final_score') ? "s.final_score" : "NULL AS final_score";

    $sql = "
        SELECT
            s.id,
            s.student_id,
            s.assessment_id,
            {$studentNameExpr} AS student_name,
            {$regExpr},
            {$assessmentExpr} AS assessment_title,
            {$workflowExpr},
            {$scoreExpr},
            {$submittedExpr},
            {$maxScoreExpr}
        FROM lms_submissions s
        {$assessmentJoin}
        {$studentJoin}
        ORDER BY s.id DESC
        LIMIT 10
    ";

    $res = $db->query($sql);

    if ($res) {
        $recentSubmissions = $res->fetch_all(MYSQLI_ASSOC);
        $res->free();
    }
}

/*
|--------------------------------------------------------------------------
| Recent released results
|--------------------------------------------------------------------------
*/

$recentReleased = [];

if (ad_tbl($db, 'lms_submissions') && ad_col($db, 'lms_submissions', 'workflow_status')) {
    $studentTable = ad_tbl($db, 'studentss') ? 'studentss' : (ad_tbl($db, 'students') ? 'students' : null);
    $studentNameCol = $studentTable ? (ad_first_col($db, $studentTable, ['full_name', 'name', 'student_name']) ?? 'id') : null;
    $regCol = $studentTable ? ad_first_col($db, $studentTable, ['center_reg_no', 'reference_no', 'reg_no']) : null;

    $studentJoin = '';
    $studentNameExpr = "CONCAT('Student #', s.student_id)";
    $regExpr = "'' 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 ($regCol) {
            $regExpr = "st.`{$regCol}` AS reg_no";
        }
    }

    $assessmentJoin = '';
    $assessmentExpr = "CONCAT('Assessment #', s.assessment_id)";
    $maxScoreExpr = "100 AS max_score";

    if (ad_tbl($db, 'lms_assessments')) {
        $assessmentJoin = "LEFT JOIN lms_assessments a ON a.id = s.assessment_id";
        $assessmentExpr = "COALESCE(a.title, CONCAT('Assessment #', s.assessment_id))";
        $maxScoreExpr = ad_col($db, 'lms_assessments', 'max_score') ? "COALESCE(a.max_score, 100) AS max_score" : "100 AS max_score";
    }

    $releasedExpr = ad_col($db, 'lms_submissions', 'released_at') ? "s.released_at" : "NULL AS released_at";
    $scoreExpr = ad_col($db, 'lms_submissions', 'final_score') ? "s.final_score" : "NULL AS final_score";

    $sql = "
        SELECT
            s.id,
            s.student_id,
            s.assessment_id,
            {$studentNameExpr} AS student_name,
            {$regExpr},
            {$assessmentExpr} AS assessment_title,
            {$scoreExpr},
            {$maxScoreExpr},
            {$releasedExpr}
        FROM lms_submissions s
        {$assessmentJoin}
        {$studentJoin}
        WHERE LOWER(COALESCE(s.workflow_status,'')) IN ('released','published')
        ORDER BY s.released_at DESC, s.id DESC
        LIMIT 8
    ";

    $res = $db->query($sql);

    if ($res) {
        $recentReleased = $res->fetch_all(MYSQLI_ASSOC);
        $res->free();
    }
}

/*
|--------------------------------------------------------------------------
| Assessment progress summary
|--------------------------------------------------------------------------
*/

$assessmentProgress = [];

if (ad_tbl($db, 'lms_assessments')) {
    $courseJoin = '';
    $courseNameExpr = "CONCAT('Course #', a.course_id)";

    if (ad_tbl($db, 'courses')) {
        $courseNameCol = ad_first_col($db, 'courses', ['course_name', 'name', 'title', 'label']) ?? 'id';
        $courseJoin = "LEFT JOIN courses c ON c.id = a.course_id";
        $courseNameExpr = "COALESCE(c.`{$courseNameCol}`, CONCAT('Course #', a.course_id))";
    }

    $sql = "
        SELECT
            a.id,
            COALESCE(a.title, CONCAT('Assessment #', a.id)) AS title,
            {$courseNameExpr} AS course_name,
            COUNT(s.id) AS submission_count,
            SUM(CASE WHEN LOWER(COALESCE(s.workflow_status,'')) IN ('submitted','pending','') THEN 1 ELSE 0 END) AS pending_count,
            SUM(CASE WHEN LOWER(COALESCE(s.workflow_status,'')) IN ('under_review','coord_review','coordinator_review','admin_review') THEN 1 ELSE 0 END) AS review_count,
            SUM(CASE WHEN LOWER(COALESCE(s.workflow_status,'')) IN ('coord_approved','approved') THEN 1 ELSE 0 END) AS approved_count,
            SUM(CASE WHEN LOWER(COALESCE(s.workflow_status,'')) IN ('released','published') THEN 1 ELSE 0 END) AS released_count
        FROM lms_assessments a
        LEFT JOIN lms_submissions s ON s.assessment_id = a.id
        {$courseJoin}
        GROUP BY a.id
        ORDER BY a.id DESC
        LIMIT 8
    ";

    $res = $db->query($sql);

    if ($res) {
        $assessmentProgress = $res->fetch_all(MYSQLI_ASSOC);
        $res->free();
    }
}

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

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

    .dash-title {
        font-size: 28px;
        font-weight: 950;
        letter-spacing: -.04em;
        color: #0f172a;
        margin: 0;
    }

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

    .dash-kpi {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 18px;
        padding: 16px;
        height: 100%;
        box-shadow: 0 8px 22px rgba(15, 23, 42, .045);
    }

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

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

    .dash-icon {
        width: 46px;
        height: 46px;
        border-radius: 16px;
        display: grid;
        place-items: center;
        font-size: 22px;
    }

    .dash-card {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 18px;
        box-shadow: 0 8px 22px rgba(15, 23, 42, .045);
        overflow: hidden;
    }

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

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

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

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

    .workflow-pill {
        display: flex;
        align-items: center;
        justify-content: space-between;
        border: 1px solid #e5e7eb;
        border-radius: 14px;
        padding: 10px 12px;
        background: #fff;
        margin-bottom: 8px;
    }

    .progress-thin {
        height: 8px;
        border-radius: 999px;
    }

    .quick-card {
        display: block;
        text-decoration: none;
        height: 100%;
    }

    .quick-card-inner {
        border: 1px solid #e5e7eb;
        background: #f8fafc;
        border-radius: 16px;
        padding: 16px;
        height: 100%;
        transition: .15s ease;
    }

    .quick-card-inner:hover {
        background: #eef6ff;
        border-color: #bfdbfe;
        transform: translateY(-1px);
    }
</style>

<div class="dash-hero">
    <div class="d-flex flex-column flex-lg-row justify-content-between gap-3">
        <div>
            <h1 class="dash-title">Admin Dashboard</h1>
            <div class="dash-sub">
                Final ELMS overview: students, assessments, submissions, marking workflow, releases and quick actions.
            </div>
        </div>

        <div class="d-flex flex-wrap gap-2 align-items-start">
            <a href="/elms/admin/assessments.php" class="btn btn-admin-primary">
                <i class="bi bi-plus-circle me-1"></i>
                New Assessment
            </a>
            <a href="/elms/admin/reports.php" class="btn btn-outline-primary rounded-pill">
                <i class="bi bi-bar-chart me-1"></i>
                Reports
            </a>
            <a href="/elms/admin/release.php" class="btn btn-outline-success rounded-pill">
                <i class="bi bi-send-check me-1"></i>
                Release
            </a>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-xl-3 col-md-6">
        <div class="dash-kpi">
            <div class="d-flex justify-content-between">
                <div>
                    <div class="dash-kpi-label">Total Students</div>
                    <div class="dash-kpi-value"><?= number_format($totalLearners) ?></div>
                </div>
                <div class="dash-icon bg-primary-subtle text-primary">
                    <i class="bi bi-people"></i>
                </div>
            </div>
            <a href="/elms/admin/student/" class="btn btn-sm btn-admin-primary mt-3">View Students</a>
        </div>
    </div>

    <div class="col-xl-3 col-md-6">
        <div class="dash-kpi">
            <div class="d-flex justify-content-between">
                <div>
                    <div class="dash-kpi-label">Active Batches</div>
                    <div class="dash-kpi-value"><?= number_format($activeBatches) ?></div>
                </div>
                <div class="dash-icon bg-warning-subtle text-warning">
                    <i class="bi bi-calendar2-week"></i>
                </div>
            </div>
            <a href="/elms/admin/batches" class="btn btn-sm btn-outline-warning rounded-pill mt-3">Manage Batches</a>
        </div>
    </div>

    <div class="col-xl-3 col-md-6">
        <div class="dash-kpi">
            <div class="d-flex justify-content-between">
                <div>
                    <div class="dash-kpi-label">Active Assessments</div>
                    <div class="dash-kpi-value"><?= number_format($activeAssessments) ?></div>
                </div>
                <div class="dash-icon bg-success-subtle text-success">
                    <i class="bi bi-clipboard-check"></i>
                </div>
            </div>
            <a href="/elms/admin/assessments" class="btn btn-sm btn-outline-success rounded-pill mt-3">Assessments</a>
        </div>
    </div>

    <div class="col-xl-3 col-md-6">
        <div class="dash-kpi">
            <div class="d-flex justify-content-between">
                <div>
                    <div class="dash-kpi-label">Total Submissions</div>
                    <div class="dash-kpi-value"><?= number_format($totalSubmissions) ?></div>
                </div>
                <div class="dash-icon bg-info-subtle text-info">
                    <i class="bi bi-inboxes"></i>
                </div>
            </div>
            <a href="/elms/admin/assessments/submissions.php" class="btn btn-sm btn-outline-info rounded-pill mt-3">Submissions</a>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-xl-2 col-md-4">
        <div class="dash-kpi">
            <div class="dash-kpi-label">Pending Marking</div>
            <div class="dash-kpi-value text-warning"><?= number_format($pendingLecturerMarking) ?></div>
        </div>
    </div>

    <div class="col-xl-2 col-md-4">
        <div class="dash-kpi">
            <div class="dash-kpi-label">Correction</div>
            <div class="dash-kpi-value text-danger"><?= number_format($needsCorrection) ?></div>
        </div>
    </div>

    <div class="col-xl-2 col-md-4">
        <div class="dash-kpi">
            <div class="dash-kpi-label">Provisional</div>
            <div class="dash-kpi-value text-primary"><?= number_format($provisional) ?></div>
        </div>
    </div>

    <div class="col-xl-2 col-md-4">
        <div class="dash-kpi">
            <div class="dash-kpi-label">Under Review</div>
            <div class="dash-kpi-value text-info"><?= number_format($underReview) ?></div>
        </div>
    </div>

    <div class="col-xl-2 col-md-4">
        <div class="dash-kpi">
            <div class="dash-kpi-label">Approved</div>
            <div class="dash-kpi-value text-success"><?= number_format($approvedNotReleased) ?></div>
        </div>
    </div>

    <div class="col-xl-2 col-md-4">
        <div class="dash-kpi">
            <div class="dash-kpi-label">Released</div>
            <div class="dash-kpi-value text-success"><?= number_format($releasedResults) ?></div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-xl-8">
        <div class="dash-card h-100">
            <div class="dash-card-head">
                <div>
                    <h5 class="fw-bold mb-1">Assessment Progress Summary</h5>
                    <div class="text-muted small">Latest assessments with submission, review, approved and released counts.</div>
                </div>

                <a href="/elms/admin/assessments.php" class="btn btn-sm btn-outline-primary rounded-pill">
                    View Assessments
                </a>
            </div>

            <div class="table-responsive">
                <table class="table table-hover align-middle table-dash mb-0">
                    <thead>
                        <tr>
                            <th>Assessment</th>
                            <th>Course</th>
                            <th class="text-center">Submissions</th>
                            <th class="text-center">Pending</th>
                            <th class="text-center">Review</th>
                            <th class="text-center">Approved</th>
                            <th class="text-center">Released</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php if (!$assessmentProgress): ?>
                            <tr>
                                <td colspan="7" class="text-center text-muted py-5">
                                    <i class="bi bi-inbox fs-2 d-block mb-2"></i>
                                    No assessment records found.
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($assessmentProgress as $row): ?>
                                <tr>
                                    <td>
                                        <div class="fw-bold"><?= h($row['title'] ?? '-') ?></div>
                                        <div class="small text-muted">ID: <?= (int)$row['id'] ?></div>
                                    </td>

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

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

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

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

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

                                    <td class="text-center">
                                        <span class="badge text-bg-success"><?= (int)$row['released_count'] ?></span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <div class="col-xl-4">
        <div class="dash-card h-100">
            <div class="dash-card-head">
                <div>
                    <h5 class="fw-bold mb-1">Workflow Status Breakdown</h5>
                    <div class="text-muted small">Current submission pipeline.</div>
                </div>
            </div>

            <div class="dash-card-body">
                <?php if (!$workflowBreakdown): ?>
                    <div class="text-center text-muted py-4">
                        <i class="bi bi-pie-chart fs-2 d-block mb-2"></i>
                        No workflow records found.
                    </div>
                <?php else: ?>
                    <?php foreach ($workflowBreakdown as $row): ?>
                        <?php
                            $st = strtolower((string)($row['status'] ?? 'submitted'));
                            $total = (int)($row['total'] ?? 0);
                            $pct = $totalSubmissions > 0 ? round(($total / $totalSubmissions) * 100, 1) : 0;
                        ?>
                        <div class="workflow-pill">
                            <div>
                                <span class="badge <?= h(ad_status_badge($st)) ?>">
                                    <?= h(ucwords(str_replace('_', ' ', $st))) ?>
                                </span>
                                <div class="small text-muted mt-1"><?= number_format($pct, 1) ?>%</div>
                            </div>

                            <strong><?= number_format($total) ?></strong>
                        </div>

                        <div class="progress progress-thin mb-2">
                            <div class="progress-bar bg-primary" style="width: <?= min(100, max(0, $pct)) ?>%"></div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-xl-7">
        <div class="dash-card h-100">
            <div class="dash-card-head">
                <div>
                    <h5 class="fw-bold mb-1">Recent Submissions</h5>
                    <div class="text-muted small">Latest submitted/updated assessment records.</div>
                </div>

                <a href="/elms/admin/submissions.php" class="btn btn-sm btn-outline-primary rounded-pill">
                    View All
                </a>
            </div>

            <div class="table-responsive">
                <table class="table table-hover align-middle table-dash mb-0">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Student</th>
                            <th>Assessment</th>
                            <th>Status</th>
                            <th>Submitted</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php if (!$recentSubmissions): ?>
                            <tr>
                                <td colspan="5" class="text-center text-muted py-5">
                                    <i class="bi bi-inbox fs-2 d-block mb-2"></i>
                                    No recent submissions found.
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($recentSubmissions as $row): ?>
                                <?php $wf = strtolower((string)($row['workflow_status'] ?? 'submitted')); ?>
                                <tr>
                                    <td class="text-muted">#<?= (int)$row['id'] ?></td>

                                    <td>
                                        <div class="fw-bold"><?= h($row['student_name'] ?? '-') ?></div>
                                        <?php if (!empty($row['reg_no'])): ?>
                                            <div class="small text-muted"><?= h($row['reg_no']) ?></div>
                                        <?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>
                                        <span class="badge <?= h(ad_status_badge($wf)) ?>">
                                            <?= h(ucwords(str_replace('_', ' ', $wf))) ?>
                                        </span>
                                    </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>
    </div>

    <div class="col-xl-5">
        <div class="dash-card h-100">
            <div class="dash-card-head">
                <div>
                    <h5 class="fw-bold mb-1">Recent Released Results</h5>
                    <div class="text-muted small">Latest results visible to students.</div>
                </div>

                <a href="/elms/admin/reports.php" class="btn btn-sm btn-outline-success rounded-pill">
                    Reports
                </a>
            </div>

            <div class="table-responsive">
                <table class="table table-hover align-middle table-dash mb-0">
                    <thead>
                        <tr>
                            <th>Student</th>
                            <th>Assessment</th>
                            <th>Score</th>
                            <th>Grade</th>
                        </tr>
                    </thead>

                    <tbody>
                        <?php if (!$recentReleased): ?>
                            <tr>
                                <td colspan="4" class="text-center text-muted py-5">
                                    <i class="bi bi-award fs-2 d-block mb-2"></i>
                                    No released results yet.
                                </td>
                            </tr>
                        <?php else: ?>
                            <?php foreach ($recentReleased as $row): ?>
                                <?php
                                    $score = (float)($row['final_score'] ?? 0);
                                    $max = (float)($row['max_score'] ?? 100);
                                    $grade = ad_grade($score, $max);
                                ?>
                                <tr>
                                    <td>
                                        <div class="fw-bold"><?= h($row['student_name'] ?? '-') ?></div>
                                        <?php if (!empty($row['reg_no'])): ?>
                                            <div class="small text-muted"><?= h($row['reg_no']) ?></div>
                                        <?php endif; ?>
                                    </td>

                                    <td>
                                        <div class="fw-semibold"><?= h($row['assessment_title'] ?? '-') ?></div>
                                    </td>

                                    <td>
                                        <strong><?= h((string)($row['final_score'] ?? '0')) ?></strong>
                                        / <?= h((string)($row['max_score'] ?? '100')) ?>
                                    </td>

                                    <td>
                                        <span class="badge <?= h(ad_grade_badge($grade)) ?>">
                                            <?= h($grade) ?>
                                        </span>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="dash-card">
    <div class="dash-card-head">
        <div>
            <h5 class="fw-bold mb-1">Quick Actions</h5>
            <div class="text-muted small">Common ELMS admin operations.</div>
        </div>
    </div>

    <div class="dash-card-body">
        <div class="row g-3">
            <div class="col-xl-3 col-md-6">
                <a href="/elms/admin/students.php" class="quick-card">
                    <div class="quick-card-inner">
                        <i class="bi bi-people fs-3 text-primary"></i>
                        <div class="fw-bold text-dark mt-2">Students</div>
                        <div class="small text-muted">View and manage learners</div>
                    </div>
                </a>
            </div>

            <div class="col-xl-3 col-md-6">
                <a href="/elms/admin/assessments.php" class="quick-card">
                    <div class="quick-card-inner">
                        <i class="bi bi-clipboard-plus fs-3 text-success"></i>
                        <div class="fw-bold text-dark mt-2">Create Assessment</div>
                        <div class="small text-muted">Assignment and project setup</div>
                    </div>
                </a>
            </div>

            <div class="col-xl-3 col-md-6">
                <a href="/elms/admin/marking.php" class="quick-card">
                    <div class="quick-card-inner">
                        <i class="bi bi-pencil-square fs-3 text-warning"></i>
                        <div class="fw-bold text-dark mt-2">Marking</div>
                        <div class="small text-muted">Review marking workflow</div>
                    </div>
                </a>
            </div>

            <div class="col-xl-3 col-md-6">
                <a href="/elms/admin/release.php" class="quick-card">
                    <div class="quick-card-inner">
                        <i class="bi bi-send-check fs-3 text-danger"></i>
                        <div class="fw-bold text-dark mt-2">Release Results</div>
                        <div class="small text-muted">Publish approved results</div>
                    </div>
                </a>
            </div>

            <div class="col-xl-3 col-md-6">
                <a href="/elms/admin/reports.php" class="quick-card">
                    <div class="quick-card-inner">
                        <i class="bi bi-bar-chart fs-3 text-info"></i>
                        <div class="fw-bold text-dark mt-2">Reports</div>
                        <div class="small text-muted">Progress and performance</div>
                    </div>
                </a>
            </div>

            <div class="col-xl-3 col-md-6">
                <a href="/elms/admin/courses.php" class="quick-card">
                    <div class="quick-card-inner">
                        <i class="bi bi-journal-bookmark fs-3 text-success"></i>
                        <div class="fw-bold text-dark mt-2">Courses</div>
                        <div class="small text-muted">Manage course records</div>
                    </div>
                </a>
            </div>

            <div class="col-xl-3 col-md-6">
                <a href="/elms/admin/batches.php" class="quick-card">
                    <div class="quick-card-inner">
                        <i class="bi bi-calendar2-week fs-3 text-warning"></i>
                        <div class="fw-bold text-dark mt-2">Batches</div>
                        <div class="small text-muted">Batch setup and schedule</div>
                    </div>
                </a>
            </div>

            <div class="col-xl-3 col-md-6">
                <a href="/elms/admin/settings.php" class="quick-card">
                    <div class="quick-card-inner">
                        <i class="bi bi-gear fs-3 text-secondary"></i>
                        <div class="fw-bold text-dark mt-2">Settings</div>
                        <div class="small text-muted">Portal configuration</div>
                    </div>
                </a>
            </div>
        </div>
    </div>
</div>

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