<?php

namespace App\Http\Controllers\Care;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Care\Concerns\ScopesToAccount;
use App\Models\Shift;
use App\Services\Care\AuditLogger;
use App\Services\Care\RosterService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class ShiftController extends Controller
{
    use ScopesToAccount;

    public function index(Request $request, RosterService $roster): View
    {
        $this->authorizeAbility($request, 'nursing.roster.manage');
        $organization = $this->organization($request);
        $owner = $this->ownerRef($request);

        $roster->ensureDefaultShifts($organization, $owner);

        $shifts = Shift::owned($owner)
            ->where('organization_id', $organization->id)
            ->orderBy('sort_order')
            ->orderBy('label')
            ->get();

        return view('care.nursing.shifts-index', [
            'shifts' => $shifts,
            'organization' => $organization,
        ]);
    }

    public function store(Request $request): RedirectResponse
    {
        $this->authorizeAbility($request, 'nursing.roster.manage');
        $organization = $this->organization($request);
        $owner = $this->ownerRef($request);

        $validated = $request->validate([
            'code' => [
                'required', 'string', 'max:50', 'alpha_dash',
                Rule::unique('care_shifts', 'code')->where(fn ($q) => $q->where('organization_id', $organization->id)->whereNull('deleted_at')),
            ],
            'label' => ['required', 'string', 'max:100'],
            'start_time' => ['required', 'date_format:H:i'],
            'end_time' => ['required', 'date_format:H:i'],
            'color' => ['nullable', 'string', 'max:20'],
        ]);

        $shift = Shift::create([
            'owner_ref' => $owner,
            'organization_id' => $organization->id,
            'code' => strtolower($validated['code']),
            'label' => $validated['label'],
            'start_time' => $validated['start_time'].':00',
            'end_time' => $validated['end_time'].':00',
            'color' => $validated['color'] ?? '#64748b',
            'sort_order' => ((int) Shift::query()->where('organization_id', $organization->id)->max('sort_order')) + 10,
            'is_active' => true,
        ]);

        AuditLogger::record($owner, 'shift.created', $organization->id, $owner, Shift::class, $shift->id);

        return redirect()->route('care.shifts.index')->with('success', 'Shift created.');
    }

    public function update(Request $request, Shift $shift): RedirectResponse
    {
        $this->authorizeAbility($request, 'nursing.roster.manage');
        $this->authorizeOwner($request, $shift);

        $validated = $request->validate([
            'label' => ['required', 'string', 'max:100'],
            'start_time' => ['required', 'date_format:H:i'],
            'end_time' => ['required', 'date_format:H:i'],
            'color' => ['nullable', 'string', 'max:20'],
            'is_active' => ['boolean'],
        ]);

        $shift->update([
            'label' => $validated['label'],
            'start_time' => $validated['start_time'].':00',
            'end_time' => $validated['end_time'].':00',
            'color' => $validated['color'] ?? $shift->color,
            'is_active' => $request->boolean('is_active', true),
        ]);

        AuditLogger::record($this->ownerRef($request), 'shift.updated', $shift->organization_id, $this->ownerRef($request), Shift::class, $shift->id);

        return redirect()->route('care.shifts.index')->with('success', 'Shift updated.');
    }
}
