<?php
/**
 * Shared Entity Blocks Section
 * Renders the blocks table with add/reorder/edit/delete for any entity type.
 *
 * Required variables:
 *   $entity_type  - 'page', 'item', or 'category'
 *   $entity_id    - The entity's ID
 */

use Mtc\Modules\BlockRegistry\Models\EntityBlock;
use Mtc\Modules\BlockRegistry\Models\BlockTemplateAssignment;
use Mtc\Modules\BlockRegistry\Services\TemplateRegionRegistry;

// Resolve the page template name for this entity
$pageTemplateName = TemplateRegionRegistry::resolveTemplateName($entity_type, (int) $entity_id);
$hasBlockTemplates = false;
if ($pageTemplateName) {
    $hasBlockTemplates = BlockTemplateAssignment::where('template_name', $pageTemplateName)->exists();
}

// Get entity blocks for this entity with global block relationships
$entityBlocks = EntityBlock::forEntity($entity_type, $entity_id)
    ->with(['block', 'block.fields', 'block.category', 'sourceBlock', 'sourceBlock.block', 'sourceBlock.block.category'])
    ->ordered()
    ->get();

// Group blocks by region. Legacy NULL rows are bucketed into the default
// region so they keep showing up in templates that now have regions.
$regions = TemplateRegionRegistry::regionsFor($pageTemplateName);
$blocksByRegion = [];
foreach ($regions as $region) {
    $blocksByRegion[$region] = collect();
}
foreach ($entityBlocks as $block) {
    $regionKey = $block->region ?: TemplateRegionRegistry::DEFAULT_REGION;
    if (!isset($blocksByRegion[$regionKey])) {
        // Block is in a region the template no longer declares — surface it
        // anyway under its stored region so editors can move/remove it.
        $blocksByRegion[$regionKey] = collect();
    }
    $blocksByRegion[$regionKey]->push($block);
}

$hasMultipleRegions = count($blocksByRegion) > 1;

// Entity-specific labels
$entityLabels = [
    'page' => 'this page',
    'item' => 'this product',
    'category' => 'this category',
];
$entityLabel = $entityLabels[$entity_type] ?? 'this item';

/**
 * Render one region's table+actions block. Closure scoped here so we don't
 * leak helpers to the rest of the admin.
 */
