<?php
declare(strict_types=1);

namespace App\Service\Utils;

use App\Attribute\BillingSettingDefaultValue;
use App\Attribute\OrganizationDefaultValue;
use App\Entity\Access\Access;
use ReflectionClass;
use ReflectionException;

/**
 * Class EntityUtils : Gestion des valeurs par défauts devant être présentes dans les entités.
 * @package App\Service\Utils
 */
class EntityUtils
{
    /**
     * @throws ReflectionException
     */
    public function defaultValueSettersByAccess(mixed $entity, Access $access): void
    {
        $this->organizationDefaultValue($entity, $access);
        $this->billingSettingDefaultValueDefaultValue($entity, $access);
    }

    /**
     * @param mixed $entity
     * @param Access $access
     * @throws ReflectionException
     */
    protected function organizationDefaultValue(mixed $entity, Access $access): void
    {
        $reflection = new ReflectionClass($entity::class);
        $organizationFaultValue = $reflection->getAttributes(OrganizationDefaultValue::class)[0] ?? null;
        $fieldName = $organizationFaultValue?->getArguments()['fieldName'] ?? null;
        if($fieldName){
            $entity->{sprintf('set%s', ucfirst($fieldName))}(...[$access->getOrganization()]);
        }
    }

    /**
     * @param mixed $entity
     * @param Access $access
     * @throws ReflectionException
     */
    protected function billingSettingDefaultValueDefaultValue(mixed $entity, Access $access): void
    {
        $reflection = new ReflectionClass($entity::class);
        $billingSettingDefaultValueDefault = $reflection->getAttributes(BillingSettingDefaultValue::class)[0] ?? null;
        $fieldName = $billingSettingDefaultValueDefault?->getArguments()['fieldName'] ?? null;
        if($fieldName){
            $entity->{sprintf('set%s', ucfirst($fieldName))}(...[$access->getOrganization()?->getBillingSetting()]);
        }
    }
}
