<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Http\Controllers\Controller;
use App\Services\Care\RosterService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\View\View;

class MyShiftsController extends Controller
{
    use ScopesToAccount;

    public function index(Request $request, RosterService $roster): View
    {
        $this->authorizeAbility($request, 'nursing.my_shifts.view');
        $member = $this->member($request);
        abort_unless($member, 403);

        $weekStart = $request->filled('week')
            ? Carbon::parse($request->input('week'))->startOfWeek(Carbon::MONDAY)
            : now()->startOfWeek(Carbon::MONDAY);

        $grid = $roster->memberWeek($member, $this->ownerRef($request), $weekStart);

        $byDate = [];
        foreach ($grid['entries'] as $entry) {
            $byDate[$entry->duty_date->toDateString()][] = $entry;
        }

        return view('care.nursing.my-shifts', [
            'member' => $member,
            'weekStart' => $grid['week_start'],
            'days' => $grid['days'],
            'entriesByDate' => $byDate,
            'todayEntries' => $grid['today'],
            'prevWeek' => $grid['week_start']->copy()->subWeek()->toDateString(),
            'nextWeek' => $grid['week_start']->copy()->addWeek()->toDateString(),
            'roles' => config('care.roles'),
        ]);
    }
}
