<?php
// /elms/student/assessments/submit.php
declare(strict_types=1);

$PAGE_TITLE = 'Submit Assessment';
$ACTIVE = 'assessments';

require_once __DIR__ . '/../../includes/student_auth.php';
require_once __DIR__ . '/../../includes/elms_notifications.php';
require_once __DIR__ . '/../../includes/elms_settings.php';

$mysqli = $mysqli ?? ($conn ?? null);

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

$mysqli->set_charset('utf8mb4');
$maxMb = (int)elms_setting($mysqli, 'max_upload_size_mb', '10');
$maxMb = max(1, $maxMb);

$allowedTypesText = elms_setting($mysqli, 'allowed_file_types', 'pdf,doc,docx,ppt,pptx,jpg,png,zip');
$allowed = array_values(array_filter(array_map('trim', explode(',', strtolower($allowedTypesText)))));

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

if (!function_exists('sa_table_exists')) {
    function sa_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;
    }
}

if (!function_exists('sa_col_exists')) {
    function sa_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;
    }
}

if (!function_exists('sa_first_col')) {
    function sa_first_col(mysqli $db, string $table, array $cols): ?string {
        if (!sa_table_exists($db, $table)) return null;

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

        return null;
    }
}

if (!function_exists('flash')) {
    function flash($key, $value = null) {
        if ($value === null) {
            $msg = $_SESSION['flash'][$key] ?? null;
            unset($_SESSION['flash'][$key]);
            return $msg;
        }

        $_SESSION['flash'][$key] = $value;
        return null;
    }
}

if (!function_exists('clean_file_name')) {
    function clean_file_name(string $name): string {
        $name = preg_replace('/[^A-Za-z0-9._-]+/', '_', $name);
        return trim((string)$name, '._');
    }
}

if (!function_exists('public_file_url')) {
    function public_file_url(string $relative): string {
        $relative = str_replace('\\', '/', trim($relative));

        if ($relative === '') return '';
        if (preg_match('#^https?://#i', $relative)) return $relative;
        if (str_starts_with($relative, '/elms/')) return $relative;
        if (str_starts_with($relative, '/uploads/')) return '/elms' . $relative;
        if (str_starts_with($relative, 'uploads/')) return '/elms/' . $relative;

        return '/elms/uploads/submissions/' . ltrim($relative, '/');
    }
}

