<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\Bed;
use App\Models\CareUnit;
use App\Models\Visit;
use App\Services\Care\VisitPlacementService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class VisitPlacementController extends Controller
{
    use ScopesToAccount;

    public function store(Request $request, CareUnit $careUnit, VisitPlacementService $placements): RedirectResponse
    {
        $this->authorizeAbility($request, 'inpatient.placement.manage');
        $this->authorizeOwner($request, $careUnit);
        $organization = $this->organization($request);
        abort_unless((int) $careUnit->organization_id === (int) $organization->id, 404);

        $validated = $request->validate([
            'visit_id' => ['required', 'integer', 'exists:care_visits,id'],
            'bed_id' => ['nullable', 'integer', 'exists:care_beds,id'],
            'notes' => ['nullable', 'string', 'max:2000'],
        ]);

        $visit = Visit::owned($this->ownerRef($request))
            ->where('organization_id', $organization->id)
            ->findOrFail($validated['visit_id']);
        $this->authorizeBranch($request, (int) $visit->branch_id);

        $bed = null;
        if (! empty($validated['bed_id'])) {
            $bed = Bed::owned($this->ownerRef($request))
                ->where('care_unit_id', $careUnit->id)
                ->findOrFail($validated['bed_id']);
        }

        $placements->place(
            $visit,
            $careUnit,
            $bed,
            $this->ownerRef($request),
            $this->actorRef($request),
            $validated['notes'] ?? null,
        );

        return redirect()
            ->route('care.care-units.show', $careUnit)
            ->with('success', 'Patient placed on this care unit.');
    }

    public function transfer(Request $request, Visit $visit, VisitPlacementService $placements): RedirectResponse
    {
        $this->authorizeAbility($request, 'inpatient.placement.manage');
        $this->authorizeOwner($request, $visit);
        $this->authorizeBranch($request, (int) $visit->branch_id);
        $organization = $this->organization($request);

        $validated = $request->validate([
            'care_unit_id' => ['required', 'integer', 'exists:care_care_units,id'],
            'bed_id' => ['nullable', 'integer', 'exists:care_beds,id'],
            'notes' => ['nullable', 'string', 'max:2000'],
        ]);

        $unit = CareUnit::owned($this->ownerRef($request))
            ->where('organization_id', $organization->id)
            ->findOrFail($validated['care_unit_id']);

        $bed = null;
        if (! empty($validated['bed_id'])) {
            $bed = Bed::owned($this->ownerRef($request))
                ->where('care_unit_id', $unit->id)
                ->findOrFail($validated['bed_id']);
        }

        $placements->transfer(
            $visit,
            $unit,
            $bed,
            $this->ownerRef($request),
            $this->actorRef($request),
            $validated['notes'] ?? null,
        );

        return redirect()
            ->route('care.care-units.show', $unit)
            ->with('success', 'Patient transferred.');
    }

    public function destroy(Request $request, Visit $visit, VisitPlacementService $placements): RedirectResponse
    {
        $this->authorizeAbility($request, 'inpatient.placement.manage');
        $this->authorizeOwner($request, $visit);
        $this->authorizeBranch($request, (int) $visit->branch_id);

        $unitId = $visit->care_unit_id;

        $placements->dischargePlacement(
            $visit,
            $this->ownerRef($request),
            $this->actorRef($request),
            $request->input('notes'),
        );

        if ($unitId) {
            return redirect()
                ->route('care.care-units.show', $unitId)
                ->with('success', 'Placement discharged; bed freed if applicable.');
        }

        return back()->with('success', 'Placement discharged.');
    }
}
