<?php
namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;

class OpenAudioMCController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware(['auth', 'verified', '2fa']);
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Contracts\Support\Renderable
     */
    public function index()
    {
        $url = env('OPENAUDIOMC_URL', '');
        if(empty($url))
            return  view('openaudiomc')->with(['type' => 1]);

        if(!filter_var($url, FILTER_VALIDATE_URL))
            return  view('openaudiomc')->with(['type' => 1]);

        $key = explode('/', $url);
        $key = $key[count($key) - 1];
        if(!preg_match('/^([a-zA-Z0-9]{8})\-([a-zA-Z0-9]{4})\-([a-zA-Z0-9]{4})\-([a-zA-Z0-9]{4})\-([a-zA-Z0-9]{12})$/', $key))
            return view('openaudiomc')->with(['type' => 1]);

        $url = str_replace('%UUID%', Auth::user()->fixedUUID(), $url);
        $result = file_get_contents($url);
        if(!$this->isJson($result))
            return view('openaudiomc')->with(['type' => 1]);

        $json = json_decode($result);
        if(isset($json->errors) && !empty($json->errors))
            return  view('openaudiomc')->with(['type' => 2]);

        if(!isset($json->response))
            return  view('openaudiomc')->with(['type' => 2]);

        $response = $json->response;
        if(!isset($response->isConnected) || !isset($response->sessionUrl))
            return  view('openaudiomc')->with(['type' => 2]);

        if($response->isConnected)
            return view('openaudiomc')->with(['type' => 3]);

        $link = $json->response->sessionUrl;
        header('Location: '.$link);
        exit;
    }

    private function isJson($string) {
        if(empty($string))
            return false;

        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }

}