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

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

$PAGE_TITLE = 'Marking';
$ACTIVE = 'marking';

@date_default_timezone_set('Asia/Colombo');

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

function lm_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 lm_action_label(string $status): array {
    $status = strtolower(trim($status));

    return match ($status) {
        'submitted', 'pending' => ['Mark', 'btn-lux', false],
        'needs_correction' => ['Re-check', 'btn-warning rounded-4 fw-bold', false],
        'graded_provisional' => ['Continue', 'btn-secondary rounded-4 fw-bold', false],
        'under_review', 'coord_review', 'coordinator_review', 'admin_review' => ['View', 'btn-outline-info rounded-4 fw-bold', true],
        'coord_approved', 'approved' => ['View', 'btn-outline-success rounded-4 fw-bold', true],
        'released', 'published' => ['View', 'btn-outline-success rounded-4 fw-bold', true],
        default => ['Open', 'btn-lux', false],
    };
}

$rows = [];
$error = '';

$totalSubmitted = 0;
$totalCorrection = 0;
$totalProvisional = 0;
$totalReview = 0;
$totalApproved = 0;
$totalReleased = 0;

$statusFilter = strtolower(trim((string)($_GET['status'] ?? 'active')));
$q = trim((string)($_GET['q'] ?? ''));

$allowedFilters = ['active', 'submitted', 'needs_correction', 'graded_provisional', 'under_review', 'coord_approved', 'released', 'all'];
if (!in_array($statusFilter, $allowedFilters, true)) {
    $statusFilter = 'active';
}

