<?php declare(strict_types=1);
/* /elms/admin/assessments/submissions.php */

define('APP_ROOT', dirname(__DIR__, 2));
if (session_status() === PHP_SESSION_NONE) session_start();

$PAGE_TITLE = 'Submissions';
$ACTIVE = 'submissions';

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

@$mysqli->set_charset('utf8mb4');

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

function app_base_web(): string {
    $script = $_SERVER['SCRIPT_NAME'] ?? '/elms/admin/assessments/submissions.php';
    $base = rtrim(dirname($script, 3), '/');
    return $base === '' ? '/' : $base;
}

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

function col_exists(mysqli $db, string $t, string $c): bool {
    $t = $db->real_escape_string($t);
    $c = $db->real_escape_string($c);
    $rs = $db->query("SHOW COLUMNS FROM `{$t}` LIKE '{$c}'");
    $ok = $rs && $rs->num_rows > 0;
    if ($rs) $rs->free();
    return $ok;
}

function label_col(mysqli $db, string $t, array $cands): string {
    $rs = $db->query("SHOW COLUMNS FROM `{$t}`");
    if (!$rs) return 'id';

    $cols = [];
    while ($r = $rs->fetch_assoc()) $cols[] = $r['Field'];
    $rs->free();

    foreach ($cands as $c) {
        if (in_array($c, $cols, true)) return $c;
    }
    return 'id';
}

function stmt_all_assoc(mysqli_stmt $st): array {
    $meta = $st->result_metadata();
    if (!$meta) return [];

    $row = [];
    $bind = [];
    $out = [];

    while ($f = $meta->fetch_field()) {
        $row[$f->name] = null;
        $bind[] = &$row[$f->name];
    }

    call_user_func_array([$st, 'bind_result'], $bind);

    while ($st->fetch()) {
        $copy = [];
        foreach ($row as $k => $v) $copy[$k] = $v;
        $out[] = $copy;
    }

    return $out;
}

function stmt_one_assoc(mysqli_stmt $st): ?array {
    $all = stmt_all_assoc($st);
    return $all[0] ?? null;
}

function webify_upload_href(string $path): string {
    $p = trim($path);
    if ($p === '') return '';

    if (preg_match('#^https?://#i', $p)) return $p;

    $p = str_replace('\\', '/', $p);

    if (preg_match('#^/?uploads/#i', $p)) {
        return app_base_web() . '/' . ltrim($p, '/');
    }

    if ($p[0] === '/') return $p;

    return app_base_web() . '/' . ltrim($p, '/');
}

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

    return match (true) {
        str_contains($s, 'submitted') => 'text-bg-warning',
        str_contains($s, 'review') => 'text-bg-info',
        str_contains($s, 'correction') => 'text-bg-danger',
        str_contains($s, 'marked') || str_contains($s, 'graded') => 'text-bg-primary',
        str_contains($s, 'approved') => 'text-bg-success',
        str_contains($s, 'released') => 'text-bg-success',
        default => 'text-bg-secondary',
    };
}

function is_previewable_file(string $href): bool {
    $ext = strtolower(pathinfo(parse_url($href, PHP_URL_PATH) ?? '', PATHINFO_EXTENSION));
    return in_array($ext, ['pdf','jpg','jpeg','png','gif','webp','txt'], true);
}

$assessment_id = (int)($_GET['assessment_id'] ?? 0);
$batch_id      = (int)($_GET['batch_id'] ?? 0);

$STUD_TBL = table_exists($mysqli, 'studentss') ? 'studentss' : (table_exists($mysqli, 'students') ? 'students' : null);
if (!$STUD_TBL) exit('Students table not found');

$studLabel = label_col($mysqli, $STUD_TBL, ['full_name', 'name', 'student_name', 'title']);
$studReg   = col_exists($mysqli, $STUD_TBL, 'center_reg_no') ? 'center_reg_no' : (col_exists($mysqli, $STUD_TBL, 'reference_no') ? 'reference_no' : 'id');

