<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Car;
use App\Traits\TemplateTrait;

class CarController extends Controller
{
    use TemplateTrait;

    /**
     * Browse all available cars (public, paginated)
     */
    public function index(Request $request)
    {
        $query = Car::available()->with(['photos' => fn($q) => $q->orderBy('sort_order')]);

        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('make', 'like', "%{$search}%")
                  ->orWhere('model', 'like', "%{$search}%");
            });
        }

        if ($request->filled('make')) {
            $query->where('make', $request->make);
        }

        if ($request->filled('min_price')) {
            $query->where('price', '>=', $request->min_price);
        }

        if ($request->filled('max_price')) {
            $query->where('price', '<=', $request->max_price);
        }

        $cars = $query->orderBy('featured', 'desc')->orderBy('created_at', 'desc')->paginate(12);

        $makes = Car::available()->select('make')->distinct()->pluck('make');

        return view('user.cars.index', compact('cars', 'makes'))
            ->with('title', 'Available Inventory');
    }

    /**
     * Show full car detail page
     */
    public function show(Car $car)
    {
        $car->load(['photos' => fn($q) => $q->orderBy('sort_order')]);

        $relatedCars = Car::available()
            ->where('id', '!=', $car->id)
            ->where('make', $car->make)
            ->with(['photos' => fn($q) => $q->orderBy('sort_order')])
            ->take(4)
            ->get();

        return view('user.cars.show', compact('car', 'relatedCars'))
            ->with('title', $car->name);
    }
}
