<?php
declare(strict_types=1);

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

require_once __DIR__ . '/../includes/admin_auth.php';
require_once __DIR__ . '/../includes/admin_layout_top.php';

if (!isset($mysqli) && isset($conn)) {
    $mysqli = $conn;
}

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

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

if (!function_exists('col_exists')) {
    function col_exists(mysqli $db, string $table, string $col): bool {
        $safeTable = $db->real_escape_string($table);
        $safeCol   = $db->real_escape_string($col);
        $res = $db->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeCol}'");
        return $res && $res->num_rows > 0;
    }
}

$msg = '';
$err = '';

if (!tbl_exists($mysqli, 'lms_submissions')) {
    $err = 'lms_submissions table not found.';
}

if (!$err && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['submission_id'] ?? 0);
    $score = trim($_POST['final_score'] ?? '');
    $feedback = trim($_POST['admin_feedback'] ?? '');
    $adminId = (int)($GLOBALS['ADMIN_ID'] ?? 0);

    if ($id <= 0) {
        $err = 'Invalid submission.';
    } elseif ($score === '' || !is_numeric($score)) {
        $err = 'Valid final score is required.';
    } else {
        $sets = [];
        $vals = [];
        $types = '';

        if (col_exists($mysqli, 'lms_submissions', 'final_score')) {
            $sets[] = 'final_score=?';
            $vals[] = (float)$score;
            $types .= 'd';
        }

        if (col_exists($mysqli, 'lms_submissions', 'admin_feedback')) {
            $sets[] = 'admin_feedback=?';
            $vals[] = $feedback;
            $types .= 's';
        }

        if (col_exists($mysqli, 'lms_submissions', 'workflow_status')) {
            $sets[] = "workflow_status='admin_review'";
        }

        if (col_exists($mysqli, 'lms_submissions', 'admin_marked_by')) {
            $sets[] = 'admin_marked_by=?';
            $vals[] = $adminId;
            $types .= 'i';
        }

        if (col_exists($mysqli, 'lms_submissions', 'updated_at')) {
            $sets[] = 'updated_at=NOW()';
        }

        if ($sets) {
            $vals[] = $id;
            $types .= 'i';

            $stmt = $mysqli->prepare("UPDATE lms_submissions SET " . implode(',', $sets) . " WHERE id=? LIMIT 1");
            $stmt->bind_param($types, ...$vals);

            if ($stmt->execute()) {
                $msg = 'Marks updated successfully.';
            } else {
                $err = 'Mark update failed: ' . $stmt->error;
            }
            $stmt->close();
        }
    }
}

$rows = [];

if (!$err) {
    $select = [
        's.id',
        col_exists($mysqli, 'lms_submissions', 'student_id') ? 's.student_id' : 'NULL AS student_id',
        col_exists($mysqli, 'lms_submissions', 'assessment_id') ? 's.assessment_id' : 'NULL AS assessment_id',
        col_exists($mysqli, 'lms_submissions', 'final_score') ? 's.final_score' : 'NULL AS final_score',
        col_exists($mysqli, 'lms_submissions', 'workflow_status') ? 's.workflow_status' : "'' AS workflow_status",
        col_exists($mysqli, 'lms_submissions', 'updated_at') ? 's.updated_at' : 'NULL AS updated_at',
    ];

    $joins = '';

    if (tbl_exists($mysqli, 'lms_assessments') && col_exists($mysqli, 'lms_assessments', 'title') && col_exists($mysqli, 'lms_submissions', 'assessment_id')) {
        $select[] = 'a.title AS assessment_title';
        $joins .= ' LEFT JOIN lms_assessments a ON a.id = s.assessment_id ';
    } else {
        $select[] = "'' AS assessment_title";
    }

    if (tbl_exists($mysqli, 'studentss') && col_exists($mysqli, 'lms_submissions', 'student_id')) {
        $nameCol = col_exists($mysqli, 'studentss', 'full_name') ? 'full_name' : (col_exists($mysqli, 'studentss', 'name') ? 'name' : '');
        if ($nameCol) {
            $select[] = "st.`{$nameCol}` AS student_name";
            $joins .= ' LEFT JOIN studentss st ON st.id = s.student_id ';
        } else {
            $select[] = "'' AS student_name";
        }
    } else {
        $select[] = "'' AS student_name";
    }

    $where = '';
    if (col_exists($mysqli, 'lms_submissions', 'workflow_status')) {
        $where = "WHERE s.workflow_status IN ('coord_approved','admin_review','marked','submitted')";
    }

    $sql = "SELECT " . implode(',', $select) . " FROM lms_submissions s {$joins} {$where} ORDER BY s.id DESC LIMIT 100";
    $res = $mysqli->query($sql);
    if ($res) {
        $rows = $res->fetch_all(MYSQLI_ASSOC);
    }
}

