<?php

namespace App\Http\Controllers;

use App\Menu;
use App\MqttTopic;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Auth;

class TopicController extends Controller
{
    public function index()
    {
        return view('NastaveniTopic.nastaveniTopic', ['dataC' => MqttTopic::all(),'menu' => Menu::getData()]);
    }

    public function updateServer(Request $request)
    {
        MqttTopic::where('aktivni', '=',1)->update(['aktivni' => 0]);
        $emailSettings = MqttTopic::find($request->all()['aktivni']);
        $emailSettings->aktivni = 1;
        $emailSettings->update();

        return redirect()->route('topic-index')->with('message', 'Změněno');
    }


    public function add()
    {
        return view('NastaveniTopic.nastaveniTopicAdd', ['menu' => Menu::getData()]);
    }

    public function create(Request $request)
    {
        $data = $this->validatorRequestu($request);

        if ($data->fails())
        {
            return redirect()->back()->withErrors($data->errors())->with('message-fail', 'Něco se nepovedlo :( ');
        }
        MqttTopic::create([
            'nazev' => $request->get('nazev'),
            'topic' => $request->get('topic'),
            'vlozil' => Auth::user()->id,
        ])->save();

        return redirect()->route('topic-index')->with('message', 'Nastavení vytvořeno');
    }

    protected function validatorRequestu(Request $data)
    {
        return Validator::make($data->all(), [
            'nazev' => ['required', 'string'],
            'topic' => ['required','string'],
        ]);
    }

    public function delete(MqttTopic $idmqtt_topic)
    {
        try
        {
            $idmqtt_topic->delete();
        }
        catch (Exception $e)
        {
            return redirect()->route('topic-index')->with('message-fail','Vyskytla se chyba'.$e);
        }
        return redirect()->route('topic-index')->with('message','Nastavení smazáno');
    }


    public function edit(MqttTopic $idmqtt_topic)
    {
        return view('NastaveniTopic.nastaveniTopicEdit',['dataC' => $idmqtt_topic,'menu' => Menu::getData()]);
    }

    public function update(Request $request, MqttTopic $idmqtt_topic)
    {
        $request->except('_token');
        $request->merge(['vlozil' => Auth::user()->id]);
        $dataValidate = $this->validatorRequestu($request);
        if ($dataValidate->fails())
        {
            return redirect()->back()->withErrors($dataValidate->errors())->with('message-fail', 'Něco se nepovedlo :(');
        }

        $idmqtt_topic->update($request->all());
        return redirect()->route('topic-index')->with('message', 'Nastavení upraveno');
    }
}
