@extends('admin.layouts.app')

@section('title', isset($offer) ? admin_trans('edit_offer') : admin_trans('add_offer'))
@section('page-title', isset($offer) ? admin_trans('edit_offer') : admin_trans('add_offer'))

@section('content')

<div class="space-y-6" x-data="offerForm()">
    
    <!-- Header with Back Button -->
    <div class="flex items-center gap-4">
        <x-button variant="outline" icon="arrow-left" href="{{ route('admin.offers.index') }}">
            {{ admin_trans('back_to_offers') }}
        </x-button>
        <div>
            <h1 class="text-2xl font-bold text-primary">
                {{ isset($offer) ? admin_trans('edit_offer') : admin_trans('add_offer') }}
            </h1>
            @if(isset($offer))
                <p class="text-sm text-tertiary">
                    {{ admin_trans('offer_id') }}: #{{ $offer->id }}
                </p>
            @endif
        </div>
    </div>

    @if(!$currentCountry)
        <x-alert variant="warning" icon="globe">
            <div>
                <h4 class="font-semibold">{{ admin_trans('no_country_selected') }}</h4>
                <p class="mt-1">{{ admin_trans('select_country_to_manage_offers') }}</p>
            </div>
        </x-alert>
    @else
        <!-- Current Context -->
        <x-alert variant="info" icon="info">
            <div class="flex items-center gap-3">
                <span class="text-2xl mb-3">{{ $currentCountry->flag_emoji }}</span>
                <div>
                    <h4 class="font-semibold">
                        {{ isset($offer) ? admin_trans('editing_offer_for') : admin_trans('creating_offer_for') }}
                    </h4>
                    <p class="text-sm opacity-75">{{ $currentCountry->getName() }}</p>
                </div>
            </div>
        </x-alert>

        <!-- Main Form -->
        <form method="POST" action="{{ isset($offer) ? route('admin.offers.update', $offer) : route('admin.offers.store') }}" enctype="multipart/form-data" class="space-y-6">
            @csrf
            @if(isset($offer)) @method('PUT') @endif

          
            <!-- Basic Information -->
            <x-card title="{{ admin_trans('basic_information') }}" icon="info">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    
                    <!-- Store Selection -->
                    <div class="md:col-span-2">
                        @php
                            $storesArray = $availableStores->map(function($countryStore) {
                                $translation = $countryStore->store->translations->first();
                                return [
                                    'id' => $countryStore->id,
                                    'name' => $translation->name ?? 'Store #' . $countryStore->store_id
                                ];
                            })->toArray();
                            $selectedStore = isset($offer) ? $offer->country_store_id : old('country_store_id');
                        @endphp
                        <x-searchable-select
                            name="country_store_id"
                            :label="admin_trans('store')"
                            :placeholder="admin_trans('search_stores')"
                            :options="$storesArray"
                            :selected="$selectedStore"
                            :required="true"
                            valueKey="id"
                            labelKey="name"
                        />
                    </div>

                    <!-- Brand Selection (Optional) -->
                    <div class="md:col-span-2">
                        @php
                            $brandsArray = $brands->map(function($brand) {
                                $translation = $brand->translations->first();
                                return [
                                    'id' => $brand->id,
                                    'name' => $translation->name ?? 'Brand #' . $brand->id
                                ];
                            })->toArray();
                            $selectedBrand = isset($offer) ? $offer->brand_id : old('brand_id');
                        @endphp
                        <x-searchable-select
                            name="brand_id"
                            :label="admin_trans('brand')"
                            :placeholder="admin_trans('search_brands')"
                            :options="$brandsArray"
                            :selected="$selectedBrand"
                            valueKey="id"
                            labelKey="name"
                        />
                    </div>

                    <!-- Offer Type -->
                    <x-select :label="admin_trans('offer_type')" name="type" :required="true" @change="handleTypeChange($event)">
                        <option value="">{{ admin_trans('select_type') }}</option>
                        <option value="code" {{ (isset($offer) && $offer->type === 'code') || old('type') === 'code' ? 'selected' : '' }}>
                            {{ admin_trans('coupon_code') }}
                        </option>
                        <option value="deal" {{ (isset($offer) && $offer->type === 'deal') || old('type') === 'deal' ? 'selected' : '' }}>
                            {{ admin_trans('deal') }}
                        </option>
                    </x-select>

                    <!-- Coupon Code (shown only for code type) -->
                    <div x-show="offerType === 'code'" x-cloak>
                        <x-input 
                            :label="admin_trans('coupon_code')" 
                            name="code" 
                            placeholder="{{ admin_trans('enter_coupon_code') }}"
                            value="{{ isset($offer) ? $offer->code : old('code') }}"
                        />
                    </div>

                    <!-- Status -->
                    <x-select :label="admin_trans('status')" name="status" :required="true">
                        <option value="">{{ admin_trans('select_status') }}</option>
                        <option value="draft" {{ (isset($offer) && $offer->status === 'draft') || old('status') === 'draft' ? 'selected' : '' }}>
                            {{ admin_trans('draft') }}
                        </option>
                        <option value="active" {{ (isset($offer) && $offer->status === 'active') || old('status') === 'active' || (!isset($offer) && !old('status')) ? 'selected' : '' }}>
                            {{ admin_trans('active') }}
                        </option>
                    </x-select>

                    <!-- Currency -->
                    <x-select :label="admin_trans('currency')" name="currency">
                        <option value="">{{ admin_trans('select_currency') }}</option>
                        <option value="USD" {{ (isset($offer) && $offer->currency === 'USD') || old('currency') === 'USD' || (!isset($offer) && !old('currency')) ? 'selected' : '' }}>USD</option>
                        <option value="EUR" {{ (isset($offer) && $offer->currency === 'EUR') || old('currency') === 'EUR' ? 'selected' : '' }}>EUR</option>
                        <option value="SAR" {{ (isset($offer) && $offer->currency === 'SAR') || old('currency') === 'SAR' ? 'selected' : '' }}>SAR</option>
                        <option value="AED" {{ (isset($offer) && $offer->currency === 'AED') || old('currency') === 'AED' ? 'selected' : '' }}>AED</option>
                        <option value="EGP" {{ (isset($offer) && $offer->currency === 'EGP') || old('currency') === 'EGP' ? 'selected' : '' }}>EGP</option>
                    </x-select>

                    <!-- Expiry Date -->
                    <x-input 
                        :label="admin_trans('expiry_date')" 
                        name="expires_at" 
                        type="datetime-local"
                        value="{{ isset($offer) && $offer->expires_at ? $offer->expires_at->format('Y-m-d\TH:i') : old('expires_at') }}"
                        :hint="admin_trans('leave_empty_for_no_expiry')"
                    />
                </div>
            </x-card>

            <!-- Discount Information -->
            <x-card title="{{ admin_trans('discount_information') }}" icon="percent">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    
                    <!-- Promotion Type -->
                    <div class="md:col-span-2">
                        <x-select :label="admin_trans('promotion_type')" name="promotion_type" :required="true" @change="handlePromotionTypeChange($event)">
                            <option value="">{{ admin_trans('select_promotion_type') }}</option>
                            <option value="monetary" {{ (isset($offer) && $offer->promotion_type === 'monetary') || old('promotion_type') === 'monetary' ? 'selected' : '' }}>
                                {{ admin_trans('fixed_amount') }}
                            </option>
                            <option value="percent" {{ (isset($offer) && $offer->promotion_type === 'percent') || old('promotion_type') === 'percent' ? 'selected' : '' }}>
                                {{ admin_trans('percentage') }}
                            </option>
                            <option value="upto_monetary" {{ (isset($offer) && $offer->promotion_type === 'upto_monetary') || old('promotion_type') === 'upto_monetary' ? 'selected' : '' }}>
                                {{ admin_trans('up_to_amount') }}
                            </option>
                            <option value="upto_percent" {{ (isset($offer) && $offer->promotion_type === 'upto_percent') || old('promotion_type') === 'upto_percent' ? 'selected' : '' }}>
                                {{ admin_trans('up_to_percentage') }}
                            </option>
                            <option value="custom_label" {{ (isset($offer) && $offer->promotion_type === 'custom_label') || old('promotion_type') === 'custom_label' ? 'selected' : '' }}>
                                {{ admin_trans('custom_label') }}
                            </option>
                        </x-select>
                    </div>

                    <!-- Promotion Value -->
                    <x-input 
                        :label="admin_trans('promotion_value')" 
                        name="promotion_value" 
                        type="number" 
                        step="0.01" 
                        min="0"
                        value="{{ isset($offer) ? $offer->promotion_value : old('promotion_value') }}"
                        placeholder="{{ admin_trans('enter_promotion_value') }}"
                    />

                    <!-- Discount Percentage -->
                    <x-input 
                        :label="admin_trans('discount_percentage')" 
                        name="discount_value" 
                        type="number" 
                        step="0.01" 
                        min="0" 
                        max="100"
                        value="{{ isset($offer) ? $offer->discount_value : old('discount_value') }}"
                        placeholder="{{ admin_trans('enter_discount_percentage') }}"
                        :hint="admin_trans('used_for_sorting_display')"
                    />

                    <!-- Regular Price -->
                    <x-input 
                        :label="admin_trans('regular_price')" 
                        name="regular_price" 
                        type="number" 
                        step="0.01" 
                        min="0"
                        value="{{ isset($offer) ? $offer->regular_price : old('regular_price') }}"
                        placeholder="{{ admin_trans('original_price') }}"
                    />

                    <!-- Sale Price -->
                    <x-input 
                        :label="admin_trans('sale_price')" 
                        name="sale_price" 
                        type="number" 
                        step="0.01" 
                        min="0"
                        value="{{ isset($offer) ? $offer->sale_price : old('sale_price') }}"
                        placeholder="{{ admin_trans('discounted_price') }}"
                    />
                </div>
            </x-card>

        
