{{--
    Вьюха: Список автомобилей с фильтрами и пагинацией
    Создана: 2026-05-06
    Контроллер: Admin\CarController::index()
    Переменные: $cars (LengthAwarePaginator), $makes, $platforms — для фильтров
--}}
@extends('admin.layout')

@section('title', 'Автомобили')

@section('content_header')
    <div class="d-flex justify-content-between align-items-center">
        <h1 class="m-0">Автомобили</h1>
        <a href="{{ route('admin.cars.create') }}" class="btn btn-primary btn-sm">
            <i class="fas fa-plus"></i> Добавить
        </a>
    </div>
@stop

@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('admin.dashboard') }}">Главная</a></li>
    <li class="breadcrumb-item active">Автомобили</li>
@stop

@section('content')
    @if(session('success'))
        <div class="alert alert-success alert-dismissible">
            <button type="button" class="close" data-dismiss="alert">&times;</button>
            {{ session('success') }}
        </div>
    @endif

    @php
        // Базовые параметры фильтра (без platform и page) — для построения URL кнопок площадок
        $baseParams = array_filter(
            request()->only(['q', 'status', 'condition', 'make']),
            fn($v) => $v !== null && $v !== ''
        );
        $activePlatform = request('platform', '');
    @endphp

    {{-- Быстрый фильтр по площадкам — кнопки из справочника --}}
    @if($platforms->isNotEmpty())
    <div class="mb-3 d-flex flex-wrap align-items-center" style="gap:6px">
        <span class="text-muted small mr-1"><i class="fas fa-map-marker-alt"></i> Площадка:</span>
        <a href="{{ route('admin.cars.index', $baseParams) }}"
           class="btn btn-sm {{ $activePlatform === '' ? 'btn-primary' : 'btn-outline-secondary' }}">
            Все
        </a>
        @foreach($platforms as $platform)
            <a href="{{ route('admin.cars.index', array_merge($baseParams, ['platform' => $platform])) }}"
               class="btn btn-sm {{ $activePlatform === $platform ? 'btn-primary' : 'btn-outline-secondary' }}">
                {{ $platform }}
            </a>
        @endforeach
        @if($activePlatform !== '')
            <a href="{{ route('admin.cars.index', $baseParams) }}" class="btn btn-sm btn-link text-danger p-0 ml-1">
                <i class="fas fa-times"></i> сбросить
            </a>
        @endif
    </div>
    @endif

    {{-- Фильтры (поиск + остальные поля) --}}
    <div class="card card-outline card-secondary mb-3">
        <div class="card-header">
            <h3 class="card-title"><i class="fas fa-filter mr-1"></i> Фильтры</h3>
            <div class="card-tools">
                <button type="button" class="btn btn-tool" data-card-widget="collapse">
                    <i class="fas fa-minus"></i>
                </button>
            </div>
        </div>
        <div class="card-body">
            <form method="GET" action="{{ route('admin.cars.index') }}">
                @if($activePlatform)
                    <input type="hidden" name="platform" value="{{ $activePlatform }}">
                @endif
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group mb-2">
                            <input type="text" name="q" class="form-control form-control-sm"
                                   placeholder="Марка, модель, VIN, заголовок..." value="{{ request('q') }}">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group mb-2">
                            <select name="status" class="form-control form-control-sm">
                                <option value="">Статус</option>
                                <option value="active" @selected(request('status') === 'active')>Активен</option>
                                <option value="sold"   @selected(request('status') === 'sold')>Продан</option>
                                <option value="draft"  @selected(request('status') === 'draft')>Черновик</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group mb-2">
                            <select name="condition" class="form-control form-control-sm">
                                <option value="">Состояние</option>
                                <option value="new"  @selected(request('condition') === 'new')>Новый</option>
                                <option value="used" @selected(request('condition') === 'used')>Б/У</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group mb-2">
                            <select name="make" class="form-control form-control-sm">
                                <option value="">Марка</option>
                                @foreach($makes as $make)
                                    <option value="{{ $make }}" @selected(request('make') === $make)>{{ $make }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary btn-sm">
                                <i class="fas fa-search"></i> Найти
                            </button>
                            <a href="{{ route('admin.cars.index') }}" class="btn btn-default btn-sm ml-1">
                                <i class="fas fa-times"></i>
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    {{-- Таблица --}}
    <div class="card">
        <div class="card-body p-0">
            <table class="table table-hover table-sm mb-0">
                <thead>
                    <tr>
                        <th style="width:50px">ID</th>
                        <th style="width:60px">Фото</th>
                        <th>Марка / Модель</th>
                        <th>Год</th>
                        <th>Площадка</th>
                        <th>Статус</th>
                        <th>Состояние</th>
                        <th>Цена (₽)</th>
                        <th>Пробег</th>
                        <th style="width:100px">Действия</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($cars as $car)
                        <tr>
                            <td>{{ $car->id }}</td>
                            <td>
                                @if($car->photo_main)
                                    <img src="{{ Storage::url($car->photo_main) }}"
                                         class="img-thumbnail" style="width:48px;height:36px;object-fit:cover;">
                                @else
                                    <div class="bg-light text-center" style="width:48px;height:36px;line-height:36px;font-size:10px;color:#aaa">
                                        <i class="fas fa-car"></i>
                                    </div>
                                @endif
                            </td>
                            <td>
                                <a href="{{ route('admin.cars.edit', $car) }}">
                                    {{ $car->make }} {{ $car->model }}
                                </a>
                                @if($car->generation)
                                    <small class="text-muted">{{ $car->generation }}</small>
                                @endif
                            </td>
                            <td>{{ $car->year }}</td>
                            <td>
                                @if($car->platform)
                                    <span class="badge badge-light border">{{ $car->platform }}</span>
                                @else
                                    <span class="text-muted">—</span>
                                @endif
                            </td>
                            <td>
                                @php
                                    $badge = match($car->status) {
                                        'active' => 'success',
                                        'sold'   => 'secondary',
                                        'draft'  => 'warning',
                                        default  => 'light',
                                    };
                                @endphp
                                <span class="badge badge-{{ $badge }}">{{ $car->status_label }}</span>
                            </td>
                            <td>{{ $car->condition_label }}</td>
                            <td>{{ $car->price_rub ? number_format($car->price_rub, 0, '.', ' ') : '—' }}</td>
                            <td>{{ $car->mileage_km ? number_format($car->mileage_km, 0, '.', ' ') . ' км' : '—' }}</td>
                            <td>
                                <a href="{{ route('admin.cars.edit', $car) }}"
                                   class="btn btn-xs btn-info" title="Редактировать">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <form action="{{ route('admin.cars.destroy', $car) }}" method="POST"
                                      class="d-inline"
                                      onsubmit="return confirm('Удалить автомобиль?')">
                                    @csrf @method('DELETE')
                                    <button class="btn btn-xs btn-danger" title="Удалить">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="10" class="text-center text-muted py-4">
                                Автомобили не найдены.
                                <a href="{{ route('admin.cars.create') }}">Добавить первый</a>
                            </td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        @if($cars->hasPages())
            <div class="card-footer">
                {{ $cars->links() }}
            </div>
        @endif
    </div>
@stop

@section('plugins.Select2', true)
