<?php

namespace Modules\HR\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
use Modules\Core\Helpers\ApiResponse;
use Modules\Core\Http\Requests\UpdateStatusRequest;
use Modules\Employee\Models\EmployeeSetting;
use Modules\Employee\Services\EmployeeService;
use Modules\HR\DTO\HrSettingFilter;
use Modules\HR\Http\Requests\SalaryStructure\StoreSalaryStructureRequest;
use Modules\HR\Http\Requests\SalaryStructure\UpdateSalaryStructureRequest;
use Modules\HR\Models\HrSettings;
use Modules\HR\Services\SalaryStructureService;
use Modules\HR\Transformers\SalaryStructureResource;

class SalaryStructureController extends Controller
{
    use AuthorizesRequests;
    /**
     * Display a listing of the resource.
     */

    public function __construct(
        protected SalaryStructureService $salaryStructureService,
        protected EmployeeService $employeeService
    ) {}

    public function index(Request $request, $employeeId)
    {
        $this->authorize('employeeSettingView', EmployeeSetting::class);
        $employee = $this->employeeService->find($employeeId);
        $filter = HrSettingFilter::fromRequest($request);
        $response = $this->salaryStructureService->list($employee, $filter);
        return (SalaryStructureResource::collection($response))->additional([
            'status' => true,
            'message' => 'Salary structure retrieved successfully.'
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(StoreSalaryStructureRequest $request, $employeeId)
    {
        $this->authorize('employeeSettingManage', EmployeeSetting::class);

        $employee = $this->employeeService->find($employeeId);

        $salaryStructure = $this->salaryStructureService->store($employee, $request->validated());

        return (new SalaryStructureResource($salaryStructure))->additional([
            'status' => true,
            'message' => 'Salary structure created successfully.'
        ]);
    }

    public function show($employeeId)
    {
        $this->authorize('employeeSettingView', EmployeeSetting::class);

        $employee =    $this->employeeService->find($employeeId);
        $salaryStructure = $this->salaryStructureService->getActiveSalaryStructure($employee);

        return (new SalaryStructureResource($salaryStructure->load('items')))->additional([
            'status' => true,
            'message' => 'Salary structure retrieved successfully.'
        ]);
    }


    public function updateStatus(UpdateStatusRequest $request, $id)
    {
        $this->authorize('hrSettingManage', HrSettings::class);
        $this->salaryStructureService->updateStatus(
            $this->salaryStructureService->show($id),
            $request->validated()
        );
        return ApiResponse::successResponse('Salary structure status updated successfully.');
    }
}
