<?php

namespace App\Http\Controllers\Admin\Hr;

use App\Http\Controllers\Concerns\FlashesEntityMessage;
use App\Http\Controllers\Concerns\ParsesDataTableQuery;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Hr\ApproveLeaveRequestRequest;
use App\Http\Requests\Admin\Hr\RejectLeaveRequestRequest;
use App\Http\Requests\Admin\Hr\SubmitLeaveRequest;
use App\Models\LeaveRequest;
use App\Services\Hr\LeaveRequestService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class LeaveRequestController extends Controller
{
    use FlashesEntityMessage, ParsesDataTableQuery;

    public function __construct(
        private readonly LeaveRequestService $leaveRequestService,
    ) {}

    public function index(Request $request): Response
    {
        $tableQuery = $this->parseDataTableQuery($request);
        $pageData = $this->leaveRequestService->indexPageData($tableQuery, $request->user());

        return Inertia::render('admin/hr/leave-requests/Index', [
            ...$pageData,
            'filters' => $this->dataTableFilters($tableQuery),
        ]);
    }

    public function store(SubmitLeaveRequest $request): RedirectResponse
    {
        $this->leaveRequestService->create($request->validated(), $request->user());

        $this->flashSuccess('Pengajuan cuti berhasil diajukan.');

        return redirect()->route('admin.hr.leave_requests.index');
    }

    public function update(SubmitLeaveRequest $request, LeaveRequest $leaveRequest): RedirectResponse
    {
        $this->leaveRequestService->update($leaveRequest, $request->validated(), $request->user());

        $this->flashUpdated('Pengajuan cuti');

        return redirect()->route('admin.hr.leave_requests.index');
    }

    public function destroy(LeaveRequest $leaveRequest): RedirectResponse
    {
        $this->leaveRequestService->delete($leaveRequest);

        $this->flashDeleted('Pengajuan cuti');

        return redirect()->route('admin.hr.leave_requests.index');
    }

    public function approve(ApproveLeaveRequestRequest $request, LeaveRequest $leaveRequest): RedirectResponse
    {
        $this->leaveRequestService->approve($leaveRequest, $request->user());

        $this->flashSuccess('Pengajuan cuti berhasil disetujui.');

        return redirect()->route('admin.hr.leave_requests.index');
    }

    public function reject(RejectLeaveRequestRequest $request, LeaveRequest $leaveRequest): RedirectResponse
    {
        $this->leaveRequestService->reject(
            $leaveRequest,
            $request->validated('reason'),
            $request->user(),
        );

        $this->flashSuccess('Pengajuan cuti berhasil ditolak.');

        return redirect()->route('admin.hr.leave_requests.index');
    }
}
