<?php
// /elms/lecturer/grade.php
declare(strict_types=1);

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

@date_default_timezone_set('Asia/Colombo');

$PAGE_TITLE = 'Grade Submission';
$ACTIVE = 'marking';

$submissionId = (int)($_GET['id'] ?? 0);

if ($submissionId <= 0) {
    header("Location: /elms/lecturer/marking.php");
    exit;
}

/* ---------------- Helpers ---------------- */
function grade_tbl_exists(mysqli $db, string $table): bool {
    $table = $db->real_escape_string($table);
    $res = $db->query("SHOW TABLES LIKE '{$table}'");
    $ok = $res && $res->num_rows > 0;
    if ($res) $res->free();
    return $ok;
}

function grade_col_exists(mysqli $db, string $table, string $col): bool {
    $table = str_replace('`', '``', $table);
    $col = $db->real_escape_string($col);
    $res = $db->query("SHOW COLUMNS FROM `{$table}` LIKE '{$col}'");
    $ok = $res && $res->num_rows > 0;
    if ($res) $res->free();
    return $ok;
}

function grade_first_col(mysqli $db, string $table, array $cols): ?string {
    foreach ($cols as $col) {
        if (grade_col_exists($db, $table, $col)) {
            return $col;
        }
    }
    return null;
}

function grade_redirect(int $id, string $type): void {
    header("Location: /elms/lecturer/grade.php?id={$id}&{$type}=1");
    exit;
}

