<?php

namespace App\Repositories;

use App\Models\AppConfiguration;
use App\Models\ExitPopupConfiguration;
use App\Models\SplashConfiguration;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Spatie\MediaLibrary\MediaCollections\Exceptions\FileDoesNotExist;
use Spatie\MediaLibrary\MediaCollections\Exceptions\FileIsTooBig;
use Symfony\Component\HttpKernel\Exception\UnprocessableEntityHttpException;

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

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

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


    public function store($input)
    {
        try {
            DB::beginTransaction();
            $inputArr = Arr::except($input, ['_token']);
            $inputArr['enable_Image'] = isset($input['enable_Image']) ? 1 : 0;

            foreach ($inputArr as $key => $value) {
                $button = ExitPopupConfiguration::where('key', $key)->first();
                if (!$button) {
                    continue;
                }
                $button->update(['value' => $value]);

                if (in_array($key, ['Image']) && !empty($value)) {

                    $button->clearMediaCollection(ExitPopupConfiguration::IMAGE);
                    $media = $button->addMedia($value)->toMediaCollection(ExitPopupConfiguration::IMAGE,
                        config('app.media_disc'));
                    $button->update(['value' => $media->getUrl()]);
                }
            }


            DB::commit();

            return true;
        } catch (\Exception $e) {
            DB::rollBack();

            return new UnprocessableEntityHttpException($e->getMessage());
        }
    }
}
