<?php

namespace App\Http\Controllers;

use App\ApiAuth;
use App\Menu;
use App\Mqtt_data_request;
use App\Stanice;
use Exception;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class ApiController extends Controller
{
    public const API_USER = 2;

    public function validateApi(Request $request, $idStanice)
    {

        $data = $request->all();
        if(ApiAuth::authUser($request->server()['PHP_AUTH_USER'],$request->server()['PHP_AUTH_PW']))
        {
            $n = new AutomatickeBanovaniController();

            if(isset($idStanice) && is_numeric($idStanice) && ($n->banChecker($idStanice) && Stanice::isBanned($idStanice)[0]->ban === 0))
            {
                return $request->isJson($data) ? $this->saveToDB($data, $idStanice) : response()->json(['msg' => 'Invalid json string'], 400);
            }

            return response()->json(['msg' => 'Invalid ID station'],400);
        }

        return response()->json(['msg' => 'Unauthorized'],401);


    }

    private function saveToDB($data, $idStanice)
    {
        try {
            Stanice::staniceExist($idStanice, self::API_USER);
        } catch (Exception $e) {
            dump( $e);
        }
        $db = new Mqtt_data_request(['id_stanice'=>$idStanice,'topic'=>'data', 'data'=>json_encode($data), 'vlozil' => self::API_USER]);
        if($db->save())
        {
            return response()->json(['msg' => 'Data saved'], 201);
        }

        return response()->json(['msg' => 'Save failed'], 400);
    }




    public function index()
    {
        return view('NastaveniAuthApi.apiAuth',['menu' => Menu::getData()]);
    }

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

    public function edit(ApiAuth $idapi_auth)
    {
        return view('NastaveniAuthApi.apiAuthEdit', ['define' => $idapi_auth,'menu' => Menu::getData() ]);
    }

    /**
     * @param Request $request
     * @param ApiAuth $idapi_auth
     * @return RedirectResponse
     */
    public function update(Request $request, ApiAuth $idapi_auth): RedirectResponse
    {
        $request->except('_token');
        $data = $this->validatorR($request);
        if ($data->fails())
        {
            return redirect()->back()->with('message-fail', 'Jméno nebo heslo nebylo vyplněno správně');
        }

        $idapi_auth->update($request->all());
        return redirect()->route('apiAuth-index')->with('message', 'Přístup upraven');
    }

    public function create(Request $request): RedirectResponse
    {
        $data = $this->validatorR($request);
        if ($data->fails())
        {
            return redirect()->back()->with('message-fail', 'Jméno nebo heslo nebylo vyplněno správně');
        }

        ApiAuth::create([
            'nazev' => $request->get('nazev'),
            'user' => $request->get('user'),
            'password' => $request->get('password'),
        ])->save();

        return redirect()->route('apiAuth-index')->with('message','Přístup vytvořen');
    }

    public function delete(ApiAuth $idapi_auth)
    {
        try
        {
            $idapi_auth->delete();
        }
        catch (Exception $e)
        {
            return redirect()->route('apiAuth-index')->with('message','Vyskytla se chyba'.$e);
        }
        return redirect()->route('apiAuth-index')->with('message','Přístup smazán');

    }

    protected function validatorR(Request $data)
    {
        return Validator::make($data->all(), [
            'user' => ['required'],
            'password' => ['required', 'string', 'min:8'],
        ]);
    }

}