function grade_status_badge(string $status): array {
    $status = strtolower(trim($status));

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

function public_submission_url(string $path): string {
    $path = str_replace('\\', '/', trim($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/uploads/submissions/' . ltrim($path, '/');
}

/* ---------------- DB safety ---------------- */
if (!isset($mysqli) || !($mysqli instanceof mysqli)) {
    http_response_code(500);
    echo "Database connection not found.";
    exit;
}

if (!grade_tbl_exists($mysqli, 'lms_submissions') || !grade_tbl_exists($mysqli, 'lms_assessments')) {
    http_response_code(500);
    echo "Required tables not found.";
    exit;
}

/* ---------------- Column detection ---------------- */
$studentTable = grade_tbl_exists($mysqli, 'studentss')
    ? 'studentss'
    : (grade_tbl_exists($mysqli, 'students') ? 'students' : null);

$studentNameCol = $studentTable ? (grade_first_col($mysqli, $studentTable, ['full_name', 'name', 'student_name']) ?? 'id') : null;

$assessmentTitleCol = grade_first_col($mysqli, 'lms_assessments', ['title', 'name']) ?? 'id';

$hasWorkflow      = grade_col_exists($mysqli, 'lms_submissions', 'workflow_status');
$hasFinalScore    = grade_col_exists($mysqli, 'lms_submissions', 'final_score');
$hasFeedback      = grade_col_exists($mysqli, 'lms_submissions', 'feedback');
$hasLectFeedback  = grade_col_exists($mysqli, 'lms_submissions', 'lecturer_feedback');
$hasCorrection    = grade_col_exists($mysqli, 'lms_submissions', 'correction_note');
$hasGradedAt      = grade_col_exists($mysqli, 'lms_submissions', 'graded_at');
$hasUpdatedAt     = grade_col_exists($mysqli, 'lms_submissions', 'updated_at');
$hasFilePath      = grade_col_exists($mysqli, 'lms_submissions', 'file_path');
$hasOriginalName  = grade_col_exists($mysqli, 'lms_submissions', 'original_name');
$hasStudentNote   = grade_col_exists($mysqli, 'lms_submissions', 'student_note');
$hasAnswerText    = grade_col_exists($mysqli, 'lms_submissions', 'answer_text');
$hasSubmissionTxt = grade_col_exists($mysqli, 'lms_submissions', 'submission_text');
$hasSubmittedAt   = grade_col_exists($mysqli, 'lms_submissions', 'submitted_at');
$hasCorrectedFile = grade_col_exists($mysqli, 'lms_submissions', 'corrected_file_path');
$hasCorrectedName = grade_col_exists($mysqli, 'lms_submissions', 'corrected_original_name');

$feedbackCol = $hasLectFeedback ? 'lecturer_feedback' : ($hasFeedback ? 'feedback' : null);
$textCol = $hasAnswerText ? 'answer_text' : ($hasSubmissionTxt ? 'submission_text' : null);

/* ---------------- Load submission function ---------------- */
function load_grade_submission(
    mysqli $mysqli,
    int $submissionId,
    ?string $studentTable,
    ?string $studentNameCol,
    string $assessmentTitleCol,
    bool $hasWorkflow,
    bool $hasFinalScore,
    ?string $feedbackCol,
    ?string $textCol,
    bool $hasStudentNote,
    bool $hasFilePath,
    bool $hasOriginalName,
    bool $hasSubmittedAt,
bool $hasCorrectedFile,
bool $hasCorrectedName
): ?array {
    $joinStudent = '';
    $studentExpr = "CONCAT('#', s.student_id)";

    if ($studentTable && $studentNameCol) {
        $joinStudent = "LEFT JOIN {$studentTable} st ON st.id = s.student_id";
        $studentExpr = "COALESCE(st.`{$studentNameCol}`, CONCAT('#', s.student_id))";
    }

    $selectExtra = [];
    $selectExtra[] = $hasWorkflow ? "s.workflow_status" : "'submitted' AS workflow_status";
    $selectExtra[] = $hasFinalScore ? "s.final_score" : "NULL AS final_score";
    $selectExtra[] = $feedbackCol ? "s.{$feedbackCol} AS feedback" : "'' AS feedback";
    $selectExtra[] = $textCol ? "s.{$textCol} AS submission_text" : "'' AS submission_text";
    $selectExtra[] = $hasStudentNote ? "s.student_note" : "'' AS student_note";
    $selectExtra[] = $hasFilePath ? "s.file_path" : "'' AS file_path";
    $selectExtra[] = $hasOriginalName ? "s.original_name" : "'' AS original_name";
    $selectExtra[] = $hasSubmittedAt ? "s.submitted_at" : "NULL AS submitted_at";
    $selectExtra[] = $hasCorrectedFile ? "s.corrected_file_path" : "'' AS corrected_file_path";
$selectExtra[] = $hasCorrectedName ? "s.corrected_original_name" : "'' AS corrected_original_name";

    $sql = "
        SELECT
            s.id,
            s.student_id,
            s.assessment_id,
            s.batch_id,
            a.`{$assessmentTitleCol}` AS assessment_title,
            {$studentExpr} AS student_name,
            " . implode(",\n            ", $selectExtra) . "
        FROM lms_submissions s
        JOIN lms_assessments a ON a.id = s.assessment_id
        {$joinStudent}
        WHERE s.id = ?
        LIMIT 1
    ";

    $stmt = $mysqli->prepare($sql);
    if (!$stmt) {
        return null;
    }

    $stmt->bind_param("i", $submissionId);
    $stmt->execute();
    $row = $stmt->get_result()->fetch_assoc();
    $stmt->close();

    return $row ?: null;
}

/* ---------------- Pre-load for lock check ---------------- */
$submission = load_grade_submission(
    $mysqli,
    $submissionId,
    $studentTable,
    $studentNameCol,
    $assessmentTitleCol,
    $hasWorkflow,
    $hasFinalScore,
    $feedbackCol,
    $textCol,
    $hasStudentNote,
    $hasFilePath,
    $hasOriginalName,
    $hasSubmittedAt,
    $hasCorrectedFile,
    $hasCorrectedName
);

if (!$submission) {
    require_once __DIR__ . '/../includes/lecturer_layout_top.php';
    ?>

    <div class="lux-card">
        <div class="lux-card-body text-center py-5">
            <i class="bi bi-exclamation-triangle fs-1 text-warning"></i>
            <h5 class="fw-bold mt-3">Submission not found</h5>
            <p class="text-muted">The requested submission could not be found.</p>
            <a href="/elms/lecturer/marking.php" class="btn btn-lux">Back to Marking</a>
        </div>
    </div>

    <?php
    require_once __DIR__ . '/../includes/lecturer_layout_bottom.php';
    exit;
}

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

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

$isLocked = in_array($currentStatus, $lockedStatuses, true);

/* ---------------- Handle POST ---------------- */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($isLocked) {
        grade_redirect($submissionId, 'locked');
    }

    $action = (string)($_POST['action'] ?? '');
    $score = trim((string)($_POST['final_score'] ?? ''));
    $feedback = trim((string)($_POST['feedback'] ?? ''));

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

    if ($action === 'save_grade' || $action === 'submit_review') {
        if ($hasFinalScore) {
            $scoreFloat = $score === '' ? null : (float)$score;
            $sets[] = "final_score = ?";
            $types .= 'd';
            $vals[] = $scoreFloat;
        }

        if ($feedbackCol) {
            $sets[] = "{$feedbackCol} = ?";
            $types .= 's';
            $vals[] = $feedback;
        }

        if ($hasWorkflow) {
            $sets[] = "workflow_status = ?";
            $types .= 's';
            $vals[] = $action === 'submit_review' ? 'under_review' : 'graded_provisional';
        }

        if ($hasGradedAt) {
            $sets[] = "graded_at = NOW()";
        }

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

        if ($sets) {
            $sql = "UPDATE lms_submissions SET " . implode(', ', $sets) . " WHERE id = ? AND LOWER(COALESCE(workflow_status,'')) NOT IN ('under_review','coord_review','coordinator_review','admin_review','coord_approved','approved','released','published')";
            $types .= 'i';
            $vals[] = $submissionId;

            $stmt = $mysqli->prepare($sql);
            if ($stmt) {
                $stmt->bind_param($types, ...$vals);
                $stmt->execute();
                $stmt->close();
            }
        }

        grade_redirect($submissionId, $action === 'submit_review' ? 'submitted' : 'saved');
    }

    if ($action === 'request_correction') {
        $sets = [];
        $types = '';
        $vals = [];

        if ($hasWorkflow) {
            $sets[] = "workflow_status = ?";
            $types .= 's';
            $vals[] = 'needs_correction';
        }

        if ($feedbackCol) {
            $sets[] = "{$feedbackCol} = ?";
            $types .= 's';
            $vals[] = $feedback;
        }

        if ($hasCorrection) {
            $sets[] = "correction_note = ?";
            $types .= 's';
            $vals[] = $feedback;
        }

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

        if ($sets) {
            $sql = "UPDATE lms_submissions SET " . implode(', ', $sets) . " WHERE id = ? AND LOWER(COALESCE(workflow_status,'')) NOT IN ('under_review','coord_review','coordinator_review','admin_review','coord_approved','approved','released','published')";
            $types .= 'i';
            $vals[] = $submissionId;

            $stmt = $mysqli->prepare($sql);
            if ($stmt) {
                $stmt->bind_param($types, ...$vals);
                $stmt->execute();
                $stmt->close();
            }
        }

        grade_redirect($submissionId, 'correction');
    }

    grade_redirect($submissionId, 'invalid');
}

/* ---------------- Refresh after possible redirects ---------------- */
$submission = load_grade_submission(
    $mysqli,
    $submissionId,
    $studentTable,
    $studentNameCol,
    $assessmentTitleCol,
    $hasWorkflow,
    $hasFinalScore,
    $feedbackCol,
    $textCol,
    $hasStudentNote,
    $hasFilePath,
    $hasOriginalName,
    $hasSubmittedAt,
    $hasCorrectedFile,
    $hasCorrectedName
);

$currentStatus = strtolower(trim((string)($submission['workflow_status'] ?? 'submitted')));
$isLocked = in_array($currentStatus, $lockedStatuses, true);
[$statusText, $statusClass] = grade_status_badge($currentStatus);

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

<?php if (isset($_GET['saved'])): ?>
    <div class="alert alert-success border-0 rounded-4 shadow-sm">
        <i class="bi bi-check-circle"></i> Grade saved as provisional.
    </div>
<?php endif; ?>

<?php if (isset($_GET['submitted'])): ?>
    <div class="alert alert-success border-0 rounded-4 shadow-sm">
        <i class="bi bi-send-check"></i> Grade submitted for review.
    </div>
<?php endif; ?>

<?php if (isset($_GET['correction'])): ?>
    <div class="alert alert-warning border-0 rounded-4 shadow-sm">
        <i class="bi bi-arrow-counterclockwise"></i> Correction request sent to student.
    </div>
<?php endif; ?>

<?php if (isset($_GET['locked'])): ?>
    <div class="alert alert-info border-0 rounded-4 shadow-sm">
        <i class="bi bi-lock"></i> This submission is locked. It is already under review, approved, or released.
    </div>
<?php endif; ?>

<?php if (isset($_GET['invalid'])): ?>
    <div class="alert alert-danger border-0 rounded-4 shadow-sm">
        <i class="bi bi-exclamation-triangle"></i> Invalid action.
    </div>
<?php endif; ?>

<?php if ($isLocked): ?>
    <div class="alert alert-info rounded-4">
        <i class="bi bi-shield-lock me-1"></i>
        This submission is <strong><?= lecturer_h($statusText) ?></strong>. Lecturer editing is disabled.
    </div>
<?php endif; ?>

<div class="row g-3">
    <div class="col-lg-8">
        <div class="lux-card mb-3">
            <div class="lux-card-header d-flex justify-content-between align-items-center">
                <div>
                    <h5 class="mb-1 fw-bold">Grade Submission</h5>
                    <div class="text-muted small">
                        <?= lecturer_h($submission['assessment_title'] ?? '-') ?>
                    </div>
                </div>

                <div class="d-flex flex-wrap gap-2 align-items-center">
    <?php
    $originalHref = !empty($submission['file_path'])
        ? public_submission_url((string)$submission['file_path'])
        : '';

    $correctedHref = !empty($submission['corrected_file_path'])
        ? public_submission_url((string)$submission['corrected_file_path'])
        : '';

    $openHref = $correctedHref ?: $originalHref;
    ?>

    <?php if ($openHref): ?>
        <a href="<?= lecturer_h($openHref) ?>"
           target="_blank"
           class="btn btn-sm btn-outline-primary rounded-pill px-3 fw-bold">
            <i class="bi bi-box-arrow-up-right me-1"></i>
            Open
        </a>
    <?php endif; ?>

    <?php if (!$isLocked): ?>
        <a href="/elms/lecturer/mark_pdf.php?submission_id=<?= (int)$submission['id'] ?>&assessment_id=<?= (int)$submission['assessment_id'] ?>&batch_id=<?= (int)$submission['batch_id'] ?>"
   target="_blank"
   class="btn btn-sm btn-outline-danger rounded-pill px-3 fw-bold">
    <i class="bi bi-pencil-square me-1"></i>
    Mark / Grade
</a>
    <?php endif; ?>

    <span class="badge <?= lecturer_h($statusClass) ?> rounded-pill px-3 py-2">
        <?= lecturer_h($statusText) ?>
    </span>
</div>
            </div>

            <div class="lux-card-body">
                <form method="post" id="gradeForm">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label small fw-bold">Student</label>
                            <input type="text" class="form-control" value="<?= lecturer_h($submission['student_name'] ?? '-') ?>" readonly>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label small fw-bold">Batch</label>
                            <input type="text" class="form-control" value="<?= lecturer_h((string)($submission['batch_id'] ?? '-')) ?>" readonly>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label small fw-bold">Assessment</label>
                            <input type="text" class="form-control" value="<?= lecturer_h($submission['assessment_title'] ?? '-') ?>" readonly>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label small fw-bold">Final Score</label>
                            <input type="number"
                                   step="0.01"
                                   min="0"
                                   max="100"
                                   name="final_score"
                                   class="form-control"
                                   value="<?= lecturer_h((string)($submission['final_score'] ?? '')) ?>"
                                   placeholder="Enter score"
                                   <?= $isLocked ? 'readonly disabled' : '' ?>>
                        </div>

                        <div class="col-12">
                            <label class="form-label small fw-bold">Lecturer Feedback / Correction Note</label>
                            <textarea name="feedback"
                                      rows="5"
                                      class="form-control"
                                      placeholder="Enter feedback or correction note"
                                      <?= $isLocked ? 'readonly disabled' : '' ?>><?= lecturer_h((string)($submission['feedback'] ?? '')) ?></textarea>
                        </div>
                    </div>

                    <div class="d-flex flex-wrap gap-2 justify-content-end mt-4">
                        <a href="/elms/lecturer/marking.php" class="btn btn-light border rounded-4">
                            Back
                        </a>

                        <?php if (!$isLocked): ?>
                            <button type="submit" name="action" value="request_correction" class="btn btn-warning rounded-4 fw-bold">
                                <i class="bi bi-arrow-counterclockwise"></i>
                                Request Correction
                            </button>

                            <button type="submit" name="action" value="save_grade" class="btn btn-secondary rounded-4 fw-bold">
                                <i class="bi bi-save"></i>
                                Save Provisional
                            </button>

                            <button type="submit" name="action" value="submit_review" class="btn btn-lux">
                                <i class="bi bi-send-check"></i>
                                Submit for Review
                            </button>
                        <?php else: ?>
                            <button type="button" class="btn btn-secondary rounded-4 fw-bold" disabled>
                                <i class="bi bi-lock"></i>
                                Locked
                            </button>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="col-lg-4">
        <div class="lux-card mb-3">
            <div class="lux-card-header">
                <h5 class="mb-1 fw-bold">Student Submission</h5>
                <div class="text-muted small">Submitted answer / file preview.</div>
            </div>

            <div class="lux-card-body">
                <?php if (!empty($submission['student_note'])): ?>
                    <div class="mb-3">
                        <div class="small text-muted fw-bold mb-1">Student Note</div>
                        <div class="border rounded-4 p-3 bg-white" style="white-space:pre-wrap;">
                            <?= lecturer_h((string)$submission['student_note']) ?>
                        </div>
                    </div>
                <?php endif; ?>

                <?php if (!empty($submission['submission_text'])): ?>
                    <div class="mb-3">
                        <div class="small text-muted fw-bold mb-1">Text Answer</div>
                        <div class="border rounded-4 p-3 bg-white" style="white-space:pre-wrap;">
                            <?= lecturer_h((string)$submission['submission_text']) ?>
                        </div>
                    </div>
                <?php endif; ?>

                <?php if (empty($submission['student_note']) && empty($submission['submission_text'])): ?>
                    <p class="text-muted mb-0">No text answer found.</p>
                <?php endif; ?>

                <?php if (!empty($submission['file_path'])): ?>
                    <hr>
                    <a href="<?= lecturer_h(public_submission_url((string)$submission['file_path'])) ?>" target="_blank" class="btn btn-sm btn-lux">
                        <i class="bi bi-paperclip"></i>
                        <?= lecturer_h(!empty($submission['original_name']) ? (string)$submission['original_name'] : 'Open Attached File') ?>
                    </a>
                <?php endif; ?>

                <?php if (!empty($submission['submitted_at'])): ?>
                    <div class="small text-muted mt-3">
                        Submitted: <?= lecturer_h((string)$submission['submitted_at']) ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <div class="lux-card">
            <div class="lux-card-header">
                <h5 class="mb-1 fw-bold">Workflow</h5>
                <div class="text-muted small">Current standard marking flow.</div>
            </div>

            <div class="lux-card-body">
                <div class="d-grid gap-2 small">
                    <div class="border rounded-4 p-3 bg-white">
                        <strong>submitted</strong>
                        <div class="text-muted">Student submitted assessment.</div>
                    </div>

                    <div class="border rounded-4 p-3 bg-white">
                        <strong>needs_correction</strong>
                        <div class="text-muted">Lecturer requested correction.</div>
                    </div>

                    <div class="border rounded-4 p-3 bg-white">
                        <strong>graded_provisional</strong>
                        <div class="text-muted">Lecturer saved marks.</div>
                    </div>

                    <div class="border rounded-4 p-3 bg-white">
                        <strong>under_review</strong>
                        <div class="text-muted">Sent for Coordinator/Admin approval.</div>
                    </div>

                    <div class="border rounded-4 p-3 bg-white">
                        <strong>coord_approved</strong>
                        <div class="text-muted">Coordinator/Admin approved.</div>
                    </div>

                    <div class="border rounded-4 p-3 bg-white">
                        <strong>released</strong>
                        <div class="text-muted">Visible to student after release.</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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