<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 leading-tight">
            افزودن محصول جدید
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 bg-white border-b border-gray-200">

                    @if ($errors->any())
                        <div class="mb-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
                            <strong class="font-bold">خطا!</strong>
                            <span class="block sm:inline">برخی فیلدها نیاز به بررسی دارند.</span>
                            <ul class="mt-3 list-disc list-inside text-sm">
                                @foreach ($errors->all() as $error)
                                    <li>{{ $error }}</li>
                                @endforeach
                            </ul>
                        </div>
                    @endif

                    <form action="{{ route('admin.products.store') }}" method="POST" enctype="multipart/form-data" class="grid grid-cols-2 gap-6">
                        @csrf

                        <div class="col-span-1">
                            <x-input-label for="name" value="نام محصول" />
                            <x-text-input id="name" class="block mt-1 w-full" type="text" name="name" :value="old('name')" required autofocus />
                        </div>

                        <div class="col-span-1">
                            <x-input-label for="code" value="کد محصول" />
                            <x-text-input id="code" class="block mt-1 w-full" type="text" name="code" :value="old('code')" required />
                        </div>

                        <div class="col-span-1">
                            <x-input-label for="category_id" value="دسته‌بندی" />
                            <select name="category_id" id="category_id" class="block mt-1 w-full border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 rounded-md shadow-sm">
                                <option value="">انتخاب دسته‌بندی (اختیاری)</option>
                                @foreach($categories as $category)
                                    <option value="{{ $category->id }}" {{ old('category_id') == $category->id ? 'selected' : '' }}>
                                        {{ $category->name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        
                        <div class="col-span-1">
                            <x-input-label for="price" value="قیمت (ریال)" />
                            <x-text-input id="price" class="block mt-1 w-full" type="number" name="price" :value="old('price')" required />
                        </div>

                        <div class="col-span-1">
                            <x-input-label for="discount_price" value="قیمت با تخفیف (ریال) - اختیاری" />
                            <x-text-input id="discount_price" class="block mt-1 w-full" type="number" name="discount_price" :value="old('discount_price')" />
                        </div>
                        
                        <div class="col-span-1">
                            <x-input-label for="stock" value="موجودی" />
                            <x-text-input id="stock" class="block mt-1 w-full" type="number" name="stock" :value="old('stock', 0)" required />
                        </div>

                        <div class="col-span-1">
                            <x-input-label for="status" value="وضعیت" />
                            <select name="status" id="status" class="block mt-1 w-full border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 rounded-md shadow-sm">
                                <option value="active" {{ old('status') == 'active' ? 'selected' : '' }}>فعال</option>
                                <option value="inactive" {{ old('status') == 'inactive' ? 'selected' : '' }}>غیرفعال</option>
                            </select>
                        </div>

                        <div class="col-span-1">
                            <x-input-label for="image" value="تصویر محصول" />
                            <input id="image" class="block mt-1 w-full file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-indigo-50 file:text-indigo-700 hover:file:bg-indigo-100" type="file" name="image" />
                        </div>
                        
                        <div class="col-span-2 mt-6 pt-6 border-t border-gray-200">
                             <x-input-label value="تخصیص به گزینه‌های طرح" class="mb-2 text-lg font-medium" />
                             <div class="grid grid-cols-3 gap-4 max-h-60 overflow-y-auto p-4 border rounded-md">
                                @foreach($planOptions as $option)
                                <div class="flex items-center">
                                    <input type="checkbox" id="plan_option_{{ $option->id }}" name="plan_options[]" value="{{ $option->id }}"
                                           class="rounded border-gray-300 text-indigo-600 shadow-sm focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
                                           {{ (is_array(old('plan_options')) && in_array($option->id, old('plan_options'))) ? 'checked' : '' }}
                                    >
                                    <label for="plan_option_{{ $option->id }}" class="mr-2 text-sm text-gray-700">
                                        {{ $option->plan->name }} ({{ $option->months }} ماهه)
                                    </label>
                                </div>
                                @endforeach
                             </div>
                        </div>

                        {{-- --------------------------------------------------------------------------------- --}}
                        {{-- ✅✅✅ بخش ویژگی‌های محصول (کد نهایی و اصلاح شده) ✅✅✅ --}}
                        {{-- --------------------------------------------------------------------------------- --}}
                        <div class="col-span-2 mt-6 pt-6 border-t border-gray-200">
                            <h3 class="text-lg font-medium text-gray-900">ویژگی‌های محصول</h3>
                            <p class="mt-1 text-sm text-gray-600">حداکثر 10 ویژگی </p>
                        </div>

                        <div
                            class="col-span-2"
                            {{-- 
                                1. x-data با تک کوتیشن باز شده است.
                                2. htmlspecialchars حذف شد.
                                3. از {!! json_encode(...) !!} برای رندر صحیح آرایه جاوا اسکریپت استفاده شده است.
                            --}}
                            x-data='{
                                features: {!! json_encode(old('features', [])) !!},
                                newKey: "",
                                newValue: "",
                                addFeature() {
                                    if (this.newKey.trim() === "" || this.newValue.trim() === "") return;
                                    if (this.features.length >= 10) {
                                        alert("حداکثر ۱۰ ویژگی مجاز است.");
                                        return;
                                    }
                                    this.features.push({ key: this.newKey, value: this.newValue });
                                    this.newKey = "";
                                    this.newValue = "";
                                },
                                removeFeature(index) {
                                    this.features.splice(index, 1);
                                }
                            }'
                        >
                            {{-- این input های hidden مقادیر را برای ارسال به کنترلر آماده می‌کنند --}}
                            <template x-for="(feature, index) in features" :key="index">
                                <div>
                                    <input type="hidden" :name="`features[${index}][key]`" :value="feature.key">
                                    <input type="hidden" :name="`features[${index}][value]`" :value="feature.value">
                                </div>
                            </template>

                            {{-- لیست ویژگی‌های اضافه شده --}}
                            <ul class="mb-4 space-y-2">
                                <template x-for="(feature, index) in features" :key="index">
                                    <li class="flex items-center justify-between p-2 bg-gray-100 rounded-md">
                                        <div>
                                            <strong class="text-gray-800" x-text="feature.key"></strong>:
                                            <span class="text-gray-700" x-text="feature.value"></span>
                                        </div>
                                        <button type="button" @click="removeFeature(index)" class="text-red-500 hover:text-red-700 p-1">
                                            (حذف)
                                        </button>
                                    </li>
                                </template>
                            </ul>

                            {{-- فرم افزودن ویژگی جدید --}}
                            <template x-if="features.length < 10">
                                <div class="flex space-x-2 space-x-reverse">
                                    <div class="flex-1">
                                        <x-input-label for="newKey" value="نام ویژگی" />
                                        <x-text-input x-model="newKey" id="newKey" class="block w-full mt-1" type="text" />
                                    </div>
                                    <div class="flex-1">
                                        <x-input-label for="newValue" value="مقدار ویژگی" />
                                        <x-text-input x-model="newValue" id="newValue" class="block w-full mt-1" type="text" />
                                    </div>
                                    <div class="self-end">
                                        <x-primary-button type="button" @click="addFeature()">
                                            افزودن
                                        </x-primary-button>
                                    </div>
                                </div>
                            </template>
                        </div>
                        {{-- --------------------------------------------------------------------------------- --}}
                        {{-- ✅✅✅ END: بخش "ویژگی‌های محصول" ✅✅✅ --}}
                        {{-- --------------------------------------------------------------------------------- --}}


                        <div class="col-span-2 flex items-center justify-end mt-6 pt-6 border-t border-gray-200">
                            <x-primary-button>
                                ذخیره محصول
                            </x-primary-button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</x-app-layout>