<?php
/**
 * Helpers for admin pages — same structure as admin/xui_management.php
 */

function admin_page_shell_open(): void
{
    if (!empty($GLOBALS['_admin_shell_open'])) {
        return;
    }
    $GLOBALS['_admin_shell_open'] = true;
    echo '<div class="admin-page"><div class="container-fluid"><div class="row"><div class="col-12">';
}

function admin_page_shell_close(): void
{
    if (empty($GLOBALS['_admin_shell_open'])) {
        return;
    }
    unset($GLOBALS['_admin_shell_open']);
    echo '</div></div></div></div>';
}

/**
 * Main content card (title from $page_title, optional header actions HTML)
 */
function admin_page_card_open(?string $actionsHtml = null): void
{
    admin_page_shell_open();
    $title = htmlspecialchars($GLOBALS['page_title'] ?? '', ENT_QUOTES, 'UTF-8');
    echo '<div class="card admin-main-card"><div class="card-header d-flex justify-content-between align-items-center flex-wrap gap-2">';
    echo '<h3 class="card-title mb-0">' . $title . '</h3>';
    if ($actionsHtml !== null && $actionsHtml !== '') {
        echo '<div class="card-header-actions">' . $actionsHtml . '</div>';
    }
    echo '</div><div class="card-body">';
    $GLOBALS['_admin_card_open'] = true;
}

function admin_page_card_close(): void
{
    if (!empty($GLOBALS['_admin_card_open'])) {
        echo '</div></div>';
        unset($GLOBALS['_admin_card_open']);
    }
    admin_page_shell_close();
}

function admin_should_auto_shell(): bool
{
    if (!function_exists('isAdmin') || !isAdmin()) {
        return false;
    }
    $script = $_SERVER['SCRIPT_NAME'] ?? '';
    return strpos($script, '/admin/') !== false;
}
