<?php

namespace Modules\Payroll\Repositories;

use Modules\Payroll\DTO\EmployeeLoansFilter;
use Modules\Payroll\Enums\EmployeeLoansStatusEnum;
use Modules\Payroll\Models\EmployeeLoan;

class EmployeeLoanRepository
{
    public function all(EmployeeLoansFilter $filter, array $columns = ['*'], array $relationships = [])
    {
        return EmployeeLoan::query()
            ->select($columns)
            ->with($relationships)
            ->search($filter->search)
            ->filterByStatus($filter->status)
            ->dateRange($filter->from_date, $filter->to_date)
            ->orderBy('issue_date', 'desc')
            ->paginate($filter->perPage ?? 15);
    }

    public function find($id)
    {
        return EmployeeLoan::findOrFail($id);
    }

    public function create(array $data)
    {
        return EmployeeLoan::create([
            'employee_id'           => $data['employee_id'],
            'loan_no'                => $data['loan_no'],
            'loan_type'              => $data['loan_type'] ?? null,
            'principal_amount'       => $data['principal_amount'],
            'interest_rate'          => $data['interest_rate'] ?? 0,
            'installment_months'     => $data['installment_months'],
            'interest_amount'        => $data['interest_amount'],
            'total_payable'          => $data['total_payable'],
            'remaining_amount'       => $data['remaining_amount'],
            'monthly_installment'    => $data['monthly_installment'],
            'issue_date'              => $data['issue_date'],
            'start_deduction_date'    => $data['start_deduction_date'],
            'remarks'                 => $data['remarks'] ?? null,
        ]);
    }

    public function update(EmployeeLoan $employeeLoan, array $data)
    {
        $employeeLoan->update([
            'loan_type'              => $data['loan_type'] ?? null,
            'principal_amount'       => $data['principal_amount'],
            'interest_rate'          => $data['interest_rate'] ?? 0,
            'installment_months'     => $data['installment_months'],
            'interest_amount'        => $data['interest_amount'],
            'total_payable'          => $data['total_payable'],
            'remaining_amount'       => $data['remaining_amount'],
            'monthly_installment'    => $data['monthly_installment'],
            'issue_date'              => $data['issue_date'],
            'start_deduction_date'    => $data['start_deduction_date'],
            'remarks'                 => $data['remarks'] ?? null,
        ]);

        return $employeeLoan->fresh();
    }
}
