<?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;

// Resolve the page template name for this entity
$templateMap = ['item' => 'shop_item', 'category' => 'shop_category'];
$pageTemplateName = $templateMap[$entity_type] ?? null;
if ($entity_type === 'page' && $pageTemplateName === null) {
    try {
        $page = \ContentManagerPanel::loadPage($entity_id, false);
        $pageTemplateName = $page->template ?? null;
    } catch (\Exception $e) {
        // Fall through
    }
}
$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();

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

<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" data-entity-type="<?= htmlspecialchars($entity_type) ?>" data-entity-id="<?= (int) $entity_id ?>">
        <div class="entity-blocks-actions">
            <a href="#" class="add-block-from-registry-btn btn-add-block" title="Add block from Block Registry">
                <i class="fa fa-plus"></i> Add New Block
            </a>
            <?php if ($hasBlockTemplates) { ?>
            <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 (count($entityBlocks) > 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($entityBlocks) > 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="entityBlocksSortable">
                    <?php $rowNumber = 1; ?>
                    <?php foreach ($entityBlocks 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 from Block Registry added to <?= $entityLabel ?> yet.
                <br><br>
                <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>

<link rel="stylesheet" href="/modules/BlockRegistry/admin/css/block_registry.css">
<script src="/modules/BlockRegistry/js/block-registry-entity-blocks.js"></script>
<?php if ($entity_type !== 'page') { ?>
<script src="/modules/BlockRegistry/js/block-registry-standalone.js"></script>
<?php } ?>
