<?php

namespace App\Modules\HR\Shifts\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Shifts\Repositories\EmployeeShiftAssignmentRepository;
use App\Modules\HR\Shifts\Repositories\ShiftWorkforceRepository;
use App\Modules\HR\Shifts\Requests\StoreShiftSwapRequest;
use App\Modules\HR\Shifts\Requests\StoreShiftRotationRequest;
use App\Modules\HR\Shifts\Services\ShiftRotationService;
use App\Modules\HR\Shifts\Services\ShiftSwapService;
use Carbon\CarbonImmutable;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ShiftCalendarController extends Controller
{
    public function index(
        Request $request,
        EmployeeShiftAssignmentRepository $assignments,
        ShiftWorkforceRepository $workforce,
    ): View {
        $month = CarbonImmutable::parse((string) $request->query('month', now()->format('Y-m').'-01'));
        $tenantId = $this->tenantId();

        return view('pages.hr.shifts.calendar', [
            'month' => $month,
            'assignments' => $assignments->calendarForTenant($tenantId, $month),
            'rotations' => $workforce->rotations($tenantId),
            'swaps' => $workforce->swaps($tenantId),
        ]);
    }

    public function storeSwap(StoreShiftSwapRequest $request, ShiftSwapService $service): RedirectResponse
    {
        $service->submit($this->tenantId(), $request->validated());

        return back()->with('status', __('shifts.swap.submitted'));
    }

    public function storeRotation(
        StoreShiftRotationRequest $request,
        ShiftRotationService $service,
    ): RedirectResponse {
        $service->create($this->tenantId(), $request->validated(), (int) $request->user()->id);

        return back()->with('status', __('shifts.rotation.created'));
    }

    public function reviewSwap(int $swap, ShiftSwapService $service): RedirectResponse
    {
        $service->review(
            $this->tenantId(),
            $swap,
            request()->boolean('approve'),
            (int) request()->user()->id,
        );

        return back()->with('status', __('shifts.swap.reviewed'));
    }

    private function tenantId(): int
    {
        $id = auth()->user()?->tenant_id;
        abort_if($id === null, 403);

        return (int) $id;
    }
}
