<?php

namespace App\Modules\Payroll\Repositories;

use App\Modules\Payroll\Models\PayrollAdjustment;
use App\Modules\Payroll\Support\PayrollAdjustmentType;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
class PayrollAdjustmentRepository
{
    /**
     * @param  array<string, mixed>  $data
     */
    public function create(array $data): PayrollAdjustment
    {
        return PayrollAdjustment::query()->create($data);
    }

    public function sumSignedForEmployeePeriod(int $tenantId, int $employeeId, int $payrollPeriodId): string
    {
        $earnings = (float) PayrollAdjustment::query()
            ->where('tenant_id', $tenantId)
            ->where('employee_id', $employeeId)
            ->where('payroll_period_id', $payrollPeriodId)
            ->whereIn('type', PayrollAdjustmentType::earnings())
            ->sum('amount');
        $ded = (float) PayrollAdjustment::query()
            ->where('tenant_id', $tenantId)
            ->where('employee_id', $employeeId)
            ->where('payroll_period_id', $payrollPeriodId)
            ->where('type', PayrollAdjustmentType::DEDUCTION)
            ->sum('amount');

        return (string) round($earnings - $ded, 2);
    }

    public function deleteSystemOvertimeForEmployeePeriod(int $tenantId, int $employeeId, int $payrollPeriodId): void
    {
        PayrollAdjustment::query()
            ->where('tenant_id', $tenantId)
            ->where('employee_id', $employeeId)
            ->where('payroll_period_id', $payrollPeriodId)
            ->where('type', PayrollAdjustmentType::OVERTIME)
            ->where('reason', 'like', 'Auto OT%')
            ->delete();
    }

    public function paginateForPeriod(int $tenantId, int $payrollPeriodId, int $perPage = 30): LengthAwarePaginator
    {
        return PayrollAdjustment::query()
            ->where('tenant_id', $tenantId)
            ->where('payroll_period_id', $payrollPeriodId)
            ->with(['employee:id,full_name', 'creator:id,name'])
            ->orderByDesc('id')
            ->paginate($perPage)
            ->withQueryString();
    }

    /**
     * @return Collection<int, PayrollAdjustment>
     */
    public function listForEmployeePeriod(int $tenantId, int $employeeId, int $payrollPeriodId): Collection
    {
        return PayrollAdjustment::query()
            ->where('tenant_id', $tenantId)
            ->where('employee_id', $employeeId)
            ->where('payroll_period_id', $payrollPeriodId)
            ->orderBy('id')
            ->get();
    }
}
