<?php

namespace App\Http\Controllers;

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

class NastaveniWuController extends Controller
{
    public function index()
    {
        $data = new WuDefinicePristupu();
        return view('NastaveniWu.nastaveniWu',['dataC' => $data->getData(),'menu' => Menu::getData()]);
    }

    public function edit(WuDefinicePristupu $data)
    {
        return view('NastaveniWu.nastaveniWuEdit',['data' => $data,'menu' => Menu::getData()]);
    }
    public function update(Request $request,WuDefinicePristupu $data)
    {
        $request->except('_token');
        $dataValidate = $this->validatorPristupu($request);
        if ($dataValidate->fails())
        {
            return redirect()->back()->withErrors($dataValidate->errors())->with('message-fail', 'Nastala chyba nevyplněním obou políček');
        }

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

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

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

        if ($data->fails())
        {
            return redirect()->back()->withErrors($data->errors())->with('message-fail', 'Nastala chyba nevyplněním obou políček');
        }
        WuDefinicePristupu::create([
            'id_wu_station' => $request->get('id_wu_station'),
            'pass' => $request->get('pass'),
            'id_stanice' => $request->get('id_stanice'),
        ])->save();
        return redirect()->route('nastaveniWu-index')->with('message', 'Přístup vytvořen');
    }

    protected function validatorPristupu(Request $data)
    {
        return Validator::make($data->all(), [
            'id_wu_station' => ['required'],
            'pass' => ['required'],
        ]);
    }

    public function export($request)
    {
        $n = new ExportToWUController();
        $n->requestToWU((int)$request);
        return redirect()->route('nastaveniWu-index')->with('message', 'Požadevek odeslán');
    }


    public function delete(WuDefinicePristupu $data)
    {
        try
        {
            $data->delete();
        }
        catch (Exception $e)
        {
            return redirect()->route('nastaveniWu-index')->with('message','Vyskytla se chyba'.$e);
        }
        return redirect()->route('nastaveniWu-index')->with('message','Veličina smazána');
    }
}
