<?php

namespace app\themes\svo\services;

use kernel\App;
use kernel\helpers\Debug;
use kernel\models\Option;
use kernel\modules\option\service\OptionService;

class MainPageSliderService
{
    protected OptionService $optionService;
    protected string $sliderKey = 'main_news_slider';

    public function __construct()
    {
        $this->optionService = new OptionService();
    }

    /**
     * Получить список слайдов
     *
     * @return array
     */
    public function getSlides(): array
    {
        $option = Option::where('key', $this->sliderKey)->first();

        if (!$option || empty($option->value)) {
            return [];
        }

        $data = json_decode($option->value, true);

        return $data['ids'] ?? [];
    }

    /**
     * Добавить слайд
     *
     * @param int $slideId
     * @return bool
     */
    public function addSlide(int $slideId): bool
    {
        return App::$db->capsule::connection()->transaction(function () use ($slideId) {
            $option = Option::firstOrNew(['key' => $this->sliderKey]);

            $currentValue = $option->value ? json_decode($option->value, true) : ['ids' => []];

            if (in_array($slideId, $currentValue['ids'])) {
                return true; // слайд уже есть, ничего не делаем
            }

            $currentValue['ids'][] = $slideId;
            $option->value = json_encode($currentValue);

            return $option->save();
        });
    }

    /**
     * Удалить слайд
     *
     * @param int $slideId
     * @return bool
     */
    public function removeSlide(int $slideId): bool
    {
        return App::$db->capsule::connection()->transaction(function () use ($slideId) {
            /** @var Option $option */
            $option = Option::where('key', $this->sliderKey)->first();

            if (!$option || empty($option->value)) {
                return false;
            }

            $currentValue = json_decode($option->value, true);

            if (!in_array($slideId, $currentValue['ids'] ?? [])) {
                return false; // слайда нет в списке
            }

            $currentValue['ids'] = array_diff($currentValue['ids'], [$slideId]);
            $option->value = json_encode($currentValue);

            return $option->save();
        });
    }
}