<?php

namespace Modules\Payroll\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Modules\Payroll\DTO\PayrollCyclesFilter;
use Modules\Payroll\Http\Requests\PayrollCycle\StorePayrollCycleRequest;
use Modules\Payroll\Http\Requests\PayrollCycle\UpdatePayrollCycleRequest;
use Modules\Payroll\Models\PayrollCycle;
use Modules\Payroll\Models\PayrollSetting;
use Modules\Payroll\Services\PayrollCycleService;
use Modules\Payroll\Transformers\PayrollCycleResource;

class PayrollCycleController extends Controller
{
    use AuthorizesRequests;
    public function __construct(protected PayrollCycleService $payrollCycleService) {}

    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $this->authorize('payrollSettingView', PayrollSetting::class);
        $filter = PayrollCyclesFilter::fromRequest($request);
        $response = $this->payrollCycleService->list($filter);

        return (PayrollCycleResource::collection($response))->additional([
            'status' => true,
            'message' => 'Payroll cycles retrieved successfully.'
        ]);
    }

    public function store(StorePayrollCycleRequest $request)
    {
        $this->authorize('payrollSettingManage', PayrollSetting::class);

        $payrollCycle = $this->payrollCycleService->store($request->validated());

        return (new PayrollCycleResource($payrollCycle))->additional([
            'status' => true,
            'message' => 'Payroll cycle created successfully.'
        ]);
    }

    public function show($id)
    {
        $this->authorize('payrollSettingView', PayrollSetting::class);

        return (new PayrollCycleResource($this->payrollCycleService->show($id)))->additional([
            'status' => true,
            'message' => 'Payroll cycle retrieved successfully.'
        ]);
    }

    public function update(UpdatePayrollCycleRequest $request, $id)
    {
        $this->authorize('payrollSettingManage', PayrollSetting::class);

        $payrollCycle = PayrollCycle::findOrFail($id);

        $payrollCycle = $this->payrollCycleService->update(
            $payrollCycle,
            $request->validated()
        );

        return (new PayrollCycleResource($payrollCycle))->additional([
            'status' => true,
            'message' => 'Payroll cycle updated successfully.'
        ]);
    }
}