<!-- Multi-language Content -->
@if($availableLocales->count() > 0)
    <x-card title="{{ admin_trans('offer_content') }}" icon="globe">
        <x-tabs defaultTab="{{ $availableLocales->first()->id }}">
            <div class="flex flex-wrap gap-2 border-b mb-6" style="border-color: var(--color-border);">
                @foreach($availableLocales as $locale)
                    <button type="button" 
                        @click="activeTab = '{{ $locale->id }}'; 
                                window.saveAllEditors && window.saveAllEditors(); 
                                $nextTick(() => { 
                                    setTimeout(() => { 
                                        if(window.SecureTinyMCE) {
                                            window.SecureTinyMCE.init(); 
                                            // إعادة تطبيق الثيم بعد تغيير التاب
                                            setTimeout(() => {
                                                if(window.SecureTinyMCE.updateAllThemes) {
                                                    window.SecureTinyMCE.updateAllThemes();
                                                }
                                            }, 500);
                                        }
                                    }, 300); 
                                });"
                        :class="activeTab === '{{ $locale->id }}' ? 'text-primary bg-primary-light' : 'text-tertiary hover:text-primary'"
                        class="flex items-center gap-2 px-4 py-2 border-b transition-colors font-medium">
                        <i data-lucide="globe" class="w-4 h-4"></i>
                        {{ $locale->language->name ?? $locale->name }}
                        @if($locale->direction === 'rtl')
                            <span class="text-xs">(ع)</span>
                        @endif
                    </button>
                @endforeach
            </div>

            @foreach($availableLocales as $locale)
                @php
                    $translation = isset($offer) ? $offer->translations->where('locale_id', $locale->id)->first() : null;
                @endphp
                <x-tab-content :tab="$locale->id">
                    <div class="space-y-6" 
                         data-direction="{{ $locale->direction }}" 
                         @if($locale->direction === 'rtl') dir="rtl" @endif>
                        
                        {{-- Offer Title --}}
                        <x-input 
                            :label="admin_trans('offer_title')" 
                            name="translations[{{ $locale->id }}][title]" 
                            placeholder="{{ admin_trans('enter_offer_title') }}" 
                            :required="$loop->first"
                            value="{{ $translation ? $translation->title : old('translations.'.$locale->id.'.title') }}"
                        />
                        
                        {{-- FIXED: Offer Description with Enhanced RTL Dark Mode Support --}}
                        <x-tinymce 
                            name="translations[{{ $locale->id }}][description]"
                            :height="300"
                            placeholder="{{ admin_trans('enter_offer_description') }}"
                            :value="$translation ? $translation->description : old('translations.'.$locale->id.'.description')"
                            :required="$loop->first"
                            :locale="$locale->code"
                            :direction="$locale->direction"
                            :language="$locale->direction === 'rtl' ? 'ar' : 'en'"
                        >
                            @if($loop->first)
                            <span style="color: var(--color-text-primary);"> {{ admin_trans('offer_description') }}</span>
                            <span class="text-red-500"></span>
                            @endif
                        </x-tinymce>
                        
                        {{-- Final URL --}}
                        <x-input 
                            :label="admin_trans('final_url')" 
                            name="translations[{{ $locale->id }}][final_url]" 
                            type="url" 
                            placeholder="https://example.com/offer"
                            value="{{ $translation ? $translation->final_url : old('translations.'.$locale->id.'.final_url') }}"
                            :hint="admin_trans('tracking_or_affiliate_url')"
                        />
                    </div>
                </x-tab-content>
            @endforeach
        </x-tabs>
    </x-card>
