<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Models\SettingManagement\Setting;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\Valuestore\Valuestore;

class SettingController extends Controller{
    public function __construct(){

        $this->middleware('permission:setting-list')
            ->only(["index"]);

        $this->middleware('permission:setting-show')
            ->only(["show"]);

        $this->middleware('permission:setting-create')
            ->only(["store"]);

        $this->middleware('permission:setting-update')
            ->only(['update',"edit"]);

    }


    public function index(): View{
        $section = (isset(request()->section) && request()->section != '') ? request()->section : 'General';
        $setting_sections = Setting::select('section')->distinct()->pluck('section');
        $settings = Setting::get();
        //$settings = Setting::whereSection($section)->get();

        return view('backend.settings.index', compact('section', 'setting_sections', 'settings'));
    }

    public function update(Request $request): RedirectResponse{
        for ($i = 0; $i < count($request->id); $i++) {
            $input['value'] = $request->value[$i] ?? null;
            Setting::find($request->id[$i])->update($input);
        }
        $this->generateCache();

        return redirect()->route('admin.settings.index')->with([
            'message' => action_message("update"),
            'alert-type' => 'success'
        ]);
    }

    public function edit(Request $request){

        $response = [
            'message' => __("No Edit"),
            'success' => false,
        ];

        DB::beginTransaction();
        try {
            $data = $request->all();
           // dd($data);
            Setting::upsert($data,['id',"key"]);
            DB::commit();
            $response['success'] = true;
            $response['message'] = __("All settings updated.");
            $this->generateCache();
        }catch (\Exception $exception){
            DB::rollBack();
            $response['message'] = $exception->getMessage();
            $response['exception'] = $exception;

        }

        return response()->json($response);
    }

    private function generateCache(){
        $settings = Valuestore::make(config_path('settings.json'));

        Setting::all()->each(function ($item) use ($settings) {
            $settings->put($item->key, $item->value);
        });
    }
}
