<?php
/**
 * Template Region Registry
 *
 * Declares which named "regions" each page template exposes for block
 * placement. A template not listed here implicitly has a single "main"
 * region — existing block-based templates continue to behave exactly as
 * before. Templates with multiple regions render each region in a
 * separate sortable list in the admin and a separate render call on the
 * frontend.
 */
namespace Mtc\Modules\BlockRegistry\Services;

class TemplateRegionRegistry
{
    /**
     * Default region used when no region is specified.
     */
    public const DEFAULT_REGION = 'main';

    /**
     * Map of template_name => ordered array of region slugs.
     * The order here determines admin UI order.
     */
    private const TEMPLATE_REGIONS = [
        'content_sidebar.twig' => ['header', 'main', 'footer'],
    ];

    /**
     * Pretty labels for region slugs (used in admin section headings).
     */
    private const REGION_LABELS = [
        'header' => 'Header',
        'main'   => 'Main',
        'footer' => 'Footer',
    ];

    /**
     * Get the ordered list of region slugs for a given template.
     * Returns ['main'] for any template not explicitly listed.
     */
    public static function regionsFor(?string $templateName): array
    {
        if (!$templateName) {
            return [self::DEFAULT_REGION];
        }
        return self::TEMPLATE_REGIONS[$templateName] ?? [self::DEFAULT_REGION];
    }

    /**
     * True when the template declares more than one region.
     */
    public static function hasMultipleRegions(?string $templateName): bool
    {
        return count(self::regionsFor($templateName)) > 1;
    }

    /**
     * Human-readable label for a region slug.
     */
    public static function labelFor(string $region): string
    {
        return self::REGION_LABELS[$region] ?? ucfirst(str_replace(['-', '_'], ' ', $region));
    }

    /**
     * True when a region slug is valid for the given template.
     */
    public static function isValidRegion(?string $templateName, ?string $region): bool
    {
        if ($region === null) {
            return true;
        }
        return in_array($region, self::regionsFor($templateName), true);
    }

    /**
     * Resolve the page-template name for an entity. Used by region
     * validation, cache invalidation, and the admin entity-blocks
     * template to look up which regions apply to a given entity.
     *
     * Shop entities use fixed template names; pages defer to
     * ContentManagerPanel. Anything else returns null (single 'main'
     * region).
     */
    public static function resolveTemplateName(?string $entityType, int $entityId): ?string
    {
        if ($entityType === 'item') {
            return 'shop_item';
        }
        if ($entityType === 'category') {
            return 'shop_category';
        }
        if ($entityType === 'page' && $entityId > 0) {
            try {
                $page = \ContentManagerPanel::loadPage($entityId, false);
                return $page->template ?? null;
            } catch (\Exception $e) {
                // A transient DB failure here would mean callers (cache
                // invalidation, region validation) silently fall back to
                // the default region. Log so the anomaly is traceable
                // without disrupting the request.
                \Illuminate\Support\Facades\Log::debug(
                    'TemplateRegionRegistry: loadPage failed; falling back to no template',
                    ['entity_id' => $entityId, 'error' => $e->getMessage()]
                );
                return null;
            }
        }
        return null;
    }
}
