@extends('layouts.app')

@section('content')

<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 2rem; margin-top: 15px;">
    <h2 style="color: #d4af37; font-size: 1.5rem; font-weight: bold;">
        {{ app()->getLocale() == 'ar' ? 'تعديل سيارة' : 'Edit Car' }}: {{ $car->title }}
    </h2>
    <a href="{{ route('admin.cars.index') }}" style="background: #666; color: white; padding: 0.5rem 1rem; border-radius: 0.5rem; text-decoration: none; font-size: 0.875rem; font-weight: bold;">
        {{ app()->getLocale() == 'ar' ? 'عودة' : 'Back' }}
    </a>
</div>

<div class="py-12" x-data="carForm()">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <form action="{{ route('admin.cars.update', $car->id) }}" method="POST" enctype="multipart/form-data" class="space-y-8">
                @csrf @method('PUT')
                
                <!-- 1) Core Identity -->
                <div class="bg-[#111] border border-gray-800 rounded-2xl p-8">
                    <h3 class="text-[#d4af37] font-bold mb-6 flex items-center gap-2">
                        <span class="p-2 bg-[#d4af37]/10 rounded-lg">🆔</span>
                        {{ app()->getLocale() == 'ar' ? 'البيانات الأساسية' : 'Core Identity' }}
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'الفرع' : 'Branch' }}</label>
                            <select name="branch_id" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                <option value="">{{ app()->getLocale() == 'ar' ? 'اختر الفرع' : 'Select Branch' }}</option>
                                @foreach($branches as $branch)
                                    <option value="{{ $branch->id }}" {{ old('branch_id', $car->branch_id) == $branch->id ? 'selected' : '' }}>{{ $branch->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'الشركة المصنعة' : 'Brand' }}</label>
                            <select name="brand_id" x-model="brand_id" @change="fetchModels()" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                <option value="">{{ app()->getLocale() == 'ar' ? 'اختر الشركة' : 'Select Brand' }}</option>
                                @foreach($brands as $brand)
                                    <option value="{{ $brand->id }}">{{ $brand->name }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'الموديل' : 'Model' }}</label>
                            <select name="car_model_id" x-model="car_model_id" @change="fetchTrims()" required :disabled="isLoadingModels" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none disabled:opacity-50 transition-opacity">
                                <option value="" x-text="isLoadingModels ? 'جاري التحميل...' : '{{ app()->getLocale() == 'ar' ? 'اختر الموديل' : 'Select Model' }}'"></option>
                                <template x-for="model in models" :key="model.id">
                                    <option :value="model.id" x-text="model.name" :selected="model.id == car_model_id"></option>
                                </template>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'الفئة / التريم' : 'Trim' }}</label>
                            <select name="trim_id" x-model="trim_id" required :disabled="isLoadingTrims" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none disabled:opacity-50 transition-opacity">
                                <option value="" x-text="isLoadingTrims ? 'جاري التحميل...' : '{{ app()->getLocale() == 'ar' ? 'اختر الفئة' : 'Select Trim' }}'"></option>
                                <template x-for="trim in trims" :key="trim.id">
                                    <option :value="trim.id" x-text="trim.name" :selected="trim.id == trim_id"></option>
                                </template>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'سنة الصنع' : 'Year' }}</label>
                            <select name="year" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                @for($y = date('Y') + 1; $y >= 2000; $y--)
                                    <option value="{{ $y }}" {{ old('year', $car->year) == $y ? 'selected' : '' }}>{{ $y }}</option>
                                @endfor
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'نوع الهيكل' : 'Body Type' }}</label>
                            <select name="body_type" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                @php
                                    $body_types = [
                                        'sedan' => ['ar' => 'سيدان', 'en' => 'Sedan'],
                                        'suv' => ['ar' => 'SUV', 'en' => 'SUV'],
                                        'crossover' => ['ar' => 'كروس أوفر', 'en' => 'Crossover'],
                                        'hatchback' => ['ar' => 'هاتشباك', 'en' => 'Hatchback'],
                                        'coupe' => ['ar' => 'كوبيه', 'en' => 'Coupe'],
                                        'pickup' => ['ar' => 'بيك أب', 'en' => 'Pickup'],
                                        'van' => ['ar' => 'فان', 'en' => 'Van'],
                                        'convertible' => ['ar' => 'مكشوفة', 'en' => 'Convertible'],
                                    ];
                                @endphp
                                @foreach($body_types as $value => $labels)
                                    <option value="{{ $value }}" {{ old('body_type', $car->body_type) == $value ? 'selected' : '' }}>
                                        {{ app()->getLocale() == 'ar' ? $labels['ar'] : $labels['en'] }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'رقم اللوحة' : 'Plate Number' }}</label>
                            <input type="text" name="plate_number" value="{{ old('plate_number', $car->plate_number) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'رقم المسلسل (VIN)' : 'Serial Number (VIN)' }}</label>
                            <input type="text" name="vin" value="{{ old('vin', $car->vin) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                    </div>
                    <div class="mt-6">
                        <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'عنوان العرض (يظهر في الموقع)' : 'Display Title' }}</label>
                        <input type="text" name="title" value="{{ old('title', $car->title) }}" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                    </div>
                </div>

                <!-- 2) Technical Data -->
                <div class="bg-[#111] border border-gray-800 rounded-2xl p-8">
                    <h3 class="text-[#d4af37] font-bold mb-6 flex items-center gap-2">
                        <span class="p-2 bg-[#d4af37]/10 rounded-lg">⚙️</span>
                        {{ app()->getLocale() == 'ar' ? 'البيانات الفنية' : 'Technical Data' }}
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'نوع المحرك' : 'Engine Type' }}</label>
                            <select name="fuel_type" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                <option value="petrol" {{ old('fuel_type', $car->fuel_type) == 'petrol' ? 'selected' : '' }}>بنزين</option>
                                <option value="diesel" {{ old('fuel_type', $car->fuel_type) == 'diesel' ? 'selected' : '' }}>ديزل</option>
                                <option value="electric" {{ old('fuel_type', $car->fuel_type) == 'electric' ? 'selected' : '' }}>كهرباء</option>
                                <option value="hybrid" {{ old('fuel_type', $car->fuel_type) == 'hybrid' ? 'selected' : '' }}>هايبرد</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'ناقل الحركة' : 'Transmission' }}</label>
                            <select name="transmission" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                <option value="automatic" {{ old('transmission', $car->transmission) == 'automatic' ? 'selected' : '' }}>أوتوماتيك</option>
                                <option value="manual" {{ old('transmission', $car->transmission) == 'manual' ? 'selected' : '' }}>عادي</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'نظام الدفع' : 'Drive Type' }}</label>
                            <select name="drive_type" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                <option value="FWD" {{ old('drive_type', $car->drive_type) == 'FWD' ? 'selected' : '' }}>أمامي (FWD)</option>
                                <option value="RWD" {{ old('drive_type', $car->drive_type) == 'RWD' ? 'selected' : '' }}>خلفي (RWD)</option>
                                <option value="AWD" {{ old('drive_type', $car->drive_type) == 'AWD' ? 'selected' : '' }}>رباعي (AWD)</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'سعة المحرك' : 'Engine Size' }}</label>
                            <input type="text" name="engine_size" value="{{ old('engine_size', $car->engine_size) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'عدد الأحصنة' : 'Horsepower' }}</label>
                            <input type="number" name="horsepower" value="{{ old('horsepower', $car->horsepower) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'عدد المقاعد' : 'Seats' }}</label>
                            <input type="number" name="seats" value="{{ old('seats', $car->seats) }}" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'عدد الأبواب' : 'Doors' }}</label>
                            <input type="number" name="doors" value="{{ old('doors', $car->doors) }}" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                    </div>
                </div>

                <!-- 3) Usage Data -->
                <div class="bg-[#111] border border-gray-800 rounded-2xl p-8">
                    <h3 class="text-[#d4af37] font-bold mb-6 flex items-center gap-2">
                        <span class="p-2 bg-[#d4af37]/10 rounded-lg">🛣️</span>
                        {{ app()->getLocale() == 'ar' ? 'بيانات الاستخدام' : 'Usage Data' }}
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'عدد الكيلومترات' : 'Mileage' }}</label>
                            <input type="number" name="mileage" value="{{ old('mileage', $car->mileage) }}" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'حالة السيارة' : 'Condition' }}</label>
                            <select name="condition" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                <option value="new" {{ old('condition', $car->condition) == 'new' ? 'selected' : '' }}>جديدة</option>
                                <option value="used" {{ old('condition', $car->condition) == 'used' ? 'selected' : '' }}>مستعملة</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'اللون الخارجي' : 'Exterior Color' }}</label>
                            <input type="text" name="color_ext" value="{{ old('color_ext', $car->color_ext) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'اللون الداخلي' : 'Interior Color' }}</label>
                            <input type="text" name="color_int" value="{{ old('color_int', $car->color_int) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                    </div>
                </div>

                <!-- 4) Commercial Data -->
                <div class="bg-[#111] border border-gray-800 rounded-2xl p-8">
                    <h3 class="text-[#d4af37] font-bold mb-6 flex items-center gap-2">
                        <span class="p-2 bg-[#d4af37]/10 rounded-lg">💰</span>
                        {{ app()->getLocale() == 'ar' ? 'البيانات التجارية' : 'Commercial Data' }}
                    </h3>
                    
                    <div class="mb-8">
                        <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'نوع المعاملة' : 'Transaction Type' }}</label>
                        <select name="type" x-model="type" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                            <option value="sale">بيع فقط</option>
                            <option value="rent">تأجير فقط</option>
                            <option value="both">كلاهما (بيع وتأجير)</option>
                        </select>
                    </div>

                    <!-- Sale Section -->
                    <template x-if="type === 'sale' || type === 'both'">
                        <div class="space-y-6 border-b border-gray-800 pb-8 mb-8">
                            <h4 class="font-bold text-white">{{ app()->getLocale() == 'ar' ? 'بيانات البيع' : 'Sale Details' }}</h4>
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                                <div>
                                    <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'سعر البيع' : 'Sale Price' }}</label>
                                    <input type="number" name="price" value="{{ old('price', $car->price) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                </div>
                                <div class="flex items-end pb-3">
                                    <label class="inline-flex items-center cursor-pointer">
                                        <input type="checkbox" name="is_installment_available" value="1" {{ old('is_installment_available', $car->is_installment_available) ? 'checked' : '' }} class="rounded border-gray-800 bg-black text-[#d4af37] focus:ring-[#d4af37]">
                                        <span class="mr-2 text-sm text-gray-400">متاح تقسيط؟</span>
                                    </label>
                                </div>
                                <div>
                                    <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'الدفعة الأولى' : 'Down Payment' }}</label>
                                    <input type="number" name="first_payment" value="{{ old('first_payment', $car->first_payment) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                </div>
                                <div>
                                    <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'مدة التقسيط (شهر)' : 'Installment Period (Months)' }}</label>
                                    <input type="number" name="installment_months" value="{{ old('installment_months', $car->installment_months) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                </div>
                            </div>
                        </div>
                    </template>

                    <!-- Rent Section -->
                    <template x-if="type === 'rent' || type === 'both'">
                        <div class="space-y-6 border-b border-gray-800 pb-8 mb-8">
                            <h4 class="font-bold text-white">{{ app()->getLocale() == 'ar' ? 'بيانات التأجير' : 'Rent Details' }}</h4>
                            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                                <div>
                                    <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'السعر اليومي' : 'Daily Price' }}</label>
                                    <input type="number" name="daily_price" value="{{ old('daily_price', $car->daily_price) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                </div>
                                <div>
                                    <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'السعر الأسبوعي' : 'Weekly Price' }}</label>
                                    <input type="number" name="weekly_price" value="{{ old('weekly_price', $car->weekly_price) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                </div>
                                <div>
                                    <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'السعر الشهري' : 'Monthly Price' }}</label>
                                    <input type="number" name="monthly_price" value="{{ old('monthly_price', $car->monthly_price) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                </div>
                                <div>
                                    <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'مبلغ التأمين' : 'Insurance Deposit' }}</label>
                                    <input type="number" name="insurance_deposit" value="{{ old('insurance_deposit', $car->insurance_deposit) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                </div>
                                <div>
                                    <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'الحد الأقصى للكيلومترات (يومي)' : 'Max Daily Mileage' }}</label>
                                    <input type="number" name="max_mileage_daily" value="{{ old('max_mileage_daily', $car->max_mileage_daily) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                </div>
                            </div>
                        </div>
                    </template>

                    <div class="bg-black/20 border border-gray-800 rounded-2xl p-6 mb-8">
                        <h3 class="text-[#d4af37] font-bold mb-6 flex items-center gap-2">
                            <span class="p-2 bg-[#d4af37]/10 rounded-lg">🚀</span>
                            {{ app()->getLocale() == 'ar' ? 'عزز تجربتك لهذه السيارة' : 'Enhance Experience for this Car' }}
                        </h3>
                        <p class="text-sm text-gray-400 mb-6">{{ app()->getLocale() == 'ar' ? 'حدد الخدمات الإضافية المتاحة لهذه السيارة، ويمكنك تخصيص السعر لكل خدمة.' : 'Select available add-ons for this car and customize prices.' }}</p>
                        
                        <div class="grid grid-cols-1 gap-4">
                            @foreach($addOns as $addOn)
                                @php
                                    $carAddOn = $car->addOns()->find($addOn->id);
                                    $isSelected = !is_null($carAddOn);
                                    $customPrice = $carAddOn ? $carAddOn->pivot->custom_price : null;
                                    $isSuggested = $carAddOn ? $carAddOn->pivot->is_suggested_bundle : false;
                                @endphp
                                <div class="bg-black border border-gray-800 rounded-xl p-4 flex items-center justify-between hover:border-[#d4af37]/30 transition-all">
                                    <div class="flex items-center gap-4 flex-1">
                                        <input type="checkbox" name="add_ons[]" value="{{ $addOn->id }}" id="addon_{{ $addOn->id }}" 
                                               {{ $isSelected ? 'checked' : '' }}
                                               class="w-5 h-5 rounded border-gray-800 bg-black text-[#d4af37] focus:ring-[#d4af37]">
                                        <div>
                                            <label for="addon_{{ $addOn->id }}" class="text-white font-bold cursor-pointer block">
                                                {{ $addOn->name }} 
                                                @if($addOn->badge)
                                                    <span class="bg-[#d4af37] text-black text-[10px] px-2 py-0.5 rounded-full mr-2">{{ $addOn->badge }}</span>
                                                @endif
                                            </label>
                                            <span class="text-gray-500 text-xs">{{ $addOn->description }}</span>
                                        </div>
                                    </div>
                                    
                                    <div class="flex items-center gap-6">
                                        <div class="text-left">
                                            <label class="block text-[10px] text-gray-500 mb-1">{{ app()->getLocale() == 'ar' ? 'السعر المخصص (اختياري)' : 'Custom Price (Optional)' }}</label>
                                            <div class="flex items-center gap-2">
                                                <input type="number" name="add_on_custom_prices[{{ $addOn->id }}]" step="0.01" 
                                                       value="{{ $customPrice }}"
                                                       placeholder="{{ $addOn->price }}"
                                                       class="w-24 bg-black border border-gray-800 rounded-lg px-2 py-1.5 text-white text-center text-sm focus:border-[#d4af37] outline-none">
                                                <span class="text-gray-600 text-xs">ر.س / {{ $addOn->price_type == 'daily' ? 'يومي' : 'ثابت' }}</span>
                                            </div>
                                        </div>
                                        
                                        @if($addOn->is_bundle)
                                            <div class="flex flex-col items-center gap-1 border-r border-gray-800 pr-6">
                                                <label class="block text-[10px] text-[#d4af37] mb-1">{{ app()->getLocale() == 'ar' ? 'باقة مقترحة' : 'Suggested Bundle' }}</label>
                                                <input type="radio" name="suggested_bundle_id" value="{{ $addOn->id }}" 
                                                       {{ $isSuggested ? 'checked' : '' }}
                                                       class="w-4 h-4 rounded-full border-gray-800 bg-black text-[#d4af37] focus:ring-[#d4af37]">
                                            </div>
                                        @endif
                                    </div>
                                </div>
                            @endforeach
                        </div>
                    </div>

                    <div class="mb-8">
                        <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'الحالة التشغيلية' : 'Operational Status' }}</label>
                        <select name="status" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                            <option value="available" {{ old('status', $car->status) == 'available' ? 'selected' : '' }}>متوفرة</option>
                            <option value="reserved" {{ old('status', $car->status) == 'reserved' ? 'selected' : '' }}>محجوزة</option>
                            <option value="rented" {{ old('status', $car->status) == 'rented' ? 'selected' : '' }}>مؤجرة</option>
                            <option value="sold" {{ old('status', $car->status) == 'sold' ? 'selected' : '' }}>مباعة</option>
                            <option value="maintenance" {{ old('status', $car->status) == 'maintenance' ? 'selected' : '' }}>تحت الصيانة</option>
                        </select>
                    </div>

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                        <div class="md:col-span-2">
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'المميزات (افصل بينها بفاصلة)' : 'Features (Comma separated)' }}</label>
                            <input type="text" name="features" value="{{ old('features', is_array($car->features) ? implode(', ', $car->features) : '') }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none" placeholder="فتحة سقف, كراسي جلد, نظام ملاحة">
                        </div>
                    </div>

                    <div class="mb-8">
                        <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'الوصف التفصيلي' : 'Full Description' }}</label>
                        <textarea name="description" rows="5" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">{{ old('description', $car->description) }}</textarea>
                    </div>

                    <div class="mb-8">
                        <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'الصور الحالية' : 'Current Images' }}</label>
                        <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
                            @foreach($car->images as $image)
                                <div class="relative group h-32 rounded-lg overflow-hidden border border-gray-800">
                                    <img src="{{ str_starts_with($image->path, 'http') ? $image->path : asset('storage/'.$image->path) }}" class="w-full h-full object-cover">
                                    <div class="absolute inset-0 bg-black/60 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
                                        <label class="cursor-pointer text-red-500 hover:text-red-400 flex items-center gap-1">
                                            <input type="checkbox" name="delete_images[]" value="{{ $image->id }}" class="rounded border-gray-800 bg-black text-red-500 focus:ring-red-500">
                                            <span class="text-xs">{{ app()->getLocale() == 'ar' ? 'حذف' : 'Delete' }}</span>
                                        </label>
                                    </div>
                                    @if($image->is_main)
                                        <div class="absolute top-2 left-2 bg-[#d4af37] text-black text-[10px] px-2 py-0.5 rounded font-bold">MAIN</div>
                                    @endif
                                </div>
                            @endforeach
                        </div>
                    </div>

                    <div class="mb-8">
                        <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'تحديث الصورة الرئيسية' : 'Update Main Image' }}</label>
                        <div>
                            <input type="file" name="main_image" accept="image/*" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                            <div id="editMainImagePreview" style="margin-top: 0.5rem; width: 150px; height: 150px; border: 1px solid #333; border-radius: 0.5rem; overflow: hidden; background: #1a1a1a; display: none;">
                                <img id="editMainImageImg" style="width: 100%; height: 100%; object-fit: cover;">
                            </div>
                        </div>
                    </div>

                    <div>
                        <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'إضافة صور إضافية (حد أقصى 4)' : 'Add Additional Images (Max 4)' }}</label>
                        <input type="file" name="additional_images[]" multiple accept="image/*" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        <div id="editAdditionalImagesPreview" style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 1rem; margin-top: 1rem;">
                        </div>
                    </div>

                    <script>
                        document.querySelector('input[name="main_image"]').addEventListener('change', function(e) {
                            const file = e.target.files[0];
                            if (file) {
                                const reader = new FileReader();
                                reader.onload = function(event) {
                                    document.getElementById('editMainImageImg').src = event.target.result;
                                    document.getElementById('editMainImagePreview').style.display = 'block';
                                };
                                reader.readAsDataURL(file);
                            }
                        });

                        document.querySelector('input[name="additional_images[]"]').addEventListener('change', function(e) {
                            const preview = document.getElementById('editAdditionalImagesPreview');
                            preview.innerHTML = '';
                            Array.from(e.target.files).slice(0, 4).forEach((file, index) => {
                                const reader = new FileReader();
                                reader.onload = function(event) {
                                    const div = document.createElement('div');
                                    div.style.cssText = 'width: 100%; padding-top: 100%; position: relative; border: 1px solid #333; border-radius: 0.5rem; overflow: hidden; background: #1a1a1a;';
                                    const img = document.createElement('img');
                                    img.src = event.target.result;
                                    img.style.cssText = 'position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover;';
                                    div.appendChild(img);
                                    preview.appendChild(div);
                                };
                                reader.readAsDataURL(file);
                            });
                        });
                    </script>
                </div>

                <!-- 5) Depreciation Data -->
                <div class="bg-[#111] border border-gray-800 rounded-2xl p-8 mb-8" x-data="{ method: '{{ old('depreciation_method', $car->depreciation_method) }}' }">
                    <h3 class="text-[#d4af37] font-bold mb-6 flex items-center gap-2">
                        <span class="p-2 bg-[#d4af37]/10 rounded-lg">📉</span>
                        {{ app()->getLocale() == 'ar' ? 'بيانات الإهلاك' : 'Depreciation Data' }}
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'سعر الشراء' : 'Purchase Price' }}</label>
                            <input type="number" step="0.01" name="purchase_price" value="{{ old('purchase_price', $car->purchase_price) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'تاريخ الشراء' : 'Purchase Date' }}</label>
                            <input type="date" name="purchase_date" value="{{ old('purchase_date', $car->purchase_date?->format('Y-m-d')) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'العمر الإنتاجي (سنوات)' : 'Useful Life (Years)' }}</label>
                            <input type="number" name="useful_life_years" value="{{ old('useful_life_years', $car->useful_life_years) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'القيمة المتبقية (خردة)' : 'Salvage Value' }}</label>
                            <input type="number" step="0.01" name="salvage_value" value="{{ old('salvage_value', $car->salvage_value) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'طريقة الإهلاك' : 'Depreciation Method' }}</label>
                            <select name="depreciation_method" x-model="method" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                                <option value="straight_line">{{ app()->getLocale() == 'ar' ? 'القسط الثابت' : 'Straight Line' }}</option>
                                <option value="declining_balance">{{ app()->getLocale() == 'ar' ? 'القسط المتناقص' : 'Declining Balance' }}</option>
                                <option value="units_of_production">{{ app()->getLocale() == 'ar' ? 'حسب الكيلومترات' : 'Units of Production' }}</option>
                            </select>
                        </div>
                        <div x-show="method == 'declining_balance'">
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'نسبة الإهلاك السنوي' : 'Annual Rate (%)' }}</label>
                            <input type="number" step="0.01" name="depreciation_rate" value="{{ old('depreciation_rate', $car->depreciation_rate) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none" placeholder="0.20">
                        </div>
                        <div x-show="method == 'units_of_production'">
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'إجمالي الكيلومترات المتوقع' : 'Total Expected KM' }}</label>
                            <input type="number" name="total_expected_mileage" value="{{ old('total_expected_mileage', $car->total_expected_mileage) }}" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                        <div class="flex items-center mt-8">
                            <label class="flex items-center cursor-pointer gap-3">
                                <input type="checkbox" name="is_leased" value="1" {{ old('is_leased', $car->is_leased) ? 'checked' : '' }} class="w-5 h-5 rounded border-gray-800 bg-black text-[#d4af37] focus:ring-[#d4af37]">
                                <span class="text-sm text-gray-400">{{ app()->getLocale() == 'ar' ? 'سيارة مؤجرة (Lease)' : 'Leased Vehicle' }}</span>
                            </label>
                        </div>
                    </div>
                </div>

                <div class="flex flex-row-reverse justify-start gap-4 pb-12">
                    <button type="submit" class="bg-[#d4af37] hover:bg-[#b08d2a] text-black px-20 py-4 rounded-xl font-bold shadow-lg shadow-[#d4af37]/20 transition-all hover:scale-[1.02]" style="padding-left:.75rem; ;padding-right:.75rem;">
                        {{ app()->getLocale() == 'ar' ? 'تحديث البيانات' : 'Update Car' }}
                    </button>
                    <a href="{{ route('admin.cars.index') }}" class="px-8 py-3 rounded-xl border border-gray-800 text-gray-400 hover:bg-white/5 transition-all">
                        {{ app()->getLocale() == 'ar' ? 'إلغاء' : 'Cancel' }}
                    </a>
                </div>
            </form>

            <!-- 5) Registration & Inspection -->
            <div class="mt-8 bg-[#111] border border-gray-800 rounded-2xl p-8" style="margin-top: 1rem;">
                <h3 class="text-[#d4af37] font-bold mb-6 flex items-center gap-2">
                    <span class="p-2 bg-[#d4af37]/10 rounded-lg">📄</span>
                    {{ app()->getLocale() == 'ar' ? 'الاستمارة والفحص الدوري' : 'Registration & Inspection' }}
                </h3>

                @php
                    $doc = $car->document;
                    $status_colors = [
                        'valid' => 'bg-green-500/20 text-green-400',
                        'expiring_soon' => 'bg-yellow-500/20 text-yellow-400',
                        'expired' => 'bg-red-500/20 text-red-400'
                    ];
                    $status_labels = [
                        'valid' => ['ar' => 'ساري', 'en' => 'Valid'],
                        'expiring_soon' => ['ar' => 'سينتهي قريباً', 'en' => 'Expiring Soon'],
                        'expired' => ['ar' => 'منتهي', 'en' => 'Expired']
                    ];
                @endphp

                @if($doc)
                    <div class="mb-8 p-6 bg-black/40 rounded-xl border border-gray-800">
                        <div class="flex items-center justify-between mb-4">
                            <span class="text-xs font-bold uppercase tracking-widest text-gray-500">
                                {{ app()->getLocale() == 'ar' ? 'الوضع الحالي' : 'Current Status' }}
                            </span>
                            <span class="px-3 py-1 rounded-full text-xs font-bold {{ $status_colors[$doc->calculated_status] }}">
                                {{ $status_labels[$doc->calculated_status][app()->getLocale()] }}
                            </span>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                            <div class="flex items-center gap-4">
                                <div class="p-3 bg-gray-800 rounded-lg">📅</div>
                                <div>
                                    <div class="text-xs text-gray-500 uppercase">{{ app()->getLocale() == 'ar' ? 'تاريخ انتهاء الاستمارة' : 'Registration Expiry' }}</div>
                                    <div class="font-bold text-white">{{ $doc->registration_expiry_date->format('Y-m-d') }}</div>
                                </div>
                            </div>
                            <div class="flex items-center gap-4">
                                <div class="p-3 bg-gray-800 rounded-lg">🔍</div>
                                <div>
                                    <div class="text-xs text-gray-500 uppercase">{{ app()->getLocale() == 'ar' ? 'تاريخ انتهاء الفحص' : 'Inspection Expiry' }}</div>
                                    <div class="font-bold text-white">{{ $doc->inspection_expiry_date->format('Y-m-d') }}</div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mt-6 flex gap-4">
                            @if($doc->registration_document)
                                <a href="{{ asset('storage/' . $doc->registration_document) }}" target="_blank" class="text-xs text-blue-400 hover:underline">
                                    {{ app()->getLocale() == 'ar' ? 'عرض الاستمارة' : 'View Registration Doc' }}
                                </a>
                            @endif
                            @if($doc->inspection_document)
                                <a href="{{ asset('storage/' . $doc->inspection_document) }}" target="_blank" class="text-xs text-blue-400 hover:underline">
                                    {{ app()->getLocale() == 'ar' ? 'عرض الفحص' : 'View Inspection Doc' }}
                                </a>
                            @endif
                        </div>
                    </div>
                @endif

                <form action="{{ $doc ? route('admin.vehicle-documents.update', $doc->id) : route('admin.vehicle-documents.store') }}" method="POST" enctype="multipart/form-data">
                    @csrf
                    @if($doc) @method('PUT') @endif
                    <input type="hidden" name="car_id" value="{{ $car->id }}">

                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'تاريخ انتهاء الاستمارة' : 'Registration Expiry Date' }}</label>
                            <input type="date" name="registration_expiry_date" value="{{ old('registration_expiry_date', $doc?->registration_expiry_date?->format('Y-m-d')) }}" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'صورة الاستمارة' : 'Registration Document' }}</label>
                            <input type="file" name="registration_document" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2 text-white focus:border-[#d4af37] outline-none text-sm">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'تاريخ آخر فحص دوري' : 'Last Inspection Date' }}</label>
                            <input type="date" name="inspection_date" value="{{ old('inspection_date', $doc?->inspection_date?->format('Y-m-d')) }}" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'تاريخ انتهاء الفحص' : 'Inspection Expiry Date' }}</label>
                            <input type="date" name="inspection_expiry_date" value="{{ old('inspection_expiry_date', $doc?->inspection_expiry_date?->format('Y-m-d')) }}" required class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none">
                        </div>
                        <div>
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'صورة الفحص الدوري' : 'Inspection Document' }}</label>
                            <input type="file" name="inspection_document" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2 text-white focus:border-[#d4af37] outline-none text-sm">
                        </div>
                        <div class="md:col-span-2">
                            <label class="block text-sm text-gray-400 mb-2">{{ app()->getLocale() == 'ar' ? 'ملاحظات' : 'Notes' }}</label>
                            <textarea name="notes" rows="2" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none text-sm">{{ old('notes', $doc?->notes) }}</textarea>
                        </div>
                    </div>

                    <div class="mt-8 flex justify-end">
                        <button type="submit" class="bg-[#d4af37] text-black px-12 py-3 rounded-xl font-bold hover:bg-[#b08d2a] transition-all" style="padding-left:.75rem; ;padding-right:.75rem;">
                            {{ app()->getLocale() == 'ar' ? 'حفظ بيانات الوثائق' : 'Save Document Data' }}
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        function carForm() {
            return {
                brand_id: '{{ $car->brand_id }}',
                car_model_id: '{{ $car->car_model_id }}',
                trim_id: '{{ $car->trim_id }}',
                type: '{{ $car->type }}',
                models: [],
                trims: [],
                isLoadingModels: false,
                isLoadingTrims: false,
                async init() {
                    if (this.brand_id) {
                        await this.fetchModels(false);
                        if (this.car_model_id) {
                            await this.fetchTrims(false);
                        }
                    }
                },
                async fetchModels(reset = true) {
                    if (reset) {
                        this.car_model_id = '';
                        this.trim_id = '';
                        this.trims = [];
                        this.models = [];
                    }
                    if (!this.brand_id) return;
                    
                    this.isLoadingModels = true;
                    try {
                        const response = await fetch(`{{ route('admin.api.models') }}?brand_id=${this.brand_id}`);
                        this.models = await response.json();
                    } catch (error) {
                        console.error('Error fetching models:', error);
                    } finally {
                        this.isLoadingModels = false;
                    }
                },
                async fetchTrims(reset = true) {
                    if (reset) {
                        this.trim_id = '';
                        this.trims = [];
                    }
                    if (!this.car_model_id) return;

                    this.isLoadingTrims = true;
                    try {
                        const response = await fetch(`{{ route('admin.api.trims') }}?model_id=${this.car_model_id}`);
                        this.trims = await response.json();
                    } catch (error) {
                        console.error('Error fetching trims:', error);
                    } finally {
                        this.isLoadingTrims = false;
                    }
                }
            }
        }
    </script>

@endsection