$renderRegion = function ($region, $blocks) use ($hasBlockTemplates, $hasMultipleRegions, $entity_type, $entity_id, $entityLabel) {
    $regionLabel = TemplateRegionRegistry::labelFor($region);
    $sortableId = $hasMultipleRegions
        ? 'entityBlocksSortable-' . preg_replace('/[^a-z0-9_-]/i', '', $region)
        : 'entityBlocksSortable';
    $regionAttr = $region !== TemplateRegionRegistry::DEFAULT_REGION ? $region : '';
    ?>
    <div class="entityBlocksRegion" data-region="<?= htmlspecialchars($region) ?>">
        <?php if ($hasMultipleRegions) { ?>
            <h2 class="entityBlocksRegion__heading">
                <?= htmlspecialchars($regionLabel) ?>
                <span class="badge"><?= count($blocks) ?></span>
            </h2>
        <?php } ?>

        <div class="entity-blocks-actions">
            <a href="#"
               class="add-block-from-registry-btn btn-add-block"
               data-region="<?= htmlspecialchars($regionAttr) ?>"
               title="Add block to <?= htmlspecialchars($regionLabel) ?>">
                <i class="fa fa-plus"></i> Add New Block
            </a>
            <?php if ($hasBlockTemplates && !$hasMultipleRegions) { ?>
            <a href="#" class="add-template-from-registry-btn btn-add-block" title="Add blocks from a template">
                <i class="fa fa-clipboard"></i> Add Template
            </a>
            <?php } ?>
            <?php if (!$hasMultipleRegions && count($blocks) > 0) { ?>
            <a href="/admin/blocks/preview/<?= htmlspecialchars($entity_type) ?>/<?= (int) $entity_id ?>"
               target="_blank"
               title="Preview all blocks"
               class="btn-preview">
                <i class="fa fa-eye"></i> Preview
            </a>
            <?php } ?>
        </div>

        <?php if (count($blocks) > 0) { ?>
            <table class="entityBlocksTable">
                <thead>
                    <tr>
                        <th class="col-handle"></th>
                        <th class="col-num">#</th>
                        <th>Block</th>
                        <th>Category</th>
                        <th class="col-status">Status</th>
                        <th class="col-actions">Actions</th>
                    </tr>
                </thead>
                <tbody id="<?= $sortableId ?>" class="entityBlocksSortable" data-region="<?= htmlspecialchars($regionAttr) ?>">
                    <?php $rowNumber = 1; ?>
                    <?php foreach ($blocks as $entityBlock) { ?>
                        <?php
                        $isGlobalRef = $entityBlock->isGlobalReference();
                        $isOrphaned = $isGlobalRef && !$entityBlock->sourceBlock;
                        $rowClass = $entityBlock->isDraft() ? 'entity-block-row--draft' : '';
                        if ($isGlobalRef) {
                            $rowClass .= ' entity-block-row--global';
                        }
                        ?>
                        <tr class="<?= $rowClass ?>" data-entity-block-id="<?= $entityBlock->id ?>">
                            <td class="drag-handle">
                                <i class="fa fa-bars"></i>
                            </td>
                            <td class="entity-block-num">
                                <?= $rowNumber++ ?>
                            </td>
                            <td>
                                <?php if ($isGlobalRef && !$isOrphaned) { ?>
                                    <?php
                                    $globalPreviewUrl = '';
                                    if ($entityBlock->sourceBlock && $entityBlock->sourceBlock->block && $entityBlock->sourceBlock->block->hasTemplate()) {
                                        $globalPreviewUrl = '/admin/blocks/data/' . $entityBlock->source_block_id . '/preview';
                                    }
                                    ?>
                                    <span class="entity-block-name-wrap"<?= $globalPreviewUrl ? ' data-preview-url="' . htmlspecialchars($globalPreviewUrl) . '"' : '' ?>>
                                    <i class="fa fa-globe entity-block-icon" style="color:#28a745;"></i>
                                    <strong><?= htmlspecialchars($entityBlock->sourceBlock->name ?? 'Global Block') ?></strong>
                                    <span class="entity-block-global-badge">Synced</span>
                                    <div class="entity-block-snippet">
                                        <?= htmlspecialchars($entityBlock->sourceBlock->block->name ?? '') ?>
                                    </div>
                                    </span>
                                <?php } elseif ($isOrphaned) { ?>
                                    <i class="fa fa-exclamation-triangle entity-block-icon" style="color:#dc3545;"></i>
                                    <strong style="color:#dc3545;">Source Deleted</strong>
                                    <div class="entity-block-snippet" style="color:#dc3545;">
                                        This global block's source has been removed.
                                    </div>
                                <?php } else { ?>
                                    <?php
                                    $blockPreviewUrl = '';
                                    if ($entityBlock->block && $entityBlock->block->hasTemplate()) {
                                        $blockPreviewUrl = '/admin/blocks/data/' . $entityBlock->id . '/preview';
                                    }
                                    ?>
                                    <span class="entity-block-name-wrap"<?= $blockPreviewUrl ? ' data-preview-url="' . htmlspecialchars($blockPreviewUrl) . '"' : '' ?>>
                                    <i class="fa <?= htmlspecialchars($entityBlock->block->icon ?? 'fa-cube') ?> entity-block-icon"></i>
                                    <strong><?= htmlspecialchars($entityBlock->block->name ?? 'Unknown Block') ?></strong>
                                    <?php
                                    $snippet = '';
                                    if (!empty($entityBlock->data)) {
                                        foreach ($entityBlock->data as $key => $value) {
                                            if (is_string($value) && !empty(trim($value)) && strlen(trim($value)) > 3) {
                                                $snippet = strip_tags($value);
                                                $snippet = trim($snippet);
                                                if (strlen($snippet) > 50) {
                                                    $snippet = substr($snippet, 0, 50) . '...';
                                                }
                                                break;
                                            }
                                        }
                                    }
                                    ?>
                                    <?php if ($snippet) { ?>
                                        <div class="entity-block-snippet">
                                            "<?= htmlspecialchars($snippet) ?>"
                                        </div>
                                    <?php } ?>
                                    </span>
                                <?php } ?>
                            </td>
                            <td class="entity-block-category">
                                <?php if ($isGlobalRef && !$isOrphaned) { ?>
                                    <?= htmlspecialchars($entityBlock->sourceBlock->block->category->name ?? 'Uncategorized') ?>
                                <?php } else { ?>
                                    <?= htmlspecialchars($entityBlock->block->category->name ?? 'Uncategorized') ?>
                                <?php } ?>
                            </td>
                            <td>
                                <?php if ($isGlobalRef) { ?>
                                    <span class="toggleStatusBtn toggleStatusBtn--published" style="cursor:default;">
                                        Synced
                                    </span>
                                <?php } elseif ($entityBlock->isPublished()) { ?>
                                    <button type="button"
                                            class="toggleStatusBtn toggleStatusBtn--published"
                                            data-entity-block-id="<?= $entityBlock->id ?>"
                                            data-status="published">
                                        Published
                                    </button>
                                <?php } else { ?>
                                    <button type="button"
                                            class="toggleStatusBtn toggleStatusBtn--draft"
                                            data-entity-block-id="<?= $entityBlock->id ?>"
                                            data-status="draft">
                                        Draft
                                    </button>
                                <?php } ?>
                            </td>
                            <td>
                                <?php if ($isGlobalRef && !$isOrphaned) { ?>
                                    <a href="/admin/blocks/data/<?= $entityBlock->source_block_id ?>"
                                       class="btn btn-edit-data btn-edit-data--global"
                                       target="_blank">
                                        <i class="fa fa-pencil"></i> Edit Global
                                    </a>
                                <?php } elseif (!$isOrphaned) { ?>
                                    <a href="/admin/blocks/data/<?= $entityBlock->id ?>"
                                       class="btn btn-edit-data">
                                        <i class="fa fa-pencil"></i> Edit Data
                                    </a>
                                <?php } ?>
                                <button type="button"
                                        class="btn btn-remove-block removeEntityBlockBtn"
                                        data-entity-block-id="<?= $entityBlock->id ?>">
                                    <i class="fa fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                    <?php } ?>
                </tbody>
            </table>
        <?php } else { ?>
            <p class="entity-blocks-empty">
                <i class="fa fa-info-circle"></i>
                No blocks added to <?= htmlspecialchars($regionLabel) ?> yet.
            </p>
        <?php } ?>
    </div>
    <?php
};
?>

<fieldset class="show entityBlocksFieldset">
    <h1>
        <a class="show el">
            <i class="fa fa-cubes"></i>
            Block Registry Blocks
            <span class="badge">
                <?= count($entityBlocks) ?>
            </span>
        </a>
    </h1>

    <div class="entityBlocksList<?= $hasMultipleRegions ? ' entityBlocksList--multiRegion' : '' ?>"
         data-entity-type="<?= htmlspecialchars($entity_type) ?>"
         data-entity-id="<?= (int) $entity_id ?>"
         data-multi-region="<?= $hasMultipleRegions ? '1' : '0' ?>">

        <?php foreach ($blocksByRegion as $region => $blocks) {
            $renderRegion($region, $blocks);
        } ?>

        <?php if (count($entityBlocks) === 0 && !$hasMultipleRegions) { ?>
            <p class="entity-blocks-empty entity-blocks-empty--global">
                <span>
                    Click the <strong>Add New Block</strong> button above to add blocks from the registry.
                </span>
            </p>
        <?php } ?>
    </div>
</fieldset>

<template id="blockPickerContentTemplate">
    <div class="block-picker">
        <div class="block-picker-header">
            <div class="block-picker-search">
                <input type="text" id="blockPickerSearch" placeholder="Search blocks..." />
            </div>
            <div class="block-picker-filter">
                <select id="blockPickerCategory">
                    <option value="">All Categories</option>
                </select>
            </div>
        </div>
        <div class="block-picker-content" id="blockPickerContent">
            <div class="block-picker-loading">Loading blocks...</div>
        </div>
    </div>
</template>

<?php
$brAdminBase = base_path('modules/BlockRegistry');
$brCssV = @filemtime($brAdminBase . '/admin/css/block_registry.css') ?: 0;
$brJsEntityV = @filemtime($brAdminBase . '/js/block-registry-entity-blocks.js') ?: 0;
$brJsStandaloneV = @filemtime($brAdminBase . '/js/block-registry-standalone.js') ?: 0;
?>
<link rel="stylesheet" href="/modules/BlockRegistry/admin/css/block_registry.css?v=<?= $brCssV ?>">
<script src="/modules/BlockRegistry/js/block-registry-entity-blocks.js?v=<?= $brJsEntityV ?>"></script>
<?php if ($entity_type !== 'page') { ?>
<script src="/modules/BlockRegistry/js/block-registry-standalone.js?v=<?= $brJsStandaloneV ?>"></script>
<?php } ?>
