<?php

namespace App\Modules\HR\Attendance\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\HR\Attendance\Models\Holiday;
use App\Modules\HR\Attendance\Repositories\HolidayRepository;
use App\Modules\HR\Attendance\Requests\HolidayRequest;
use App\Modules\HR\Attendance\Services\HolidayService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class HolidayController extends Controller
{
    public function index(Request $request, HolidayRepository $holidays): View
    {
        $editId = (int) $request->query('edit');

        return view('pages.hr.attendance.holidays', [
            'holidays' => $holidays->paginate($this->tenantId()),
            'editing' => $editId > 0 ? $holidays->find($this->tenantId(), $editId) : null,
        ]);
    }

    public function store(HolidayRequest $request, HolidayService $service): RedirectResponse
    {
        $service->save($this->tenantId(), $request->validated());

        return back()->with('status', __('attendance.holidays.saved'));
    }

    public function update(
        HolidayRequest $request,
        Holiday $holiday,
        HolidayService $service,
    ): RedirectResponse {
        abort_unless((int) $holiday->tenant_id === $this->tenantId(), 404);
        $service->save($this->tenantId(), $request->validated(), $holiday);

        return back()->with('status', __('attendance.holidays.saved'));
    }

    public function destroy(Holiday $holiday, HolidayService $service): RedirectResponse
    {
        abort_unless((int) $holiday->tenant_id === $this->tenantId(), 404);
        $service->delete($holiday);

        return back()->with('status', __('attendance.holidays.deleted'));
    }

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

        return (int) $id;
    }
}
