<?php

namespace Modules\Payroll\Repositories;

use Modules\Payroll\DTO\EmployeeAdvancesFilter;
use Modules\Payroll\Enums\EmployeeAdvancesStatusEnum;
use Modules\Payroll\Models\EmployeeAdvance;

class EmployeeAdvanceRepository
{
    public function all(EmployeeAdvancesFilter $filter, array $columns = ['*'], array $relationships = [])
    {
        return EmployeeAdvance::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 EmployeeAdvance::findOrFail($id);
    }

    public function create(array $data)
    {
        return EmployeeAdvance::create([
            'employee_id'           => $data['employee_id'],
            'advance_no'              => $data['advance_no'],
            'advance_amount'          => $data['advance_amount'],
            'remaining_amount'       => $data['remaining_amount'],
            'installment_months'     => $data['installment_months'],
            'monthly_deduction'      => $data['monthly_deduction'],
            'paid_installments'      => $data['paid_installments'] ?? 0,
            'issue_date'              => $data['issue_date'],
            'start_deduction_date'    => $data['start_deduction_date'],
            'remarks'                 => $data['remarks'] ?? null,
        ]);
    }

    public function update(EmployeeAdvance $employeeAdvance, array $data)
    {
        $employeeAdvance->update([
            'advance_amount'          => $data['advance_amount'],
            'remaining_amount'       => $data['remaining_amount'],
            'installment_months'     => $data['installment_months'],
            'monthly_deduction'      => $data['monthly_deduction'],
            'paid_installments'      => $data['paid_installments'] ?? 0,
            'issue_date'              => $data['issue_date'],
            'start_deduction_date'    => $data['start_deduction_date'],
            'remarks'                 => $data['remarks'] ?? null,
        ]);

        return $employeeAdvance;
    }
}
