<?php

namespace App\Classes\Modules\Affiliate\Services;

use App\Classes\Modules\Affiliate\DataTransferObjects\AffiliateSettingsObject;
use App\Models\KeyValuePair;

class UpdatesAffiliateSettings
{
    const SETTING_KEY = 'affiliate_code_binding_days';

    /**
     * @param AffiliateSettingsObject $object
     * @return array
     */
    public function execute(AffiliateSettingsObject $object): array
    {
        $keyValuePair = KeyValuePair::where('key', self::SETTING_KEY)
            ->whereNull('owner_type')
            ->whereNull('owner_id')
            ->first();

        if ($keyValuePair) {
            $keyValuePair->value = (string) $object->getCodeBindingDays();
            $keyValuePair->save();
        } else {
            $keyValuePair = new KeyValuePair();
            $keyValuePair->key = self::SETTING_KEY;
            $keyValuePair->value = (string) $object->getCodeBindingDays();
            $keyValuePair->owner_type = null;
            $keyValuePair->owner_id = null;
            $keyValuePair->save();
        }

        return [
            'code_binding_days' => $object->getCodeBindingDays()
        ];
    }
}

