<?php
// Block Registry Hooks
// Auto-discovered by core/includes/twig.php via modules/*/hooks.php glob

use Twig\TwigFunction;
use Illuminate\Support\Facades\Event;
use Mtc\Shop\Events\ItemAdminTabnavEvent;

/**
 * Register "Blocks" tab on the product admin tabnav
 */
Event::listen(
    'Mtc\Shop\Events\ItemAdminTabnavEvent',
    function (ItemAdminTabnavEvent $event) {
        $request = $event->getRequest();
        $selected = strpos($_SERVER['REQUEST_URI'], '/modules/BlockRegistry/admin/products/blocks.php') !== false ? 'selected' : '';
        return '<li class="' . $selected . '"><a href="/modules/BlockRegistry/admin/products/blocks.php?id=' . (int) $request['id'] . '">Blocks</a></li>';
    }
);

/**
 * Render a single entity block by its ID
 * Usage: {{ render_block(entityBlockId) }}
 */
$twig->addFunction(new TwigFunction('render_block', function($entityBlockId) use ($twig) {
    $service = app(\Mtc\Modules\BlockRegistry\Services\EntityBlockService::class);
    $service->setTwig($twig);

    $entityBlock = \Mtc\Modules\BlockRegistry\Models\EntityBlock::with(['block', 'block.fields'])
        ->find($entityBlockId);

    if (!$entityBlock || $entityBlock->isDraft()) {
        return '';
    }

    return $service->renderBlock($entityBlock) ?? '';
}, ['is_safe' => ['html']]));

/**
 * Render all entity blocks for a page (or other entity) that have templates
 * Usage: {{ render_entity_blocks('page', pageId) }}
 * Usage: {{ render_entity_blocks('page', p.id) }}
 */
$twig->addFunction(new TwigFunction('render_entity_blocks', function($entityType, $entityId) use ($twig) {
    $service = app(\Mtc\Modules\BlockRegistry\Services\EntityBlockService::class);
    $service->setTwig($twig);

    return $service->renderEntityBlocks($entityType, $entityId);
}, ['is_safe' => ['html']]));

/**
 * Render entity blocks of a specific block type
 * Usage: {{ render_blocks_by_type('page', pageId, 'title-banner') }}
 */
$twig->addFunction(new TwigFunction('render_blocks_by_type', function($entityType, $entityId, $blockSlug) use ($twig) {
    $service = app(\Mtc\Modules\BlockRegistry\Services\EntityBlockService::class);
    $service->setTwig($twig);

    return $service->renderBlocksByType($entityType, $entityId, $blockSlug);
}, ['is_safe' => ['html']]));

/**
 * Get entity blocks data with optional rendering
 * Usage: {% set blocks = get_entity_blocks('page', p.id) %}
 * Usage: {% set blocks = get_entity_blocks('page', p.id, true) %} (includes rendered HTML)
 */
$twig->addFunction(new TwigFunction('get_entity_blocks', function($entityType, $entityId, $includeRendering = false) use ($twig) {
    $service = app(\Mtc\Modules\BlockRegistry\Services\EntityBlockService::class);
    $service->setTwig($twig);

    if ($includeRendering) {
        return $service->getBlocksWithRendering($entityType, $entityId);
    }

    return $service->getBlocksForEntity($entityType, $entityId);
}));

/**
 * Render a global block by its ID directly
 * Useful for hardcoding site-wide elements in layout templates
 * Usage: {{ render_global_block(42) }}
 */
/**
 * Get products by an array of IDs (for block templates that need product data)
 * Usage: {% set products = get_products_by_ids([1, 2, 3]) %}
 */
$twig->addFunction(new TwigFunction('get_products_by_ids', function(array $ids) {
    if (empty($ids)) {
        return collect();
    }
    return \Mtc\Shop\Item::query()
        ->whereIn('id', $ids)
        ->active()
        ->with(['defaultImage', 'images', 'sizes'])
        ->get();
}));

$twig->addFunction(new TwigFunction('render_global_block', function($globalBlockId) use ($twig) {
    $service = app(\Mtc\Modules\BlockRegistry\Services\EntityBlockService::class);
    $service->setTwig($twig);

    $entityBlock = \Mtc\Modules\BlockRegistry\Models\EntityBlock::with(['block', 'block.fields'])
        ->where('entity_type', 'global')
        ->find($globalBlockId);

    if (!$entityBlock || $entityBlock->isDraft()) {
        return '';
    }

    return $service->renderBlock($entityBlock) ?? '';
}, ['is_safe' => ['html']]));

/**
 * Render a global block by its block definition slug
 * Usage: {{ render_global_block_by_slug('quick-icons-bar') }}
 * Usage: {{ render_global_block_by_slug('quick-icons-bar', { class: 'quickIconsBar--light' }) }}
 */
$twig->addFunction(new TwigFunction('render_global_block_by_slug', function(string $slug, array $extraContext = []) use ($twig) {
    $service = app(\Mtc\Modules\BlockRegistry\Services\EntityBlockService::class);
    $service->setTwig($twig);

    $entityBlock = \Mtc\Modules\BlockRegistry\Models\EntityBlock::with(['block', 'block.fields'])
        ->where('entity_type', 'global')
        ->whereNull('source_block_id')
        ->whereHas('block', function ($q) use ($slug) {
            $q->where('slug', $slug);
        })
        ->first();

    if (!$entityBlock || $entityBlock->isDraft()) {
        return '';
    }

    return $service->renderBlock($entityBlock, $extraContext) ?? '';
}, ['is_safe' => ['html']]));
