<?php

namespace App\Modules\HR\Shifts\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\HR\Shifts\Models\Shift;
use App\Modules\HR\Shifts\Repositories\ShiftRepository;
use App\Modules\HR\Shifts\Requests\StoreShiftRequest;
use App\Modules\HR\Shifts\Requests\UpdateShiftRequest;
use App\Modules\HR\Shifts\Services\ShiftCrudService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class ShiftPageController extends Controller
{
    public function __construct(
        private readonly ShiftCrudService $shifts,
        private readonly ShiftRepository $shiftRepository,
    ) {}

    public function index(Request $request): View
    {
        $this->authorize('viewAny', Shift::class);
        $tenant = $this->tenant();

        return view('pages.hr.shifts.index', [
            'shifts' => $this->shiftRepository->paginateForIndex((int) $tenant->id, $request),
        ]);
    }

    public function create(): View
    {
        $this->authorize('create', Shift::class);

        return view('pages.hr.shifts.create');
    }

    public function store(StoreShiftRequest $request): RedirectResponse
    {
        $this->shifts->create((int) $this->tenant()->id, $request->validated(), (int) $request->user()->id);

        return redirect()->route('hr.shifts.index')->with('status', __('shifts.flash.created'));
    }

    public function edit(Shift $shift): View
    {
        $this->authorize('update', $shift);

        return view('pages.hr.shifts.edit', ['shift' => $shift]);
    }

    public function update(UpdateShiftRequest $request, Shift $shift): RedirectResponse
    {
        $this->shifts->update($shift, $request->validated(), (int) $request->user()->id);

        return redirect()->route('hr.shifts.index')->with('status', __('shifts.flash.updated'));
    }

    public function deactivate(Shift $shift): RedirectResponse
    {
        $this->authorize('deactivate', $shift);
        $this->shifts->deactivate($shift, (int) request()->user()->id);

        return redirect()->route('hr.shifts.index')->with('status', __('shifts.flash.deactivated'));
    }

    public function reactivate(Shift $shift): RedirectResponse
    {
        $this->authorize('update', $shift);
        $this->shifts->reactivate($shift, (int) request()->user()->id);

        return redirect()->route('hr.shifts.index')->with('status', __('shifts.flash.reactivated'));
    }

    private function tenant(): Tenant
    {
        $t = auth()->user()?->tenant;
        abort_if($t === null, 403);

        return $t;
    }
}