if (!isset($mysqli) || !($mysqli instanceof mysqli)) {
    $error = 'Database connection not found.';
} elseif (!lm_tbl_exists($mysqli, 'lms_submissions')) {
    $error = 'lms_submissions table not found.';
} else {
    $hasAssess = lm_tbl_exists($mysqli, 'lms_assessments');
    $studentTable = lm_tbl_exists($mysqli, 'studentss') ? 'studentss' : (lm_tbl_exists($mysqli, 'students') ? 'students' : null);

    $hasWorkflow = lm_col_exists($mysqli, 'lms_submissions', 'workflow_status');
    $hasScore = lm_col_exists($mysqli, 'lms_submissions', 'final_score');
    $hasSubmittedAt = lm_col_exists($mysqli, 'lms_submissions', 'submitted_at');
    $hasUpdatedAt = lm_col_exists($mysqli, 'lms_submissions', 'updated_at');
    $hasGradedAt = lm_col_exists($mysqli, 'lms_submissions', 'graded_at');

    $assessmentTitleCol = $hasAssess ? (lm_first_col($mysqli, 'lms_assessments', ['title', 'name']) ?? 'id') : null;

    $joinAssess = $hasAssess ? "LEFT JOIN lms_assessments a ON a.id = s.assessment_id" : "";
    $assTitle = $hasAssess && $assessmentTitleCol
        ? "COALESCE(a.`{$assessmentTitleCol}`, CONCAT('#', s.assessment_id))"
        : "CONCAT('#', s.assessment_id)";

    $joinStudent = "";
    $stuName = "CONCAT('#', s.student_id)";

    if ($studentTable) {
        $stuNameCol = lm_first_col($mysqli, $studentTable, ['full_name', 'name', 'student_name']) ?? 'id';
        $joinStudent = "LEFT JOIN {$studentTable} st ON st.id = s.student_id";
        $stuName = "COALESCE(st.`{$stuNameCol}`, CONCAT('#', s.student_id))";
    }

    $statusExpr = $hasWorkflow ? "s.workflow_status" : "'submitted'";
    $scoreExpr = $hasScore ? "s.final_score" : "NULL";

    $dateExpr = $hasSubmittedAt ? "s.submitted_at"
        : ($hasUpdatedAt ? "s.updated_at"
        : ($hasGradedAt ? "s.graded_at" : "s.id"));

    /*
 * Lecturer marking visibility:
 * For now show all assessment submissions in the lecturer marking queue.
 * This avoids hiding valid student submissions when lecturer_courses /
 * lecturer_batches mappings are incomplete or submission.batch_id is 0.
 */
$lecturerId = (int)($LECTURER_USER['id'] ?? 0);
$filterJoin = '';
$baseWhere = [];
$types = '';
$params = [];

    $where = $baseWhere;

    if ($hasWorkflow) {
        if ($statusFilter === 'active') {
            $where[] = "LOWER(COALESCE(s.workflow_status,'')) IN ('submitted','pending','needs_correction','graded_provisional','under_review','coord_review','coordinator_review','admin_review','coord_approved','approved','released','published')";
        } elseif ($statusFilter !== 'all') {
            if ($statusFilter === 'under_review') {
                $where[] = "LOWER(COALESCE(s.workflow_status,'')) IN ('under_review','coord_review','coordinator_review','admin_review')";
            } elseif ($statusFilter === 'coord_approved') {
                $where[] = "LOWER(COALESCE(s.workflow_status,'')) IN ('coord_approved','approved')";
            } elseif ($statusFilter === 'released') {
                $where[] = "LOWER(COALESCE(s.workflow_status,'')) IN ('released','published')";
            } else {
                $where[] = "LOWER(COALESCE(s.workflow_status,'')) = ?";
                $types .= 's';
                $params[] = $statusFilter;
            }
        }
    }

    if ($q !== '') {
        $where[] = "({$stuName} LIKE ? OR {$assTitle} LIKE ? OR {$statusExpr} LIKE ?)";
        $like = "%{$q}%";
        $types .= 'sss';
        $params[] = $like;
        $params[] = $like;
        $params[] = $like;
    }

    $whereSql = $where ? "WHERE " . implode(" AND ", $where) : "";

    $sql = "
        SELECT 
            s.id,
            s.student_id,
            s.assessment_id,
            s.batch_id,
            {$stuName} AS student_name,
            {$assTitle} AS assessment_title,
            {$statusExpr} AS workflow_status,
            {$scoreExpr} AS final_score,
            {$dateExpr} AS action_date
        FROM lms_submissions s
        {$joinAssess}
        {$joinStudent}
        {$filterJoin}
        {$whereSql}
        ORDER BY 
            CASE LOWER(COALESCE({$statusExpr}, '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 300
    ";

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

    if (!$stmt) {
        $error = 'Marking SQL error: ' . $mysqli->error;
    } else {
        if ($types !== '') {
            $stmt->bind_param($types, ...$params);
        }

        $stmt->execute();
        $res = $stmt->get_result();

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

        $stmt->close();
    }

    foreach ($rows as $r) {
        $st = strtolower((string)($r['workflow_status'] ?? 'submitted'));

        if (in_array($st, ['submitted', 'pending'], true)) {
            $totalSubmitted++;
        } elseif ($st === 'needs_correction') {
            $totalCorrection++;
        } elseif ($st === 'graded_provisional') {
            $totalProvisional++;
        } elseif (in_array($st, ['under_review', 'coord_review', 'coordinator_review', 'admin_review'], true)) {
            $totalReview++;
        } elseif (in_array($st, ['coord_approved', 'approved'], true)) {
            $totalApproved++;
        } elseif (in_array($st, ['released', 'published'], true)) {
            $totalReleased++;
        }
    }
}

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

<div class="row g-3 mb-3">
    <div class="col-md-2">
        <div class="lux-card h-100">
            <div class="lux-card-body">
                <div class="text-muted small fw-bold text-uppercase">Submitted</div>
                <div class="fs-3 fw-bold"><?= (int)$totalSubmitted ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-2">
        <div class="lux-card h-100">
            <div class="lux-card-body">
                <div class="text-muted small fw-bold text-uppercase">Correction</div>
                <div class="fs-3 fw-bold"><?= (int)$totalCorrection ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-2">
        <div class="lux-card h-100">
            <div class="lux-card-body">
                <div class="text-muted small fw-bold text-uppercase">Provisional</div>
                <div class="fs-3 fw-bold"><?= (int)$totalProvisional ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-2">
        <div class="lux-card h-100">
            <div class="lux-card-body">
                <div class="text-muted small fw-bold text-uppercase">Review</div>
                <div class="fs-3 fw-bold"><?= (int)$totalReview ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-2">
        <div class="lux-card h-100">
            <div class="lux-card-body">
                <div class="text-muted small fw-bold text-uppercase">Approved</div>
                <div class="fs-3 fw-bold"><?= (int)$totalApproved ?></div>
            </div>
        </div>
    </div>

    <div class="col-md-2">
        <div class="lux-card h-100">
            <div class="lux-card-body">
                <div class="text-muted small fw-bold text-uppercase">Released</div>
                <div class="fs-3 fw-bold"><?= (int)$totalReleased ?></div>
            </div>
        </div>
    </div>
</div>

<div class="lux-card mb-3">
    <div class="lux-card-body">
        <form method="get" class="row g-2 align-items-end">
            <div class="col-lg-6">
                <label class="form-label small fw-bold">Search</label>
                <input type="text"
                       name="q"
                       class="form-control"
                       value="<?= lecturer_h($q) ?>"
                       placeholder="Search student, assessment or status...">
            </div>

            <div class="col-lg-3">
                <label class="form-label small fw-bold">Status</label>
                <select name="status" class="form-select">
                    <option value="active" <?= $statusFilter === 'active' ? 'selected' : '' ?>>Active Workflow</option>
                    <option value="submitted" <?= $statusFilter === 'submitted' ? 'selected' : '' ?>>Submitted</option>
                    <option value="needs_correction" <?= $statusFilter === 'needs_correction' ? 'selected' : '' ?>>Needs Correction</option>
                    <option value="graded_provisional" <?= $statusFilter === 'graded_provisional' ? 'selected' : '' ?>>Provisional</option>
                    <option value="under_review" <?= $statusFilter === 'under_review' ? 'selected' : '' ?>>Under Review</option>
                    <option value="coord_approved" <?= $statusFilter === 'coord_approved' ? 'selected' : '' ?>>Approved</option>
                    <option value="released" <?= $statusFilter === 'released' ? 'selected' : '' ?>>Released</option>
                    <option value="all" <?= $statusFilter === 'all' ? 'selected' : '' ?>>All</option>
                </select>
            </div>

            <div class="col-lg-3">
                <button class="btn btn-lux w-100">
                    <i class="bi bi-funnel"></i> Apply
                </button>
            </div>
        </form>
    </div>
</div>

<div class="lux-card">
    <div class="lux-card-header d-flex justify-content-between align-items-center">
        <div>
            <h5 class="mb-1 fw-bold">Marking Queue</h5>
            <div class="text-muted small">
                Manage submitted, correction, provisional, review, approved and released submissions.
            </div>
        </div>

        <span class="badge-lux"><?= count($rows) ?> Items</span>
    </div>

    <div class="lux-card-body">
        <?php if ($error): ?>
            <div class="alert alert-warning rounded-4">
                <strong>Notice:</strong> <?= lecturer_h($error) ?>
            </div>
        <?php endif; ?>

        <?php if (!$rows): ?>
            <div class="text-center py-5">
                <i class="bi bi-check2-circle fs-1 text-muted"></i>
                <h6 class="mt-3 fw-bold">No marking items</h6>
                <p class="text-muted mb-0">Pending submissions will appear here after students submit assessments.</p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table align-middle">
                    <thead>
                    <tr>
                        <th style="width:70px;">ID</th>
                        <th>Student</th>
                        <th>Assessment</th>
                        <th>Batch</th>
                        <th>Score</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th class="text-end">Action</th>
                    </tr>
                    </thead>

                    <tbody>
                    <?php foreach ($rows as $r): ?>
                        <?php
                            $rawStatus = strtolower((string)($r['workflow_status'] ?? 'submitted'));
                            [$statusText, $statusClass] = lm_status_badge($rawStatus);
                            [$actionText, $buttonClass, $viewOnly] = lm_action_label($rawStatus);
                        ?>

                        <tr>
                            <td class="text-muted">#<?= (int)$r['id'] ?></td>

                            <td class="fw-bold">
                                <?= lecturer_h($r['student_name'] ?? '-') ?>
                            </td>

                            <td>
                                <div class="fw-semibold">
                                    <?= lecturer_h($r['assessment_title'] ?? '-') ?>
                                </div>
                                <div class="small text-muted">
                                    Assessment ID: <?= (int)($r['assessment_id'] ?? 0) ?>
                                </div>
                            </td>

                            <td>
                                <span class="badge-lux">
                                    <?= lecturer_h((string)($r['batch_id'] ?? '-')) ?>
                                </span>
                            </td>

                            <td>
                                <?php if ($r['final_score'] !== null && $r['final_score'] !== ''): ?>
                                    <span class="fw-bold"><?= lecturer_h((string)$r['final_score']) ?></span>
                                <?php else: ?>
                                    <span class="text-muted">Not marked</span>
                                <?php endif; ?>
                            </td>

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

                            <td class="text-muted small">
                                <?= lecturer_h((string)($r['action_date'] ?? '-')) ?>
                            </td>

                            <td class="text-end">
                                <a href="/elms/lecturer/grade.php?id=<?= (int)$r['id'] ?>"
                                   class="btn btn-sm <?= lecturer_h($buttonClass) ?>">
                                    <?= lecturer_h($actionText) ?>
                                </a>

                                <?php if ($viewOnly): ?>
                                    <div class="small text-muted mt-1">Read-only</div>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

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