<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Brand;
use App\Models\CarModel;
use Illuminate\Http\Request;

class CarModelController extends Controller
{
    public function index(Request $request)
    {
        $query = CarModel::with('brand')->withCount('trims');

        if ($request->filled('search')) {
            $query->where(function ($q) use ($request) {
                $q->where('name', 'like', '%'.$request->search.'%')
                    ->orWhereHas('brand', function ($bq) use ($request) {
                        $bq->where('name', 'like', '%'.$request->search.'%');
                    });
            });
        }

        $models = $query->orderBy('name')->paginate(15)->withQueryString();

        return view('admin.models.index', compact('models'));
    }

    public function create()
    {
        $brands = Brand::orderBy('name')->get();

        return view('admin.models.create', compact('brands'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'brand_id' => 'required|exists:brands,id',
            'name' => 'required|max:255',
        ]);
        CarModel::create($request->all());

        return redirect()->route('admin.models.index')->with('success', 'تمت إضافة الموديل بنجاح');
    }

    public function edit(CarModel $model)
    {
        $brands = Brand::orderBy('name')->get();

        return view('admin.models.edit', compact('model', 'brands'));
    }

    public function update(Request $request, CarModel $model)
    {
        $request->validate([
            'brand_id' => 'required|exists:brands,id',
            'name' => 'required|max:255',
        ]);
        $model->update($request->all());

        return redirect()->route('admin.models.index')->with('success', 'تم تحديث الموديل بنجاح');
    }

    public function destroy(CarModel $model)
    {
        $model->delete();

        return redirect()->route('admin.models.index')->with('success', 'تم حذف الموديل بنجاح');
    }
}
