@extends('daylight::layouts.app')

@section('title', __('daylight::store.edit_brand'))

@section('content')
    <div x-data="{ showConfirmDeleteModal: false }">
        <x-daylight::page-header :title="__('daylight::general.edit_page', ['page' => $brand->name])">
            @can('update:brands')
                <x-daylight::buttons.danger @click.prevent="showConfirmDeleteModal = true">
                    {{ __('daylight::store.delete_brand') }}
                </x-daylight::buttons.danger>
            @endif
        </x-daylight::page-header>

        <x-daylight::session-messages/>

        <form
            method="post"
            action="{{ route('daylight.store.brands.update', $brand) }}"
            x-on:submit="
                const jsonFields = document.querySelectorAll('textarea[name^=components_json]');
                jsonFields.forEach((field) => {
                    const match = field.name.match(/\[(\d+)\]/);
                    if (match) {
                        const index = parseInt(match[1]);
                        const componentEl = field.closest('[wire\\:id]');
                        if (componentEl) {
                            const livewireId = componentEl.getAttribute('wire:id');
                            if (livewireId && window.Livewire) {
                                const component = window.Livewire.find(livewireId);
                                if (component && component.get && component.get('components')) {
                                    const components = component.get('components');
                                    if (components && components[index]) {
                                        field.value = JSON.stringify(components[index]);
                                    }
                                }
                            }
                        }
                    }
                });
            "
        >
            @csrf
            @method('PUT')
            <input type="hidden" name="locale" value="{{ request()->get('locale', app()->getLocale()) }}">

            <x-daylight::input.group
                :label="__('daylight::general.name')"
                :error="$errors->first('name')"
                for="code"
            >
                <x-daylight::input.text
                    name="name"
                    id="name"
                    value="{{ old('name', $brand->name) }}"
                    :disabled="!auth()->user()->can('update:brands')"
                />
            </x-daylight::input.group>

            <x-daylight::input.group
                :label="__('daylight::general.color')"
                :error="$errors->first('color')"
                for="code"
            >
                <x-daylight::input.color
                    name="color"
                    id="color"
                    value="{{ old('color', $brand->color) }}"
                    :disabled="!auth()->user()->can('update:brands')"
                />
            </x-daylight::input.group>

        <x-daylight::input.group
            :label="__('daylight::general.logo')"
            :error="$errors->first('logo')"
            for="logo"
        >
            <livewire:daylight::media-selector
                name="logo"
                :initial-media="old('media', $brand->gallery)"
                :single-file="true"
            />
        </x-daylight::input.group>

            <x-daylight::locale-selector :route="route('daylight.store.brands.edit', $brand)"/>

            <x-daylight::seo :page="$translation"/>

            <div>
                <h2 class="mt-12">{{ __('daylight::general.components') }}</h2>

                <x-daylight::input.group
                    :label="__('daylight::general.components')"
                    :error="$errors->first('components')"
                    for="components"
                >
                    @php
                        $jsonComponents = old('components_json', []);
                        $componentsFromJson = [];

                        if (!empty($jsonComponents) && is_array($jsonComponents)) {
                            foreach ($jsonComponents as $index => $jsonComponent) {
                                if (is_string($jsonComponent)) {
                                    $decoded = json_decode($jsonComponent, true);
                                    if (is_array($decoded)) {
                                        $componentsFromJson[$index] = $decoded;
                                    }
                                } elseif (is_array($jsonComponent)) {
                                    $componentsFromJson[$index] = $jsonComponent;
                                }
                            }
                        }

                        // Get old() components data (may be incomplete after validation error)
                        $oldComponents = old('components', []);

                        // Merge: use old() components as base (correct order), then merge JSON data into them
                        // Match by _uid or id instead of index to handle reordering/deletion correctly
                        if (!empty($oldComponents) && is_array($oldComponents)) {
                            $matchedComponents = [];
                            $usedJsonIndices = [];

                            // Start with old() components (these have the correct order and include new components)
                            foreach ($oldComponents as $oldIndex => $oldComponent) {
                                $oldId = $oldComponent['id'] ?? null;
                                $oldUid = $oldComponent['_uid'] ?? null;
                                $matched = false;

                                // Try to find matching JSON component by id or _uid
                                if (!empty($componentsFromJson)) {
                                    foreach ($componentsFromJson as $jsonIndex => $jsonComponent) {
                                        if (in_array($jsonIndex, $usedJsonIndices)) {
                                            continue; // Already matched
                                        }

                                        $jsonId = $jsonComponent['id'] ?? null;
                                        $jsonUid = $jsonComponent['_uid'] ?? null;

                                        // Match by id (for existing components) or _uid (for new components)
                                        if (($oldId && $oldId === $jsonId) || ($oldUid && $oldUid === $jsonUid)) {
                                            // Deep merge: preserve JSON structure but update with form values only if not empty
                                            if (isset($oldComponent['data']) && isset($jsonComponent['data'])) {
                                                // Start with JSON data (full data)
                                                $mergedData = $jsonComponent['data'];
                                                
                                                // For each field in old data, update the JSON data only if value is set
                                                foreach ($oldComponent['data'] as $fieldName => $fieldValue) {
                                                    // Only update if the field value is not null and not empty string
                                                    // This prevents empty form values from overwriting existing JSON data
                                                    if ($fieldValue !== null && $fieldValue !== '') {
                                                        // For media and related fields, keep JSON version (has full data)
                                                        // For other fields, use form value if set
                                                        $fieldType = null;
                                                        if (isset($jsonComponent['type'])) {
                                                            $registry = app(\Daylight\Core\Modules\PageBuilder\Registries\ComponentRegistry::class);
                                                            $definition = $registry->getDefinition($jsonComponent['type']);
                                                            if ($definition) {
                                                                $field = collect($definition->fields())->firstWhere('name', $fieldName);
                                                                if ($field) {
                                                                    $fieldType = $field->type;
                                                                }
                                                            }
                                                        }

                                                        // Only update non-media/related fields with form values
                                                        if (!in_array($fieldType, ['media', 'related'])) {
                                                            $mergedData[$fieldName] = $fieldValue;
                                                        }
                                                    }
                                                }
                                                
                                                $jsonComponent['data'] = $mergedData;
                                            } elseif (isset($jsonComponent['data'])) {
                                                // If old() has no data, use JSON data
                                                // (keep as is, already set)
                                            }
                                            // Ensure other fields from old() are preserved if missing in JSON
                                            $matchedComponents[] = array_merge($jsonComponent, $oldComponent);
                                            $usedJsonIndices[] = $jsonIndex;
                                            $matched = true;
                                            break;
                                        }
                                    }
                                }

                                // If no JSON match found, use old() component as-is (newly added component)
                                if (! $matched) {
                                    $matchedComponents[] = $oldComponent;
                                }
                            }

                            $componentsData = $matchedComponents;
                        } elseif (!empty($componentsFromJson)) {
                            // No old() data, use JSON data
                            $componentsData = array_values($componentsFromJson);
                        } else {
                            // Fallback to original components
                            $componentsData = $components;
                        }

                        // Normalize data
                        if (is_string($componentsData)) {
                            $componentsData = json_decode($componentsData, true);
                        }
                        if ($componentsData instanceof \Illuminate\Support\Collection) {
                            $componentsData = $componentsData->toArray();
                        }
                        $componentsData = $componentsData ?: [];
                    @endphp

                    <livewire:daylight::page-builder
                        :components="$componentsData"
                        :availableComponents="$availableComponents->toArray()"
                        name="components"
                    />
                </x-daylight::input.group>
            </div>

            @can('update:brands')
                <div class="mt-6 flex items-center justify-end gap-x-3">
                    <x-daylight::buttons.secondary href="{{ route('daylight.store.brands.index') }}" element="a">
                        {{ __('daylight::general.cancel') }}
                    </x-daylight::buttons.secondary>

                    <x-daylight::buttons.primary type="submit">
                        {{ __('daylight::general.save') }}
                    </x-daylight::buttons.primary>
                </div>
            @endcan
        </form>

        <x-daylight::modal.confirm-delete-modal>
            <x-slot name="content">
                <h3 class="text-base font-semibold leading-6 text-gray-900"
                    id="modal-title">{{ __('daylight::general.delete_object', ['object' => __('daylight::store.daylight::store.brand')]) }}</h3>
                <div class="mt-2">
                    <p class="text-sm text-gray-500">
                        {{ __('daylight::general.delete_confirm', ['object' => __('daylight::store.daylight::store.brand')]) }}
                    </p>
                </div>
            </x-slot>

            <x-slot name="footer">
                <form method="post" action="{{ route('daylight.store.brands.destroy', $brand) }}">
                    @csrf
                    @method('DELETE')

                    <button type="button"
                            class="mt-3 inline-flex w-full justify-center rounded-md bg-white px-3 py-2 text-sm font-semibold text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 hover:bg-gray-100 sm:mt-0 sm:w-auto"
                            @click.prevent="showConfirmDeleteModal = false">
                        {{ __('daylight::general.cancel') }}
                    </button>

                    <button type="submit"
                            class="inline-flex w-full justify-center rounded-md bg-red-600 px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-red-500 sm:ml-2 sm:w-auto">
                        {{ __('daylight::general.delete') }}
                    </button>
                </form>
            </x-slot>
        </x-daylight::modal.confirm-delete-modal>
    </div>
@endsection
