<?php

declare(strict_types=1);

namespace CliqThemes\StoreLocator\Data\Definition;

defined('ABSPATH') || exit;

use CliqThemes\StoreLocator\I18n\ContentTranslator;
use CliqThemes\StoreLocator\Models\Category;
use CliqThemes\UI\Data\DataProviderRegistry;
use CliqThemes\UI\Data\OrmTableProvider;

/**
 * Provider definition for the Category entity.
 */
final class CategoryProviderDefinition implements ProviderDefinition
{
    public function key(): string
    {
        return 'categories';
    }

    /**
     * @return array<string, mixed>
     */
    public function register(DataProviderRegistry $registry, ProviderContext $context): array
    {

        // Parent-category options (for making a category a sub-category). '0' =
        // top level. Reuses the shared category option list (a [{value,label}]
        // array — the shape SelectField expects), with a "None" entry prepended.
        // Excluding self isn't done here (a static field list can't know which
        // record is being edited).
        $parentOptions = array_merge(
            [['value' => '0', 'label' => __('— None (top level) —', 'cliq-store-locator')]],
            $context->categoryOptions()
        );

        // Categories — scope out translation rows and overlay the active language's name.
        $categoryProvider = new OrmTableProvider(
            Category::class,
            [
                'icon' => ['label' => __('Icon', 'cliq-store-locator'), 'sortable' => false],
                'name' => ['label' => __('Category', 'cliq-store-locator')],
                'slug' => ['label' => __('Slug', 'cliq-store-locator')],
                'parent_id' => ['label' => __('Parent', 'cliq-store-locator'), 'sortable' => false],
                'ordering' => ['label' => __('Order', 'cliq-store-locator')],
            ],
            [
                'q' => [
                    'label' => __('Search', 'cliq-store-locator'),
                    'type' => 'text',
                    'operator' => 'search',
                    'fields' => ['name', 'slug'],
                ],
                'is_active' => [
                    'label' => __('Status', 'cliq-store-locator'),
                    'type' => 'select',
                    'options' => [
                        '1' => __('Active', 'cliq-store-locator'),
                        '0' => __('Inactive', 'cliq-store-locator'),
                    ],
                ],
            ]
        );
        $categoryProvider->addListProcessor(ContentTranslator::listProcessor('cliq_sl_categories', ['name']));

        // Show the "Parent" column by NAME (the stored value is an id). Runs on
        // the list rows only — the edit form still reads the raw parent_id. '0'
        // / none renders as a dash.
        $categoryNames = [];
        foreach ($context->categoryOptions() as $opt) {
            $categoryNames[(string) ($opt['value'] ?? '')] = (string) ($opt['label'] ?? '');
        }
        $categoryProvider->addListProcessor(static function (array $records) use ($categoryNames): array {
            return array_map(static function (array $record) use ($categoryNames): array {
                $pid = (string) ($record['parent_id'] ?? '');
                $record['parent_id'] = ($pid !== '' && $pid !== '0') ? ($categoryNames[$pid] ?? '—') : '—';
                return $record;
            }, $records);
        });

        $registry->register('categories', $categoryProvider);
        $fields = [
            ['name' => 'name', 'label' => __('Name', 'cliq-store-locator'), 'type' => 'text', 'required' => true],
            ['name' => 'slug', 'label' => __('Slug', 'cliq-store-locator'), 'type' => 'text', 'required' => true, 'slugFrom' => 'name'],
            ['name' => 'parent_id', 'label' => __('Parent category', 'cliq-store-locator'), 'type' => 'select', 'default' => '0', 'options' => $parentOptions, 'help' => __('Make this a sub-category. On the storefront, clicking a parent shows its sub-categories (with a "View all" option) instead of jumping straight to stores.', 'cliq-store-locator')],
            ['name' => 'color', 'label' => __('Color', 'cliq-store-locator'), 'type' => 'color', 'default' => '#3858e9', 'help' => __('Used by a Category tile design\'s "Automatic" background color option (Color section), so each category can show its own color.', 'cliq-store-locator')],
        ];
        /**
         * Filter the fields a category is edited with.
         *
         * @param array<int, array<string, mixed>> $fields
         * @param ProviderContext                  $context option sources
         */
        $fields = apply_filters('cliq_sl_admin_category_fields', $fields, $context);
        $fields[] = ['name' => 'icon', 'label' => __('Icon', 'cliq-store-locator'), 'type' => 'icon-picker', 'help' => __('Pick an in-house icon and recolor it.', 'cliq-store-locator')];
        $fields[] = ['name' => 'ordering', 'label' => __('Order', 'cliq-store-locator'), 'type' => 'number', 'default' => 0];
        $fields[] = ['name' => 'is_active', 'label' => __('Active', 'cliq-store-locator'), 'type' => 'toggle', 'default' => true];

        return [
            'primaryKey' => 'id',
            'label' => __('Category', 'cliq-store-locator'),
            'fields' => $fields,
        ];
    }
}
