<?php
declare(strict_types=1);

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

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

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

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;
}

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 = '';

$studentsTable = tbl_exists($mysqli, 'studentss') ? 'studentss' : (tbl_exists($mysqli, 'students') ? 'students' : '');

if ($studentsTable === '') {
    $err = 'Students table not found.';
}

if ($studentsTable && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = (int)($_POST['student_id'] ?? 0);
    $action = $_POST['action'] ?? '';

    if ($id > 0) {
        if ($action === 'verify') {
            if (col_exists($mysqli, $studentsTable, 'verification_status')) {
                $stmt = $mysqli->prepare("UPDATE `{$studentsTable}` SET verification_status='verified' WHERE id=? LIMIT 1");
            } elseif (col_exists($mysqli, $studentsTable, 'status')) {
                $stmt = $mysqli->prepare("UPDATE `{$studentsTable}` SET status='active' WHERE id=? LIMIT 1");
            } else {
                $stmt = null;
            }

            if ($stmt) {
                $stmt->bind_param('i', $id);
                if ($stmt->execute()) {
                    $msg = 'Student verified successfully.';
                }
                $stmt->close();
            }
        }

        if ($action === 'reject') {
            if (col_exists($mysqli, $studentsTable, 'verification_status')) {
                $stmt = $mysqli->prepare("UPDATE `{$studentsTable}` SET verification_status='rejected' WHERE id=? LIMIT 1");
            } elseif (col_exists($mysqli, $studentsTable, 'status')) {
                $stmt = $mysqli->prepare("UPDATE `{$studentsTable}` SET status='inactive' WHERE id=? LIMIT 1");
            } else {
                $stmt = null;
            }

            if ($stmt) {
                $stmt->bind_param('i', $id);
                if ($stmt->execute()) {
                    $msg = 'Student rejected successfully.';
                }
                $stmt->close();
            }
        }
    }
}

$rows = [];

if ($studentsTable) {
    $select = ['id'];

    $select[] = col_exists($mysqli, $studentsTable, 'full_name') ? 'full_name' : (col_exists($mysqli, $studentsTable, 'name') ? 'name AS full_name' : "'' AS full_name");
    $select[] = col_exists($mysqli, $studentsTable, 'center_reg_no') ? 'center_reg_no' : "'' AS center_reg_no";
    $select[] = col_exists($mysqli, $studentsTable, 'reference_no') ? 'reference_no' : "'' AS reference_no";
    $select[] = col_exists($mysqli, $studentsTable, 'mobile') ? 'mobile' : "'' AS mobile";
    $select[] = col_exists($mysqli, $studentsTable, 'email') ? 'email' : "'' AS email";

    if (col_exists($mysqli, $studentsTable, 'verification_status')) {
        $select[] = 'verification_status';
    } elseif (col_exists($mysqli, $studentsTable, 'status')) {
        $select[] = 'status AS verification_status';
    } else {
        $select[] = "'pending' AS verification_status";
    }

    $select[] = col_exists($mysqli, $studentsTable, 'created_at') ? 'created_at' : 'NULL AS created_at';

    $sql = "SELECT " . implode(',', $select) . " FROM `{$studentsTable}` ORDER BY 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">Verification</h4>
            <div class="text-muted small">Review and verify student records.</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>Student</th>
                            <th>Reg No</th>
                            <th>Reference</th>
                            <th>Contact</th>
                            <th>Status</th>
                            <th>Created</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 students found.</td>
                            </tr>
                        <?php endif; ?>

                        <?php foreach ($rows as $r): ?>
                            <?php
                                $st = strtolower((string)($r['verification_status'] ?? 'pending'));
                                $badge = match ($st) {
                                    'verified', 'active' => 'bg-success',
                                    'rejected', 'inactive', 'suspended' => 'bg-danger',
                                    default => 'bg-warning text-dark',
                                };
                            ?>
                            <tr>
                                <td class="fw-semibold"><?= h($r['full_name'] ?? '') ?></td>
                                <td><?= h($r['center_reg_no'] ?? '') ?></td>
                                <td><?= h($r['reference_no'] ?? '') ?></td>
                                <td>
                                    <div><?= h($r['mobile'] ?? '') ?></div>
                                    <div class="small text-muted"><?= h($r['email'] ?? '') ?></div>
                                </td>
                                <td><span class="badge <?= $badge ?>"><?= h(ucfirst($st)) ?></span></td>
                                <td class="small text-muted"><?= h($r['created_at'] ?? '-') ?></td>
                                <td class="text-end">
                                    <form method="post" class="d-inline">
                                        <input type="hidden" name="student_id" value="<?= (int)$r['id'] ?>">
                                        <input type="hidden" name="action" value="verify">
                                        <button class="btn btn-outline-success btn-sm">Verify</button>
                                    </form>

                                    <form method="post" class="d-inline">
                                        <input type="hidden" name="student_id" value="<?= (int)$r['id'] ?>">
                                        <input type="hidden" name="action" value="reject">
                                        <button class="btn btn-outline-danger btn-sm">Reject</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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