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

@section('title', __('daylight::general.edit_page', ['page' => $page->translations->first()?->name]))

@section('content')
    <div x-data="{ showConfirmDeleteModal: false }">
        <x-daylight::page-header :title="__('daylight::general.edit_page', ['page' => $page->translations->first()?->name])">
            @can('delete:pages')
                <x-daylight::buttons.danger @click.prevent="showConfirmDeleteModal = true">
                    {{ __('daylight::content.delete_page') }}
                </x-daylight::buttons.danger>
            @endif
        </x-daylight::page-header>

        <x-daylight::session-messages/>

        <form
            method="post"
            action="{{ route('daylight.content.pages.update', $page) }}"
            x-data="{ name: '{{ old('name', $page->translations->first()?->name) }}' }"
            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::locale-selector :route="route('daylight.content.pages.edit', $page)"/>

            <x-daylight::input.group
                :label="__('daylight::general.name')"
                :error="$errors->first('name')"
                for="name"
            >
                <x-daylight::input.text name="name" id="name" value="{{ old('name', $page->name) }}" x-model="name"/>
            </x-daylight::input.group>

            <x-daylight::input.group
                :label="__('daylight::general.slug')"
                :error="$errors->first('slug')"
                :helpText="__('daylight::content.fields.help_slug_unique')"
                for="slug"
            >
                <x-daylight::input.text name="slug" id="slug" value="{{ old('slug', $page->slug) }}" x-slug="name" readonly/>
            </x-daylight::input.group>

            @if($templates->isNotEmpty())
                <x-daylight::input.group
                        :label="__('daylight::content.fields.template')"
                        :error="$errors->first('template')"
                        for="template"
                >
                    <x-daylight::input.select name="template" id="template">
                        @foreach($templates as $template)
                            <option value="{{ $template->getKey() }}" {{ old('template', $page->template) === $template->getKey() ? 'selected' : '' }}>
                                {{ $template->getLabel() }}
                            </option>
                        @endforeach
                    </x-daylight::input.select>
                </x-daylight::input.group>
            @endif

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

            <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 JSON as base (has full data), then merge with old() to preserve any form values
                        if (!empty($componentsFromJson)) {
                            $componentsData = $componentsFromJson;

                            // Merge old() data into JSON data to preserve any form field values
                            if (!empty($oldComponents) && is_array($oldComponents)) {
                                foreach ($oldComponents as $index => $oldComponent) {
                                    if (isset($componentsData[$index]) && is_array($oldComponent)) {
                                        // Deep merge: preserve JSON structure but update with form values
                                        if (isset($oldComponent['data']) && isset($componentsData[$index]['data'])) {
                                            // For each field in old data, update the JSON data
                                            foreach ($oldComponent['data'] as $fieldName => $fieldValue) {
                                                // Only update if the field value is not empty or if it's explicitly set
                                                // This preserves media/related fields from JSON while updating text fields from form
                                                if (isset($componentsData[$index]['data'][$fieldName])) {
                                                    // For media and related fields, keep JSON version (has full data)
                                                    // For other fields, use form value
                                                    $fieldType = null;
                                                    if (isset($componentsData[$index]['type'])) {
                                                        $registry = app(\Daylight\Core\Modules\PageBuilder\Registries\ComponentRegistry::class);
                                                        $definition = $registry->getDefinition($componentsData[$index]['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'])) {
                                                        $componentsData[$index]['data'][$fieldName] = $fieldValue;
                                                    }
                                                } else {
                                                    $componentsData[$index]['data'][$fieldName] = $fieldValue;
                                                }
                                            }
                                        }
                                    } elseif (!isset($componentsData[$index])) {
                                        // Component exists in old() but not in JSON, add it
                                        $componentsData[$index] = $oldComponent;
                                    }
                                }
                            }
                        } elseif (!empty($oldComponents)) {
                            // No JSON data, use old() data
                            $componentsData = $oldComponents;
                        } 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>

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

                <x-daylight::buttons.primary type="submit">
                    {{ __('daylight::general.save') }}
                </x-daylight::buttons.primary>
            </div>
        </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.page')]) }}</h3>
                <div class="mt-2">
                    <p class="text-sm text-gray-500">
                        {{ __('daylight::general.delete_confirm', ['object' => __('daylight::store.daylight::store.page')]) }}
                    </p>
                </div>
            </x-slot>

            <x-slot name="footer">
                <form method="post" action="{{ route('daylight.content.pages.destroy', $page) }}">
                    @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
