<?php

namespace Modules\Setting\Repositories;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Modules\Setting\Interfaces\SettingRepositoryInterface;
use Modules\Setting\Models\Setting;
use Modules\User\Models\Module;

class SettingRepository implements SettingRepositoryInterface
{

    public function get(Request $request)
    {
        $settings = Setting::cursor();
        return $settings;
    }

    public function getItem(Setting $setting)
    {
        return $setting ;
    }

    //
    public function save(Request $request):void
    {
        $this->saveData($request);
    }

    private function saveData(Request $request ) :void
    {
        $data = $request->all();
        $userRole = Auth::user()->role;

        !$request->has('website_disable') && $userRole == 'super_admin' ? $data['website_disable'] = 0 : 1;
        !$request->has('dashboard_disable') && $userRole == 'super_admin' ? $data['dashboard_disable'] = 0 : 1;

        if ($request->has('update')){
            foreach ($data as $key => $value) {

                Setting::where('key', $key)->update([
                    'value' => $value
                ]);

            }
        } else {
            foreach ($data as $key => $value) {
                Setting::create([
                    'key' => $key,
                    'value' => $value,
                ]);
            }
        }
    }
    public function modules(Request $request):void
    {
        $fields = $request->fields;
        $moduleName = $request->module_name;

        $data = array_merge_recursive($moduleName, $fields);

        foreach ($data as $path => $field) {
            Module::where('path', $path)->update([
                'meta' => $field
            ]);
        }
    }

}
