<?php

namespace App\Http\Controllers\specialty;

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

class specialtyController extends Controller
{
    public function index()
    {
        $data = Specialties::orderByDesc('created_at')->get();
        return view('admin.specialty.index', compact('data'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
        ]);
        $specialty = new Specialties();
        $specialty->name = $request->name;
        $specialty->save();
        return redirect()->route('specialty.index')->with('success','تم اضافه التخصص بنجاح');
    }

    public function update(Request $request, $id)
    {
        $specialty = Specialties::findOrFail($id);

        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string'],
        ]);

        $specialty->update($data);

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

    public function destroy($id)
    {
        $specialty = Specialties::withCount('doctorProfiles')->findOrFail($id);

        if ($specialty->doctor_profiles_count > 0) {
            return redirect()
                ->route('specialty.index')
                ->with('error', 'لا يمكن حذف التخصص لوجود دكاترة مرتبطين به.');
        }

        $specialty->delete();

        return redirect()
            ->route('specialty.index')
            ->with('success', 'تم حذف التخصص بنجاح.');
    }


    public function doctors($id)
    {
        $specialty = Specialties::with([
            'doctorProfiles.user',
            'doctorProfiles.user.clinic',
            'doctorProfiles.branch'
        ])->findOrFail($id);

        return view('admin.specialty.doctors', compact('specialty'));
    }
}
