<?php
// /elms/admin/approvals.php
declare(strict_types=1);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$PAGE_TITLE = 'Admin Approvals';
$ACTIVE = 'approvals';

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

$helpers = __DIR__ . '/../includes/helpers.php';
if (is_file($helpers)) {
    require_once $helpers;
}

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

if (!isset($mysqli) || !($mysqli instanceof mysqli)) {
    http_response_code(500);
    echo 'Database connection not initialized.';
    exit;
}

@$mysqli->set_charset('utf8mb4');

if (!function_exists('esc')) {
    function esc($s): string
    {
        return htmlspecialchars((string)$s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    }
}

if (!function_exists('admin_table_exists')) {
    function admin_table_exists(mysqli $db, string $table): bool
    {
        try {
            $st = $db->prepare("
                SELECT 1
                FROM INFORMATION_SCHEMA.TABLES
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = ?
                LIMIT 1
            ");
            $st->bind_param('s', $table);
            $st->execute();
            $ok = (bool)$st->get_result()->fetch_row();
            $st->close();

            return $ok;
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('admin_col_exists')) {
    function admin_col_exists(mysqli $db, string $table, string $col): bool
    {
        try {
            $st = $db->prepare("
                SELECT 1
                FROM INFORMATION_SCHEMA.COLUMNS
                WHERE TABLE_SCHEMA = DATABASE()
                  AND TABLE_NAME = ?
                  AND COLUMN_NAME = ?
                LIMIT 1
            ");
            $st->bind_param('ss', $table, $col);
            $st->execute();
            $ok = (bool)$st->get_result()->fetch_row();
            $st->close();

            return $ok;
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('format_approval_dt')) {
    function format_approval_dt($value): string
    {
        $value = trim((string)$value);

        if ($value === '' || $value === '0000-00-00' || $value === '0000-00-00 00:00:00') {
            return '—';
        }

        $time = strtotime($value);

        return $time ? date('d M Y, h:i A', $time) : $value;
    }
}

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

if (!admin_table_exists($mysqli, 'lms_submissions')) {
    $error = 'lms_submissions table not found.';
} elseif (!admin_table_exists($mysqli, 'lms_assessments')) {
    $error = 'lms_assessments table not found.';
} else {
    $hasWorkflow = admin_col_exists($mysqli, 'lms_submissions', 'workflow_status');
    $hasFinalScore = admin_col_exists($mysqli, 'lms_submissions', 'final_score');
    $hasScore = admin_col_exists($mysqli, 'lms_submissions', 'score');
    $hasMarks = admin_col_exists($mysqli, 'lms_submissions', 'marks');
    $hasUpdated = admin_col_exists($mysqli, 'lms_submissions', 'updated_at');
    $hasSubmitted = admin_col_exists($mysqli, 'lms_submissions', 'submitted_at');
    $hasBatch = admin_col_exists($mysqli, 'lms_submissions', 'batch_id');

    $scoreSelect = 'NULL AS final_score';

    if ($hasFinalScore) {
        $scoreSelect = 's.final_score AS final_score';
    } elseif ($hasScore) {
        $scoreSelect = 's.score AS final_score';
    } elseif ($hasMarks) {
        $scoreSelect = 's.marks AS final_score';
    }

    $updatedSelect = 'NULL AS updated_at';

    if ($hasUpdated) {
        $updatedSelect = 's.updated_at AS updated_at';
    } elseif ($hasSubmitted) {
        $updatedSelect = 's.submitted_at AS updated_at';
    }

    $batchSelect = $hasBatch ? 's.batch_id' : 'NULL AS batch_id';

    $where = $hasWorkflow
        ? "WHERE s.workflow_status IN ('coord_approved', 'admin_review')"
        : "WHERE 1=0";

    try {
        $sql = "
            SELECT
                s.id,
                s.student_id,
                $batchSelect,
                s.assessment_id,
                $scoreSelect,
                $updatedSelect,
                a.title
                " . ($hasWorkflow ? ", s.workflow_status" : ", 'pending' AS workflow_status") . "
            FROM lms_submissions s
            JOIN lms_assessments a ON a.id = s.assessment_id
            $where
            ORDER BY updated_at DESC, s.id DESC
            LIMIT 50
        ";

        $res = $mysqli->query($sql);

        if ($res) {
            while ($row = $res->fetch_assoc()) {
                $rows[] = $row;
            }

            $res->free();
        }
    } catch (Throwable $e) {
        $error = 'Unable to load approval records.';
    }
}

$total = count($rows);

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

<style>
    .approval-hero {
        background: linear-gradient(135deg, #eff6ff 0%, #f8fafc 48%, #eef2ff 100%);
        border: 1px solid #dbeafe;
        border-radius: 22px;
        padding: 22px;
        box-shadow: 0 10px 28px rgba(15, 23, 42, .06);
    }

    .approval-chip {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 7px 11px;
        border-radius: 999px;
        background: #fff;
        border: 1px solid #e5e7eb;
        color: #475569;
        font-size: 12px;
        font-weight: 700;
    }

    .approval-card {
        background: #fff;
        border: 1px solid #e5e7eb;
        border-radius: 20px;
        box-shadow: 0 8px 24px rgba(15, 23, 42, .055);
        overflow: hidden;
    }

    .approval-card-header {
        padding: 18px 20px;
        border-bottom: 1px solid #e5e7eb;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 14px;
        flex-wrap: wrap;
    }

    .approval-table thead th {
        background: #f8fafc;
        color: #64748b;
        font-size: 12px;
        text-transform: uppercase;
        letter-spacing: .04em;
        white-space: nowrap;
    }

    .approval-title {
        font-weight: 800;
        color: #111827;
    }
</style>

<div class="approval-hero mb-4">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
        <div>
            <h4 class="fw-bold mb-1">Admin Approvals</h4>
            <div class="text-muted">
                Review coordinator-approved assessment marks before final release.
            </div>
        </div>

        <div class="d-flex flex-wrap gap-2">
            <span class="approval-chip">
                <i class="bi bi-patch-check text-primary"></i>
                <?= number_format($total) ?> Pending
            </span>

            <span class="approval-chip">
                <i class="bi bi-shield-check text-success"></i>
                Role: <?= esc(admin_role()) ?>
            </span>
        </div>
    </div>
</div>

<?php if ($error !== ''): ?>
    <div class="alert alert-danger border-0 rounded-4 shadow-sm">
        <i class="bi bi-exclamation-triangle me-1"></i>
        <?= esc($error) ?>
    </div>
<?php endif; ?>

<div class="approval-card">
    <div class="approval-card-header">
        <div>
            <h5 class="mb-0 fw-bold">Waiting for Admin Review</h5>
            <div class="text-muted small">Latest 50 approval items</div>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table approval-table table-hover align-middle mb-0">
            <thead>
                <tr>
                    <th style="width:80px;">#</th>
                    <th>Assessment</th>
                    <th>Student</th>
                    <th>Batch</th>
                    <th>Score</th>
                    <th>Status</th>
                    <th>Updated</th>
                    <th class="text-end">Action</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$rows): ?>
                    <tr>
                        <td colspan="8" class="text-center text-muted py-4">
                            No items waiting for admin approval.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($rows as $row): ?>
                        <?php
                            $workflow = (string)($row['workflow_status'] ?? '');
                            $badge = match (strtolower($workflow)) {
                                'coord_approved' => 'bg-success',
                                'admin_review' => 'bg-warning text-dark',
                                default => 'bg-secondary',
                            };
                        ?>

                        <tr>
                            <td class="fw-semibold">
                                <?= (int)$row['id'] ?>
                            </td>

                            <td>
                                <div class="approval-title">
                                    <?= esc($row['title'] ?? ('Assessment #' . (int)$row['assessment_id'])) ?>
                                </div>
                                <div class="small text-muted">
                                    Assessment ID: <?= (int)$row['assessment_id'] ?>
                                </div>
                            </td>

                            <td>
                                #<?= esc($row['student_id'] ?? '') ?>
                            </td>

                            <td>
                                <?= !empty($row['batch_id']) ? '#' . esc($row['batch_id']) : '<span class="text-muted">—</span>' ?>
                            </td>

                            <td>
                                <?php if ($row['final_score'] !== null && $row['final_score'] !== ''): ?>
                                    <span class="badge bg-primary">
                                        <?= esc($row['final_score']) ?>
                                    </span>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>

                            <td>
                                <span class="badge <?= esc($badge) ?>">
                                    <?= esc($workflow !== '' ? $workflow : 'pending') ?>
                                </span>
                            </td>

                            <td class="small text-muted">
                                <?= esc(format_approval_dt($row['updated_at'] ?? '')) ?>
                            </td>

                            <td class="text-end">
                                <a class="btn btn-sm btn-admin-primary"
                                   href="approve_decide.php?sid=<?= (int)$row['id'] ?>">
                                    <i class="bi bi-eye me-1"></i>
                                    Review
                                </a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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