@extends('layouts.app')

@section('content')

<div class="py-12" x-data="searchForm()">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <!-- Add Car Button -->
            @can('create_vehicles')
            <div class="mb-6 flex justify-end">
                <a href="{{ route('admin.cars.create') }}" class="px-6 py-3 rounded-lg bg-[#d4af37] text-black text-sm font-bold hover:bg-[#b08d2a] transition-colors flex items-center gap-2">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
                    {{ app()->getLocale() == 'ar' ? '+ إضافة سيارة' : '+ Add Car' }}
                </a>
            </div>
            @endcan

            <!-- Advanced Search Form -->
            <div class="bg-[#111] border border-gray-800 rounded-2xl p-6 mb-8">
                <form action="{{ route('admin.cars.index') }}" method="GET">
                    <div class="grid grid-cols-1 md:grid-cols-4 gap-6">
                        <!-- Basic Search -->
                        <div class="md:col-span-2">
                            <label class="block text-xs text-gray-500 mb-2 uppercase tracking-wider">{{ app()->getLocale() == 'ar' ? 'بحث عام (العنوان، الوصف، رقم الهيكل)' : 'General Search (Title, Desc, VIN)' }}</label>
                            <div class="relative">
                                <span class="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-500">🔍</span>
                                <input type="text" name="search" value="{{ request('search') }}" class="w-full bg-black border-gray-800 rounded-lg pr-10 pl-4 py-2.5 text-white focus:border-[#d4af37] outline-none text-sm" placeholder="{{ app()->getLocale() == 'ar' ? 'بحث...' : 'Search...' }}">
                            </div>
                        </div>

                        <!-- Brand -->
                        <div>
                            <label class="block text-xs text-gray-500 mb-2 uppercase tracking-wider">{{ app()->getLocale() == 'ar' ? 'الماركة' : 'Brand' }}</label>
                            <select name="brand_id" x-model="brand_id" @change="fetchModels()" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none text-sm">
                                <option value="">{{ app()->getLocale() == 'ar' ? 'الكل' : 'All Brands' }}</option>
                                @foreach($brands as $brand)
                                    <option value="{{ $brand->id }}">{{ $brand->name }}</option>
                                @endforeach
                            </select>
                        </div>

                        <!-- Status -->
                        <div>
                            <label class="block text-xs text-gray-500 mb-2 uppercase tracking-wider">{{ app()->getLocale() == 'ar' ? 'الحالة' : 'Status' }}</label>
                            <select name="status" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none text-sm">
                                <option value="all">{{ app()->getLocale() == 'ar' ? 'الكل' : 'All Status' }}</option>
                                <option value="available" {{ request('status') == 'available' ? 'selected' : '' }}>{{ app()->getLocale() == 'ar' ? 'متوفرة' : 'Available' }}</option>
                                <option value="reserved" {{ request('status') == 'reserved' ? 'selected' : '' }}>{{ app()->getLocale() == 'ar' ? 'محجوزة' : 'Reserved' }}</option>
                                <option value="rented" {{ request('status') == 'rented' ? 'selected' : '' }}>{{ app()->getLocale() == 'ar' ? 'مؤجرة' : 'Rented' }}</option>
                                <option value="sold" {{ request('status') == 'sold' ? 'selected' : '' }}>{{ app()->getLocale() == 'ar' ? 'مباعة' : 'Sold' }}</option>
                                <option value="maintenance" {{ request('status') == 'maintenance' ? 'selected' : '' }}>{{ app()->getLocale() == 'ar' ? 'صيانة' : 'Maintenance' }}</option>
                            </select>
                        </div>
                    </div>

                    <!-- Collapsible Advanced Filters -->
                    <div x-show="showAdvanced" x-transition class="grid grid-cols-1 md:grid-cols-4 gap-6 mt-6 pt-6 border-t border-gray-800">
                        <!-- Model -->
                        <div>
                            <label class="block text-xs text-gray-500 mb-2 uppercase tracking-wider">{{ app()->getLocale() == 'ar' ? 'الموديل' : 'Model' }}</label>
                            <select name="car_model_id" x-model="car_model_id" :disabled="isLoadingModels" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none text-sm disabled:opacity-50">
                                <option value="">{{ app()->getLocale() == 'ar' ? 'اختر الماركة أولاً' : 'Select Brand First' }}</option>
                                <template x-for="model in models" :key="model.id">
                                    <option :value="model.id" x-text="model.name" :selected="model.id == {{ request('car_model_id', 0) }}"></option>
                                </template>
                            </select>
                        </div>

                        <!-- Year -->
                        <div>
                            <label class="block text-xs text-gray-500 mb-2 uppercase tracking-wider">{{ app()->getLocale() == 'ar' ? 'سنة الصنع' : 'Year' }}</label>
                            <select name="year" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none text-sm">
                                <option value="">{{ app()->getLocale() == 'ar' ? 'الكل' : 'All Years' }}</option>
                                @for($y = date('Y') + 1; $y >= 2000; $y--)
                                    <option value="{{ $y }}" {{ request('year') == $y ? 'selected' : '' }}>{{ $y }}</option>
                                @endfor
                            </select>
                        </div>

                        <!-- Type -->
                        <div>
                            <label class="block text-xs text-gray-500 mb-2 uppercase tracking-wider">{{ app()->getLocale() == 'ar' ? 'نوع المعاملة' : 'Type' }}</label>
                            <select name="type" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none text-sm">
                                <option value="all">{{ app()->getLocale() == 'ar' ? 'الكل' : 'All Types' }}</option>
                                <option value="sale" {{ request('type') == 'sale' ? 'selected' : '' }}>{{ app()->getLocale() == 'ar' ? 'بيع' : 'Sale' }}</option>
                                <option value="rent" {{ request('type') == 'rent' ? 'selected' : '' }}>{{ app()->getLocale() == 'ar' ? 'تأجير' : 'Rent' }}</option>
                                <option value="both" {{ request('type') == 'both' ? 'selected' : '' }}>{{ app()->getLocale() == 'ar' ? 'كلاهما' : 'Both' }}</option>
                            </select>
                        </div>

                        <!-- Condition -->
                        <div>
                            <label class="block text-xs text-gray-500 mb-2 uppercase tracking-wider">{{ app()->getLocale() == 'ar' ? 'الحالة' : 'Condition' }}</label>
                            <select name="condition" class="w-full bg-black border-gray-800 rounded-lg px-4 py-2.5 text-white focus:border-[#d4af37] outline-none text-sm">
                                <option value="all">{{ app()->getLocale() == 'ar' ? 'الكل' : 'All' }}</option>
                                <option value="new" {{ request('condition') == 'new' ? 'selected' : '' }}>{{ app()->getLocale() == 'ar' ? 'جديدة' : 'New' }}</option>
                                <option value="used" {{ request('condition') == 'used' ? 'selected' : '' }}>{{ app()->getLocale() == 'ar' ? 'مستعملة' : 'Used' }}</option>
                            </select>
                        </div>
                    </div>

                    <div class="flex items-center justify-between mt-8">
                        <button type="button" @click="showAdvanced = !showAdvanced" class="text-xs text-[#d4af37] hover:underline flex items-center gap-1">
                            <span x-text="showAdvanced ? '{{ app()->getLocale() == 'ar' ? 'إخفاء خيارات البحث المتقدم' : 'Hide Advanced Filters' }}' : '{{ app()->getLocale() == 'ar' ? 'إظهار خيارات البحث المتقدم' : 'Show Advanced Filters' }}'"></span>
                            <svg class="w-3 h-3 transition-transform" :class="showAdvanced ? 'rotate-180' : ''" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path></svg>
                        </button>

                        <div class="flex gap-4">
                            <a href="{{ route('admin.cars.index') }}" class="px-6 py-2 rounded-lg bg-gray-800 text-white text-sm hover:bg-gray-700 transition-colors">
                                {{ app()->getLocale() == 'ar' ? 'إعادة تعيين' : 'Reset' }}
                            </a>
                            <button type="submit" class="px-8 py-2 rounded-lg bg-[#d4af37] text-black text-sm font-bold hover:bg-[#b08d2a] transition-colors">
                                {{ app()->getLocale() == 'ar' ? 'بحث' : 'Search' }}
                            </button>
                        </div>
                    </div>
                </form>
            </div>

            <div class="bg-[#111] border border-gray-800 rounded-2xl overflow-hidden">
                <table class="w-full {{ app()->getLocale() == 'ar' ? 'text-right' : 'text-left' }}">
                    <thead class="bg-black/50 text-gray-500 text-xs uppercase">
                        <tr>
                            <th class="px-6 py-4">{{ app()->getLocale() == 'ar' ? 'السيارة' : 'Car' }}</th>
                            <th class="px-6 py-4">{{ app()->getLocale() == 'ar' ? 'النوع' : 'Type' }}</th>
                            <th class="px-6 py-4">{{ app()->getLocale() == 'ar' ? 'السعر' : 'Price' }}</th>
                            <th class="px-6 py-4">{{ app()->getLocale() == 'ar' ? 'الحالة' : 'Status' }}</th>
                            <th class="px-6 py-4">{{ app()->getLocale() == 'ar' ? 'سنة الصنع' : 'Year' }}</th>
                            <th class="px-6 py-4">{{ app()->getLocale() == 'ar' ? 'العمليات' : 'Actions' }}</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-800">
                        @foreach($cars as $car)
                        <tr class="hover:bg-white/5 transition-colors">
                            <td class="px-6 py-4 flex items-center">
                                @php
                                    $displayImage = $car->mainImage ?? $car->images->first();
                                    $imagePath = $displayImage ? $displayImage->path : null;
                                    // Local placeholder if image fails or doesn't exist
                                    $imageUrl = $imagePath ? (str_starts_with($imagePath, 'http') ? $imagePath : asset('storage/'.$imagePath)) : asset('images/login-bg.png');
                                @endphp
                                <div class="w-12 h-12 rounded bg-gray-800 overflow-hidden {{ app()->getLocale() == 'ar' ? 'ml-4' : 'mr-4' }} border border-gray-700">
                                    <img src="{{ $imageUrl }}" class="w-full h-full object-cover" onerror="this.src='{{ asset('images/login-bg.png') }}'">
                                </div>
                                <div class="font-bold text-sm text-white">{{ $car->title }}</div>
                            </td>
                            <td class="px-6 py-4 text-xs">{{ $car->type }}</td>
                            <td class="px-6 py-4 text-sm text-[#d4af37]">{{ number_format($car->price ?? $car->daily_price) }} {{ app()->getLocale() == 'ar' ? 'ر.س' : 'SAR' }}</td>
                            <td class="px-6 py-4">
                                @php $dynamicStatus = $car->dynamic_status; @endphp
                                <span class="text-[10px] px-2 py-0.5 rounded-full 
                                    {{ $dynamicStatus['color'] == 'green' ? 'bg-green-500/20 text-green-400' : 'bg-red-500/20 text-red-400' }}">
                                    {{ $dynamicStatus['label'] }}
                                </span>
                            </td>
                            <td class="px-6 py-4 text-sm">{{ $car->year }}</td>
                            <td class="px-6 py-4 space-x-2 space-x-reverse">
                                <a href="{{ route('admin.cars.show', $car->id) }}" class="text-[#d4af37] hover:text-[#e8c547] text-xs font-bold">{{ app()->getLocale() == 'ar' ? '👁️ عرض' : '👁️ View' }}</a>
                                @can('edit_vehicles')
                                <a href="{{ route('admin.cars.edit', $car->id) }}" class="text-blue-400 hover:text-blue-300 text-xs">{{ app()->getLocale() == 'ar' ? 'تعديل' : 'Edit' }}</a>
                                @endcan
                                @can('delete_vehicles')
                                <form action="{{ route('admin.cars.destroy', $car->id) }}" method="POST" class="inline">
                                    @csrf @method('DELETE')
                                    <button type="submit" class="text-red-400 hover:text-red-300 text-xs" onclick="return confirm('{{ app()->getLocale() == 'ar' ? 'هل أنت متأكد؟' : 'Are you sure?' }}')">{{ app()->getLocale() == 'ar' ? 'حذف' : 'Delete' }}</button>
                                </form>
                                @endcan
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
                <div class="p-4 border-t border-gray-800">
                    {{ $cars->links() }}
                </div>
            </div>
        </div>
    </div>
    @push('scripts')
    <script>
        function searchForm() {
            return {
                brand_id: '{{ request('brand_id') }}',
                car_model_id: '{{ request('car_model_id') }}',
                models: [],
                isLoadingModels: false,
                showAdvanced: {{ request('car_model_id') || request('year') || request('condition') ? 'true' : 'false' }},

                init() {
                    if (this.brand_id) {
                        this.fetchModels();
                    }
                },

                fetchModels() {
                    if (!this.brand_id) {
                        this.models = [];
                        this.car_model_id = '';
                        return;
                    }
                    this.isLoadingModels = true;
                    fetch(`{{ route('admin.api.models') }}?brand_id=${this.brand_id}`)
                        .then(res => res.json())
                        .then(data => {
                            this.models = data;
                            this.isLoadingModels = false;
                        });
                }
            }
        }
    </script>
    @endpush
@endsection
