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

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

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

        <x-daylight::session-messages/>

        <form method="post" action="{{ route('daylight.store.products.update', $product) }}">
            @csrf
            @method('PUT')

            <input type="hidden" name="locale" value="{{ request()->get('locale', app()->getLocale()) }}">

            <div x-data="{ activeTab: 'general', type: '{{ old('type', $product->type) }}' }" class="w-full">
                <div class="flex border-b">
                    <button @click.prevent="activeTab = 'general'" :class="{ 'bg-gray-100 text-sky-600': activeTab === 'general', 'text-gray-600': activeTab !== 'tab1' }" class="px-4 py-2 focus:outline-none font-semibold text-sm cursor-pointer rounded border-1 mb-4 border-blue-500">{{ __('daylight::settings.general') }}</button>
                    <button @click.prevent="activeTab = 'variants'" x-show="type !== 'simple'"  :class="{ 'bg-gray-100 text-sky-600': activeTab === 'variants', 'text-gray-600': activeTab !== 'tab2' }" class="px-4 py-2 focus:outline-none font-semibold text-sm cursor-pointer rounded border-1 mb-4 border-blue-500">{{ __('daylight::store.variants') }}</button>
                    <button @click.prevent="activeTab = 'content'" :class="{ 'bg-gray-100 text-sky-600': activeTab === 'content', 'text-gray-600': activeTab !== 'tab2' }" class="px-4 py-2 focus:outline-none font-semibold text-sm cursor-pointer rounded border-1 mb-4 border-blue-500">{{ __('Content') }}</button>
                </div>

                <div x-show="activeTab === 'general'">
                    <h2 class="mt-6">{{ __('daylight::settings.general') }}</h2>

                    <x-daylight::input.group
                        :label="__('Type *')"
                        :error="$errors->first('type')"
                        for="type"
                    >
                        <x-daylight::input.select name="type" id="type" x-model="type" @change="document.querySelector('#sku') && (document.querySelector('#sku').value = null)">
                            <option value="simple">{{ __('Simple') }}</option>
                            <option value="variable">{{ __('Variable') }}</option>
                        </x-daylight::input.select>
                    </x-daylight::input.group>

                    <div x-cloak x-show="type === 'simple'">
                        <x-daylight::input.group
                            :label="__('SKU *')"
                            :error="$errors->first('sku')"
                            for="sku"
                        >
                            <livewire:daylight::sku-input
                                :sku="old('sku', $product->variants->first()?->sku)"
                            />
                        </x-daylight::input.group>
                    </div>

                    <x-daylight::input.group
                        :label="__('Brand *')"
                        :error="$errors->first('brand')"
                        for="brand_id"
                    >
                        <x-daylight::input.select name="brand_id" id="brand_id" searchable :value="old('brand_id', $product->brand_id)">
                            @foreach($brands as $brand)
                                <option value="{{ $brand->id }}">{{ $brand->name }}</option>
                            @endforeach
                        </x-daylight::input.select>
                    </x-daylight::input.group>

                    <x-daylight::input.group :label="__('daylight::store.labels')" :error="$errors->first('labels')" for="labels">
                        @foreach($labels as $label)
                            <div class="flex gap-2">
                                <div class="flex h-6 shrink-0 items-center">
                                    <div class="group grid size-4 grid-cols-1">
                                        <input {{ in_array($label->id, old('labels', $product->labels->pluck('id')->toArray())) ? 'checked' : '' }} id="labels-{{ $label->id }}" type="checkbox" value="{{ $label->id }}" name="labels[]" class="col-start-1 row-start-1 appearance-none rounded border border-gray-300 bg-white checked:border-sky-600 checked:bg-sky-600 indeterminate:border-sky-600 indeterminate:bg-sky-600 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600 disabled:border-gray-300 disabled:bg-gray-100 disabled:checked:bg-gray-100 forced-colors:appearance-auto"/>

                                        <svg viewBox="0 0 14 14" fill="none" class="pointer-events-none col-start-1 row-start-1 size-3.5 self-center justify-self-center stroke-white group-has-[:disabled]:stroke-gray-950/25 dark:group-has-[:disabled]:stroke-white/25">
                                            <path d="M3 8L6 11L11 3.5" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="opacity-0 group-has-[:checked]:opacity-100"/>
                                            <path d="M3 7H11" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="opacity-0 group-has-[:indeterminate]:opacity-100"/>
                                        </svg>
                                    </div>
                                </div>
                                <div class="text-sm/6">
                                    <label for="labels-{{ $label->id }}" class="font-medium text-gray-900 dark:text-white">
                                        {{ $label->translations->first()->name ?? __('daylight::general.not_translated') }}
                                    </label>
                                </div>
                            </div>
                        @endforeach
                    </x-daylight::input.group>

                    <h2 class="mt-12 mb-4">{{ __('Category & attributes') }}</h2>

                    <livewire:daylight::attribute-selector
                        :categories="$categories"
                        :activeCategories="old('categories', $product->categories->pluck('id'))"
                        :availableAttributes="$attributes"
                        :activeAttributes="old('attributes', $product->attributeValues->groupBy('attribute_id')->map(fn ($v) => $v->pluck('id')))"
                    />

                    <h2 class="mt-12 mb-4">{{ __('Downloads') }}</h2>

                    <x-daylight::input.group
                        :label="__('Downloads')"
                        :error="$errors->first('downloads')"
                        for="media"
                    >
                        <div wire:ignore>
                            <div data-vue-app>
                                <media-selector
                                        name="downloads"
                                        display-type="list"
                                        :single-file="false"
                                        :initial-media='@json(old("downloads", $product->downloads) ? json_decode(old('downloads', $product->downloads)) : [])'
                                />
                            </div>
                        </div>
                    </x-daylight::input.group>

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

                    <x-daylight::input.group
                        :label="__('Status *')"
                        :error="$errors->first('status')"
                        for="status"
                    >
                        <x-daylight::input.select name="status" id="status" :value="old('status', $product->status)">
                            @foreach($statuses as $key => $value)
                                <option value="{{ $key }}">{{ $value }}</option>
                            @endforeach
                        </x-daylight::input.select>
                    </x-daylight::input.group>
                </div>

                <div x-show="activeTab === 'variants'" x-cloak>
                    @error('options')
                        <div class="mt-2 text-xs text-red-500">{{ $errors->first('options') }}</div>
                    @enderror
                    @error('variants')
                        <div class="mt-2 text-xs text-red-500">{{ $errors->first('variants') }}</div>
                    @enderror

                    <div wire:ignore>
                        <div data-vue-app>
                            <variation-builder
                                    :options='@json($options)'
                                    :variants='@json($variants)'
                                    :errors='@json(session()->get('errors', new \Illuminate\Support\ViewErrorBag())->getBag('default')->messages())'
                                    :locales='@json(\Daylight\Core\Modules\Multilingualism\Multilingualism::getAvailableLocales())'
                                    :selected-variants='@json($selectedVariants ?? [])'
                            />
                        </div>
                    </div>
                </div>

                <div x-show="activeTab === 'content'" x-cloak>
                    <h2 class="mt-6 mb-8">{{ __('Content') }}</h2>

                    <div x-data="{ currentLocale: '{{ app()->getLocale() }}' }">
                        <div class="sm:hidden mb-6 bg-gray-100 -mx-4 p-4">
                            <select x-model="currentLocale" id="tabs" name="tabs" class="block w-full rounded-md border-gray-300 focus:border-indigo-500 focus:ring-indigo-500">
                                @foreach(\Daylight\Core\Modules\Multilingualism\Multilingualism::getAvailableLocales() as $locale)
                                    <option
                                        {{ request()->get('locale', app()->getLocale()) === $locale ? 'selected' : '' }} value="{{ $locale }}">
                                        {{ strtoupper($locale) }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        <div class="hidden sm:flex items-center">
                            <p class="text-sm text-gray-600">{{ __('Locale *') }}:</p>
                            <nav class="ml-4 flex space-x-4" aria-label="Tabs">
                                @foreach(\Daylight\Core\Modules\Multilingualism\Multilingualism::getAvailableLocales() as $locale)
                                    <button
                                        @click.prevent="currentLocale = '{{ $locale }}'"
                                        :class="{
                                            'text-sky-700 bg-sky-100': currentLocale === '{{ $locale }}',
                                            'text-gray-500 hover:text-gray-700': currentLocale !== '{{ $locale }}'
                                        }"
                                        class="rounded-md  px-3 py-2 text-sm font-medium hover:text-gray-700 flex items-center"
                                    >
                                        <img src="{{ daylightAsset('resources/assets/images/flags/'.$locale.'.svg') }}"
                                            alt="{{ $locale }}" class="h-5 w-5 rounded-full ring-2 ring-white mr-2"
                                        >
                                        {{ strtoupper($locale) }}
                                    </button>
                                @endforeach
                            </nav>
                        </div>

                        @foreach(\Daylight\Core\Modules\Multilingualism\Multilingualism::getAvailableLocales() as $locale)
                            <div
                                x-show="currentLocale === '{{ $locale }}'" {{ $loop->first ? 'x-cloak' : '' }}
                                x-data="{
                                    name: '{{ old('translations.'.$locale.'.name', $product->translations->firstWhere('locale', $locale)?->name) }}',
                                    slug: '{{ old('translations.'.$locale.'.slug', $product->translations->firstWhere('locale', $locale)?->slug) }}'
                                }">
                                <x-daylight::input.group
                                    :label="__('Name *')"
                                    :error="$errors->first('translations.'.$locale.'.name')"
                                    for="{{ $locale }}_name"
                                >
                                    <x-daylight::input.text
                                        :name="'translations[' . $locale . '][name]'"
                                        id="{{ $locale }}_name"
                                        value="{{ old('translation.'.$locale.'.name', $product->translations->firstWhere('locale', $locale)?->name) }}"
                                        x-model="name"
                                    />
                                </x-daylight::input.group>

                                <x-daylight::input.group
                                    :label="__('Slug *')"
                                    :error="$errors->first('translations.'.$locale.'.slug')"
                                    for="{{ $locale }}_slug"
                                >
                                    <x-daylight::input.text
                                        :name="'translations[' . $locale . '][slug]'"
                                        id="{{ $locale }}_slug"
                                        value="{{ old('translations.'.$locale.'.slug', $product->translations->firstWhere('locale', $locale)?->slug) }}"
                                        readonly
                                        x-slug="name"
                                    />
                                </x-daylight::input.group>

                                <x-daylight::input.group
                                    :label="__('Description')"
                                    :error="$errors->first('translations.'.$locale.'.description')"
                                    for="{{ $locale }}_description"
                                >
                                    <x-daylight::input.wysiwyg
                                        name="translations[{{ $locale }}][description]"
                                        :value="old('translations.'.$locale . '.description', $product->translations->firstWhere('locale', $locale)?->description)"
                                        placeholder="{{ __('Write something...') }}"
                                    />
                                </x-daylight::input.group>

                                <x-daylight::input.group
                                    :label="__('Pros')"
                                    for="{{ $locale }}_pros"
                                >
                                    <div x-data='{ pros: @json(array_filter(old('translations.'.$locale.'.pros', $product->translations->firstWhere('locale', $locale)?->pros ?? []))) }'>
                                        <template x-for="(pro, index) in pros" :key="index">
                                            <div class="flex items-center mb-2">
                                                <input name="translations[{{ $locale }}][pros][]" x-model="pros[index]" type="text" class="block w-full rounded-md border border-gray-300 py-1.5 text-gray-900 shadow-sm placeholder:text-gray-400 sm:max-w-lg sm:text-sm sm:leading-6">

                                                <button @click.prevent="pros.splice(index, 1)" class="ml-2 p-2 bg-red-500 hover:bg-red-700 transition rounded-full">
                                                    <svg class="text-white w-4 h-4" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                                        <path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"></path>
                                                    </svg>
                                                </button>
                                            </div>
                                        </template>

                                        <x-daylight::buttons.primary @click.prevent="pros.push('')">
                                            {{ __('Add new') }}
                                        </x-daylight::buttons.primary>
                                    </div>

                                </x-daylight::input.group>

                                <x-daylight::input.group
                                    :label="__('Cons')"
                                    :error="$errors->first('translations.'.$locale.'.cons')"
                                    for="{{ $locale }}_cons"
                                >
                                    <div x-data='{ cons: @json(array_filter(old('translations.'.$locale.'.cons', $product->translations->firstWhere('locale', $locale)?->cons ?? []))) }'>
                                        <template x-for="(con, index) in cons" :key="index">
                                            <div class="flex items-center mb-2">
                                                <input name="translations[{{ $locale }}][cons][]" x-model="cons[index]" type="text" class="block w-full rounded-md border border-gray-300 py-1.5 text-gray-900 shadow-sm placeholder:text-gray-400 sm:max-w-lg sm:text-sm sm:leading-6">

                                                <button @click.prevent="cons.splice(index, 1)" class="ml-2 p-2 bg-red-500 hover:bg-red-700 transition rounded-full">
                                                    <svg class="text-white w-4 h-4" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                                        <path stroke-linecap="round" stroke-linejoin="round" d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0"></path>
                                                    </svg>
                                                </button>
                                            </div>
                                        </template>

                                        <x-daylight::buttons.primary @click.prevent="cons.push('')">
                                            {{ __('Add new') }}
                                        </x-daylight::buttons.primary>
                                    </div>

                                </x-daylight::input.group>

                                <div>
                                    <h2 class="mt-12">SEO</h2>

                                    <x-daylight::input.group
                                        :label="__('Robots *')"
                                        :error="$errors->first('translations.'.$locale.'.robots')"
                                        for="{{ $locale }}_robots"
                                    >
                                        <x-daylight::input.select name="translations[{{ $locale }}][robots]" id="{{ $locale }}_robots">
                                            <option value="index, follow" {{ old('translations.'.$locale.'.robots', $product->translations->firstWhere('locale', $locale)?->robots) === 'index, follow' ? 'selected' : '' }}>
                                                Default (index, follow)
                                            </option>
                                            <option value="nofollow" {{ old('translations.'.$locale.'.robots', $product->translations->firstWhere('locale', $locale)?->robots) === 'nofollow' ? 'selected' : '' }}>
                                                nofollow
                                            </option>
                                            <option value="noindex" {{ old('translations.'.$locale.'.robots', $product->translations->firstWhere('locale', $locale)?->robots) === 'noindex' ? 'selected' : '' }}>
                                                noindex
                                            </option>
                                            <option value="noindex, nofollow" {{ old('translations.'.$locale.'.robots', $product->translations->firstWhere('locale', $locale)?->robots) === 'noindex, nofollow' ? 'selected' : '' }}>
                                                noindex, nofollow
                                            </option>
                                        </x-daylight::input.select>
                                    </x-daylight::input.group>

                                    <x-daylight::input.group
                                        :label="__('Title')"
                                        :error="$errors->first('translations.'.$locale.'.meta_title')"
                                        for="{{ $locale }}_meta_title"
                                    >
                                        <x-daylight::input.text name="translations[{{ $locale }}][meta_title]" id="{{ $locale }}_meta_title" value="{{ old('translations.'.$locale.'.meta_title', $product->translations->firstWhere('locale', $locale)?->meta_title) }}"/>
                                    </x-daylight::input.group>

                                    <x-daylight::input.group
                                        :label="__('Description')"
                                        :error="$errors->first('translations.'.$locale.'.meta_description')"
                                        for="{{ $locale }}_meta_description"
                                    >
                                        <x-daylight::input.textarea name="translations[{{ $locale }}][meta_description]" id="{{ $locale }}_meta_description">
                                            {{ old('translations.'.$locale.'.meta_description', $product->translations->firstWhere('locale', $locale)?->meta_description) }}
                                        </x-daylight::input.textarea>
                                    </x-daylight::input.group>
                                </div>
                            </div>
                        @endforeach
                    </div>
                </div>
            </div>

            @can('update:products')
                <div class="mt-6 flex items-center justify-end gap-x-3">
                    <x-daylight::buttons.secondary href="{{ route('daylight.store.products.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>

        <script>
            document.addEventListener('variant-selected', function (event) {
                let nameInput = document.querySelector('#en_name')
                let originalDescription = document.querySelector('#original-description')

                if (nameInput && nameInput.value === '') {
                    nameInput.value = event.detail[0].variant.title;

                    nameInput.dispatchEvent(new Event('input'));
                }

                if(event.detail[0].variant.description) {
                    console.log(event.detail[0])

                    originalDescription.querySelector('p').innerHTML = event.detail[0].variant.description;
                    originalDescription.classList.remove('hidden');
                } else {
                    originalDescription.classList.add('hidden');
                }
            });
        </script>

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

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