$SUB_TBL = null;

foreach (['lms_submissions', 'lms_assessment_submissions'] as $tryTbl) {
    if (
        table_exists($mysqli, $tryTbl) &&
        col_exists($mysqli, $tryTbl, 'assessment_id') &&
        col_exists($mysqli, $tryTbl, 'student_id')
    ) {
        $SUB_TBL = $tryTbl;
        break;
    }
}

if (!$SUB_TBL) exit('Submissions table not found');

if (!col_exists($mysqli, $SUB_TBL, 'feedback')) {
    $mysqli->query("ALTER TABLE `$SUB_TBL` ADD COLUMN `feedback` TEXT NULL");
}
if (!col_exists($mysqli, $SUB_TBL, 'workflow_status') && !col_exists($mysqli, $SUB_TBL, 'status')) {
    $mysqli->query("ALTER TABLE `$SUB_TBL` ADD COLUMN `workflow_status` VARCHAR(50) NOT NULL DEFAULT 'submitted'");
}
if (!col_exists($mysqli, $SUB_TBL, 'marked_at')) {
    $mysqli->query("ALTER TABLE `$SUB_TBL` ADD COLUMN `marked_at` DATETIME NULL");
}
if (!col_exists($mysqli, $SUB_TBL, 'marked_by')) {
    $mysqli->query("ALTER TABLE `$SUB_TBL` ADD COLUMN `marked_by` INT NULL");
}

if (
    !col_exists($mysqli, $SUB_TBL, 'final_score') &&
    !col_exists($mysqli, $SUB_TBL, 'provisional_score') &&
    !col_exists($mysqli, $SUB_TBL, 'marks') &&
    !col_exists($mysqli, $SUB_TBL, 'score')
) {
    $mysqli->query("ALTER TABLE `$SUB_TBL` ADD COLUMN `marks` DECIMAL(10,2) NULL");
}

$scoreCol = col_exists($mysqli, $SUB_TBL, 'final_score') ? 'final_score' :
    (col_exists($mysqli, $SUB_TBL, 'provisional_score') ? 'provisional_score' :
    (col_exists($mysqli, $SUB_TBL, 'marks') ? 'marks' : 'score'));

$statusCol = col_exists($mysqli, $SUB_TBL, 'workflow_status') ? 'workflow_status' : 'status';

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST' && ($_POST['action'] ?? '') === 'save_marking') {
    $submission_id = (int)($_POST['submission_id'] ?? 0);
    $scoreRaw      = trim((string)($_POST['score'] ?? ''));
    $feedback      = trim((string)($_POST['feedback'] ?? ''));
    $newStatus     = trim((string)($_POST['workflow_status'] ?? 'under_review'));

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

    if (!in_array($newStatus, $allowedStatuses, true)) {
        $newStatus = 'under_review';
    }

    $maxScoreLimit = 100.0;
    if ($assessment_id > 0 && table_exists($mysqli, 'lms_assessments') && col_exists($mysqli, 'lms_assessments', 'max_score')) {
        $mx = $mysqli->prepare("SELECT COALESCE(max_score, 100) AS max_score FROM lms_assessments WHERE id=? LIMIT 1");
        if ($mx) {
            $mx->bind_param('i', $assessment_id);
            $mx->execute();
            $mxRow = stmt_one_assoc($mx);
            $mx->close();
            $maxScoreLimit = (float)($mxRow['max_score'] ?? 100);
        }
    }

    $scoreVal = ($scoreRaw === '') ? null : (float)$scoreRaw;
    
$correctedPath = null;
$correctedName = null;

