<?php

namespace App\Modules\HR\Overtime\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\HR\Overtime\Models\OvertimeRatePolicy;
use App\Modules\HR\Overtime\Repositories\OvertimeRatePolicyRepository;
use App\Modules\HR\Overtime\Requests\StoreOvertimeRatePolicyRequest;
use App\Modules\HR\Overtime\Requests\UpdateOvertimeRatePolicyRequest;
use App\Modules\HR\Overtime\Services\OvertimeRatePolicyService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class OvertimeRatePolicyPageController extends Controller
{
    public function __construct(
        private readonly OvertimeRatePolicyService $policies,
        private readonly OvertimeRatePolicyRepository $repository,
    ) {}

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

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

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

        return view('pages.hr.overtime.rates.create');
    }

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

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

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

        return view('pages.hr.overtime.rates.edit', ['policy' => $policy]);
    }

    public function update(UpdateOvertimeRatePolicyRequest $request, OvertimeRatePolicy $policy): RedirectResponse
    {
        $this->policies->update($policy, $request->validated());

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

    public function deactivate(OvertimeRatePolicy $policy): RedirectResponse
    {
        $this->authorize('deactivate', $policy);
        $this->policies->deactivate($policy);

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

    public function reactivate(OvertimeRatePolicy $policy): RedirectResponse
    {
        $this->authorize('update', $policy);
        $this->policies->reactivate($policy);

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

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

        return $t;
    }
}
