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

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

$PAGE_TITLE = 'Assessments';
$ACTIVE = 'assessments';

$search = trim((string)($_GET['q'] ?? ''));
$view   = (string)($_GET['view'] ?? 'pending');
$limit  = max(10, min(100, (int)($_GET['limit'] ?? 20)));

function tbl_exists_assess(mysqli $db, string $table): bool {
    $table = $db->real_escape_string($table);
    $res = $db->query("SHOW TABLES LIKE '{$table}'");
    return $res && $res->num_rows > 0;
}

function col_exists_assess(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}'");
    return $res && $res->num_rows > 0;
}

$rows = [];

if (isset($mysqli) && $mysqli instanceof mysqli && tbl_exists_assess($mysqli, 'lms_submissions') && tbl_exists_assess($mysqli, 'lms_assessments')) {
    $studentTable = tbl_exists_assess($mysqli, 'studentss') ? 'studentss' : (tbl_exists_assess($mysqli, 'students') ? 'students' : null);

    $assessmentTitleCol = col_exists_assess($mysqli, 'lms_assessments', 'title') ? 'title' : 'name';
    $studentNameCol = $studentTable && col_exists_assess($mysqli, $studentTable, 'full_name') ? 'full_name' : 'name';

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

    $submittedCol = col_exists_assess($mysqli, 'lms_submissions', 'submitted_at') ? 'submitted_at' :
        (col_exists_assess($mysqli, 'lms_submissions', 'created_at') ? 'created_at' : 'id');

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

    if ($view !== 'all' && col_exists_assess($mysqli, 'lms_submissions', 'workflow_status')) {
        $where[] = "LOWER(s.workflow_status) IN ('submitted','needs_correction','pending','draft')";
    }

    if ($search !== '') {
        $where[] = "({$studentExpr} LIKE ? OR a.{$assessmentTitleCol} LIKE ?)";
        $like = "%{$search}%";
        $params[] = $like;
        $params[] = $like;
        $types .= 'ss';
    }

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

    $sql = "
        SELECT 
            s.id AS submission_id,
            s.student_id,
            s.assessment_id,
            s.batch_id,
            s.{$submittedCol} AS submitted_at,
            " . (col_exists_assess($mysqli, 'lms_submissions', 'workflow_status') ? "s.workflow_status" : "'pending' AS workflow_status") . ",
            a.{$assessmentTitleCol} AS assessment_title,
            {$studentExpr} AS student_name
        FROM lms_submissions s
        JOIN lms_assessments a ON a.id = s.assessment_id
        {$joinStudent}
        {$whereSql}
        ORDER BY s.id DESC
        LIMIT ?
    ";

    $params[] = $limit;
    $types .= 'i';

    $stmt = $mysqli->prepare($sql);
    if ($stmt) {
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
        $stmt->close();
    }
}

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

<div class="lux-card mb-3">
    <div class="lux-card-header">
        <h5 class="mb-1 fw-bold">Assessments</h5>
        <div class="text-muted small">Search and open submitted assessments for grading.</div>
    </div>

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

            <div class="col-md-2">
                <label class="form-label small fw-bold">View</label>
                <select name="view" class="form-select">
                    <option value="pending" <?= $view !== 'all' ? 'selected' : '' ?>>Pending</option>
                    <option value="all" <?= $view === 'all' ? 'selected' : '' ?>>All</option>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label small fw-bold">Limit</label>
                <select name="limit" class="form-select">
                    <?php foreach ([10,20,50,100] as $n): ?>
                        <option value="<?= $n ?>" <?= $limit === $n ? 'selected' : '' ?>><?= $n ?></option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <button class="btn btn-lux w-100">
                    <i class="bi bi-search"></i> Apply
                </button>
            </div>
        </form>
    </div>
</div>

<div class="lux-card">
    <div class="lux-card-body">
        <?php if (!$rows): ?>
            <div class="text-center py-5">
                <i class="bi bi-clipboard-x fs-1 text-muted"></i>
                <h6 class="mt-3 fw-bold">No assessments found</h6>
                <p class="text-muted mb-0">Submitted assessments will appear here.</p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table align-middle">
                    <thead>
                    <tr>
                        <th>Student</th>
                        <th>Assessment</th>
                        <th>Batch</th>
                        <th>Status</th>
                        <th>Submitted</th>
                        <th class="text-end">Action</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($rows as $r): ?>
                        <tr>
                            <td class="fw-bold"><?= lecturer_h($r['student_name'] ?? '-') ?></td>
                            <td><?= lecturer_h($r['assessment_title'] ?? '-') ?></td>
                            <td><span class="badge-lux"><?= lecturer_h((string)($r['batch_id'] ?? '-')) ?></span></td>
                            <td>
                                <span class="badge bg-light text-dark border">
                                    <?= lecturer_h((string)($r['workflow_status'] ?? 'pending')) ?>
                                </span>
                            </td>
                            <td class="text-muted small"><?= lecturer_h((string)($r['submitted_at'] ?? '-')) ?></td>
                            <td class="text-end">
                                <a href="/elms/lecturer/grade.php?id=<?= (int)$r['submission_id'] ?>" class="btn btn-sm btn-lux">
                                    Grade
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

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