<?php

namespace App\Repositories;

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

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

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

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

    /**
     * @param $input
     *
     *
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|void
     */
    
    public function update($input,$id)
    {
        $inputArr = Arr::except($input, ['_token']);
        $inputArr['enable_splash_logo'] = isset($inputArr['enable_splash_logo']) ? '1' : '0';
        $inputArr['enable_splash_title'] = isset($inputArr['enable_splash_title']) ? '1' : '0';
        $inputArr['enable_splash_background'] = isset($inputArr['enable_splash_background']) ? '1' : '0';
        foreach ($inputArr as $key => $value) {


            /** @var SplashConfiguration $splashConfiguration */
            $splashConfiguration = SplashConfiguration::where('key', $key)->first();
            if (! $splashConfiguration) {
                continue;
            }

            $splashConfiguration->update(['value' => $value]);
            if (in_array($key, ['splash_logo']) && ! empty($value)) {
                $splashConfiguration->clearMediaCollection(SplashConfiguration::SPLASH_LOGO);
                $media = $splashConfiguration->addMedia($value)->toMediaCollection(SplashConfiguration::SPLASH_LOGO, config('app.media_disc'));
                $splashConfiguration->update(['value' => $media->getUrl()]);
            }

            if (in_array($key, ['splash_background']) && ! empty($value)) {
                $splashConfiguration->clearMediaCollection(SplashConfiguration::SPLASH_BACKGROUND);
                $media = $splashConfiguration->addMedia($value)->toMediaCollection(SplashConfiguration::SPLASH_BACKGROUND, config('app.media_disc'));
                $splashConfiguration->update(['value' => $media->getUrl()]);
            }
        }
 
    }
}
