<?php

namespace App\Repositories;

use App\Models\AppConfiguration;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Spatie\MediaLibrary\MediaCollections\Exceptions\FileDoesNotExist;
use Spatie\MediaLibrary\MediaCollections\Exceptions\FileIsTooBig;

/**
 * Class AppConfigurationRepository
 */
class AppConfigurationRepository extends BaseRepository
{
    public $fieldSearchable = [
        'key',
    ];

    /**
     * @inheritDoc
     */
    public function getFieldsSearchable()
    {
        return $this->fieldSearchable;
    }

    /**
     * @inheritDoc
     */
    public function model()
    {
        return AppConfiguration::class;
    }

    /**
     * @param  array  $input
     * @param  int  $userId
     *
     * @return void
     * @throws FileIsTooBig
     *
     * @throws FileDoesNotExist
     */
    public function update($input,$userId)
    {
        $inputArr = Arr::except($input, ['_token']);

        foreach ($inputArr as $key => $value) {

            /** @var AppConfiguration $appConfiguration */
            $appConfiguration = AppConfiguration::where('key', $key)->first();
          
            if (! $appConfiguration) {
                continue;
            }
          
            $appConfiguration->update(['value' => $value]);

            if (in_array($key, ['app_logo']) && ! empty($value)) {
                $appConfiguration->clearMediaCollection(AppConfiguration::APPLOGO);
                $media = $appConfiguration->addMedia($value)->toMediaCollection(AppConfiguration::APPLOGO, config('app.media_disc'));
                $appConfiguration->update(['value' => $media->getUrl()]);
            }

            if (in_array($key, ['floating_buttton_logo']) && ! empty($value)) {
                $appConfiguration->clearMediaCollection(AppConfiguration::FLOATINGBUTTON);
                $media = $appConfiguration->addMedia($value)->toMediaCollection(AppConfiguration::FLOATINGBUTTON, config('app.media_disc'));
                $appConfiguration->update(['value' => $media->getUrl()]);
            }
        }
    }
}
