<?php

namespace App\Modules\HR\Loans\Repositories;

use App\Modules\HR\Loans\Models\Loan;
use App\Modules\HR\Loans\Models\LoanInstallment;
use Carbon\Carbon;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;

class LoanRepository
{
    public function paginate(int $tenantId, ?int $employeeId = null): LengthAwarePaginator
    {
        return Loan::query()->with(['employee:id,full_name', 'installments'])
            ->where('tenant_id', $tenantId)
            ->when($employeeId, fn ($q) => $q->where('employee_id', $employeeId))
            ->latest()->paginate();
    }

    public function create(array $data): Loan
    {
        return Loan::query()->create($data);
    }

    public function update(Loan $loan, array $data): Loan
    {
        $loan->update($data);

        return $loan->fresh('installments');
    }

    public function deductionForPeriod(int $tenantId, int $employeeId, string $start, string $end, int $periodId): float
    {
        return (float) LoanInstallment::query()
            ->whereHas('loan', fn ($q) => $q
                ->where('tenant_id', $tenantId)
                ->where('employee_id', $employeeId)
                ->whereIn('status', ['approved', 'active', 'partially_paid']))
            ->whereBetween('due_date', [Carbon::parse($start), Carbon::parse($end)])
            ->where('status', 'pending')->where(fn ($q) => $q->whereNull('payroll_period_id')->orWhere('payroll_period_id', $periodId))
            ->sum('amount');
    }
}
