<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use App\HttpModels\ClientLobbyModel;
use App\HttpModels\MeetingModel;
use App\Models\AppSession;

use Cookie;

use App\Models\Lobby;

class ClientController extends Controller
{

    // GET /care_months

	public function entranceLobby(Request $request, Lobby $lobby) {
        if (!$lobby->id || !$lobby->is_stranger_accessible) {
            \abort(404);
            return;
        }

        $sessionKey = Cookie::get('sessionKey');

        $lobbyModel = new ClientLobbyModel($lobby);
        // $response = response()->view('client/index',compact('lobbyModel'),200);

        if(!$sessionKey){
            $loginUrl = env('BACKEND_URL', 'http://localhost:8080') . '/api/session/createStrangerSession';

            $httpResponse = Http::asForm()->post($loginUrl)->json();

            if(!$httpResponse['success']){
                return back()->with("message", $httpResponse['message']);
            }

            $sessionKey = $httpResponse['data'];

            // $cookie = cookie()->forever('sessionKey', $sessionKey, '/');

            cookie()->queue('sessionKey', $sessionKey, 1440, '/');

            // $response = new \Illuminate\Http\Response(view('client/index'));
            // $response->withCookie($cookie);
            // return $response;
        }
        // else {
        //     return view('client/index');
        // }
        $session = AppSession::where("session_key",$sessionKey)->first();
        $meeting = null;
        if ($session->meetingParticipant 
                && $session->meetingParticipant->meeting->is_active
                && ($session->meetingParticipant->meeting->lobby_id === $lobby->id || $session->meetingParticipant->meeting->lobby_id == null) ) {
            $meeting = new MeetingModel($session->meetingParticipant->meeting);
        }
        return view('client/index',compact('lobbyModel','meeting','sessionKey'));
	}
}