if (
    isset($_FILES['corrected_file']) &&
    !empty($_FILES['corrected_file']['name']) &&
    is_uploaded_file($_FILES['corrected_file']['tmp_name'])
) {
    $allowed = ['pdf','doc','docx','jpg','jpeg','png','webp'];
    $original = (string)$_FILES['corrected_file']['name'];
    $ext = strtolower(pathinfo($original, PATHINFO_EXTENSION));

    if (!in_array($ext, $allowed, true)) {
        $_SESSION['flash_err'] = 'Invalid corrected file type.';
        header("Location: submissions.php?assessment_id={$assessment_id}&batch_id={$batch_id}");
        exit;
    }

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

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

    $safeName = date('Ymd_His') . '_CORR_SUB' . $submission_id . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
    $dest = $uploadDir . '/' . $safeName;

    if (!move_uploaded_file($_FILES['corrected_file']['tmp_name'], $dest)) {
        $_SESSION['flash_err'] = 'Corrected file upload failed.';
        header("Location: submissions.php?assessment_id={$assessment_id}&batch_id={$batch_id}");
        exit;
    }

    $correctedPath = 'uploads/corrected_submissions/' . $safeName;
    $correctedName = $original;
}
    if ($submission_id <= 0) {
        $_SESSION['flash_err'] = 'Invalid submission.';
    } elseif ($scoreVal !== null && ($scoreVal < 0 || $scoreVal > $maxScoreLimit)) {
        $_SESSION['flash_err'] = 'Marks must be between 0 and ' . number_format($maxScoreLimit, 2) . '.';
    } else {
        $adminId = (int)($_SESSION['admin_id'] ?? $_SESSION['user_id'] ?? 0);

        $stmt = $mysqli->prepare("
            UPDATE `$SUB_TBL`
SET `$scoreCol` = ?,
    `feedback` = ?,
    `$statusCol` = ?,
    `corrected_file_path` = COALESCE(?, corrected_file_path),
    `corrected_original_name` = COALESCE(?, corrected_original_name),
    `marked_at` = NOW(),
    `marked_by` = ?
WHERE id = ?
        ");

        if ($stmt) {
            $stmt->bind_param('dssssii', $scoreVal, $feedback, $newStatus, $correctedPath, $correctedName, $adminId, $submission_id);
            $stmt->execute();
            $stmt->close();
            $_SESSION['flash_ok'] = 'Submission updated successfully.';
        } else {
            $_SESSION['flash_err'] = 'Unable to save marking.';
        }
    }

    header("Location: submissions.php?assessment_id={$assessment_id}&batch_id={$batch_id}");
    exit;
}

$courseLabel = table_exists($mysqli, 'courses') ? label_col($mysqli, 'courses', ['course_name', 'name', 'title', 'label']) : 'id';
$batchLabel  = table_exists($mysqli, 'batches') ? label_col($mysqli, 'batches', ['batch_name', 'name', 'title', 'batch_code']) : 'id';

