<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\CareUnit;
use App\Models\MarOrder;
use App\Models\Visit;
use App\Services\Care\CarePermissions;
use App\Services\Care\MarService;
use Carbon\Carbon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class MarController extends Controller
{
    use ScopesToAccount;

    public function unitBoard(Request $request, CareUnit $careUnit, MarService $mar): View
    {
        $this->authorizeAbility($request, 'mar.view');
        $this->authorizeOwner($request, $careUnit);
        $organization = $this->organization($request);
        abort_unless((int) $careUnit->organization_id === (int) $organization->id, 404);

        $day = $request->filled('date')
            ? Carbon::parse($request->input('date'))->startOfDay()
            : now()->startOfDay();

        $rows = $mar->unitRoundBoard($careUnit, $this->ownerRef($request), $day);
        $canAdminister = app(CarePermissions::class)->can($this->member($request), 'mar.administer');

        return view('care.nursing.mar-board', [
            'unit' => $careUnit->load('department.branch'),
            'day' => $day,
            'rows' => $rows,
            'canAdminister' => $canAdminister,
            'statuses' => config('care.mar_administration_statuses'),
            'stateLabels' => config('care.mar_slot_states'),
        ]);
    }

    public function visitChart(Request $request, Visit $visit, MarService $mar): View
    {
        $this->authorizeAbility($request, 'mar.view');
        $this->authorizeOwner($request, $visit);
        $this->authorizeBranch($request, (int) $visit->branch_id);

        $day = $request->filled('date')
            ? Carbon::parse($request->input('date'))->startOfDay()
            : now()->startOfDay();

        $orders = $mar->syncOrdersForVisit($visit, $this->ownerRef($request));
        $chart = [];
        foreach ($orders as $order) {
            $chart[] = [
                'order' => $order,
                'slots' => $mar->dueSlotsForOrder($order, $day),
            ];
        }

        return view('care.nursing.mar-visit', [
            'visit' => $visit->load(['patient', 'careUnit', 'bed']),
            'day' => $day,
            'chart' => $chart,
            'canAdminister' => app(CarePermissions::class)->can($this->member($request), 'mar.administer'),
            'statuses' => config('care.mar_administration_statuses'),
            'stateLabels' => config('care.mar_slot_states'),
            'frequencies' => config('care.mar_frequency_codes'),
        ]);
    }

    public function administer(Request $request, MarOrder $marOrder, MarService $mar): RedirectResponse
    {
        $this->authorizeAbility($request, 'mar.administer');
        $this->authorizeOwner($request, $marOrder);

        $validated = $request->validate([
            'status' => ['required', 'string', Rule::in(array_keys(config('care.mar_administration_statuses')))],
            'scheduled_for' => ['nullable', 'date'],
            'dose_given' => ['nullable', 'string', 'max:255'],
            'route' => ['nullable', 'string', 'max:100'],
            'witness_by' => ['nullable', 'string', 'max:255'],
            'reason' => ['nullable', 'string', 'max:500'],
            'notes' => ['nullable', 'string', 'max:2000'],
            'redirect_to' => ['nullable', 'string', 'max:500'],
        ]);

        $mar->recordAdministration(
            $marOrder,
            $validated['status'],
            $this->ownerRef($request),
            $this->actorRef($request),
            isset($validated['scheduled_for']) ? Carbon::parse($validated['scheduled_for']) : null,
            $validated['dose_given'] ?? null,
            $validated['route'] ?? null,
            $validated['witness_by'] ?? null,
            $validated['reason'] ?? null,
            $validated['notes'] ?? null,
        );

        $redirect = $validated['redirect_to'] ?? null;
        if ($redirect && str_starts_with($redirect, url('/'))) {
            return redirect()->to($redirect)->with('success', 'MAR entry recorded.');
        }

        return back()->with('success', 'MAR entry recorded.');
    }
}
