<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Http\Requests\ProcedureRequest;
use App\Models\Procedure;

class ProcedureController extends Controller
{
    public function index()
    {
        $this->authorize('viewAny', Procedure::class);

        return view('procedures.index', [
            'procedures' => Procedure::query()
                ->when(request('q'), fn ($q, $term) => $q->where(
                    fn ($w) => $w->where('name_en', 'like', "%$term%")->orWhere('name_ar', 'like', "%$term%")
                ))
                ->orderBy('category')->orderBy('name_en')
                ->paginate(40)->withQueryString(),
            'categories' => config('dental.procedure_categories'),
            'conditions' => config('dental.conditions'),
        ]);
    }

    public function store(ProcedureRequest $request)
    {
        $this->authorize('create', Procedure::class);
        Procedure::create($request->validated());

        return back()->with('status', __('Procedure added.'));
    }

    public function update(ProcedureRequest $request, Procedure $procedure)
    {
        $this->authorize('update', $procedure);
        $procedure->update($request->validated());

        return back()->with('status', __('Changes saved.'));
    }

    public function destroy(Procedure $procedure)
    {
        $this->authorize('delete', $procedure);
        $procedure->delete(); // soft delete keeps plan items intact

        return back()->with('status', __('Procedure removed.'));
    }
}
