<?php
/**
 * Block Registry Template Assignment Model
 * Links blocks to templates (whitelist)
 */
namespace Mtc\Modules\BlockRegistry\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class BlockRegistryTemplateAssignment extends Model
{
    protected $table = 'block_registry_template_assignments';

    protected $fillable = [
        'block_id',
        'template_name',
        'is_default',
        'order_index',
    ];

    protected $casts = [
        'block_id' => 'integer',
        'is_default' => 'boolean',
        'order_index' => 'integer',
    ];

    /**
     * Get the block
     */
    public function block(): BelongsTo
    {
        return $this->belongsTo(BlockRegistry::class, 'block_id');
    }

    /**
     * Get all blocks assigned to a template
     */
    public static function getBlocksForTemplate(string $templateName): \Illuminate\Support\Collection
    {
        return self::where('template_name', $templateName)
            ->with(['block.category', 'block.fields'])
            ->orderBy('order_index')
            ->get()
            ->pluck('block')
            ->filter();
    }

    /**
     * Get default blocks for a template (auto-added to new pages)
     */
    public static function getDefaultBlocksForTemplate(string $templateName): \Illuminate\Support\Collection
    {
        return self::where('template_name', $templateName)
            ->where('is_default', true)
            ->with(['block.category', 'block.fields'])
            ->orderBy('order_index')
            ->get()
            ->pluck('block')
            ->filter();
    }

    /**
     * Check if a block is assigned to a template
     */
    public static function isBlockAssignedToTemplate(int $blockId, string $templateName): bool
    {
        return self::where('block_id', $blockId)
            ->where('template_name', $templateName)
            ->exists();
    }

    /**
     * Get all unique template names that have block assignments
     */
    public static function getAllAssignedTemplates(): array
    {
        return self::distinct()
            ->pluck('template_name')
            ->toArray();
    }
}
