<?php

declare(strict_types=1);

namespace CliqThemes\StoreLocator\Data\Definition;

defined('ABSPATH') || exit;

/**
 * Derives the list of custom (meta) fields from a store form schema: everything
 * that is not a core store-table column or a non-data field type. Single source
 * of truth shared by the store provider (token formats) and the admin builder
 * config, so the lists always match the form.
 */
final class StoreCustomFields
{
    /**
     * @param array<string, mixed> $form
     *
     * @return array<int, array{key: string, label: string, type: string}>
     */
    public static function fromForm(array $form): array
    {
        $core = [
            'name', 'slug', 'status', 'city', 'country', 'phone', 'email', 'website',
            'brand', 'brand_id', 'featured', 'description', 'logo_id', 'marker_id', 'marker_source',
            'owner_id', 'hero_media', 'hero_media_preview',
            'categories', 'category_id', 'latitude', 'longitude',
        ];
        // 'hours'/'map'/'conditional' are structural, non-scalar built-in field
        // types (Opening Hours, the Location map picker, and field-group
        // wrappers) — none is a real filterable/bindable custom field, but
        // without this exclusion each masqueraded as one in the admin
        // builder's "bind to" picker (meta:opening_hours, meta:location…),
        // whose stored value can never match a plain string/number filter
        // (e.g. opening_hours stores a serialized per-day schedule array).
        $skipTypes = ['media', 'gallery', 'hidden', 'heading', 'divider', 'submit', 'hours', 'map', 'conditional'];

        $out = [];
        foreach ($form['sections'] ?? [] as $section) {
            foreach ($section['groups'] ?? [] as $group) {
                foreach ($group['fields'] ?? [] as $field) {
                    $key = $field['name'] ?? '';
                    $type = $field['type'] ?? 'text';
                    if ($key === '' || in_array($key, $core, true) || in_array($type, $skipTypes, true)) {
                        continue;
                    }
                    $out[$key] = ['key' => $key, 'label' => $field['label'] ?? $key, 'type' => $type];
                }
            }
        }

        return array_values($out);
    }
}
