<?php

namespace Modules\HR\Repositories;

use Modules\Core\Enums\StatusEnum;
use Modules\HR\DTO\HrSettingFilter;
use Modules\HR\Models\LeavePolicy;
use Modules\HR\Models\SalaryStructureItem;

class SalaryStructureItemRepository
{

    public function createItems(array $payload): void
    {
        SalaryStructureItem::insert($payload);
    }


    public function all(HrSettingFilter $filter, $columns = ['*'])
    {
        return SalaryStructureItem::query()
            ->filterStatus($filter->status)
            ->select($columns)
            // ->search($filter->search)
            ->paginate($filter->perPage ?? 15);
    }

    public function find($id)
    {
        return SalaryStructureItem::with(['salaryComponent:id,name,code', 'salaryStructure:id,name'])->findOrFail($id);
    }

    public function create(array $data)
    {
        return SalaryStructureItem::create([
            'salary_structure_id'  => $data['salary_structure_id'],
            'salary_component_id'  => $data['salary_component_id'],
            'use_default_rule'     => $data['use_default_rule'] ?? false,
            'calculation_type'     => $data['calculation_type'],
            'amount'               => $data['amount'] ?? null,
            'percentage'           => $data['percentage'] ?? null,
            'formula'              => $data['formula'] ?? null,
            'calculation_basis'    => $data['calculation_basis'] ?? null,
            'status'               => $data['status'] ?? StatusEnum::ACTIVE,
        ]);
    }


    public function update(SalaryStructureItem $salaryStructureItem, array $data)
    {
        $salaryStructureItem->update([
            'salary_structure_id' => $data['salary_structure_id'],
            'salary_component_id' => $data['salary_component_id'],
            'use_default_rule' => $data['use_default_rule'] ?? false,
            'calculation_type' => $data['calculation_type'],
            'amount' => $data['amount'] ?? 0,
            'percentage' => $data['percentage'] ?? null,
            'formula' => $data['formula'] ?? null,
            'calculation_basis' => $data['calculation_basis'] ?? null,
            'status' => $data['status'] ?? StatusEnum::ACTIVE,
        ]);
        return $salaryStructureItem->fresh();
    }

    public function updateStatus(SalaryStructureItem $salaryStructureItem, array $status)
    {
        $salaryStructureItem->update([
            'status' => $status['status'] ?? StatusEnum::ACTIVE,
        ]);

        return $salaryStructureItem;
    }
}
