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

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

define('APP_ROOT', dirname(__DIR__, 2)); // .../elms

$PAGE_TITLE = 'Students';
$ACTIVE = 'students';

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

$helpers = APP_ROOT . '/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');

/* ---------------- Helpers ---------------- */

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

if (!function_exists('student_table_exists')) {
    function student_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('student_columns')) {
    function student_columns(mysqli $db, string $table): array
    {
        $cols = [];

        try {
            if ($rs = $db->query("SHOW COLUMNS FROM `$table`")) {
                while ($row = $rs->fetch_assoc()) {
                    $cols[] = $row['Field'];
                }

                $rs->free();
            }
        } catch (Throwable $e) {
            return [];
        }

        return $cols;
    }
}

if (!function_exists('student_mask_password')) {
    function student_mask_password(?string $password): string
    {
        $password = (string)$password;

        if ($password === '') {
            return '—';
        }

        if (
            preg_match('/^\$2y\$/', $password)
            || preg_match('/^\$argon2/i', $password)
            || strlen($password) > 45
        ) {
            return '•••••• (hash)';
        }

        if (strlen($password) > 10) {
            return substr($password, 0, 7) . '…';
        }

        return $password;
    }
}

/* ---------------- Table ---------------- */

$STU_TBL = student_table_exists($mysqli, 'studentss')
    ? 'studentss'
    : (student_table_exists($mysqli, 'students') ? 'students' : '');

require_once APP_ROOT . '/includes/admin_layout_top.php';

if ($STU_TBL === '') {
    echo '
        <div class="alert alert-danger border-0 rounded-4 shadow-sm">
            Students table not found. Expected table: <code>studentss</code> or <code>students</code>.
        </div>
    ';

    require_once APP_ROOT . '/includes/admin_layout_bottom.php';
    exit;
}

$COLS = student_columns($mysqli, $STU_TBL);
$has = fn(string $c): bool => in_array($c, $COLS, true);

/* ---------------- Column mappings ---------------- */

$col_id = $has('id') ? 'id' : null;

$col_center_no = $has('center_reg_no')
    ? 'center_reg_no'
    : ($has('centre_reg_no') ? 'centre_reg_no' : null);

$col_ref_no = $has('reference_no')
    ? 'reference_no'
    : ($has('ref_no') ? 'ref_no' : null);

$col_title = $has('title') ? 'title' : null;

$col_fullname = $has('full_name')
    ? 'full_name'
    : ($has('name') ? 'name' : null);

$col_email = $has('academic_email')
    ? 'academic_email'
    : ($has('email')
        ? 'email'
        : ($has('email_address') ? 'email_address' : null));

$col_nic = $has('nic_passport')
    ? 'nic_passport'
    : ($has('nic') ? 'nic' : null);

$col_mobile = $has('mobile')
    ? 'mobile'
    : ($has('phone')
        ? 'phone'
        : ($has('contact_no') ? 'contact_no' : null));

$col_status = $has('status')
    ? 'status'
    : ($has('student_status') ? 'student_status' : null);

$col_pwd = null;
foreach (['academic_plain_password', 'password_plain', 'plain_password', 'password', 'academic_password_hash'] as $c) {
    if ($has($c)) {
        $col_pwd = $c;
        break;
    }
}

/* ---------------- Inputs ---------------- */

$q = trim((string)($_GET['q'] ?? ''));
$status = trim((string)($_GET['status'] ?? ''));

$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 25;

if (!in_array($perPage, [10, 25, 50, 100], true)) {
    $perPage = 25;
}

$offset = ($page - 1) * $perPage;

/* ---------------- Select ---------------- */

$select = [];

$select[] = $col_id ? "s.`$col_id` AS id" : "NULL AS id";
$select[] = $col_center_no ? "s.`$col_center_no` AS center_reg_no" : "'' AS center_reg_no";
$select[] = $col_ref_no ? "s.`$col_ref_no` AS reference_no" : "'' AS reference_no";
$select[] = $col_title ? "s.`$col_title` AS title" : "'' AS title";
$select[] = $col_fullname ? "s.`$col_fullname` AS full_name" : "'' AS full_name";
$select[] = $col_email ? "s.`$col_email` AS email_address" : "'' AS email_address";
$select[] = $col_mobile ? "s.`$col_mobile` AS mobile" : "'' AS mobile";
$select[] = $col_nic ? "s.`$col_nic` AS nic_passport" : "'' AS nic_passport";
$select[] = $col_status ? "s.`$col_status` AS status" : "'Active' AS status";
$select[] = $col_pwd ? "s.`$col_pwd` AS pwd" : "'' AS pwd";

