<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Enums\EmployeeAdvanceStatus;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Finance\EmployeeAdvancePaymentRequest;
use App\Http\Requests\Admin\Finance\EmployeeAdvanceRequest;
use App\Http\Requests\PaginatedRequest;
use App\Models\EmployeeAdvance;
use App\Services\Admin\Finance\EmployeeAdvanceService;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class EmployeeAdvanceController extends Controller
{
    public function __construct(
        private EmployeeAdvanceService $service
    ) {}

    public function index(PaginatedRequest $request): Response
    {
        return Inertia::render('admin/finance/employee-advance/index', [
            'employeeAdvances' => $this->service->paginated(
                ...$request->validatedWithDefaults(),
                filters: $request->only(['status']),
            ),
            'filters' => $request->only(['status']),
            'filterOptions' => [
                'statusOptions' => EmployeeAdvanceStatus::toSelect(),
            ],
        ]);
    }

    public function store(EmployeeAdvanceRequest $request): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->store($request->validated()),
            'Kasbon berhasil ditambahkan.',
            'admin.finance.employee-advances.index'
        );
    }

    public function update(EmployeeAdvanceRequest $request, EmployeeAdvance $employeeAdvance): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->update($employeeAdvance, $request->validated()),
            'Kasbon berhasil diperbarui.',
            'admin.finance.employee-advances.index'
        );
    }

    public function destroy(EmployeeAdvance $employeeAdvance): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->destroy($employeeAdvance),
            'Kasbon berhasil dihapus.',
            'admin.finance.employee-advances.index'
        );
    }

    public function approve(EmployeeAdvance $employeeAdvance): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->approve($employeeAdvance),
            'Kasbon berhasil disetujui.',
            'admin.finance.employee-advances.index'
        );
    }

    public function pay(EmployeeAdvancePaymentRequest $request, EmployeeAdvance $employeeAdvance): RedirectResponse
    {
        return $this->handleAction(
            fn () => $this->service->pay($employeeAdvance, $request->validated('amount')),
            'Pembayaran kasbon berhasil.',
            'admin.finance.employee-advances.index'
        );
    }
}
