<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Http\Requests\DentistRequest;
use App\Models\Dentist;
use Illuminate\Support\Facades\DB;

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

        return view('dentists.index', [
            'dentists' => Dentist::withCount('schedules')->orderBy('name')->paginate(20),
        ]);
    }

    public function create()
    {
        $this->authorize('create', Dentist::class);

        return view('dentists.form', ['dentist' => new Dentist(['color' => '#0EA5E9', 'slot_duration_min' => 30, 'buffer_min' => 0, 'status' => 'active'])]);
    }

    public function store(DentistRequest $request)
    {
        $this->authorize('create', Dentist::class);

        $dentist = DB::transaction(function () use ($request) {
            $dentist = Dentist::create($request->safe()->except('schedules'));
            $dentist->schedules()->createMany($request->scheduleRows());

            return $dentist;
        });

        return redirect()->route('tenant.dentists.index')
            ->with('status', __(':name was added.', ['name' => $dentist->name]));
    }

    public function edit(Dentist $dentist)
    {
        $this->authorize('update', $dentist);
        $dentist->load('schedules');

        return view('dentists.form', compact('dentist'));
    }

    public function update(DentistRequest $request, Dentist $dentist)
    {
        $this->authorize('update', $dentist);

        DB::transaction(function () use ($request, $dentist) {
            $dentist->update($request->safe()->except('schedules'));
            $dentist->schedules()->delete();
            $dentist->schedules()->createMany($request->scheduleRows());
        });

        return redirect()->route('tenant.dentists.index')
            ->with('status', __('Changes saved.'));
    }

    public function destroy(Dentist $dentist)
    {
        $this->authorize('delete', $dentist);
        $dentist->delete(); // soft delete; history is preserved

        return redirect()->route('tenant.dentists.index')
            ->with('status', __(':name was removed.', ['name' => $dentist->name]));
    }
}
