<?php

namespace App\Http\Controllers\Public;

use App\Http\Controllers\Controller;
use App\Models\Vehicle;
use Illuminate\Http\Request;

class VehicleController extends Controller
{
    public function index(Request $request)
    {
        $query = Vehicle::with(['images', 'pricing', 'branch'])->where('status', '!=', 'SOLD'); // Show Available and Reserved

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

        if ($request->filled('model')) {
            $query->where('model', 'like', '%'.$request->model.'%');
        }

        if ($request->filled('type') && $request->type != 'all') {
            $query->where('category', $request->type);
        }

        if ($request->filled('fuel_type') && $request->fuel_type != 'all') {
            $query->where('fuel_type', $request->fuel_type);
        }

        if ($request->filled('transmission') && $request->transmission != 'all') {
            $query->where('transmission', $request->transmission);
        }

        // Sorting
        switch ($request->sort_by) {
            case 'price-asc':
                $query->orderBy('price', 'asc');
                break;
            case 'price-desc':
                $query->orderBy('price', 'desc');
                break;
            case 'year-desc':
                $query->orderBy('year', 'desc');
                break;
            case 'year-asc':
                $query->orderBy('year', 'asc');
                break;
            case 'featured':
            default:
                $query->orderBy('featured', 'desc')->latest();
                break;
        }

        $vehicles = $query->paginate(12)->withQueryString();

        return view('public.vehicles.index', compact('vehicles'));
    }

    public function show($id)
    {
        $vehicle = Vehicle::with(['images', 'specifications', 'branch'])->findOrFail($id);
        $relatedVehicles = Vehicle::where('category', $vehicle->category)
            ->where('id', '!=', $vehicle->id)
            ->with(['images', 'pricing'])
            ->take(4)
            ->get();

        return view('public.vehicles.show', compact('vehicle', 'relatedVehicles'));
    }
}