/* ---------------- Where ---------------- */

$where = ['1=1'];
$types = '';
$vals = [];

if ($q !== '') {
    $parts = [];

    foreach ([$col_center_no, $col_ref_no, $col_fullname, $col_email, $col_mobile, $col_nic, $col_title] as $column) {
        if ($column) {
            $parts[] = "s.`$column` LIKE ?";
            $types .= 's';
            $vals[] = '%' . $q . '%';
        }
    }

    if ($parts) {
        $where[] = '(' . implode(' OR ', $parts) . ')';
    }
}

if ($status !== '' && $col_status) {
    $where[] = "LOWER(s.`$col_status`) = LOWER(?)";
    $types .= 's';
    $vals[] = $status;
}

/* ---------------- Count ---------------- */

$total = 0;

$sqlCount = "
    SELECT COUNT(*) AS c
    FROM `$STU_TBL` s
    WHERE " . implode(' AND ', $where);

if ($st = $mysqli->prepare($sqlCount)) {
    if ($types !== '') {
        $st->bind_param($types, ...$vals);
    }

    $st->execute();

    if ($res = $st->get_result()) {
        $total = (int)($res->fetch_assoc()['c'] ?? 0);
    }

    $st->close();
}

$pages = max(1, (int)ceil($total / $perPage));

if ($page > $pages) {
    $page = $pages;
    $offset = ($page - 1) * $perPage;
}

/* ---------------- Data ---------------- */

$orderCol = $col_id ?: 'id';

$sql = "
    SELECT " . implode(',', $select) . "
    FROM `$STU_TBL` s
    WHERE " . implode(' AND ', $where) . "
    ORDER BY s.`$orderCol` DESC
    LIMIT ?, ?
";

$rows = [];

if ($st = $mysqli->prepare($sql)) {
    if ($types === '') {
        $st->bind_param('ii', $offset, $perPage);
    } else {
        $typesAll = $types . 'ii';
        $bind = array_merge($vals, [$offset, $perPage]);
        $st->bind_param($typesAll, ...$bind);
    }

    $st->execute();

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

    $st->close();
}

/* ---------------- Stats ---------------- */

$activeCount = 0;
$inactiveCount = 0;
$suspendedCount = 0;

if ($col_status) {
    foreach ($rows as $row) {
        $stLower = strtolower(trim((string)($row['status'] ?? '')));

        if ($stLower === 'active') {
            $activeCount++;
        } elseif ($stLower === 'inactive') {
            $inactiveCount++;
        } elseif ($stLower === 'suspended') {
            $suspendedCount++;
        }
    }
}

$mkPageUrl = function (int $p): string {
    $qs = $_GET;
    $qs['page'] = $p;
    return '?' . http_build_query($qs);
};
?>

<style>
    .students-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);
    }

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

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

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

    .students-card-body {
        padding: 20px;
    }

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

    .student-name {
        font-weight: 800;
        color: #111827;
    }

    .password-mask {
        font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
        font-size: 12px;
    }
</style>

<div class="students-hero mb-4">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
        <div>
            <h4 class="fw-bold mb-1">Students</h4>
            <div class="text-muted">
                View student records from <?= esc($STU_TBL) ?> table.
            </div>
        </div>

        <div class="d-flex flex-wrap gap-2">
            <span class="students-chip">
                <i class="bi bi-people text-primary"></i>
                <?= number_format($total) ?> Records
            </span>

            <?php if ($col_status): ?>
                <span class="students-chip">
                    <i class="bi bi-check-circle text-success"></i>
                    <?= number_format($activeCount) ?> Active shown
                </span>

                <span class="students-chip">
                    <i class="bi bi-exclamation-triangle text-danger"></i>
                    <?= number_format($suspendedCount) ?> Suspended shown
                </span>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="students-card mb-4">
    <div class="students-card-header">
        <div>
            <h5 class="mb-0 fw-bold">Search Students</h5>
            <div class="text-muted small">Search by center reg no, reference no, name, email, mobile, NIC, or title.</div>
        </div>
    </div>

    <div class="students-card-body">
        <form class="row g-3 align-items-end" method="get">
            <div class="col-lg-5 col-md-7">
                <label class="form-label fw-semibold">Search</label>
                <input
                    class="form-control"
                    name="q"
                    value="<?= esc($q) ?>"
                    placeholder="Search student..."
                >
            </div>

            <?php if ($col_status): ?>
                <div class="col-lg-2 col-md-5">
                    <label class="form-label fw-semibold">Status</label>
                    <select name="status" class="form-select">
                        <option value="">All</option>
                        <?php foreach (['Active', 'Inactive', 'Suspended', 'Pending'] as $s): ?>
                            <option value="<?= esc($s) ?>" <?= strtolower($status) === strtolower($s) ? 'selected' : '' ?>>
                                <?= esc($s) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            <?php endif; ?>

            <div class="col-lg-2 col-md-4">
                <label class="form-label fw-semibold">Rows</label>
                <select name="per_page" class="form-select" onchange="this.form.submit()">
                    <?php foreach ([10, 25, 50, 100] as $n): ?>
                        <option value="<?= $n ?>" <?= $perPage === $n ? 'selected' : '' ?>>
                            <?= $n ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-lg-3 col-md-8 d-flex gap-2">
                <button class="btn btn-admin-primary w-100">
                    <i class="bi bi-search me-1"></i>
                    Search
                </button>

                <a class="btn btn-outline-secondary rounded-pill" href="./">
                    Reset
                </a>
            </div>
        </form>
    </div>
