<?php

namespace App\Http\Controllers;

use App\Models\Specialty;
use Illuminate\Http\Request;

class SpecialtyController extends Controller
{
    public function index()
    {
        $specialties = Specialty::latest()->get();
        return view('admin.doctors.specialty', compact('specialties'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:specialties,name',
        ]);

        Specialty::create(['name' => $request->name]);

        return response()->json([
            'success' => true,
            'message' => 'Specialty created successfully'
        ]);
    }


    public function destroy(Specialty $specialty)
    {
        // Check if any doctors are associated with this specialty
        $existDoctor = $specialty->doctors()->first();
        if ($existDoctor) {
            return back()->with('failed', 'This specialty is used by a doctor. Please reassign or delete the doctor first.');
        }

        $specialty->delete();
        return back()->with('success', 'Specialty deleted successfully!');
    }
}
