<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Settings;
use App\Exceptions\GlobalException;


class ConfigController extends Controller
{
     /**
     * 
     */
    public function view(Request $request){
        try{
            $settings = Settings::all();
            return view("view-config",[
                "settings"=>$settings
            ]);
        }catch(Throwable $th){
            throw new GlobalException($th->getMessage());
        }
    }
    
    /**
     * 
     */
    public function create(Request $request){
       try {
            $data = $request->all();
            $isValidArrayId = (isset($data["id"]) &&  (count($data["id"]) > 0));
            $isValidArrayKey = (isset($data["key"]) &&  (count($data["key"]) > 0));
            $isValidArrayValue = (isset($data["value"]) &&  (count($data["value"]) > 0));
            $isDataValid = (($isValidArrayId) && ($isValidArrayKey) && ($isValidArrayValue));
            if($isDataValid){
                for($i = 0; $i < count($data["id"]); $i++){
                    $model = new Settings();
                    if((trim($data["id"][$i])) !== "" && (trim($data["key"][$i]) !== "") && (trim($data["value"][$i]) !== "")){
                        if($data["id"][$i] !== "new")
                            $model = $model->find($data["id"][$i]);
                        else
                            $model->id = md5(md5($data["key"][$i] . md5($data["value"][$i])));
                        $model->key = $data["key"][$i];
                        $model->value = $data["value"][$i];
                        $model->save();
                    }  
                }
            }
            return redirect()->route("/admin/view-config");
       } catch (Throwable $th) {
        throw new GlobalException($th->getMessage());
       }
    }
}