</div>

<div class="students-card">
    <div class="students-card-header">
        <div>
            <h5 class="mb-0 fw-bold">Student List</h5>
            <div class="text-muted small">
                <?= number_format($total) ?> record<?= $total === 1 ? '' : 's' ?> · page <?= (int)$page ?> / <?= (int)$pages ?>
            </div>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table students-table table-hover align-middle mb-0">
            <thead>
                <tr>
                    <th style="width:80px;">ID</th>
                    <th>Student</th>
                    <th>Center Reg No</th>
                    <th>Reference No</th>
                    <th>Email</th>
                    <th>Mobile</th>
                    <th>NIC/Passport</th>
                    <th>Status</th>
                    <th>Password</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$rows): ?>
                    <tr>
                        <td colspan="9" class="text-center text-muted py-4">
                            No students found.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($rows as $row): ?>
                        <?php
                            $stRaw = trim((string)($row['status'] ?? 'Active'));
                            $stLower = strtolower($stRaw);

                            $badgeClass = match ($stLower) {
                                'active' => 'bg-success',
                                'inactive' => 'bg-secondary',
                                'suspended' => 'bg-danger',
                                'pending' => 'bg-warning text-dark',
                                default => 'bg-light text-dark border',
                            };
                        ?>

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

                            <td>
                                <div class="student-name">
                                    <?= esc((string)($row['full_name'] ?? '')) ?>
                                </div>

                                <?php if (!empty($row['title'])): ?>
                                    <div class="small text-muted">
                                        <?= esc((string)$row['title']) ?>
                                    </div>
                                <?php endif; ?>
                            </td>

                            <td>
                                <?= esc((string)($row['center_reg_no'] ?? '')) ?: '—' ?>
                            </td>

                            <td>
                                <?= esc((string)($row['reference_no'] ?? '')) ?: '—' ?>
                            </td>

                            <td>
                                <?php
                                    $email = (string)($row['email_address'] ?? '');
                                    echo $email !== ''
                                        ? '<a href="mailto:' . esc($email) . '" class="text-decoration-none">' . esc($email) . '</a>'
                                        : '<span class="text-muted">—</span>';
                                ?>
                            </td>

                            <td>
                                <?= esc((string)($row['mobile'] ?? '')) ?: '—' ?>
                            </td>

                            <td>
                                <?= esc((string)($row['nic_passport'] ?? '')) ?: '—' ?>
                            </td>

                            <td>
                                <span class="badge <?= esc($badgeClass) ?>">
                                    <?= esc($stRaw !== '' ? $stRaw : 'Active') ?>
                                </span>
                            </td>

                            <td>
                                <span class="password-mask text-muted">
                                    <?= esc(student_mask_password((string)($row['pwd'] ?? ''))) ?>
                                </span>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($pages > 1): ?>
        <div class="p-3 border-top d-flex flex-wrap justify-content-between align-items-center gap-2">
            <div class="text-muted small">
                Showing <?= min($total, $offset + 1) ?>–<?= min($total, $offset + count($rows)) ?> of <?= (int)$total ?>
            </div>

            <div class="btn-group">
                <a class="btn btn-sm btn-outline-secondary <?= $page <= 1 ? 'disabled' : '' ?>"
                   href="<?= esc($mkPageUrl(max(1, $page - 1))) ?>">
                    Prev
                </a>

                <button class="btn btn-sm btn-outline-secondary disabled">
                    <?= (int)$page ?>
                </button>

                <a class="btn btn-sm btn-outline-secondary <?= $page >= $pages ? 'disabled' : '' ?>"
                   href="<?= esc($mkPageUrl(min($pages, $page + 1))) ?>">
                    Next
                </a>
            </div>
        </div>
    <?php endif; ?>
</div>

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