@endif


  <!-- Categories & Occasions -->
            <x-card title="{{ admin_trans('categories_occasions') }}" icon="tag">
                <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                    
                    <!-- Categories -->
                    @if($categories->count() > 0)
                        <div x-data="{ categorySearch: '' }">
                            <label class="block text-sm font-semibold mb-3 text-primary">{{ admin_trans('categories') }}</label>

                            <!-- Search Input -->
                            <input
                                type="text"
                                x-model="categorySearch"
                                placeholder="{{ admin_trans('search_categories') }}"
                                class="input text-sm w-full mb-3"
                                style="padding-{{ is_rtl() ? 'right' : 'left' }}: 2.5rem;"
                            >
                            <div class="relative mb-3">
                                <svg class="w-4 h-4 text-tertiary absolute {{ is_rtl() ? 'right-3' : 'left-3' }} top-1/2 transform -translate-y-1/2 pointer-events-none"
                                    style="top: -2.25rem;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                                </svg>
                            </div>

                            <div class="grid grid-cols-1 gap-2 p-4 rounded-xl border max-h-64 overflow-y-auto" style="background: var(--color-bg-secondary); border-color: var(--color-border);">
                                @foreach($categories as $category)
                                    @php
                                        $categoryTranslation = $category->translations->first();
                                        $categoryName = $categoryTranslation->name ?? 'Category #' . $category->id;
                                        $isSelected = isset($offer) ? $offer->categories->contains($category->id) : false;
                                    @endphp
                                    <label
                                        class="flex items-center gap-2 p-2 rounded-lg hover:bg-primary-light cursor-pointer"
                                        x-show="categorySearch === '' || '{{ strtolower($categoryName) }}'.includes(categorySearch.toLowerCase())"
                                    >
                                        <input type="checkbox" name="categories[]" value="{{ $category->id }}"
                                            {{ $isSelected || (is_array(old('categories')) && in_array($category->id, old('categories'))) ? 'checked' : '' }}
                                            class="checkbox">
                                        <span class="text-sm text-primary">{{ $categoryName }}</span>
                                    </label>
                                @endforeach
                            </div>
                        </div>
                    @endif

                    <!-- Occasions -->
                    @if($occasions->count() > 0)
                        <div x-data="{ occasionSearch: '' }">
                            <label class="block text-sm font-semibold mb-3 text-primary">{{ admin_trans('occasions') }}</label>

                            <!-- Search Input -->
                            <input
                                type="text"
                                x-model="occasionSearch"
                                placeholder="{{ admin_trans('search_occasions') }}"
                                class="input text-sm w-full mb-3"
                                style="padding-{{ is_rtl() ? 'right' : 'left' }}: 2.5rem;"
                            >
                            <div class="relative mb-3">
                                <svg class="w-4 h-4 text-tertiary absolute {{ is_rtl() ? 'right-3' : 'left-3' }} top-1/2 transform -translate-y-1/2 pointer-events-none"
                                    style="top: -2.25rem;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                                </svg>
                            </div>

                            <div class="grid grid-cols-1 gap-2 p-4 rounded-xl border max-h-64 overflow-y-auto" style="background: var(--color-bg-secondary); border-color: var(--color-border);">
                                @foreach($occasions as $occasion)
                                    @php
                                        $occasionTranslation = $occasion->translations->first();
                                        $occasionName = $occasionTranslation->name ?? 'Occasion #' . $occasion->id;
                                        $isSelected = isset($offer) ? $offer->occasions->contains($occasion->id) : false;
                                    @endphp
                                    <label
                                        class="flex items-center gap-2 p-2 rounded-lg hover:bg-primary-light cursor-pointer"
                                        x-show="occasionSearch === '' || '{{ strtolower($occasionName) }}'.includes(occasionSearch.toLowerCase())"
                                    >
                                        <input type="checkbox" name="occasions[]" value="{{ $occasion->id }}"
                                            {{ $isSelected || (is_array(old('occasions')) && in_array($occasion->id, old('occasions'))) ? 'checked' : '' }}
                                            class="checkbox">
                                        <span class="text-sm text-primary">{{ $occasionName }}</span>
                                    </label>
                                @endforeach
                            </div>
                        </div>
                    @endif
                </div>
            </x-card>
            <!-- Offer Images -->
            <x-card title="{{ admin_trans('offer_images') }}" icon="image">
                <!-- Existing Images (for edit mode) -->
                @if(isset($offer) && $offer->getMedia('images')->count() > 0)
                    <div class="mb-6">
                        <h4 class="text-sm font-semibold mb-3 text-primary">{{ admin_trans('current_images') }}</h4>
                        <div class="grid grid-cols-2 md:grid-cols-4 gap-4">
                            @foreach($offer->getMedia('images') as $media)
                                <div class="relative group">
                                    <img src="{{ $media->getUrl() }}" alt="Offer Image" class="w-full h-24 object-cover rounded-lg border">
                                    <button type="button" 
                                        onclick="removeImage({{ $offer->id }}, 'images', {{ $media->id }})"
                                        class="absolute top-1 right-1 w-6 h-6 bg-red-500 text-white rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                                        <i data-lucide="x" class="w-3 h-3"></i>
                                    </button>
                                </div>
                            @endforeach
                        </div>
                    </div>
                @endif

                <!-- Upload New Images -->
                <x-file-upload :label="admin_trans('upload_offer_images')" name="images" accept="image/*" multiple maxSize="2MB" />
            </x-card>

            <!-- Offer Flags -->
            <x-card title="{{ admin_trans('offer_flags') }}" icon="flag">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <x-toggle 
                        name="is_featured" 
                        :label="admin_trans('featured_offer')" 
                        value="1"
                        :checked="isset($offer) ? $offer->is_featured : old('is_featured')"
                        :description="admin_trans('show_in_featured_section')"
                    />

                    <x-toggle 
                        name="is_exclusive" 
                        :label="admin_trans('exclusive_offer')" 
                        value="1"
                        :checked="isset($offer) ? $offer->is_exclusive : old('is_exclusive')"
                        :description="admin_trans('exclusive_to_our_platform')"
                    />

                    <x-toggle 
                        name="is_free_shipping" 
                        :label="admin_trans('free_shipping')" 
                        value="1"
                        :checked="isset($offer) ? $offer->is_free_shipping : old('is_free_shipping')"
                        :description="admin_trans('includes_free_shipping')"
                    />

                    <x-toggle 
                        name="is_new_customer" 
                        :label="admin_trans('new_customer_only')" 
                        value="1"
                        :checked="isset($offer) ? $offer->is_new_customer : old('is_new_customer')"
                        :description="admin_trans('valid_for_new_customers_only')"
                    />
                </div>
            </x-card>

            <!-- Action Buttons -->
            <div class="flex gap-4 justify-end pt-6 border-t" style="border-color: var(--color-border);">
                <x-button variant="outline" type="button" href="{{ route('admin.offers.index') }}">
                    {{ admin_trans('cancel') }}
                </x-button>
                <x-button variant="primary" type="submit" icon="check">
                    {{ isset($offer) ? admin_trans('update_offer') : admin_trans('create_offer') }}
                </x-button>
            </div>
        </form>
    @endif
