<?php

namespace App\Services;

use App\Models\Loan;

class LoanDeductionService
{
    /**
     * Calculate monthly loan deduction for an employee based on the payroll month.
     *
     * @param  string  $payrollMonth  Format 'YYYY-MM'
     * @return array Array of loan deduction payloads for the payroll snapshot
     */
    public function calculateForEmployee(int $employeeId, string $payrollMonth): array
    {
        $deductions = [];

        $activeLoans = Loan::where('employee_id', $employeeId)
            ->where('status', 'approved')
            ->where('remaining_balance', '>', 0)
            ->where('start_month', '<=', $payrollMonth)
            ->get();

        foreach ($activeLoans as $loan) {
            $deductionAmount = min((float) $loan->installment_amount, (float) $loan->remaining_balance);

            if ($deductionAmount > 0) {
                $deductions[] = [
                    'name' => 'Loan Installment',
                    'loan_id' => $loan->id,
                    'amount' => round($deductionAmount, 2),
                ];
            }
        }

        return $deductions;
    }
}
