<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\CareUnit;
use App\Services\Care\CarePermissions;
use App\Services\Care\NursePerformanceService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\View\View;

class NursePerformanceController extends Controller
{
    use ScopesToAccount;

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

        $from = $request->filled('from')
            ? Carbon::parse($request->input('from'))->startOfDay()
            : now()->subDays(7)->startOfDay();
        $to = $request->filled('to')
            ? Carbon::parse($request->input('to'))->endOfDay()
            : now()->endOfDay();

        $report = $performance->unitReport($careUnit, $this->ownerRef($request), $from, $to);

        return view('care.nursing.performance', [
            'unit' => $careUnit->load('department.branch'),
            'report' => $report,
            'canManage' => app(CarePermissions::class)->can($this->member($request), 'admin.departments.manage'),
        ]);
    }
}