?>

<div class="container-fluid">
    <div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-2">
        <div>
            <h4 class="mb-1">Marking</h4>
            <div class="text-muted small">Review coordinator-approved submissions and update final marks.</div>
        </div>
    </div>

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

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

    <div class="card border-0 shadow-sm">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table align-middle table-hover">
                    <thead class="table-light">
                        <tr>
                            <th>#</th>
                            <th>Student</th>
                            <th>Assessment</th>
                            <th>Current Score</th>
                            <th>Status</th>
                            <th>Updated</th>
                            <th class="text-end">Mark</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!$rows): ?>
                            <tr>
                                <td colspan="7" class="text-center text-muted py-4">No submissions found.</td>
                            </tr>
                        <?php endif; ?>

                        <?php foreach ($rows as $r): ?>
                            <tr>
                                <td><?= (int)$r['id'] ?></td>
                                <td>
                                    <div class="fw-semibold"><?= h($r['student_name'] ?: 'Student #' . ($r['student_id'] ?? '-')) ?></div>
                                    <div class="small text-muted">ID: <?= h($r['student_id'] ?? '-') ?></div>
                                </td>
                                <td><?= h($r['assessment_title'] ?: 'Assessment #' . ($r['assessment_id'] ?? '-')) ?></td>
                                <td class="fw-semibold"><?= h($r['final_score'] ?? '-') ?></td>
                                <td><span class="badge bg-info text-dark"><?= h($r['workflow_status'] ?? '') ?></span></td>
                                <td class="small text-muted"><?= h($r['updated_at'] ?? '-') ?></td>
                                <td class="text-end">
                                    <button
                                        class="btn btn-primary btn-sm"
                                        data-bs-toggle="modal"
                                        data-bs-target="#markModal"
                                        data-id="<?= (int)$r['id'] ?>"
                                        data-score="<?= h($r['final_score'] ?? '') ?>"
                                    >
                                        Update Mark
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="markModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered">
        <form method="post" class="modal-content border-0 shadow">
            <input type="hidden" name="submission_id" id="submission_id">

            <div class="modal-header">
                <h5 class="modal-title">Update Final Mark</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label">Final Score</label>
                    <input type="number" step="0.01" min="0" max="100" name="final_score" id="final_score" class="form-control" required>
                </div>

                <div class="mb-1">
                    <label class="form-label">Admin Feedback</label>
                    <textarea name="admin_feedback" rows="4" class="form-control"></textarea>
                </div>
            </div>

            <div class="modal-footer">
                <button class="btn btn-primary">
                    <i class="bi bi-check-circle me-1"></i> Save Mark
                </button>
            </div>
        </form>
    </div>
</div>

<script>
document.getElementById('markModal')?.addEventListener('show.bs.modal', function (event) {
    const btn = event.relatedTarget;
    document.getElementById('submission_id').value = btn.getAttribute('data-id') || '';
    document.getElementById('final_score').value = btn.getAttribute('data-score') || '';
});
</script>

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