<?php

namespace Modules\Setting\Services;

use App\Services\Upload\FileService;
use Modules\MainService\Views\ViewFactory;
use Modules\Setting\Interfaces\SettingRepositoryInterface;

class SettingService
{
    public function __construct(
        private SettingRepositoryInterface $settingRepository,
        private ViewFactory $viewFactory
    ){}

    public function renderView($request = [])
    {
        $request['countries'] = $this->get($request);
        return $this->render($request);
    }

    public function render($request = [])
    {
        return $this->viewFactory
            ->render($request['view'])
            ->renderView($request);
    }
    public function get(array $request = [])
    {
        $settings= $this->settingRepository->get($request);

        if(count($settings) > 0){
            foreach ($settings as $setting) {
                $settings->{$setting['key']} = $setting['value'];
            }
        } else {
            $settings = null;
        }

        return $settings;
    }

    public function getItemByKey($key)
    {
        return $this->settingRepository->getItemByKey($key);
    }

    public function save(array $request):void
    {
        foreach ($request as $key => $value)
        {
            if(in_array($key, ['intro_home','intro_admins','intro_employees','intro_sectors','intro_countries','intro_contact_lists','intro_deals','intro_companies','intro_products','intro_targets','intro_categories','intro_daily_logs','intro_regions','intro_settings']))
            {
                if ($value)
                {
                    if(is_file($value))
                    {
                        $value = FileService::uploadVideo($value);
                    }
                }
                else
                {
                    $value = $this->getItemByKey($key);
                }
            }
            $this->settingRepository->save([
                'key' => $key,
                'value' => $value
            ]);

        }
    }

}