</div>

@endsection

@push('scripts')
<script>
function offerForm() {
    return {
        offerType: '{{ isset($offer) ? $offer->type : old('type', '') }}',
        promotionType: '{{ isset($offer) ? $offer->promotion_type : old('promotion_type', '') }}',

        init() {
            // Initialize form state
            this.handleTypeChange({ target: { value: this.offerType } });
            this.handlePromotionTypeChange({ target: { value: this.promotionType } });
        },

        handleTypeChange(event) {
            this.offerType = event.target.value;
            
            // Show/hide coupon code field
            const codeField = document.querySelector('input[name="code"]');
            if (codeField) {
                if (this.offerType === 'code') {
                    codeField.closest('.w-full').style.display = 'block';
                    codeField.setAttribute('required', 'required');
                } else {
                    codeField.closest('.w-full').style.display = 'none';
                    codeField.removeAttribute('required');
                    codeField.value = '';
                }
            }
        },

        handlePromotionTypeChange(event) {
            this.promotionType = event.target.value;
            
            // Update placeholder and hints based on promotion type
            const promotionValueField = document.querySelector('input[name="promotion_value"]');
            if (promotionValueField) {
                switch (this.promotionType) {
                    case 'monetary':
                    case 'upto_monetary':
                        promotionValueField.placeholder = '{{ admin_trans("enter_amount") }}';
                        break;
                    case 'percent':
                    case 'upto_percent':
                        promotionValueField.placeholder = '{{ admin_trans("enter_percentage") }}';
                        break;
                    case 'custom_label':
                        promotionValueField.placeholder = '{{ admin_trans("enter_custom_text") }}';
                        break;
                    default:
                        promotionValueField.placeholder = '{{ admin_trans("enter_promotion_value") }}';
                }
            }
        }
    }
}

async function removeImage(offerId, collection, mediaId) {
    if (!confirm('{{ admin_trans("confirm_remove_image") }}')) return;

    try {
        const response = await fetch(`/admin/offers/${offerId}/media/${collection}/${mediaId}`, {
            method: 'DELETE',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
            }
        });

        const result = await response.json();
        
        if (result.success) {
            // Remove the image element from DOM
            event.target.closest('.relative.group').remove();
            if (window.toast) {
                toast.success('{{ admin_trans("image_removed_successfully") }}');
            }
        } else {
            if (window.toast) {
                toast.error(result.message);
            }
        }
    } catch (error) {
        console.error('Error removing image:', error);
        if (window.toast) {
            toast.error('{{ admin_trans("error_removing_image") }}');
        }
    }
}

document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') {
        lucide.createIcons();
    }
});
</script>


@endpush