if (!function_exists('fmt_dt')) {
    function fmt_dt($date): string {
        $date = trim((string)$date);

        if ($date === '' || $date === '0000-00-00' || $date === '0000-00-00 00:00:00') {
            return 'No due date';
        }

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

$student_id = (int)($GLOBALS['STUDENT_ID'] ?? ($_SESSION['student_id'] ?? 0));
$assessment_id = (int)($_GET['assessment_id'] ?? $_POST['assessment_id'] ?? 0);

if ($student_id <= 0) {
    session_destroy();
    header('Location: /elms/student/login.php');
    exit;
}

if ($assessment_id <= 0) {
    header('Location: /elms/student/assessments/assessments.php');
    exit;
}

/*
|--------------------------------------------------------------------------
| Student
|--------------------------------------------------------------------------
*/

if (!sa_table_exists($mysqli, 'studentss')) {
    http_response_code(500);
    exit('studentss table not found');
}

$studentSelect = ['id'];

foreach (['full_name', 'name', 'student_name', 'academic_email', 'center_reg_no', 'reference_no', 'lms_status', 'course_id'] as $col) {
    if (sa_col_exists($mysqli, 'studentss', $col)) {
        $studentSelect[] = "`{$col}`";
    }
}

$sql = "SELECT " . implode(', ', $studentSelect) . " FROM studentss WHERE id = ? LIMIT 1";
$st = $mysqli->prepare($sql);
$st->bind_param('i', $student_id);
$st->execute();
$student = $st->get_result()->fetch_assoc();
$st->close();

if (!$student) {
    session_destroy();
    header('Location: /elms/student/login.php');
    exit;
}

$studentName = $student['full_name'] ?? ($student['name'] ?? ($student['student_name'] ?? 'Student'));

$_SESSION['student_name']   = $studentName;
$_SESSION['academic_email'] = $student['academic_email'] ?? ($_SESSION['academic_email'] ?? '');
$_SESSION['center_reg_no']  = $student['center_reg_no'] ?? ($_SESSION['center_reg_no'] ?? '');

$GLOBALS['STUDENT_NAME'] = $_SESSION['student_name'];
$GLOBALS['STUDENT_EMAIL'] = $_SESSION['academic_email'];
$GLOBALS['STUDENT_REG_NO'] = $_SESSION['center_reg_no'];

$lms_status = strtolower(trim((string)($student['lms_status'] ?? 'active')));

if (in_array($lms_status, ['inactive', 'suspended'], true)) {
    session_destroy();
    header('Location: /elms/student/login.php');
    exit;
}

/*
|--------------------------------------------------------------------------
| Assessment
|--------------------------------------------------------------------------
*/

if (!sa_table_exists($mysqli, 'lms_assessments')) {
    http_response_code(404);
    exit('lms_assessments table not found');
}

$aTitleCol  = sa_first_col($mysqli, 'lms_assessments', ['title', 'name']) ?? 'id';
$aMaxCol    = sa_first_col($mysqli, 'lms_assessments', ['max_score', 'max_mark', 'max_marks', 'total_marks', 'marks']);
$aDueCol    = sa_first_col($mysqli, 'lms_assessments', ['due_at', 'due_date', 'deadline', 'available_to', 'close_at']);
$aBriefCol  = sa_first_col($mysqli, 'lms_assessments', ['brief', 'instructions', 'description']);
$aModuleCol = sa_col_exists($mysqli, 'lms_assessments', 'module_id') ? 'module_id' : null;
$aCourseCol = sa_col_exists($mysqli, 'lms_assessments', 'course_id') ? 'course_id' : null;
$aActiveCol = sa_first_col($mysqli, 'lms_assessments', ['active', 'is_active', 'status']);

$select = [];
$select[] = "id";
$select[] = "`{$aTitleCol}` AS title";
$select[] = $aMaxCol ? "`{$aMaxCol}` AS max_marks" : "100 AS max_marks";
$select[] = $aDueCol ? "`{$aDueCol}` AS due_at" : "NULL AS due_at";
$select[] = $aBriefCol ? "`{$aBriefCol}` AS brief" : "'' AS brief";
$select[] = $aModuleCol ? "`{$aModuleCol}` AS module_id" : "0 AS module_id";
$select[] = $aCourseCol ? "`{$aCourseCol}` AS course_id" : "0 AS course_id";

$where = "id = ?";

if ($aActiveCol) {
    if ($aActiveCol === 'status') {
        $where .= " AND LOWER(COALESCE(`{$aActiveCol}`,'')) NOT IN ('inactive','disabled','draft','archived')";
    } else {
        $where .= " AND (`{$aActiveCol}` IS NULL OR `{$aActiveCol}` IN (1,'1','active','Active','ACTIVE','yes','YES'))";
    }
}

$sql = "SELECT " . implode(', ', $select) . " FROM lms_assessments WHERE {$where} LIMIT 1";

$st = $mysqli->prepare($sql);
$st->bind_param('i', $assessment_id);
$st->execute();
$assessment = $st->get_result()->fetch_assoc();
$st->close();

if (!$assessment) {
    http_response_code(404);
    exit('Assessment not found');
}

/*
|--------------------------------------------------------------------------
| Ensure lms_submissions
|--------------------------------------------------------------------------
*/

$mysqli->query("
CREATE TABLE IF NOT EXISTS `lms_submissions` (
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `assessment_id` INT UNSIGNED NOT NULL,
    `student_id` INT UNSIGNED NOT NULL,
    `batch_id` INT NULL,
    `file_path` VARCHAR(500) NULL,
    `original_name` VARCHAR(255) NULL,
    `student_note` TEXT NULL,
    `workflow_status` VARCHAR(50) NOT NULL DEFAULT 'submitted',
    `final_score` DECIMAL(10,2) NULL,
    `lecturer_feedback` TEXT NULL,
    `submitted_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
    `graded_at` DATETIME NULL,
    `released_at` DATETIME NULL,
    PRIMARY KEY (`id`),
    KEY `idx_assessment_student` (`assessment_id`, `student_id`),
    KEY `idx_student` (`student_id`),
    KEY `idx_workflow_status` (`workflow_status`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

/*
|--------------------------------------------------------------------------
| Column detection
|--------------------------------------------------------------------------
*/

$hasBatchId      = sa_col_exists($mysqli, 'lms_submissions', 'batch_id');
$hasFilePath     = sa_col_exists($mysqli, 'lms_submissions', 'file_path');
$hasOriginalName = sa_col_exists($mysqli, 'lms_submissions', 'original_name');
$hasStudentNote  = sa_col_exists($mysqli, 'lms_submissions', 'student_note');
$hasStatus       = sa_col_exists($mysqli, 'lms_submissions', 'workflow_status');
$hasSubmittedAt  = sa_col_exists($mysqli, 'lms_submissions', 'submitted_at');
$hasUpdatedAt    = sa_col_exists($mysqli, 'lms_submissions', 'updated_at');
$hasScore        = sa_col_exists($mysqli, 'lms_submissions', 'final_score');
$hasFeedback     = sa_col_exists($mysqli, 'lms_submissions', 'lecturer_feedback');
$hasCorrectedFile = sa_col_exists($mysqli, 'lms_submissions', 'corrected_file_path');

$filePathCol = $hasFilePath ? 'file_path' : null;
$originalNameCol = $hasOriginalName ? 'original_name' : null;
$noteCol = $hasStudentNote ? 'student_note' : null;

/*
|--------------------------------------------------------------------------
| Existing Submission
|--------------------------------------------------------------------------
*/

$submission = null;

$st = $mysqli->prepare("
    SELECT *
    FROM lms_submissions
    WHERE assessment_id = ?
      AND student_id = ?
    ORDER BY id DESC
    LIMIT 1
");
$st->bind_param('ii', $assessment_id, $student_id);
$st->execute();
$submission = $st->get_result()->fetch_assoc();
$st->close();

$currentStatus = strtolower((string)($submission['workflow_status'] ?? ''));

$lockedStatuses = [
    'under_review',
    'coord_review',
    'coordinator_review',
    'admin_review',
    'coord_approved',
    'approved',
    'released',
    'published'
];

$isLocked = $submission && in_array($currentStatus, $lockedStatuses, true);
$resubmissionAllowed = elms_setting_on($mysqli, 'assignment_resubmission', 'on');

if (!$resubmissionAllowed && $submission) {
    $isLocked = true;
}
/*
|--------------------------------------------------------------------------
| Detect student batch for this assessment
|--------------------------------------------------------------------------
*/

$detectedBatchId = 0;
$assessmentCourseId = (int)($assessment['course_id'] ?? 0);

if ($assessmentCourseId > 0 && sa_table_exists($mysqli, 'enrollments') && sa_table_exists($mysqli, 'batches')) {
    $st = $mysqli->prepare("
        SELECT b.id
        FROM enrollments e
        INNER JOIN batches b ON b.id = e.batch_id
        WHERE e.student_id = ?
          AND b.course_id = ?
        ORDER BY e.id DESC
        LIMIT 1
    ");

    if ($st) {
        $st->bind_param('ii', $student_id, $assessmentCourseId);
        $st->execute();
        $batchRow = $st->get_result()->fetch_assoc();
        $st->close();

        if (!empty($batchRow['id'])) {
            $detectedBatchId = (int)$batchRow['id'];
        }
    }
}

if ($detectedBatchId <= 0 && sa_table_exists($mysqli, 'lms_assessment_batches') && sa_table_exists($mysqli, 'enrollments')) {
    $st = $mysqli->prepare("
        SELECT ab.batch_id
        FROM lms_assessment_batches ab
        INNER JOIN enrollments e ON e.batch_id = ab.batch_id
        WHERE ab.assessment_id = ?
          AND e.student_id = ?
        ORDER BY ab.batch_id DESC
        LIMIT 1
    ");

    if ($st) {
        $st->bind_param('ii', $assessment_id, $student_id);
        $st->execute();
        $batchRow = $st->get_result()->fetch_assoc();
        $st->close();

        if (!empty($batchRow['batch_id'])) {
            $detectedBatchId = (int)$batchRow['batch_id'];
        }
    }
}

if ($detectedBatchId <= 0 && $submission && !empty($submission['batch_id'])) {
    $detectedBatchId = (int)$submission['batch_id'];
}

/*
|--------------------------------------------------------------------------
| Submit Upload
|--------------------------------------------------------------------------
*/

if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
    if ($isLocked) {
        flash('err', 'This submission is already under review or released. You cannot update it now.');
        header("Location: submit.php?assessment_id={$assessment_id}");
        exit;
    }

    $note = trim((string)($_POST['student_note'] ?? ''));

    $hasNewFile = (
        isset($_FILES['submission_file']) &&
        !empty($_FILES['submission_file']['name']) &&
        is_uploaded_file($_FILES['submission_file']['tmp_name'])
    );

    if (!$hasNewFile && !$submission) {
        flash('err', 'Please upload your submission file.');
        header("Location: submit.php?assessment_id={$assessment_id}");
        exit;
    }

    $filePath = ($filePathCol && $submission && isset($submission[$filePathCol])) ? $submission[$filePathCol] : null;
    $originalName = ($originalNameCol && $submission && isset($submission[$originalNameCol])) ? $submission[$originalNameCol] : null;

    if ($hasNewFile) {
        $originalName = (string)($_FILES['submission_file']['name'] ?? '');
$ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));

if ($ext === '' || !in_array($ext, $allowed, true)) {
    flash('err', 'Invalid file type. Allowed: ' . strtoupper($allowedTypesText));
    header("Location: submit.php?assessment_id={$assessment_id}");
    exit;
}

if ((int)($_FILES['submission_file']['size'] ?? 0) > ($maxMb * 1024 * 1024)) {
    flash('err', "File too large. Maximum {$maxMb}MB allowed.");
    header("Location: submit.php?assessment_id={$assessment_id}");
    exit;
}

        $uploadDir = dirname(__DIR__, 2) . '/uploads/submissions';

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

        $safeName = date('Ymd_His') . '_A' . $assessment_id . '_S' . $student_id . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
        $dest = rtrim($uploadDir, '/\\') . DIRECTORY_SEPARATOR . clean_file_name($safeName);

        if (!move_uploaded_file($_FILES['submission_file']['tmp_name'], $dest)) {
            flash('err', 'Upload failed. Please try again.');
            header("Location: submit.php?assessment_id={$assessment_id}");
            exit;
        }

        $filePath = 'uploads/submissions/' . basename($dest);
    }

    if ($submission) {
        $sid = (int)$submission['id'];

        $sets = [];
        $types = '';
        $params = [];

        if ($hasBatchId && $detectedBatchId > 0) {
            $sets[] = "batch_id = ?";
            $types .= 'i';
            $params[] = $detectedBatchId;
        }

        if ($filePathCol) {
            $sets[] = "{$filePathCol} = ?";
            $types .= 's';
            $params[] = $filePath;
        }

        if ($originalNameCol) {
            $sets[] = "{$originalNameCol} = ?";
            $types .= 's';
            $params[] = $originalName;
        }

        if ($noteCol) {
            $sets[] = "{$noteCol} = ?";
            $types .= 's';
            $params[] = $note;
        }

        if ($hasStatus) {
            $sets[] = "workflow_status = 'submitted'";
        }

        if ($hasSubmittedAt) {
            $sets[] = "submitted_at = NOW()";
        }

        if ($hasUpdatedAt) {
            $sets[] = "updated_at = NOW()";
        }

        if ($hasScore) {
            $sets[] = "final_score = NULL";
        }

        if ($hasFeedback && in_array($currentStatus, ['needs_correction'], true)) {
            $sets[] = "lecturer_feedback = NULL";
        }

        if ($sets) {
            $sql = "UPDATE lms_submissions SET " . implode(', ', $sets) . " WHERE id = ? AND student_id = ?";
            $types .= 'ii';
            $params[] = $sid;
            $params[] = $student_id;

            $st = $mysqli->prepare($sql);

            if (!$st) {
                flash('err', 'Submission update SQL error: ' . $mysqli->error);
                header("Location: submit.php?assessment_id={$assessment_id}");
                exit;
            }

            $st->bind_param($types, ...$params);
            $st->execute();
            $st->close();
        }
        lms_notify(
    $mysqli,
    'coordinator',
    1,
    'Submission Updated',
    ($_SESSION['student_name'] ?? 'Student') . ' updated a submission for ' . ($assessment['title'] ?? 'Assessment') . '.',
    '/elms/coordinator/approval.php',
    'bi-cloud-check',
    'info'
);

        flash('ok', 'Submission updated successfully. Status changed to submitted.');
    } else {
        $cols = ['assessment_id', 'student_id'];
        $holders = ['?', '?'];
        $types = 'ii';
        $params = [$assessment_id, $student_id];

        if ($hasBatchId) {
            $cols[] = 'batch_id';
            $holders[] = '?';
            $types .= 'i';
            $params[] = $detectedBatchId > 0 ? $detectedBatchId : 0;
        }

        if ($filePathCol) {
            $cols[] = $filePathCol;
            $holders[] = '?';
            $types .= 's';
            $params[] = $filePath;
        }

        if ($originalNameCol) {
            $cols[] = $originalNameCol;
            $holders[] = '?';
            $types .= 's';
            $params[] = $originalName;
        }

        if ($noteCol) {
            $cols[] = $noteCol;
            $holders[] = '?';
            $types .= 's';
            $params[] = $note;
        }

        if ($hasStatus) {
            $cols[] = 'workflow_status';
            $holders[] = "'submitted'";
        }

        if ($hasSubmittedAt) {
            $cols[] = 'submitted_at';
            $holders[] = 'NOW()';
        }

        $sql = "
            INSERT INTO lms_submissions
                (" . implode(', ', $cols) . ")
            VALUES
                (" . implode(', ', $holders) . ")
        ";

        $st = $mysqli->prepare($sql);

        if (!$st) {
            flash('err', 'Submission insert SQL error: ' . $mysqli->error);
            header("Location: submit.php?assessment_id={$assessment_id}");
            exit;
        }

        $st->bind_param($types, ...$params);
        $st->execute();
        $st->close();
        
        lms_notify(
    $mysqli,
    'coordinator',
    1,
    'New Submission',
    ($_SESSION['student_name'] ?? 'Student') . ' submitted ' . ($assessment['title'] ?? 'Assessment') . '.',
    '/elms/coordinator/approval.php',
    'bi-cloud-arrow-up',
    'success'
);

        flash('ok', 'Submission uploaded successfully. Status: submitted.');
    }

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

/*
|--------------------------------------------------------------------------
| Refresh Submission
|--------------------------------------------------------------------------
*/

$submission = null;

$st = $mysqli->prepare("
    SELECT *
    FROM lms_submissions
    WHERE assessment_id = ?
      AND student_id = ?
    ORDER BY id DESC
    LIMIT 1
");
$st->bind_param('ii', $assessment_id, $student_id);
$st->execute();
$submission = $st->get_result()->fetch_assoc();
$st->close();

$currentStatus = strtolower((string)($submission['workflow_status'] ?? ''));
$isLocked = $submission && in_array($currentStatus, $lockedStatuses, true);

$dueText = fmt_dt($assessment['due_at'] ?? '');
$isOverdue = false;

if (!empty($assessment['due_at'])) {
    $dueTs = strtotime((string)$assessment['due_at']);
    $isOverdue = $dueTs && $dueTs < time();
}

$statusLabel = 'Not Submitted';
$statusClass = 'lux-status-pending';
$statusIcon = 'bi-clock-history';

if ($submission) {
    if ($currentStatus === 'needs_correction') {
        $statusLabel = 'Correction Required';
        $statusClass = 'lux-status-warning';
        $statusIcon = 'bi-arrow-counterclockwise';
    } elseif (in_array($currentStatus, ['released', 'published'], true)) {
        $statusLabel = 'Released';
        $statusClass = 'lux-status-submitted';
        $statusIcon = 'bi-award';
    } elseif (in_array($currentStatus, ['under_review', 'coord_review', 'coordinator_review', 'admin_review'], true)) {
        $statusLabel = 'Under Review';
        $statusClass = 'lux-status-review';
        $statusIcon = 'bi-hourglass-split';
    } elseif (in_array($currentStatus, ['coord_approved', 'approved'], true)) {
        $statusLabel = 'Approved';
        $statusClass = 'lux-status-review';
        $statusIcon = 'bi-check2-circle';
    } else {
        $statusLabel = 'Submitted';
        $statusClass = 'lux-status-submitted';
        $statusIcon = 'bi-check-circle';
    }
}

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

<style>
    .lux-page-head {
        border-radius: 26px;
        background:
            radial-gradient(circle at top right, rgba(37, 99, 235, .18), transparent 30%),
            linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
        border: 1px solid #e5e7eb;
        box-shadow: 0 16px 40px rgba(15, 23, 42, .055);
        padding: 24px;
        margin-bottom: 22px;
    }

    .lux-kicker {
        display: inline-flex;
        align-items: center;
        gap: 8px;
        background: #eff6ff;
        color: #1d4ed8;
        border: 1px solid #bfdbfe;
        border-radius: 999px;
        padding: 7px 11px;
        font-size: 12px;
        font-weight: 900;
        margin-bottom: 12px;
    }

    .lux-title {
        font-size: clamp(24px, 3vw, 34px);
        font-weight: 950;
        letter-spacing: -.04em;
        margin: 0;
        color: #0f172a;
    }

    .lux-muted {
        color: #64748b;
    }

    .lux-card {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 24px;
        box-shadow: 0 14px 34px rgba(15, 23, 42, .055);
        overflow: hidden;
    }

    .lux-card-header {
        padding: 20px 22px;
        border-bottom: 1px solid #edf2f7;
    }

    .lux-card-body {
        padding: 22px;
    }

    .lux-brief-box {
        background: #f8fafc;
        border: 1px solid rgba(15,23,42,.08);
        border-radius: 20px;
        padding: 16px;
        line-height: 1.7;
        color: #334155;
    }

    .lux-status-box {
        border-radius: 22px;
        padding: 24px;
        text-align: center;
    }

    .lux-status-pending {
        background: #fff7ed;
        color: #9a3412;
        border: 1px solid #fed7aa;
    }

    .lux-status-submitted {
        background: #ecfdf5;
        color: #047857;
        border: 1px solid #a7f3d0;
    }

    .lux-status-warning {
        background: #fffbeb;
        color: #b45309;
        border: 1px solid #fde68a;
    }

    .lux-status-review {
        background: #eff6ff;
        color: #1d4ed8;
        border: 1px solid #bfdbfe;
    }

    .lux-feedback-box {
        background: #f8fafc;
        border: 1px solid rgba(15,23,42,.08);
        border-radius: 16px;
        padding: 13px;
        line-height: 1.6;
    }

    .btn-lux-dark {
        background: #0f172a;
        border-color: #0f172a;
        color: #fff;
        border-radius: 999px;
        font-weight: 850;
    }

    .btn-lux-dark:hover {
        background: #1e293b;
        border-color: #1e293b;
        color: #fff;
    }

    @media(max-width: 576px) {
        .lux-page-head,
        .lux-card-header,
        .lux-card-body {
            padding: 18px;
        }
    }
</style>

<div class="lux-page-head">
    <div class="lux-kicker">
        <i class="bi bi-cloud-arrow-up"></i>
        Assessment Submission
    </div>

    <div class="d-flex flex-column flex-lg-row justify-content-between align-items-lg-end gap-3">
        <div>
            <h1 class="lux-title">
                <?= h($assessment['title'] ?? 'Assessment') ?>
            </h1>

            <div class="lux-muted mt-2">
                Max Marks: <?= h($assessment['max_marks'] ?? '100') ?>
                <span class="mx-1">|</span>
                Due: <?= h($dueText) ?>
            </div>
        </div>

        <div class="d-flex flex-wrap gap-2">
            <a href="/elms/student/assessments/brief.php?assessment_id=<?= (int)$assessment_id ?>"
               class="btn btn-outline-secondary rounded-pill px-4 fw-bold">
                <i class="bi bi-file-earmark-text me-1"></i>
                Brief
            </a>

            <a href="/elms/student/assessments/assessments.php"
               class="btn btn-outline-primary rounded-pill px-4 fw-bold">
                <i class="bi bi-arrow-left me-1"></i>
                Back
            </a>
        </div>
    </div>
</div>

<?php if ($msg = flash('ok')): ?>
    <div class="alert alert-success rounded-4"><?= h($msg) ?></div>
<?php endif; ?>

<?php if ($msg = flash('err')): ?>
    <div class="alert alert-danger rounded-4"><?= h($msg) ?></div>
<?php endif; ?>

<?php if ($isOverdue && !$submission): ?>
    <div class="alert alert-warning rounded-4">
        <i class="bi bi-exclamation-triangle me-1"></i>
        This assessment due date has passed. Submission may be marked as late.
    </div>
<?php endif; ?>

<?php if ($isLocked): ?>
    <div class="alert alert-info rounded-4">
        <i class="bi bi-lock me-1"></i>
        This submission is already <?= h($statusLabel) ?>. You cannot update it now.
    </div>
<?php endif; ?>

<div class="row g-4">
    <div class="col-xl-7">
        <div class="lux-card">
            <div class="lux-card-header">
                <h3 class="h6 fw-bold mb-0" style="font-weight:950;">
                    <?= $submission ? 'Update Submission' : 'Upload Submission' ?>
                </h3>
            </div>

            <div class="lux-card-body">
                <form method="post" enctype="multipart/form-data">
                    <input type="hidden" name="assessment_id" value="<?= (int)$assessment_id ?>">

                    <div class="mb-3">
                        <label class="form-label fw-bold">Submission File</label>
                        <input type="file" name="submission_file" class="form-control" <?= $isLocked ? 'disabled' : '' ?>>
                        <div class="form-text">
                            Allowed: <?= h(strtoupper($allowedTypesText)) ?>. Maximum <?= (int)$maxMb ?>MB.
                            <?php if ($submission && !$isLocked): ?>
                                Leave empty if you only want to update your note.
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="mb-4">
                        <label class="form-label fw-bold">Student Note / Comment</label>
                        <textarea name="student_note"
                                  rows="5"
                                  class="form-control"
                                  placeholder="Write any note for your lecturer..."
                                  <?= $isLocked ? 'disabled' : '' ?>><?= h($submission['student_note'] ?? '') ?></textarea>
                    </div>

                    <button class="btn btn-lux-dark px-4" <?= $isLocked ? 'disabled' : '' ?>>
                        <i class="bi bi-cloud-arrow-up me-1"></i>
                        <?= $submission ? 'Update Submission' : 'Submit Assessment' ?>
                    </button>
                </form>
            </div>
        </div>
    </div>

    <div class="col-xl-5">
        <div class="lux-card mb-4">
            <div class="lux-card-header">
                <h3 class="h6 fw-bold mb-0" style="font-weight:950;">Assessment Brief</h3>
            </div>

            <div class="lux-card-body">
                <?php if (!empty($assessment['brief'])): ?>
                    <div class="lux-brief-box">
                        <?= nl2br(h(strip_tags((string)$assessment['brief']))) ?>
                    </div>
                <?php else: ?>
                    <div class="text-muted">
                        No text brief available. Use the Brief button to check attached files.
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="lux-card">
            <div class="lux-card-header">
                <h3 class="h6 fw-bold mb-0" style="font-weight:950;">Submission Status</h3>
            </div>

            <div class="lux-card-body">
                <?php if (!$submission): ?>
                    <div class="lux-status-box lux-status-pending">
                        <i class="bi bi-clock-history fs-2 d-block mb-2"></i>
                        <div class="fw-bold">Not Submitted</div>
                        <div class="small">Upload your file before the due date.</div>
                    </div>
                <?php else: ?>
                    <div class="lux-status-box <?= h($statusClass) ?>">
                        <i class="bi <?= h($statusIcon) ?> fs-2 d-block mb-2"></i>
                        <div class="fw-bold"><?= h($statusLabel) ?></div>
                        <div class="small">
                            <?= h(fmt_dt($submission['submitted_at'] ?? '')) ?>
                        </div>
                    </div>

                    <div class="mt-3">
                        <div class="small text-muted">Workflow Status</div>
                        <div class="fw-bold"><?= h($submission['workflow_status'] ?? 'submitted') ?></div>
                    </div>

                    <div class="mt-3">
                        <div class="small text-muted">File</div>

                        <?php if (!empty($submission['file_path'])): ?>
                            <?php
                                $displayFileName = '';

                                if (isset($submission['original_name']) && trim((string)$submission['original_name']) !== '') {
                                    $displayFileName = (string)$submission['original_name'];
                                } else {
                                    $displayFileName = basename((string)$submission['file_path']);
                                }
                            ?>

                            <a href="<?= h(public_file_url((string)$submission['file_path'])) ?>"
                               target="_blank"
                               class="fw-bold text-decoration-none">
                                <i class="bi bi-file-earmark-arrow-down me-1"></i>
                                <?= h($displayFileName) ?>
                            </a>
                        <?php else: ?>
                            <div class="text-muted">No file attached.</div>
                        <?php endif; ?>
                    </div>

                    <?php if (!empty($submission['lecturer_feedback'])): ?>
                        <div class="mt-3">
                            <div class="small text-muted">Lecturer Feedback</div>
                            <div class="lux-feedback-box">
                                <?= nl2br(h((string)$submission['lecturer_feedback'])) ?>
                            </div>
                        </div>
                    <?php endif; ?>

                    <?php if (($submission['final_score'] ?? null) !== null && in_array($currentStatus, ['released', 'published'], true)): ?>
                        <div class="mt-3">
                            <div class="small text-muted">Released Marks</div>
                            <div class="fw-bold"><?= h((string)$submission['final_score']) ?></div>
                        </div>
                    <?php endif; ?>

                    <?php if (!empty($submission['batch_id'])): ?>
                        <div class="mt-3">
                            <div class="small text-muted">Batch ID</div>
                            <div class="fw-bold"><?= (int)$submission['batch_id'] ?></div>
                        </div>
                    <?php endif; ?>
                    <?php if (
    $hasCorrectedFile &&
    !empty($submission['corrected_file_path']) &&
    in_array($currentStatus, ['released', 'published'], true)
): ?>
    <div class="mt-3">
        <div class="small text-muted">Checked / Marked File</div>
        <a href="<?= h(public_file_url((string)$submission['corrected_file_path'])) ?>"
           target="_blank"
           class="fw-bold text-decoration-none text-success">
            <i class="bi bi-file-earmark-check me-1"></i>
            Open checked file
        </a>
    </div>
<?php endif; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

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