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

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

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

$PAGE_TITLE = 'Centres';
$ACTIVE = 'centres';

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('cdb_table_exists')) {
    function cdb_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('cdb_cols')) {
    function cdb_cols(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('cdb_pick_label')) {
    function cdb_pick_label(array $have, array $candidates): string
    {
        foreach ($candidates as $column) {
            if (in_array($column, $have, true)) {
                return $column;
            }
        }

        return 'id';
    }
}

if (!function_exists('centre_status_badge')) {
    function centre_status_badge($status): string
    {
        $raw = trim((string)$status);
        $lower = strtolower($raw);

        if ($lower === 'active' || $raw === '1' || $lower === 'enabled') {
            return '<span class="badge bg-success">Active</span>';
        }

        if ($lower === 'inactive' || $raw === '0' || $lower === 'disabled') {
            return '<span class="badge bg-secondary">Inactive</span>';
        }

        if ($lower === 'pending') {
            return '<span class="badge bg-warning text-dark">Pending</span>';
        }

        return '<span class="badge bg-light text-dark border">' . esc($raw !== '' ? $raw : '-') . '</span>';
    }
}

/* ---------------- Find table ---------------- */

$candidateTables = [
    'centres',
    'centers',
    'branches',
    'branch',
    'venues',
    'locations'
];

$TBL = '';

foreach ($candidateTables as $table) {
    if (cdb_table_exists($mysqli, $table)) {
        $TBL = $table;
        break;
    }
}

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

if ($TBL === '') {
    echo '
        <div class="alert alert-danger border-0 rounded-4 shadow-sm">
            Couldn’t find a table for <strong>Centres</strong>.
            Create one named <code>centres</code>, or use a compatible table name:
            <code>centers</code>, <code>branches</code>, <code>venues</code>, or <code>locations</code>.
        </div>
    ';

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

/* ---------------- Pick columns ---------------- */

$HAVE = cdb_cols($mysqli, $TBL);

$labelCol = cdb_pick_label($HAVE, [
    'name',
    'centre_name',
    'center_name',
    'branch_name',
    'venue_name',
    'title',
    'label'
]);

$codeCol = in_array('code', $HAVE, true)
    ? 'code'
    : (in_array('centre_code', $HAVE, true)
        ? 'centre_code'
        : (in_array('branch_code', $HAVE, true) ? 'branch_code' : ''));

$statusCol = in_array('status', $HAVE, true)
    ? 'status'
    : (in_array('is_active', $HAVE, true)
        ? 'is_active'
        : (in_array('active', $HAVE, true) ? 'active' : ''));

$idCol = in_array('id', $HAVE, true) ? 'id' : ($HAVE[0] ?? 'id');

/* ---------------- Filters ---------------- */

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

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

if ($q !== '') {
    $where .= " AND `$labelCol` LIKE ?";
    $types .= 's';
    $vals[] = '%' . $q . '%';
}

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

$select = "`$idCol` AS id, `$labelCol` AS label";

if ($codeCol !== '') {
    $select .= ", `$codeCol` AS code";
}

if ($statusCol !== '') {
    $select .= ", `$statusCol` AS status";
}

$sql = "
    SELECT $select
    FROM `$TBL`
    $where
    ORDER BY label ASC
";

$rows = [];

try {
    $stmt = $mysqli->prepare($sql);

    if ($stmt) {
        if ($types !== '') {
            $stmt->bind_param($types, ...$vals);
        }

        $stmt->execute();
        $rs = $stmt->get_result();

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

        $stmt->close();
    }
} catch (Throwable $e) {
    $rows = [];
}

$total = count($rows);
$activeCount = 0;
$inactiveCount = 0;

foreach ($rows as $row) {
    if ($statusCol === '') {
        continue;
    }

    $status = strtolower(trim((string)($row['status'] ?? '')));

    if ($status === 'active' || $status === '1' || $status === 'enabled') {
        $activeCount++;
    }

    if ($status === 'inactive' || $status === '0' || $status === 'disabled') {
        $inactiveCount++;
    }
}
?>

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

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

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

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

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

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

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

<div class="centre-hero mb-4">
    <div class="d-flex flex-wrap justify-content-between align-items-center gap-3">
        <div>
            <h4 class="fw-bold mb-1">Centres</h4>
            <div class="text-muted">
                Manage centres, branches, venues, or locations used by the ELMS.
            </div>
        </div>

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

            <?php if ($statusCol !== ''): ?>
                <span class="centre-chip">
                    <i class="bi bi-check-circle text-success"></i>
                    <?= number_format($activeCount) ?> Active
                </span>

                <span class="centre-chip">
                    <i class="bi bi-dash-circle text-secondary"></i>
                    <?= number_format($inactiveCount) ?> Inactive
                </span>
            <?php endif; ?>

            <span class="centre-chip">
                <i class="bi bi-database text-info"></i>
                Table: <?= esc($TBL) ?>
            </span>
        </div>
    </div>
</div>

<div class="centre-card mb-4">
    <div class="centre-card-header">
        <div>
            <h5 class="mb-0 fw-bold">Search Centres</h5>
            <div class="text-muted small">Search by centre or branch name</div>
        </div>

        <a href="edit.php" class="btn btn-admin-primary">
            <i class="bi bi-plus-circle me-1"></i>
            New Centre
        </a>
    </div>

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

            <div class="col-lg-3 col-md-4 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="index.php">
                    Reset
                </a>
            </div>
        </form>
    </div>
</div>

<div class="centre-card">
    <div class="centre-card-header">
        <div>
            <h5 class="mb-0 fw-bold">Centre List</h5>
            <div class="text-muted small"><?= number_format($total) ?> record(s) found</div>
        </div>
    </div>

    <div class="table-responsive">
        <table class="table centre-table table-hover align-middle mb-0">
            <thead>
                <tr>
                    <th style="width:80px;">ID</th>
                    <th>Name</th>

                    <?php if ($codeCol !== ''): ?>
                        <th>Code</th>
                    <?php endif; ?>

                    <?php if ($statusCol !== ''): ?>
                        <th>Status</th>
                    <?php endif; ?>

                    <th class="text-end" style="width:180px;">Actions</th>
                </tr>
            </thead>

            <tbody>
                <?php if (!$rows): ?>
                    <tr>
                        <td colspan="<?= 3 + ($codeCol !== '' ? 1 : 0) + ($statusCol !== '' ? 1 : 0) ?>" class="text-center text-muted py-4">
                            No records found.
                        </td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($rows as $row): ?>
                        <tr>
                            <td class="fw-semibold">
                                <?= (int)$row['id'] ?>
                            </td>

                            <td>
                                <div class="centre-name">
                                    <?= esc($row['label']) ?>
                                </div>
                                <div class="small text-muted">
                                    Record ID: <?= (int)$row['id'] ?>
                                </div>
                            </td>

                            <?php if ($codeCol !== ''): ?>
                                <td>
                                    <?= esc($row['code'] ?? '') ?>
                                </td>
                            <?php endif; ?>

                            <?php if ($statusCol !== ''): ?>
                                <td>
                                    <?= centre_status_badge($row['status'] ?? '') ?>
                                </td>
                            <?php endif; ?>

                            <td class="text-end">
                                <div class="d-flex justify-content-end flex-wrap gap-2">
                                    <a href="edit.php?id=<?= (int)$row['id'] ?>" class="btn btn-sm btn-outline-primary rounded-pill">
                                        Edit
                                    </a>

                                    <form method="post" action="delete.php" class="d-inline" onsubmit="return confirm('Delete this item?');">
                                        <input type="hidden" name="id" value="<?= (int)$row['id'] ?>">
                                        <button class="btn btn-sm btn-outline-danger rounded-pill">
                                            Delete
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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