<?php

namespace Modules\SpecialAttendance\Http\Controllers\Api\V11;

use App\Helpers\CoreApp\Traits\ApiReturnFormatTrait;
use Carbon\Carbon;
use Illuminate\Routing\Controller;
use Modules\SpecialAttendance\Entities\Deduction;
use Modules\SpecialAttendance\Http\Repositories\DeductionRepository;
use Modules\SpecialAttendance\Http\Requests\DeductionAppealRequest;
use Modules\SpecialAttendance\Transformers\DeductionResource;

class DeductionApiController extends Controller
{
    use ApiReturnFormatTrait;

    public function index()
    {
        try {

            $deductions = Deduction::query()
                ->with('deductionDetails')
                ->where('user_id', auth()->id())
                ->when(request('month') && request('month') != null, fn ($q) => $q->where('month', Carbon::parse(request('month'))->format('m'))
                    ->where('year', Carbon::parse(request('month'))->format('Y'))
                )
                ->latest('id')
                ->paginate(10);

            $data = DeductionResource::collection($deductions)->response()->getData(true);

            return $this->responseWithSuccess('Success', $data, 200);

        } catch (\Throwable $th) {
            return $this->responseWithError(__('Something went wrong.'), [$th->getMessage()], 400);
        }
    }

    public function appeal(DeductionAppealRequest $request, $id)
    {
        try {
            (new DeductionRepository)->appeal($id);

            return $this->responseWithSuccess(_trans('message.Appeal has been sent successfully.'));
        } catch (\Throwable $th) {
            return $this->responseWithError(__('Something went wrong.'), [$th->getMessage()], 400);
        }
    }
}