if ($assessment_id <= 0 || $batch_id <= 0) {
    $assess = [];
    if (table_exists($mysqli, 'lms_assessments')) {
        $sql = table_exists($mysqli, 'courses')
            ? "SELECT a.id, a.title, COALESCE(c.`$courseLabel`, '') AS course_label
               FROM lms_assessments a
               LEFT JOIN courses c ON c.id = a.course_id
               ORDER BY a.id DESC
               LIMIT 200"
            : "SELECT a.id, a.title, '' AS course_label
               FROM lms_assessments a
               ORDER BY a.id DESC
               LIMIT 200";

        if ($rs = $mysqli->query($sql)) {
            while ($r = $rs->fetch_assoc()) $assess[] = $r;
            $rs->free();
        }
    }

    $batches = [];
    if (table_exists($mysqli, 'batches')) {
        if ($rs = $mysqli->query("SELECT id, `$batchLabel` AS label FROM batches ORDER BY id DESC LIMIT 200")) {
            while ($r = $rs->fetch_assoc()) $batches[] = $r;
            $rs->free();
        }
    }

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

    <div class="admin-card">
        <div class="admin-card-header">
            <div>
                <h5 class="mb-0">Open Submissions</h5>
                <div class="text-muted small">Assessment එක සහ batch එක select කර submissions බලන්න.</div>
            </div>
        </div>

        <div class="admin-card-body">
            <form method="get" class="row g-3">
                <div class="col-lg-7">
                    <label class="form-label fw-bold">Assessment</label>
                    <select name="assessment_id" class="form-select" required>
                        <option value="">Choose assessment...</option>
                        <?php foreach ($assess as $a): ?>
                            <option value="<?= (int)$a['id'] ?>">
                                #<?= (int)$a['id'] ?> — <?= esc($a['title'] ?? 'Assessment') ?>
                                <?= !empty($a['course_label']) ? ' · ' . esc($a['course_label']) : '' ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-lg-5">
                    <label class="form-label fw-bold">Batch</label>
                    <select name="batch_id" class="form-select" required>
                        <option value="">Choose batch...</option>
                        <?php foreach ($batches as $b): ?>
                            <option value="<?= (int)$b['id'] ?>">
                                #<?= (int)$b['id'] ?> — <?= esc($b['label'] ?? 'Batch') ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-12">
                    <button class="btn btn-primary rounded-pill px-4 fw-bold">
                        <i class="bi bi-folder2-open me-1"></i> Open
                    </button>
                </div>
            </form>
        </div>
    </div>

    <?php
    require APP_ROOT . '/includes/admin_layout_bottom.php';
    exit;
}

$assSelectMax = col_exists($mysqli, 'lms_assessments', 'max_score')
    ? "COALESCE(a.max_score, 100) AS max_score"
    : "100 AS max_score";

