<?php

namespace App\Modules\HR\Compensation\Repositories;

use App\Modules\HR\Compensation\Models\CompensationType;
use App\Modules\HR\Compensation\Models\EmployeeCompensationItem;

class CompensationRepository
{
    public function types(int $tenantId, string $kind)
    {
        return CompensationType::query()->from($this->table($kind))->where('tenant_id', $tenantId)->orderBy('name')->get();
    }

    public function createType(int $tenantId, string $kind, array $data): CompensationType
    {
        $model = new CompensationType;
        $model->setTable($this->table($kind));
        $model->fill($data + ['tenant_id' => $tenantId])->save();

        return $model;
    }

    public function updateType(int $tenantId, string $kind, int $id, array $data): CompensationType
    {
        $model = (new CompensationType)->setTable($this->table($kind))->newQuery()
            ->where('tenant_id', $tenantId)->findOrFail($id);
        $model->update($data);

        return $model;
    }

    public function deleteType(int $tenantId, string $kind, int $id): void
    {
        (new CompensationType)->setTable($this->table($kind))->newQuery()
            ->where('tenant_id', $tenantId)->findOrFail($id)->delete();
    }

    public function attach(int $tenantId, string $kind, array $data): EmployeeCompensationItem
    {
        return EmployeeCompensationItem::query()->create($data + ['tenant_id' => $tenantId, 'item_type' => $kind]);
    }

    public function recurringTotals(int $tenantId, int $employeeId, float $salary, string $start, string $end): array
    {
        $items = EmployeeCompensationItem::query()->where('tenant_id', $tenantId)->where('employee_id', $employeeId)
            ->where('is_active', true)->whereDate('effective_from', '<=', $end)
            ->where(fn ($q) => $q->whereNull('effective_to')->orWhereDate('effective_to', '>=', $start))->get();
        $totals = ['allowance' => 0.0, 'deduction' => 0.0];
        foreach ($items as $item) {
            $type = (new CompensationType)->setTable($this->table($item->item_type))->newQuery()->find($item->type_id);
            if ($type?->is_active && $type->is_recurring) {
                $totals[$item->item_type] += $type->calculation_type === 'percentage'
                    ? $salary * ((float) ($item->percentage ?? 0) / 100) : (float) ($item->amount ?? $type->default_amount);
            }
        }

        return $totals;
    }

    private function table(string $kind): string
    {
        return $kind === 'allowance' ? 'hr_allowance_types' : 'hr_deduction_types';
    }
}
