<?php

namespace Modules\Setting\Services;

use App\Services\Upload\UploadService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Setting\Models\Setting;
use Modules\Setting\Interfaces\SettingRepositoryInterface;

class SettingService
{
    private SettingRepositoryInterface $settingRepository;

    public function __construct(SettingRepositoryInterface $settingRepository)
    {
        $this->settingRepository = $settingRepository;
    }

    public function get(Request $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 save(Request $request): void
    {
        $data = $request->all();
        $currentSettings = (array) app('site_settings');
        if ($request->website_logo) {
            $oldPhoto = 'logo.png' != $currentSettings['website_logo'] ? $currentSettings['website_logo'] : null;
            $data['website_logo'] = UploadService::upload($request->website_logo, $oldPhoto, 'settings');
        }

        if ($request->website_favicon) {
            $oldFavicon = 'favicon.ico' != $currentSettings['website_favicon'] ? $currentSettings['website_favicon'] : null;
            $data['website_favicon'] = UploadService::upload($request->website_favicon, $oldFavicon, 'settings');
        }
        // $this->settingRepository->save($request);


        $isAdmin = $request->user()->is_admin;
        !$request->has('website_disable') && $isAdmin ? $data['website_disable'] = 0 : 1;
        !$request->has('dashboard_disable') && $isAdmin ? $data['dashboard_disable'] = 0 : 1;
        // Get current settings (as array of key => value)

        // Filter to keep only changed values
        $updates = [];
        foreach ($data as $key => $value) {
            if (array_key_exists($key, $currentSettings) && $currentSettings[$key] != $value) {
                $updates[$key] = $value;
            }
        }
        // dd($updates, $data, $currentSettings);
        // DB::enableQueryLog();
        $this->settingRepository->save($updates);
        // dd(DB::getQueryLog());
    }
    public function modules(Request $request): void
    {
        $this->settingRepository->modules($request);
    }
    public function getAll()
    {
        $settings = $this->settingRepository->getAll();
        return array_column($settings, 'value', 'key');
    }
}