$A = $mysqli->prepare("
    SELECT 
        a.title,
        " . (col_exists($mysqli, 'lms_assessments', 'type') ? "a.type" : "'' AS type") . ",
        {$assSelectMax},
        " . (table_exists($mysqli, 'courses') ? "COALESCE(c.`$courseLabel`, '')" : "''") . " AS course_label
    FROM lms_assessments a
    " . (table_exists($mysqli, 'courses') ? "LEFT JOIN courses c ON c.id = a.course_id" : "") . "
    WHERE a.id = ?
    LIMIT 1
");
$A->bind_param('i', $assessment_id);
$A->execute();
$ass = stmt_one_assoc($A);
$A->close();

$B = $mysqli->prepare("SELECT `$batchLabel` AS label FROM batches WHERE id=? LIMIT 1");
$B->bind_param('i', $batch_id);
$B->execute();
$bat = stmt_one_assoc($B);
$B->close();

$maxScore = (float)($ass['max_score'] ?? 100);

$fileCol = col_exists($mysqli, $SUB_TBL, 'file_path') ? 'file_path' :
    (col_exists($mysqli, $SUB_TBL, 'attachment_path') ? 'attachment_path' :
    (col_exists($mysqli, $SUB_TBL, 'file') ? 'file' :
    (col_exists($mysqli, $SUB_TBL, 'file_name') ? 'file_name' : null)));

$subTimeCol = col_exists($mysqli, $SUB_TBL, 'submitted_at') ? 'submitted_at' :
    (col_exists($mysqli, $SUB_TBL, 'created_at') ? 'created_at' :
    (col_exists($mysqli, $SUB_TBL, 'submitted_on') ? 'submitted_on' : null));

$scoreParts = [];
foreach (['final_score', 'provisional_score', 'marks', 'score'] as $sc) {
    if (col_exists($mysqli, $SUB_TBL, $sc)) $scoreParts[] = "s.`$sc`";
}
$scoreExpr = $scoreParts ? "COALESCE(" . implode(',', $scoreParts) . ")" : "NULL";

$statusParts = [];
foreach (['workflow_status', 'status'] as $sc) {
    if (col_exists($mysqli, $SUB_TBL, $sc)) $statusParts[] = "s.`$sc`";
}
$statExpr = $statusParts ? "COALESCE(" . implode(',', $statusParts) . ")" : "'submitted'";

$timeExpr = $subTimeCol ? "s.`{$subTimeCol}`" : "NULL";
$selectFile = $fileCol ? ", s.`{$fileCol}` AS file_path" : ", NULL AS file_path";

$whereSql = "s.assessment_id = ?";
$bindTypes = "i";
$bindVals = [$assessment_id];

$sql = "
    SELECT 
        s.id,
        s.student_id,
        {$timeExpr} AS submitted_at
        {$selectFile},
        s.feedback,
        s.corrected_file_path,
s.corrected_original_name,
        {$statExpr} AS workflow_status,
        {$scoreExpr} AS score,
        stt.`{$studLabel}` AS student_name,
        stt.`{$studReg}` AS student_reg
    FROM `{$SUB_TBL}` s
    JOIN `{$STUD_TBL}` stt ON stt.id = s.student_id
    WHERE {$whereSql}
    ORDER BY {$timeExpr} DESC, s.id DESC
";

$S = $mysqli->prepare($sql);
$S->bind_param($bindTypes, ...$bindVals);
$S->execute();
$rows = stmt_all_assoc($S);
$S->close();

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

<style>
.submissions-head {
    display:flex;
    justify-content:space-between;
    gap:16px;
    align-items:center;
    flex-wrap:wrap;
}
.submission-kpi {
    display:inline-flex;
    align-items:center;
    gap:8px;
    background:#f8fafc;
    border:1px solid #e5e7eb;
    border-radius:999px;
    padding:8px 13px;
    font-weight:800;
    color:#334155;
}
.submissions-table th {
    background:#f8fafc;
    color:#475569;
    font-size:12px;
    font-weight:900;
    text-transform:uppercase;
    letter-spacing:.04em;
    white-space:nowrap;
    padding:13px 14px;
    border-bottom:1px solid #e5e7eb;
}
.submissions-table td {
    padding:15px 14px;
    vertical-align:middle;
    border-bottom:1px solid #eef2f7;
}
.submission-student {
    font-weight:900;
    color:#111827;
}
.submission-meta {
    color:#64748b;
    font-size:.78rem;
    font-weight:700;
    margin-top:3px;
}
.score-pill {
    display:inline-flex;
    align-items:center;
    justify-content:center;
    border-radius:999px;
    padding:6px 11px;
    background:#eff6ff;
    color:#1d4ed8;
    font-weight:900;
    min-width:70px;
}
.mark-modal .modal-content {
    border:0;
    border-radius:18px;
    overflow:hidden;
}
.mark-modal .modal-header {
    background:#f8fafc;
    border-bottom:1px solid #e5e7eb;
}
.file-preview-box {
    height:68vh;
    border:1px solid #e5e7eb;
    border-radius:14px;
    overflow:hidden;
    background:#f8fafc;
}
.file-preview-box iframe {
    width:100%;
    height:100%;
    border:0;
}
.no-preview {
    height:68vh;
    display:flex;
    flex-direction:column;
    align-items:center;
    justify-content:center;
    text-align:center;
    color:#64748b;
    padding:30px;
}
.mark-panel {
    border:1px solid #e5e7eb;
    border-radius:14px;
    padding:16px;
    background:#fff;
}
.submissions-table th:nth-child(5),
.submissions-table td:nth-child(5),
.submissions-table th:nth-child(6),
.submissions-table td:nth-child(6){
    text-align:center !important;
    width:110px !important;
}

.submissions-table td:nth-child(6){
    display:table-cell !important;
}

.submissions-table td:nth-child(6) .d-flex{
    justify-content:center !important;
    gap:12px !important;
    flex-wrap:nowrap !important;
}

.submissions-table .btn{
    min-width:72px;
    height:34px;
    padding:6px 12px !important;
    font-size:12px;
    font-weight:800;
    border-radius:999px !important;
    white-space:normal;
    line-height:1.05;
}
.submissions-table th:nth-child(5),
.submissions-table td:nth-child(5){
    width:120px !important;
    text-align:center !important;
}

.submissions-table th:nth-child(6),
.submissions-table td:nth-child(6){
    width:240px !important;
    text-align:center !important;
}

.submissions-table td:nth-child(6){
    display:table-cell !important;
}
.submissions-table td:nth-child(6) .d-flex{
    justify-content:center !important;
    align-items:center !important;
    gap:18px !important;
    flex-wrap:nowrap !important;
}
.submissions-table td:nth-child(5) .btn,
.submissions-table td:nth-child(6) .btn{
    min-width:76px;
    height:34px;
    padding:6px 14px !important;
    font-size:12px;
    font-weight:800;
    border-radius:999px !important;
    line-height:1.05;
    white-space:normal;
}
</style>

<div class="admin-card mb-4">
    <div class="admin-card-header submissions-head">
        <div>
            <h5 class="mb-0">Submissions — <?= esc($ass['title'] ?? ('Assessment #' . $assessment_id)) ?></h5>
            <div class="text-muted small mt-1">
                Course: <?= esc($ass['course_label'] ?? '—') ?>
                · Batch: <?= esc($bat['label'] ?? ('#' . $batch_id)) ?>
                · Max Marks: <?= esc(number_format($maxScore, 2)) ?>
            </div>
        </div>

        <div class="d-flex gap-2 flex-wrap">
            <span class="submission-kpi">
                <i class="bi bi-inbox"></i> <?= number_format(count($rows)) ?> Submissions
            </span>
            <a class="btn btn-sm btn-outline-secondary rounded-pill px-3" href="submissions.php">
                Change Assessment
            </a>
        </div>
    </div>
</div>

<?php if (!empty($_SESSION['flash_ok'])): ?>
    <div class="alert alert-success border-0 rounded-4 shadow-sm py-2">
        <i class="bi bi-check-circle me-1"></i><?= esc($_SESSION['flash_ok']) ?>
    </div>
    <?php unset($_SESSION['flash_ok']); ?>
<?php endif; ?>

<?php if (!empty($_SESSION['flash_err'])): ?>
    <div class="alert alert-danger border-0 rounded-4 shadow-sm py-2">
        <i class="bi bi-exclamation-triangle me-1"></i><?= esc($_SESSION['flash_err']) ?>
    </div>
    <?php unset($_SESSION['flash_err']); ?>
<?php endif; ?>

<div class="admin-card">
    <div class="admin-card-header">
        <div>
            <h5 class="mb-0">Student Submissions</h5>
            <div class="text-muted small">Student upload කරපු file එක open කරලා marks/feedback/status එකම තැන save කරන්න.</div>
        </div>
    </div>

    <div class="admin-card-body p-0">
        <div class="table-responsive">
            <table class="table align-middle submissions-table mb-0">
                <thead>
                    <tr>
                        <th style="min-width:240px;">Student</th>
                        <th style="width:170px;">Submitted</th>
                        <th style="width:150px;">Status</th>
                        <th style="width:130px;">Score</th>
                        <th style="width:120px;" class="text-end">File</th>
                        <th style="width:130px;" class="text-end">Action</th>
                    </tr>
                </thead>
                <tbody>
                <?php if (!$rows): ?>
                    <tr>
                        <td colspan="6" class="text-center text-muted py-5">
                            <i class="bi bi-inbox fs-2 d-block mb-2"></i>
                            No submissions yet.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($rows as $r): ?>
                        <?php
                            $status = (string)($r['workflow_status'] ?? 'submitted');
                            $score  = $r['score'];
                            $href   = !empty($r['file_path']) ? webify_upload_href((string)$r['file_path']) : '';
                            $modalId = 'markModal' . (int)$r['id'];
                            $previewable = $href && is_previewable_file($href);
                        ?>
                        <tr>
                            <td>
                                <div class="submission-student"><?= esc($r['student_name'] ?? 'Student') ?></div>
                                <div class="submission-meta">
                                    <?= esc($r['student_reg'] ?? ('ID: ' . $r['student_id'])) ?>
                                </div>
                            </td>

                            <td class="small text-muted">
                                <?= !empty($r['submitted_at']) ? esc(date('Y-m-d H:i', strtotime((string)$r['submitted_at']))) : '—' ?>
                            </td>

                            <td>
                                <span class="badge <?= esc(status_badge_class($status)) ?>">
                                    <?= esc(ucwords(str_replace('_', ' ', $status))) ?>
                                </span>
                            </td>

                            <td>
                                <?php if ($score !== null && $score !== ''): ?>
                                    <span class="score-pill"><?= esc((string)$score) ?> / <?= esc((string)(int)$maxScore) ?></span>
                                <?php else: ?>
                                    <span class="text-muted">Not marked</span>
                                <?php endif; ?>
                            </td>

                            <td class="text-end">
                                <?php if ($href): ?>
                                    <a class="btn btn-sm btn-outline-primary rounded-pill px-3" target="_blank" href="<?= esc($href) ?>">
                                        Open
                                    </a>
                                <?php else: ?>
                                    <span class="badge text-bg-secondary">No file</span>
                                <?php endif; ?>
                            </td>

                            <?php
$openHref = !empty($r['corrected_file_path'])
    ? webify_upload_href((string)$r['corrected_file_path'])
    : $href;
?>

<td class="text-end">
    <div class="d-flex gap-3 justify-content-end align-items-center flex-wrap">
        <?php if ($openHref): ?>
            <a class="btn btn-sm btn-outline-primary rounded-pill px-3"
               target="_blank"
               href="<?= esc($openHref) ?>">
                Open
            </a>
        <?php endif; ?>

        <?php if ($href && strtolower(pathinfo(parse_url($href, PHP_URL_PATH) ?? '', PATHINFO_EXTENSION)) === 'pdf'): ?>
            <a href="mark_pdf.php?submission_id=<?= (int)$r['id'] ?>&assessment_id=<?= (int)$assessment_id ?>&batch_id=<?= (int)$batch_id ?>"
               class="btn btn-sm btn-outline-danger rounded-pill px-4">
                Mark / Grade
            </a>
        <?php else: ?>
            <button type="button"
                    class="btn btn-sm btn-outline-primary rounded-pill px-3"
                    data-bs-toggle="modal"
                    data-bs-target="#<?= esc($modalId) ?>">
                Marks
            </button>
        <?php endif; ?>
    </div>
</td>
                        </tr>

                        <div class="modal fade mark-modal" id="<?= esc($modalId) ?>" tabindex="-1" aria-hidden="true">
                            <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
                                <div class="modal-content">
                                    <form method="post" enctype="multipart/form-data">
                                        <input type="hidden" name="action" value="save_marking">
                                        <input type="hidden" name="submission_id" value="<?= (int)$r['id'] ?>">

                                        <div class="modal-header">
                                            <div>
                                                <h5 class="modal-title fw-bold mb-0">View Submission & Mark</h5>
                                                <div class="text-muted small">
                                                    <?= esc($r['student_name'] ?? 'Student') ?>
                                                    · <?= esc($r['student_reg'] ?? '') ?>
                                                </div>
                                            </div>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                        </div>

                                        <div class="modal-body">
                                            <div class="row g-3">
                                                <div class="col-lg-8">
                                                    <div class="d-flex justify-content-between align-items-center mb-2">
                                                        <label class="form-label fw-bold mb-0">Uploaded File</label>
                                                        <?php if ($href): ?>
                                                            <a href="<?= esc($href) ?>" target="_blank" class="btn btn-sm btn-outline-primary rounded-pill">
                                                                Open / Download
                                                            </a>
                                                        <?php endif; ?>
                                                    </div>
                                                  <div class="file-preview-box">
                                                        <?php if (!$href): ?>
                                                            <div class="no-preview">
                                                                <i class="bi bi-file-earmark-x fs-1 mb-2"></i>
                                                                <div class="fw-bold">No uploaded file found</div>
                                                            </div>
                                                        <?php elseif ($previewable && strtolower(pathinfo(parse_url($href, PHP_URL_PATH) ?? '', PATHINFO_EXTENSION)) !== 'pdf'): ?>
    <iframe src="<?= esc($href) ?>"></iframe>
<?php elseif ($href && strtolower(pathinfo(parse_url($href, PHP_URL_PATH) ?? '', PATHINFO_EXTENSION)) === 'pdf'): ?>
    <div class="no-preview">
        <i class="bi bi-file-earmark-pdf fs-1 mb-2"></i>
        <div class="fw-bold">Use Mark PDF button to check this file</div>
        <div class="small mb-3">Marks / Status / Feedback  save </div>
    </div>
                                                        <?php else: ?>
                                                            <div class="no-preview">
                                                                <i class="bi bi-file-earmark-arrow-down fs-1 mb-2"></i>
                                                                <div class="fw-bold">Preview not available for this file type</div>
                                                                <div class="small mb-3">Word/Excel/ZIP වගේ files download/open කරන්න.</div>
                                                                <a href="<?= esc($href) ?>" target="_blank" class="btn btn-primary rounded-pill px-4">
                                                                    Open / Download File
                                                                </a>
                                                            </div>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>

                                                <div class="col-lg-4">
                                                    <div class="mark-panel">
                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Marks</label>
                                                            <input type="number"
                                                                   name="score"
                                                                   class="form-control"
                                                                   min="0"
                                                                   max="<?= esc((string)$maxScore) ?>"
                                                                   step="0.01"
                                                                   value="<?= ($score !== null && $score !== '') ? esc((string)$score) : '' ?>"
                                                                   placeholder="Enter marks">
                                                            <div class="form-text">Max: <?= esc(number_format($maxScore, 2)) ?></div>
                                                        </div>

                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Status</label>
                                                            <select name="workflow_status" class="form-select">
                                                                <?php
                                                                $statuses = [
                                                                    'submitted' => 'Submitted',
                                                                    'under_review' => 'Under Review',
                                                                    'needs_correction' => 'Needs Correction',
                                                                    'marked' => 'Marked',
                                                                    'coord_approved' => 'Coordinator Approved',
                                                                    'released' => 'Released',
                                                                ];
                                                                foreach ($statuses as $k => $v):
                                                                ?>
                                                                    <option value="<?= esc($k) ?>" <?= $status === $k ? 'selected' : '' ?>>
                                                                        <?= esc($v) ?>
                                                                    </option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                        </div>

                                                        <div class="mb-3">
                                                            <label class="form-label fw-bold">Feedback / Correction Note</label>
                                                            <textarea name="feedback"
                                                                      class="form-control"
                                                                      rows="8"
                                                                      placeholder="Studentට feedback / correction note එක දාන්න..."><?= esc($r['feedback'] ?? '') ?></textarea>
                                                        </div>
<div class="mb-3">
    <label class="form-label fw-bold">Corrected / Checked File Upload</label>
    <input type="file" name="corrected_file" class="form-control">
    <div class="form-text">PDF, Word, Image files allowed. Mark file upload.</div>

    <?php if (!empty($r['corrected_file_path'])): ?>
        <a href="<?= esc(webify_upload_href((string)$r['corrected_file_path'])) ?>" 
           target="_blank" 
           class="btn btn-sm btn-outline-success rounded-pill mt-2">
            Open Corrected File
        </a>
    <?php endif; ?>
</div>
                                                        <button class="btn btn-success w-100 rounded-pill fw-bold">
                                                            <i class="bi bi-check-circle me-1"></i>
                                                            Save
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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