<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Config;
use App\Models\User;
use Session;

class ConfigController extends Controller
{
  public static $permission_group = "Configurazione";
  public static $permissions = [
    'view-configurazione' => 'Vedi e modifica la configurazione',
  ];

  public function __construct()
  {
    $this->middleware('permission:view-configurazione')->only(['index', 'save']);
  }

  function index(){
    return view('config.index');
  }

  public function save(Request $request){
    $input = $request->all();
    // $index = 0;
    $index_file = 0;

    foreach($input['key'] as $key => $value){
      $config = Config::find($value);
      try{
        switch ($config->type) {
          case 'file':
          $file = $request->file('value');
          if($file != null && array_key_exists($key, $file)){
            $filename = $file[$key]->storeAs('public', $file[$key]->getClientOriginalName());
            $config->value = $filename;
            $index_file++;
          }
          break;

          case 'array_status':
          $config->value = json_encode($request->value[$key]);
          break;

          case 'users':
          $config->value = json_encode($request->value[$key]);
          break;

          case 'password':
          if($request->value[$key] != null && $request->value[$key] != ''){
            $config->value = $request->value[$key];
          }
          break;

          default:
          $config->value = $request->value[$key];
          // $index++;
          break;
        }
        $config->save();
      }catch(\Exception $e){

      }
    }

    Session::flash('flash_message', 'Configurazione aggiornata');
    return redirect()->route('config.index');
  }

}
