<?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\HR\DTO\AttendanceFilter;
use Modules\HR\DTO\OvertimeEntryFilter;
use Modules\HR\Models\HolidayAllowance;
use Modules\HR\Models\HrSettings;
use Modules\HR\Models\OvertimeEntry;
use Modules\HR\Services\AttendanceService;
use Modules\HR\Transformers\AttendanceResource;
use Modules\HR\Transformers\OvertimeEntryResource;

class AttendanceController extends Controller
{
    use AuthorizesRequests;
    /**
     * Display a listing of the resource.
     */
    protected $attendanceService;

    public function __construct(AttendanceService $attendanceService)
    {
        $this->attendanceService = $attendanceService;
    }

    public function getAttendances(Request $request)
    {
        $this->authorize('hrSettingView', HrSettings::class);
        $filter = AttendanceFilter::fromRequest($request);
        $response = $this->attendanceService->list($filter);

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

    public function getOvertimeEntries(Request $request)
    {
        $this->authorize('hrSettingView', HrSettings::class);
        $filter = OvertimeEntryFilter::fromRequest($request);
        $response = $this->attendanceService->getOvertimeEntries($filter);

        return (OvertimeEntryResource::collection($response))->additional([
            'status' => true,
            'message' => 'Overtime entries retrieved successfully.'
        ]);
    }

    public function approveOvertimeEntry(OvertimeEntry $overtimeEntry)
    {
        $this->authorize('approved', $overtimeEntry);

        $this->attendanceService->approveOvertime(
            $overtimeEntry
        );
        return ApiResponse::successResponse('Over time entry approved successfully.');
    }

    public function approveHolidayAllowance($holidayAllowance)
    {
        $holidayAllowance = HolidayAllowance::where('id', '=', $holidayAllowance)->firstOrFail();
        $this->authorize('approved', $holidayAllowance);

        $this->attendanceService->approveHolidayAllowance(
            $holidayAllowance
        );
        return ApiResponse::successResponse('holiday Allowance approved successfully.');
    }
}
