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

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

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

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, 'UTF-8');
    }
}

function cs_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 cs_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 cs_first_col(mysqli $db, string $table, array $cols): ?string {
    foreach ($cols as $col) {
        if (cs_col_exists($db, $table, $col)) {
            return $col;
        }
    }
    return null;
}

function cs_fetch_all_stmt(mysqli_stmt $stmt): array {
    $stmt->execute();
    $res = $stmt->get_result();
    if (!$res) return [];
    return $res->fetch_all(MYSQLI_ASSOC);
}

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

    if (preg_match('~^https?://~i', $path)) {
        return $path;
    }

    if (str_starts_with($path, '/elms/')) {
        return $path;
    }

    if (str_starts_with($path, '/uploads/')) {
        return '/elms' . $path;
    }

    if (str_starts_with($path, 'uploads/')) {
        return '/elms/' . $path;
    }

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

function cs_fmt_date($date): string {
    $date = trim((string)$date);

    if ($date === '' || $date === '0000-00-00' || $date === '0000-00-00 00:00:00') {
        return '<span class="text-muted">-</span>';
    }

    $time = strtotime($date);

    if (!$time) {
        return h($date);
    }

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

function cs_score_text(array $row): string {
    if (isset($row['final_score']) && $row['final_score'] !== null && $row['final_score'] !== '') {
        return (string)$row['final_score'];
    }

    return '-';
}

function cs_workflow_badge(string $workflow): array {
    $workflow = strtolower(trim($workflow));

    return match ($workflow) {
        'submitted', 'pending' => ['Submitted', 'text-bg-warning'],
        'needs_correction' => ['Needs Correction', 'text-bg-danger'],
        'graded_provisional' => ['Graded Provisional', 'text-bg-primary'],
        'under_review', 'coord_review', 'coordinator_review', 'admin_review' => ['Under Review', 'text-bg-info'],
        'coord_approved', 'approved' => ['Ready to Release', 'text-bg-success'],
        'released', 'published' => ['Released', 'text-bg-success'],
        default => [$workflow !== '' ? ucwords(str_replace('_', ' ', $workflow)) : 'Submitted', 'text-bg-secondary'],
    };
}

$error = '';
$summaryRows = [];
$submissionRows = [];

if (!cs_table_exists($db, 'lms_submissions')) {
    $error = 'lms_submissions table not found.';
} else {
    /*
    |--------------------------------------------------------------------------
    | Ensure important workflow columns exist
    |--------------------------------------------------------------------------
    */

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

    if (!cs_col_exists($db, 'lms_submissions', 'final_score')) {
        $db->query("ALTER TABLE lms_submissions ADD COLUMN final_score DECIMAL(10,2) NULL");
    }

    if (!cs_col_exists($db, 'lms_submissions', 'lecturer_feedback')) {
        $db->query("ALTER TABLE lms_submissions ADD COLUMN lecturer_feedback TEXT NULL");
    }

    if (!cs_col_exists($db, 'lms_submissions', 'released_at')) {
        $db->query("ALTER TABLE lms_submissions ADD COLUMN released_at DATETIME NULL");
    }

    $hasAssessments = cs_table_exists($db, 'lms_assessments');
    $hasBatches     = cs_table_exists($db, 'batches');
    $hasStudents    = cs_table_exists($db, 'studentss');
    $hasCourses     = cs_table_exists($db, 'courses');
    $hasModules     = cs_table_exists($db, 'course_modules');

    $studentNameCol = $hasStudents ? cs_first_col($db, 'studentss', ['full_name', 'name', 'student_name']) : null;
    $studentRegCol  = $hasStudents ? cs_first_col($db, 'studentss', ['center_reg_no', 'reg_no', 'registration_no', 'reference_no']) : null;

    $courseNameCol = $hasCourses ? cs_first_col($db, 'courses', ['course_name', 'name', 'title']) : null;
    $moduleNameCol = $hasModules ? cs_first_col($db, 'course_modules', ['title', 'module_name', 'name']) : null;

    $batchNameCol = $hasBatches ? cs_first_col($db, 'batches', ['batch_name', 'name', 'title']) : null;
    $batchCodeCol = $hasBatches ? cs_first_col($db, 'batches', ['batch_code', 'code']) : null;

    $hasBatchBranch = $hasBatches && cs_col_exists($db, 'batches', 'branch_id');

    /*
    |--------------------------------------------------------------------------
    | Branch scope
    |--------------------------------------------------------------------------
    */

    $branchIdsRaw = $_SESSION['branch_ids'] ?? ($_SESSION['user']['branch_ids'] ?? []);
    $branchIds = [];

    if (is_array($branchIdsRaw)) {
        $branchIds = array_values(array_filter(array_map('intval', $branchIdsRaw)));
    } elseif (is_string($branchIdsRaw) && trim($branchIdsRaw) !== '') {
        $decoded = json_decode($branchIdsRaw, true);
        if (is_array($decoded)) {
            $branchIds = array_values(array_filter(array_map('intval', $decoded)));
        } else {
            $branchIds = array_values(array_filter(array_map('intval', explode(',', $branchIdsRaw))));
        }
    }

    $singleBranchId = $_SESSION['branch_id'] ?? ($_SESSION['user']['branch_id'] ?? null);
    if (!$branchIds && !empty($singleBranchId)) {
        $branchIds[] = (int)$singleBranchId;
    }

    $branchIds = array_values(array_unique(array_filter($branchIds)));

    $scopeSql = '';
    $scopeParams = [];
    $scopeTypes = '';

    if ($hasBatchBranch && $branchIds) {
        $ph = implode(',', array_fill(0, count($branchIds), '?'));
        $scopeSql = " AND (b.branch_id IN ({$ph}) OR b.branch_id IS NULL) ";
        foreach ($branchIds as $bid) {
            $scopeParams[] = $bid;
            $scopeTypes .= 'i';
        }
    }

    /*
    |--------------------------------------------------------------------------
    | 1) Summary by assessment
    |--------------------------------------------------------------------------
    */

    if ($hasAssessments) {
        $assessmentTitleCol = cs_first_col($db, 'lms_assessments', ['title', 'name']) ?? 'id';

        $summarySelect = [
            "a.id AS assessment_id",
            "a.`{$assessmentTitleCol}` AS assessment_title",
            cs_col_exists($db, 'lms_assessments', 'available_from') ? "a.available_from" : "NULL AS available_from",
            cs_col_exists($db, 'lms_assessments', 'due_at') ? "a.due_at" : "NULL AS due_at",
            "COUNT(DISTINCT s.id) AS total_submissions",
            "MAX(s.submitted_at) AS last_submitted",

            "
            SUM(
                CASE 
                    WHEN LOWER(COALESCE(s.workflow_status,'')) IN ('submitted','pending') 
                    THEN 1 ELSE 0 
                END
            ) AS submitted_count
            ",

            "
            SUM(
                CASE 
                    WHEN LOWER(COALESCE(s.workflow_status,'')) = 'needs_correction' 
                    THEN 1 ELSE 0 
                END
            ) AS correction_count
            ",

            "
            SUM(
                CASE 
                    WHEN LOWER(COALESCE(s.workflow_status,'')) = 'graded_provisional' 
                    THEN 1 ELSE 0 
                END
            ) AS provisional_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
            ",

            "
            SUM(
                CASE 
                    WHEN s.file_path IS NOT NULL AND s.file_path <> '' 
                    THEN 1 ELSE 0 
                END
            ) AS file_count
            "
        ];

        $summaryJoins = [
            "LEFT JOIN lms_submissions s ON s.assessment_id = a.id"
        ];

        if ($hasBatches) {
            $summaryJoins[] = "LEFT JOIN batches b ON b.id = s.batch_id";
        }

        if ($hasCourses && $courseNameCol && cs_col_exists($db, 'lms_assessments', 'course_id')) {
            $summarySelect[] = "c.`{$courseNameCol}` AS course_name";
            $summaryJoins[] = "LEFT JOIN courses c ON c.id = a.course_id";
        } else {
            $summarySelect[] = "'' AS course_name";
        }

        if ($hasModules && $moduleNameCol && cs_col_exists($db, 'lms_assessments', 'module_id')) {
            $summarySelect[] = "cm.`{$moduleNameCol}` AS module_name";
            $summaryJoins[] = "LEFT JOIN course_modules cm ON cm.id = a.module_id";
        } else {
            $summarySelect[] = "'' AS module_name";
        }

        $summarySql = "
            SELECT " . implode(",\n                   ", $summarySelect) . "
            FROM lms_assessments a
            " . implode("\n            ", $summaryJoins) . "
            WHERE 1=1
            {$scopeSql}
            GROUP BY a.id
            ORDER BY a.id DESC
            LIMIT 300
        ";

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

        if (!$stmt) {
            $error = 'Summary SQL error: ' . $db->error;
        } else {
            if ($scopeParams) {
                $stmt->bind_param($scopeTypes, ...$scopeParams);
            }

            $summaryRows = cs_fetch_all_stmt($stmt);
            $stmt->close();
        }
    }

    /*
    |--------------------------------------------------------------------------
    | 2) Recent submissions list
    |--------------------------------------------------------------------------
    */

    $submissionSelect = [
        "s.id AS submission_id",
        "s.assessment_id",
        "s.batch_id",
        "s.student_id",
        cs_col_exists($db, 'lms_submissions', 'submitted_at') ? "s.submitted_at" : "NULL AS submitted_at",
        "s.workflow_status",
        cs_col_exists($db, 'lms_submissions', 'file_path') ? "s.file_path" : "'' AS file_path",
        cs_col_exists($db, 'lms_submissions', 'original_name') ? "s.original_name" : "'' AS original_name",
        cs_col_exists($db, 'lms_submissions', 'student_note') ? "s.student_note" : "'' AS student_note",
        cs_col_exists($db, 'lms_submissions', 'final_score') ? "s.final_score" : "NULL AS final_score",
        cs_col_exists($db, 'lms_submissions', 'lecturer_feedback') ? "s.lecturer_feedback" : "'' AS lecturer_feedback",
        cs_col_exists($db, 'lms_submissions', 'graded_at') ? "s.graded_at" : "NULL AS graded_at",
        cs_col_exists($db, 'lms_submissions', 'released_at') ? "s.released_at" : "NULL AS released_at",
        cs_col_exists($db, 'lms_submissions', 'updated_at') ? "s.updated_at" : "NULL AS updated_at"
    ];

    $submissionJoins = [];

    if ($hasAssessments) {
        $assessmentTitleCol = cs_first_col($db, 'lms_assessments', ['title', 'name']) ?? 'id';

        $submissionSelect[] = "a.`{$assessmentTitleCol}` AS assessment_title";
        $submissionSelect[] = cs_col_exists($db, 'lms_assessments', 'max_score') ? "a.max_score" : "100 AS max_score";
        $submissionJoins[] = "LEFT JOIN lms_assessments a ON a.id = s.assessment_id";
    } else {
        $submissionSelect[] = "CONCAT('Assessment #', s.assessment_id) AS assessment_title";
        $submissionSelect[] = "100 AS max_score";
    }

    if ($hasStudents && $studentNameCol) {
        $submissionSelect[] = "st.`{$studentNameCol}` AS student_name";
        $submissionJoins[] = "LEFT JOIN studentss st ON st.id = s.student_id";
    } else {
        $submissionSelect[] = "CONCAT('Student #', s.student_id) AS student_name";
    }

    if ($hasStudents && $studentRegCol) {
        $submissionSelect[] = "st.`{$studentRegCol}` AS student_reg_no";
    } else {
        $submissionSelect[] = "'' AS student_reg_no";
    }

    if ($hasBatches && $batchNameCol) {
        $submissionSelect[] = "b.`{$batchNameCol}` AS batch_name";
        $submissionJoins[] = "LEFT JOIN batches b ON b.id = s.batch_id";
    } elseif ($hasBatches) {
        $submissionSelect[] = "CONCAT('Batch #', s.batch_id) AS batch_name";
        $submissionJoins[] = "LEFT JOIN batches b ON b.id = s.batch_id";
    } else {
        $submissionSelect[] = "CONCAT('Batch #', s.batch_id) AS batch_name";
    }

    if ($hasBatches && $batchCodeCol) {
        $submissionSelect[] = "b.`{$batchCodeCol}` AS batch_code";
    } else {
        $submissionSelect[] = "'' AS batch_code";
    }

    if ($hasCourses && $courseNameCol && $hasAssessments && cs_col_exists($db, 'lms_assessments', 'course_id')) {
        $submissionSelect[] = "c.`{$courseNameCol}` AS course_name";
        $submissionJoins[] = "LEFT JOIN courses c ON c.id = a.course_id";
    } else {
        $submissionSelect[] = "'' AS course_name";
    }

    $submissionSql = "
        SELECT " . implode(",\n               ", $submissionSelect) . "
        FROM lms_submissions s
        " . implode("\n        ", $submissionJoins) . "
        WHERE 1=1
        {$scopeSql}
        ORDER BY 
            CASE LOWER(COALESCE(s.workflow_status,'submitted'))
                WHEN 'submitted' THEN 1
                WHEN 'pending' THEN 1
                WHEN 'needs_correction' THEN 2
                WHEN 'graded_provisional' THEN 3
                WHEN 'under_review' THEN 4
                WHEN 'coord_review' THEN 4
                WHEN 'coordinator_review' THEN 4
                WHEN 'admin_review' THEN 4
                WHEN 'coord_approved' THEN 5
                WHEN 'approved' THEN 5
                WHEN 'released' THEN 6
                WHEN 'published' THEN 6
                ELSE 9
            END ASC,
            s.id DESC
        LIMIT 500
    ";

    if (!$error) {
        $stmt = $db->prepare($submissionSql);

        if (!$stmt) {
            $error = 'Submissions SQL error: ' . $db->error;
        } else {
            if ($scopeParams) {
                $stmt->bind_param($scopeTypes, ...$scopeParams);
            }

            $submissionRows = cs_fetch_all_stmt($stmt);
            $stmt->close();
        }
    }
}

/*
|--------------------------------------------------------------------------
| KPI totals
|--------------------------------------------------------------------------
*/

$totalSubmissions = count($submissionRows);
$fileTotal = 0;
$submittedTotal = 0;
$correctionTotal = 0;
$provisionalTotal = 0;
$reviewTotal = 0;
$approvedTotal = 0;
$releasedTotal = 0;

foreach ($submissionRows as $sr) {
    if (!empty($sr['file_path'])) {
        $fileTotal++;
    }

    $wf = strtolower((string)($sr['workflow_status'] ?? 'submitted'));

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

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

<div class="d-flex justify-content-between align-items-start mb-4">
    <div>
        <h1 class="page-title">Submissions</h1>
        <div class="page-subtitle">View student assessment submissions and workflow status</div>
    </div>

    <div class="d-flex gap-2">
        <a href="/elms/coordinator/dashboard.php" class="btn btn-light border rounded-4">
            <i class="bi bi-arrow-left me-1"></i> Dashboard
        </a>

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

<?php if ($error): ?>
    <div class="alert alert-danger rounded-4">
        <strong>Error:</strong> <?= h($error) ?>
    </div>
<?php endif; ?>

<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="eden-card p-3">
            <div class="text-muted small">Total Submissions</div>
            <div class="fs-3 fw-bold"><?= number_format($totalSubmissions) ?></div>
            <i class="bi bi-inboxes fs-4 text-danger"></i>
        </div>
    </div>

    <div class="col-md-3">
        <div class="eden-card p-3">
            <div class="text-muted small">Submitted</div>
            <div class="fs-3 fw-bold"><?= number_format($submittedTotal) ?></div>
            <i class="bi bi-clock-history fs-4 text-danger"></i>
        </div>
    </div>

    <div class="col-md-3">
        <div class="eden-card p-3">
            <div class="text-muted small">Under Review</div>
            <div class="fs-3 fw-bold"><?= number_format($reviewTotal) ?></div>
            <i class="bi bi-hourglass-split fs-4 text-danger"></i>
        </div>
    </div>

    <div class="col-md-3">
        <div class="eden-card p-3">
            <div class="text-muted small">Released</div>
            <div class="fs-3 fw-bold"><?= number_format($releasedTotal) ?></div>
            <i class="bi bi-award fs-4 text-danger"></i>
        </div>
    </div>
</div>

<div class="row g-3 mb-4">
    <div class="col-md-3">
        <div class="eden-card p-3">
            <div class="text-muted small">Needs Correction</div>
            <div class="fs-3 fw-bold"><?= number_format($correctionTotal) ?></div>
            <i class="bi bi-arrow-counterclockwise fs-4 text-danger"></i>
        </div>
    </div>

    <div class="col-md-3">
        <div class="eden-card p-3">
            <div class="text-muted small">Provisional</div>
            <div class="fs-3 fw-bold"><?= number_format($provisionalTotal) ?></div>
            <i class="bi bi-pencil-square fs-4 text-danger"></i>
        </div>
    </div>

    <div class="col-md-3">
        <div class="eden-card p-3">
            <div class="text-muted small">Ready to Release</div>
            <div class="fs-3 fw-bold"><?= number_format($approvedTotal) ?></div>
            <i class="bi bi-check2-circle fs-4 text-danger"></i>
        </div>
    </div>

    <div class="col-md-3">
        <div class="eden-card p-3">
            <div class="text-muted small">With Files</div>
            <div class="fs-3 fw-bold"><?= number_format($fileTotal) ?></div>
            <i class="bi bi-paperclip fs-4 text-danger"></i>
        </div>
    </div>
</div>

<div class="eden-card p-3 mb-4">
    <div class="row g-3 align-items-center">
        <div class="col-lg-6">
            <div class="input-group">
                <span class="input-group-text bg-white border-end-0">
                    <i class="bi bi-search"></i>
                </span>
                <input type="text" id="submissionSearch" class="form-control border-start-0" placeholder="Search student, assessment, batch, status...">
            </div>
        </div>

        <div class="col-lg-3">
            <select id="workflowFilter" class="form-select">
                <option value="">All Workflow</option>
                <option value="submitted">Submitted</option>
                <option value="needs_correction">Needs Correction</option>
                <option value="graded_provisional">Graded Provisional</option>
                <option value="under_review">Under Review</option>
                <option value="coord_approved">Ready to Release</option>
                <option value="released">Released</option>
            </select>
        </div>

        <div class="col-lg-3 text-lg-end">
            <span class="badge text-bg-danger rounded-pill px-3 py-2">
                <?= number_format(count($submissionRows)) ?> Records
            </span>
        </div>
    </div>
</div>

<div class="eden-card overflow-hidden mb-4">
    <div class="px-3 py-3 border-bottom bg-white d-flex justify-content-between align-items-center">
        <strong>Recent Student Submissions</strong>
        <span class="text-muted small">Workflow aligned</span>
    </div>

    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0" id="submissionsTable">
            <thead class="table-light">
                <tr>
                    <th style="width:70px;">ID</th>
                    <th>Student</th>
                    <th>Assessment</th>
                    <th>Batch</th>
                    <th>Submitted</th>
                    <th>Score</th>
                    <th>File</th>
                    <th>Feedback</th>
                    <th>Workflow</th>
                    <th>Released</th>
                    <th class="text-end">Action</th>
                </tr>
            </thead>

            <tbody>
            <?php if (!$submissionRows): ?>
                <tr>
                    <td colspan="11" class="text-center text-muted py-5">
                        <i class="bi bi-inbox fs-2 d-block mb-2"></i>
                        No submissions found.
                    </td>
                </tr>
            <?php else: ?>
                <?php foreach ($submissionRows as $r): ?>
                    <?php
                        $workflow = strtolower((string)($r['workflow_status'] ?? 'submitted'));
                        [$workflowText, $wfBadge] = cs_workflow_badge($workflow);

                        $filterWorkflow = $workflow;
                        if (in_array($workflow, ['pending'], true)) {
                            $filterWorkflow = 'submitted';
                        } elseif (in_array($workflow, ['coord_review', 'coordinator_review', 'admin_review'], true)) {
                            $filterWorkflow = 'under_review';
                        } elseif ($workflow === 'approved') {
                            $filterWorkflow = 'coord_approved';
                        } elseif ($workflow === 'published') {
                            $filterWorkflow = 'released';
                        }

                        $fileUrl = cs_upload_url($r['file_path'] ?? '');
                        $scoreText = cs_score_text($r);
                        $maxScore = (int)($r['max_score'] ?? 100);
                    ?>

                    <tr data-workflow="<?= h($filterWorkflow) ?>">
                        <td class="text-muted">#<?= (int)$r['submission_id'] ?></td>

                        <td>
                            <div class="fw-bold"><?= h($r['student_name'] ?? ('Student #' . $r['student_id'])) ?></div>
                            <?php if (!empty($r['student_reg_no'])): ?>
                                <div class="small text-muted"><?= h($r['student_reg_no']) ?></div>
                            <?php endif; ?>
                        </td>

                        <td>
                            <div class="fw-semibold">
                                <?= h($r['assessment_title'] ?? ('Assessment #' . $r['assessment_id'])) ?>
                            </div>
                            <?php if (!empty($r['course_name'])): ?>
                                <div class="small text-muted"><?= h($r['course_name']) ?></div>
                            <?php endif; ?>
                        </td>

                        <td>
                            <div><?= h($r['batch_name'] ?? ('Batch #' . $r['batch_id'])) ?></div>
                            <?php if (!empty($r['batch_code'])): ?>
                                <div class="small text-muted"><?= h($r['batch_code']) ?></div>
                            <?php endif; ?>
                        </td>

                        <td>
                            <?= cs_fmt_date($r['submitted_at'] ?? '') ?>
                        </td>

                        <td>
                            <?php if ($scoreText !== '-'): ?>
                                <span class="fw-bold"><?= h($scoreText) ?></span>
                                <span class="text-muted small">/ <?= $maxScore ?></span>
                            <?php else: ?>
                                <span class="text-muted">Not marked</span>
                            <?php endif; ?>
                        </td>

                        <td>
                            <?php if ($fileUrl !== ''): ?>
                                <a class="btn btn-sm btn-light border rounded-pill" href="<?= h($fileUrl) ?>" target="_blank">
                                    <i class="bi bi-download me-1"></i> File
                                </a>
                            <?php else: ?>
                                <span class="text-muted">No file</span>
                            <?php endif; ?>
                        </td>

                        <td style="max-width:240px;">
                            <?php if (!empty($r['lecturer_feedback'])): ?>
                                <div class="small text-muted text-truncate">
                                    <?= h((string)$r['lecturer_feedback']) ?>
                                </div>
                            <?php else: ?>
                                <span class="text-muted">No feedback</span>
                            <?php endif; ?>
                        </td>

                        <td>
                            <span class="badge <?= h($wfBadge) ?> rounded-pill">
                                <?= h($workflowText) ?>
                            </span>
                        </td>

                        <td>
                            <?= cs_fmt_date($r['released_at'] ?? '') ?>
                        </td>

                        <td class="text-end">
                            <?php if (in_array($filterWorkflow, ['under_review', 'coord_approved'], true)): ?>
                                <a href="/elms/coordinator/approval.php" class="btn btn-sm btn-eden rounded-pill">
                                    Review
                                </a>
                            <?php elseif ($filterWorkflow === 'released'): ?>
                                <span class="badge text-bg-success rounded-pill">Done</span>
                            <?php else: ?>
                                <span class="text-muted small">Waiting</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<div class="eden-card overflow-hidden">
    <div class="px-3 py-3 border-bottom bg-white">
        <strong>Submissions by Assessment</strong>
    </div>

    <div class="table-responsive">
        <table class="table table-hover align-middle mb-0">
            <thead class="table-light">
                <tr>
                    <th>Assessment</th>
                    <th>Course / Module</th>
                    <th>Open</th>
                    <th>Due</th>
                    <th class="text-center">Total</th>
                    <th class="text-center">Submitted</th>
                    <th class="text-center">Review</th>
                    <th class="text-center">Approved</th>
                    <th class="text-center">Released</th>
                    <th class="text-center">Files</th>
                    <th>Last Submitted</th>
                </tr>
            </thead>

            <tbody>
            <?php if (!$summaryRows): ?>
                <tr>
                    <td colspan="11" class="text-center text-muted py-5">
                        <i class="bi bi-inbox fs-2 d-block mb-2"></i>
                        No assessment summary found.
                    </td>
                </tr>
            <?php else: ?>
                <?php foreach ($summaryRows as $r): ?>
                    <tr>
                        <td>
                            <div class="fw-bold"><?= h($r['assessment_title'] ?? 'Untitled Assessment') ?></div>
                            <div class="small text-muted">#<?= (int)$r['assessment_id'] ?></div>
                        </td>

                        <td>
                            <?php if (!empty($r['course_name'])): ?>
                                <div><?= h($r['course_name']) ?></div>
                            <?php else: ?>
                                <span class="text-muted">No course</span>
                            <?php endif; ?>

                            <?php if (!empty($r['module_name'])): ?>
                                <div class="small text-muted"><?= h($r['module_name']) ?></div>
                            <?php endif; ?>
                        </td>

                        <td>
                            <?= cs_fmt_date($r['available_from'] ?? '') ?>
                        </td>

                        <td>
                            <?= cs_fmt_date($r['due_at'] ?? '') ?>
                        </td>

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

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

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

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

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

                        <td class="text-center">
                            <span class="badge text-bg-light border rounded-pill">
                                <?= (int)($r['file_count'] ?? 0) ?>
                            </span>
                        </td>

                        <td>
                            <?= cs_fmt_date($r['last_submitted'] ?? '') ?>
                        </td>
                    </tr>
                <?php endforeach; ?>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const searchInput = document.getElementById('submissionSearch');
    const workflowFilter = document.getElementById('workflowFilter');
    const rows = Array.from(document.querySelectorAll('#submissionsTable tbody tr[data-workflow]'));

    function filterTable() {
        const q = (searchInput.value || '').toLowerCase().trim();
        const wf = (workflowFilter.value || '').toLowerCase().trim();

        rows.forEach(row => {
            const text = row.innerText.toLowerCase();
            const rowWf = (row.dataset.workflow || '').toLowerCase();

            const matchSearch = q === '' || text.includes(q);
            const matchWorkflow = wf === '' || rowWf === wf;

            row.style.display = (matchSearch && matchWorkflow) ? '' : 'none';
        });
    }

    searchInput.addEventListener('input', filterTable);
    workflowFilter.addEventListener('change', filterTable);
});
</script>

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