<?php

namespace App\Http\Controllers;

use App\Models\Meeting;
use App\Models\MeetingParticipant;
use Illuminate\Http\Request;
use App\Models\Pro;
use Illuminate\Support\Facades\DB;

class ProController extends Controller
{

    public function dashboard(Request $request){
        return view('pro.dashboard', ['sessionKey' => $request->cookie('sessionKey')]);
    }

    public function index(){
        $pros = Pro::all();
        return view('pro.index', compact('pros'));
    }

    public function create(){
        return view('pro.create');
    }

    public function show($uid, Request $request){
        $pro = Pro::where('uid', $uid)->first();
        return view('pro.show', compact('pro'));
    }

    public function meeting(Request $request, $meetingID) {
        $meeting = Meeting::where('uid', $meetingID)->first();
        if(!$meeting) {
            return abort(404, "Meeting no longer active");
        }
        $participants = MeetingParticipant::where('meeting_id', $meeting->id)->get();
        foreach ($participants as $participant) {
            $participant->proName = $participant->proName(); // eager-fill proName
        }
        return view('meeting', [
            'meetingID' => $meetingID,
            'participants' => $participants,
            'guest' => false
        ]);
    }

    public function meet(Request $request, $uid = false) {
        $session = DB::table('app_session')->where('session_key', $request->cookie('sessionKey'))->first();
        $pro = false;
        if($session && $session->pro_id) {
            $pro = DB::table('pro')->where('id', $session->pro_id)->first();
        }
        $client = null;
        if(!empty($uid)) {
            $client = DB::table('client')->where('uid', $uid)->first();
        }
        else if($pro->in_meeting_with_client_id) {
            $client = DB::table('client')->where('id', $pro->in_meeting_with_client_id)->first();
        }
        return view('pro-call', [
            'guest' => false,
            'session' => $session,
            'pro' => $pro,
            'client' => $client
        ]);
    }

    public function getOpentokSessionKey(Request $request, $uid) {
        $client = DB::table('client')->where('uid', $uid)->first();
        return json_encode([
            "data" => $client->opentok_session_id
        ]);
    }

}
