<?php

namespace App\Http\Controllers\Admin;

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

class TrimController extends Controller
{
    public function index(Request $request)
    {
        $query = Trim::with('carModel.brand');

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

        $trims = $query->orderBy('name')->paginate(20)->withQueryString();

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

    public function create()
    {
        $models = CarModel::with('brand')->orderBy('name')->get();

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

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

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

    public function edit(Trim $trim)
    {
        $models = CarModel::with('brand')->orderBy('name')->get();

        return view('admin.trims.edit', compact('trim', 'models'));
    }

    public function update(Request $request, Trim $trim)
    {
        $request->validate([
            'car_model_id' => 'required|exists:car_models,id',
            'name' => 'required|max:255',
        ]);
        $trim->update($request->all());

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

    public function destroy(Trim $trim)
    {
        $trim->delete();

        return redirect()->route('admin.trims.index')->with('success', 'تم حذف الفئة بنجاح');
    }
}
