<?php
/**
 * ZERTI — admin access and per-tab capabilities.
 */

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Capability required to see the ZERTI admin menu (individual tabs may use stricter caps).
 */
function zerti_admin_menu_capability(): string
{
    return (string) apply_filters('zerti_admin_menu_capability', 'zerti_access');
}

/**
 * Whether the current user may open the ZERTI admin app at all.
 */
function zerti_user_can_access_admin(): bool
{
    if (current_user_can('manage_options')) {
        return true;
    }

    return current_user_can(zerti_admin_menu_capability());
}

/**
 * Default capability per tab slug (overridden via zerti_routes() tab `cap` keys).
 *
 * @return array<string, string>
 */
function zerti_tab_default_capabilities(): array
{
    return [
        'home' => 'view_woocommerce_reports',
        'shop' => 'edit_shop_orders',
        'inventory' => 'edit_products',
        'financial' => 'view_woocommerce_reports',
        'customers' => 'list_users',
        'reviews' => 'moderate_comments',
        'comments' => 'moderate_comments',
        'bulk_action' => 'manage_woocommerce',
        'fast-import-export' => 'edit_products',
        'settings' => 'manage_options',
    ];
}

/**
 * Capability required for a tab / component slug.
 */
function zerti_tab_capability(string $slug): string
{
    $defaults = zerti_tab_default_capabilities();
    foreach (zerti_routes()['tabs'] as $tab) {
        if (($tab['slug'] ?? '') === $slug) {
            $cap = isset($tab['cap']) ? (string) $tab['cap'] : '';

            return $cap !== '' ? $cap : ($defaults[$slug] ?? 'manage_options');
        }
    }
    foreach (zerti_routes()['customer_relations']['subs'] as $sub) {
        $panel = (string) ($sub['tab'] ?? $sub['slug'] ?? '');
        if ($panel === $slug) {
            $cap = isset($sub['cap']) ? (string) $sub['cap'] : '';

            return $cap !== '' ? $cap : ($defaults[$slug] ?? 'manage_options');
        }
    }

    return $defaults[$slug] ?? 'manage_options';
}

/**
 * Whether the current user may view a tab (nav, SSR, AJAX fragment).
 */
function zerti_user_can_access_tab(string $slug): bool
{
    if ($slug === 'customer_relations') {
        foreach (zerti_routes()['customer_relations']['subs'] as $sub) {
            $panel = (string) ($sub['tab'] ?? $sub['slug'] ?? '');
            if ($panel !== '' && current_user_can(zerti_tab_capability($panel))) {
                return true;
            }
        }

        return false;
    }

    if ($slug === 'reports') {
        return zerti_user_can_access_tab('financial');
    }

    return current_user_can(zerti_tab_capability($slug));
}

/**
 * Top-level nav tabs visible to the current user.
 *
 * @return list<array{slug:string,icon:string,label:string,cap?:string}>
 */
function zerti_admin_nav_tabs(): array
{
    $tabs = zerti_routes()['tabs'];
    $visible = [];
    foreach ($tabs as $tab) {
        $slug = (string) ($tab['slug'] ?? '');
        if ($slug !== '' && zerti_user_can_access_tab($slug)) {
            $visible[] = $tab;
        }
    }

    return $visible;
}

/**
 * Tabs that render a main content panel (includes CRM subs such as customers).
 *
 * @return list<array{slug:string,icon?:string,label?:string,cap?:string}>
 */
function zerti_admin_panel_tabs(): array
{
    $routes = zerti_routes();
    $visible = [];
    $seen = [];

    foreach ($routes['tabs'] as $tab) {
        $slug = (string) ($tab['slug'] ?? '');
        if ($slug === '' || !empty($tab['nav_group'])) {
            continue;
        }
        if (!zerti_user_can_access_tab($slug)) {
            continue;
        }
        $visible[] = $tab;
        $seen[$slug] = true;
    }

    foreach ($routes['customer_relations']['subs'] as $sub) {
        $panel_slug = (string) ($sub['tab'] ?? $sub['slug'] ?? '');
        if ($panel_slug === '' || isset($seen[$panel_slug])) {
            continue;
        }
        if (!zerti_user_can_access_tab($panel_slug)) {
            continue;
        }
        $visible[] = [
            'slug' => $panel_slug,
            'icon' => (string) ($sub['icon'] ?? ''),
            'label' => (string) ($sub['label'] ?? ''),
            'cap' => (string) ($sub['cap'] ?? ''),
        ];
        $seen[$panel_slug] = true;
    }

    return $visible;
}

/**
 * @return list<string>
 */
function zerti_admin_nav_slugs(): array
{
    return array_column(zerti_admin_nav_tabs(), 'slug');
}

/**
 * @return list<string>
 */
function zerti_admin_route_tab_slugs(): array
{
    return array_column(zerti_admin_panel_tabs(), 'slug');
}

/**
 * First tab the user may open (fallback when URL points at a forbidden tab).
 */
function zerti_default_accessible_tab(): string
{
    $slugs = zerti_admin_nav_slugs();

    return $slugs[0] ?? 'home';
}

/**
 * Grant zerti_access to store roles on install / upgrade.
 */
function zerti_ensure_role_capabilities(): void
{
    foreach (['administrator', 'shop_manager'] as $role_name) {
        $role = get_role($role_name);
        if ($role && !$role->has_cap('zerti_access')) {
            $role->add_cap('zerti_access');
        }
    }
}

add_action('admin_init', 'zerti_ensure_role_capabilities');
