<?php

namespace App\Repositories;

use App\Models\AppConfiguration;
use App\Models\FloatingButton;
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 FloatingButtonRepository extends BaseRepository
{
    public $fieldSearchable = [
        'title',
    ];

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

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

    public function store($input)
    {
        try {
            DB::beginTransaction();
            $input['status'] = isset($input['status']);
            $button = FloatingButton::create($input);

            if (isset($input['floating_button_image']) && ! empty($input['floating_button_image'])) {
                $button->addMedia($input['floating_button_image'])
                    ->toMediaCollection(FloatingButton::FLOATING_BUTTON_IMAGE, config('app.media_disc'));
            }
            
            DB::commit();
            
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            
            return new UnprocessableEntityHttpException($e->getMessage());
        }
    }

    public function update($input,$id)
    {
        try {
            DB::beginTransaction();
            $floatingButton = FloatingButton::findOrFail($id);
            $input['status'] = isset($input['status']);
            $floatingButton->update($input);

            if (isset($input['floating_button_image']) && ! empty($input['floating_button_image'])) {
                $floatingButton->clearMediaCollection(FloatingButton::FLOATING_BUTTON_IMAGE);
                $floatingButton->addMedia($input['floating_button_image'])->toMediaCollection(FloatingButton::FLOATING_BUTTON_IMAGE,
                    config('app.media_disc'));
            }

            DB::commit();

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

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