<?php
declare(strict_types=1);

$PAGE_TITLE = 'Release Results';
$ACTIVE = 'release';

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);
    $action = $_POST['action'] ?? '';
    $adminId = (int)($GLOBALS['ADMIN_ID'] ?? 0);

    if ($id > 0 && $action === 'release') {
        $sets = [];

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

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

        if (col_exists($mysqli, 'lms_submissions', 'released_by')) {
            $sets[] = 'released_by=' . $adminId;
        }

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

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

            if ($stmt->execute()) {
                $msg = 'Result released successfully.';
            } else {
                $err = 'Release failed.';
            }
            $stmt->close();
        }
    }

    if ($id > 0 && $action === 'unrelease') {
        $sets = [];

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

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

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

            if ($stmt->execute()) {
                $msg = 'Result moved back to admin review.';
            } else {
                $err = 'Update failed.';
            }
            $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',
        col_exists($mysqli, 'lms_submissions', 'released_at') ? 's.released_at' : 'NULL AS released_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 ('admin_review','marked','released')";
    }

    $sql = "SELECT " . implode(',', $select) . " FROM lms_submissions s {$joins} {$where} ORDER BY s.id DESC LIMIT 150";
    $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">Release Results</h4>
            <div class="text-muted small">Release final marks to students after admin review.</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>Final Score</th>
                            <th>Status</th>
                            <th>Released</th>
                            <th class="text-end">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!$rows): ?>
                            <tr>
                                <td colspan="7" class="text-center text-muted py-4">No results found.</td>
                            </tr>
                        <?php endif; ?>

                        <?php foreach ($rows as $r): ?>
                            <?php
                                $status = strtolower((string)($r['workflow_status'] ?? ''));
                                $badge = $status === 'released' ? 'bg-success' : 'bg-warning text-dark';
                            ?>
                            <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 <?= $badge ?>"><?= h(ucfirst($status ?: 'Pending')) ?></span></td>
                                <td class="small text-muted"><?= h($r['released_at'] ?? '-') ?></td>
                                <td class="text-end">
                                    <?php if ($status === 'released'): ?>
                                        <form method="post" class="d-inline">
                                            <input type="hidden" name="submission_id" value="<?= (int)$r['id'] ?>">
                                            <input type="hidden" name="action" value="unrelease">
                                            <button class="btn btn-outline-secondary btn-sm">Unrelease</button>
                                        </form>
                                    <?php else: ?>
                                        <form method="post" class="d-inline" onsubmit="return confirm('Release this result to student?');">
                                            <input type="hidden" name="submission_id" value="<?= (int)$r['id'] ?>">
                                            <input type="hidden" name="action" value="release">
                                            <button class="btn btn-success btn-sm">
                                                <i class="bi bi-send-check me-1"></i> Release
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>

            <div class="alert alert-info mt-3 mb-0 small">
                Only <strong>admin_review / marked</strong> results should be released. Released results can be moved back to review if needed.
            </div>
        </div>
    </div>
</div>

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