<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\PeerToPeerVideoCall;
use App\Models\PeerToPeerVideoCallChat;
use Illuminate\Support\Facades\Session;
use App\Models\Organisation;
use App\Models\Video_Chat;
use App\Models\Education;
use App\Models\UserModel;
use App\Models\MeetingLinks;
use App\Models\StudentClassInfo;
use App\Models\Loby_Waiting_Clients;
use App\Models\Video_Call_Entry_Scheduling;
use App\Models\Video_Call_Entry_Classroom;
use App\Models\Chat_History;
use App\Models\VideoCallStatus;
use App\Models\VideoCallJoinUrl;
use App\Models\NormalMeetingLobyChat;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
class PeerToPeerVideoChat extends Controller
{

    public function PeerToPeerVideoCall(Request $request)
    {

        $session_emailId = Session::get('emailId');
        $receving_email_id = $request->email_id_Receving;
        $oneMinuteAgo = Carbon::now()->subMinute();
        $record = VideoCallStatus::where('email_id', $receving_email_id)
            ->where('updated_at', '>=', $oneMinuteAgo)
            ->first();

        if ($record) {
            $data = array("alreadyCalling" => true);
            print_r(json_encode($data));
        } else {
            $u_id = rand(10, 1000);

            $calling_profile_pic = $request->profile_image_calling;

            $caller_name = $request->caller_name;
            $caller_profile_pic = $request->caller_profile_image;
            $calling_name = $request->calling_name;
            $call_type = $request->call_type;
            $acountType = 'other';
            $length = 10;
            $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            $charactersLength = strlen($characters);
            $channelID = "";
            for ($i = 0; $i < $length; $i++) {
                $channelID .= $characters[random_int(0, $charactersLength - 1)];
            }
            $foundEntry = PeerToPeerVideoCall::where('Caller_Email', '=', $session_emailId)
                ->where('Receiver_Email', '=', $receving_email_id)
                ->first();
            if ($foundEntry) {
                $channelID = $foundEntry->Channel_Id;
                $foundEntry->is_call_read = false;
                $foundEntry->Is_Call_Accepted = false;
                // Update the updated_at timestamp
                $foundEntry->updated_at = now(); // or \Carbon\Carbon::now()

                $foundEntry->save();
            } else {

                PeerToPeerVideoCall::create([
                    'Caller_Email' => $session_emailId,
                    'Receiver_Email' => $receving_email_id,
                    'Caller_Profile_Pic' => $caller_profile_pic,
                    'Receiver_Profile_Pic' => $calling_profile_pic,
                    'Channel_Id' => $channelID,
                    'Caller_Full_Name' => $caller_name,
                    'Receiver_Full_Name' => $calling_name,
                    'Is_Call_Accepted' => false,
                    'user_id' => $u_id,
                ]);
            }


            $data =  array("channel_id" => $channelID);
            print_r(json_encode($data));
        }
    }

    public function CheckLobyWaitingClients(Request $request)
    {
        $channelId = $request->channelId;
        $session_emailId = Session::get('emailId');
        // $lobyWaitingUserInfo = Loby_Waiting_Clients::where('channel_id', $channelId)
        // ->where('user_email', '!=', $session_emailId)

        // ->get();

        // $user_email_add = "";
        // if ($lobyWaitingUserInfo) {
        //     foreach ($lobyWaitingUserInfo as $row) {
        //         $user_info = $this->returnUserInfo($row["user_email"]);
        //         $user_email_add = $row["user_email"];
        //         break;
        //     }
        // }

        $caller_data = PeerToPeerVideoCall::where('Channel_Id', '=',  $channelId)->where('Is_Call_Accepted', '=', true)->where('updated_at', '>', \Carbon\Carbon::now()->subMinutes(1))->get();
        if (count($caller_data) > 0) {
           foreach ($caller_data as $row) {
                $user_info = $this->returnUserInfo($row["Receiver_Email"]);
                $user_email_add = $row["Receiver_Email"];
                break;
            }
        }

        if (!empty($user_info)) {
            $data = array("user_name" => $user_info[1], "profile_pic" => $user_info[0], "user_eamil" => $user_email_add);
        } else {
            $data = array();
        }
        print_r(json_encode($data));
    }
    public function DeleteLobyWaitingClientEntry($channelId)
    {
        Loby_Waiting_Clients::where('channel_id', $channelId)->update(['is_accepted' => true]);
    }

    public function CheckCallerAcceptCall(Request $request)
    {
        $session_emailId = Session::get('emailId');
        $channelId = $request->channelId;


        $isMessageFound = false;
        $session_emailId = Session::get('emailId');
        $individualData = DB::table('Loby_Waiting_Clients as lwc')
            ->join('individuals as i', 'lwc.user_email', '=', 'i.email_id') // Join with individual table
            ->where('lwc.channel_id', $channelId)
            ->select('lwc.*', 'i.*') // Select from both Loby_Waiting_Clients and individuals table
            ->get();

        // Fetching data from organisations table if no match in individuals
        $organizationData = DB::table('Loby_Waiting_Clients as lwc')
            ->join('organisations as o', 'lwc.user_email', '=', 'o.email_id') // Join with organization table
            ->where('lwc.channel_id', $channelId)
            ->select('lwc.*', 'o.*') // Select from both Loby_Waiting_Clients and organisations table
            ->get();

            $latestMessage = NormalMeetingLobyChat::where('receiver_email', '=', $session_emailId)->where('channel_id', '=', $channelId)->orderBy('id', 'DESC')->get();
            $folderPath = "";
        if (count($latestMessage) > 0) {
            $isMessageFound = true;
            foreach ($latestMessage as $roww) {
                $folderPath = $roww["images_path"];
            }
        }

        $fileNames = [];
        if ($folderPath != "Not Uploaded") {
            if (strlen($folderPath) != 0) {
                $path = public_path($folderPath);
                $files = array_slice(scandir($path), 2);
                // Initialize an array to hold the file names
                // Loop through the scanned files
                foreach ($files as $file) {
                    // Exclude the current and parent directory references ('.' and '..')
                    if ($file !== '.' && $file !== '..') {
                        // Add the file name to the array
                        $fileNames[] = $file;
                    }
                }
            }
        }

        $isCallAccepted =  'no';

        $data = $individualData->merge($organizationData);


        $MeetingLinkData = DB::table('Loby_Waiting_Clients as lwc')
        ->join('meeting_links as m', 'lwc.user_email', '=', 'm.participant_email') // Join with organization table
        ->where('lwc.channel_id', $channelId)
        ->where('m.generated_link', $channelId)
        ->select('lwc.*', 'm.*') // Select from both Loby_Waiting_Clients and organisations table
        ->get();







        $lobyWaitingUserInfo = Loby_Waiting_Clients::where('user_email', $session_emailId)->where('channel_id', $channelId)->first();
        if ($lobyWaitingUserInfo) {
            if ($lobyWaitingUserInfo->is_accepted == true) {
                //Loby_Waiting_Clients::where('channel_id', $channelId)->where('user_email', $session_emailId)->delete();
                $isCallAccepted =  'yes';


             } //else if ($lobyWaitingUserInfo->Is_rejected == true) {

            //     Loby_Waiting_Clients::where('channel_id', $channelId)->where('user_email', $session_emailId)->delete();
            //     $data = array("is_call_rejected" => 'yes');
            //     print_r(json_encode($data));
            // } else {
            //     $data = array("is_call_accepted" => 'no');
            //     print_r(json_encode($data));
            // }
        } else {
            $isCallAccepted =  'no';

        }

        return response()->json(['status' => 'success', 'data' => $data,'latestMessage' => $latestMessage, "photoList" => $fileNames, "ImagePath" => $folderPath,"IsMessageFound" => $isMessageFound,"isCallAccepted"=>$isCallAccepted,"MeetingLinkData"=>$MeetingLinkData]);



    }
    public function PeerToPeerVideoCallDesktopView(Request $request)
    {
        $channel_id = $request->channelId;
        $this->DeleteLobyWaitingClientEntry($channel_id);
        return view('PeerToPeerVideoCall/DesktopDisplay')->with('type', 'caller')->with('camStatus', $request->camStatus)->with('micStatus', $request->micStatus)->with('channel_id',$channel_id);
    }
    public function PeerToPeerVideoCallReceiverDesktopView(Request $request)
    {


        $session_emailId = Session::get('emailId');
        // $channelId = $request->channel_id;

        $caller_data = PeerToPeerVideoCall::where('Receiver_Email', '=', $session_emailId)->where('Is_Call_Accepted', '=', 0)->where('updated_at', '>', \Carbon\Carbon::now()->subMinutes(1))->get();
        if (count($caller_data) > 0) {
            PeerToPeerVideoCall::where('Receiver_Email', $session_emailId)->update(['Is_Call_Accepted' => true]);

        }
        // $lobyWaitingUserInfoRec = Loby_Waiting_Clients::join('meeting_links', 'loby_waiting_clients.channel_id', '=', 'meeting_links.generated_link')
        //     ->where('loby_waiting_clients.channel_id', $channelId)
        //     ->whereColumn('loby_waiting_clients.user_email', '=', 'meeting_links.participant_email')
        //    ->distinct()
        //     ->select('loby_waiting_clients.*', 'meeting_links.*') // Select all columns from both tables
        //     ->get();


        // $lobyWaitingUserInfo = Loby_Waiting_Clients::where('user_email', $session_emailId)->where('channel_id', $channelId)->first();
        // if ($lobyWaitingUserInfo) {
        //     if ($lobyWaitingUserInfo->is_accepted == true) {
        //         Loby_Waiting_Clients::where('channel_id', $channelId)->where('user_email', $session_emailId)->delete();
        //         $data = array("is_call_accepted" => 'yes',"waitingParticipant" => $lobyWaitingUserInfoRec);

        //     } else if ($lobyWaitingUserInfo->Is_rejected == true) {

        //         Loby_Waiting_Clients::where('channel_id', $channelId)->where('user_email', $session_emailId)->delete();
        //         $data = array("is_call_rejected" => 'yes',"waitingParticipant" => $lobyWaitingUserInfoRec);

        //     } else {
        //         $data = array("is_call_accepted" => 'no',"waitingParticipant" => $lobyWaitingUserInfoRec);

        //     }
        // }


        return view('PeerToPeerVideoCall/DesktopDisplay')->with('type', 'receiver')->with('channel_id',$request->channel_id);

    }
    public function PeerToPeerVideoCallLoby(Request $request)
    {
        return view('PeerToPeerVideoCall/Loby')->with('type', 'caller')->with('channel_id', $request->channel_id);
        ;
    }

    public function PeerToPeerVideoCallParticipantLoby(Request $request)
    {
        $caller_profile_img = $request->caller_profile_pic;
        $caller_name = $request->caller_full_name;
        $rec_profile_img = $request->rec_profile_pic;
        $rec_full_name = $request->rec_full_name;
        $channel_id = $request->channel_id;

        Loby_Waiting_Clients::create([
            'user_email' => Session::get('emailId'),
            'channel_id' => $channel_id,
        ]);
        return view('PeerToPeerVideoCall/LobyParticipant')->with('type', 'receiver')->with('caller_profile_pic', $caller_profile_img)
            ->with('caller_name', $caller_name)->with('rec_profile_img', $rec_profile_img)->with('rec_name', $rec_full_name)->with('channel_id', $channel_id);
    }
    public function PeerToPeerVideoCallMobileParticipantLoby(Request $request)
    {
        $caller_profile_img = $request->caller_profile_pic;
        $caller_name = $request->caller_full_name;
        $rec_profile_img = $request->rec_profile_pic;
        $rec_full_name = $request->rec_full_name;
        $channel_id = $request->channel_id;

        Loby_Waiting_Clients::create([
            'user_email' => Session::get('emailId'),
            'channel_id' => $channel_id,

        ]);
        return view('PeerToPeerVideoCall/LobyMobileViewParticipant')->with('type', 'receiver')->with('caller_profile_pic', $caller_profile_img)
            ->with('caller_name', $caller_name)->with('rec_profile_img', $rec_profile_img)->with('rec_name', $rec_full_name)->with('channel_id', $channel_id);
    }

    public function PeerToPeerMobileVideoCallLoby(Request $request)
    {

        return view('PeerToPeerVideoCall/LobyMobileView')->with('type', 'caller')->with('channel_id', $request->channel_id);
        ;

    }
    public function videocalldashboardmobilePeerToPeer(Request $request)
    {
        $channel_id = $request->channelId;
        $this->DeleteLobyWaitingClientEntry($channel_id);
        return view('PeerToPeerVideoCall/MobileDisplay')->with('type', 'caller')->with('camStatus', $request->camStatus)->with('micStatus', $request->micStatus)->with('channel_id',$channel_id);
    }


    public function videocalldashboardmobileReceiverPeerToPeer(Request $request)
    {

        $session_emailId = Session::get('emailId');
        // $channelId = $request->channel_id;

        $caller_data = PeerToPeerVideoCall::where('Receiver_Email', '=', $session_emailId)->where('Is_Call_Accepted', '=', 0)->where('updated_at', '>', \Carbon\Carbon::now()->subMinutes(1))->get();
        if (count($caller_data) > 0) {
            PeerToPeerVideoCall::where('Receiver_Email', $session_emailId)->update(['Is_Call_Accepted' => true]);

        }
        return view('PeerToPeerVideoCall/MobileDisplay')->with('type', 'receiver')->with('camStatus', $request->camStatus)->with('micStatus', $request->micStatus)->with('channel_id',$request->channel_id);;
    }


    public function submitVideoChatPeerToPeer(Request $request)
    {

        $session_emailId = Session::get('emailId');
        $fullName = "";
        $profile_image = "";
        $destination = "Not Uploaded";
        $pathSaveToDb = "Not Uploaded";
        $chat_text = $request->chatText;
        $to_send_email = null;
        $chat_group_id = null;
        $isChat_group_id = null;
        $chanelIdd = $request->channelId;

        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['files'])) {
            $files = $_FILES['files'];
            $uploaded = [];
            $errors = [];
            foreach ($files['tmp_name'] as $index => $tmpName) {
                $name = $files['name'][$index];
                // $name = round(microtime(true)) . '.' . end($name);
                $name = date('dmYHis') . str_replace(" ", "", $name);
                //  $name = preg_replace('/[^\w\d_]/', '', $name);
                $error = $files['error'][$index];

                if ($error === UPLOAD_ERR_OK) {
                    $datee = date('Y-m-d_H_i_s') . '';
                    $pathSaveToDb = "ChatImages/" . $chat_group_id . "/" . $datee;
                    $path = public_path("ChatImages/" . $chat_group_id . "/" . $datee);
                    if (!file_exists($path)) {
                        mkdir($path, 0777, true);
                    }
                    $destination = $path . '/' . $name;
                    if (move_uploaded_file($tmpName, $destination)) {
                        $uploaded[] = $name;
                    }
                }

                if (!empty($uploaded)) {
                    echo "Uploaded files: " . implode(', ', $uploaded);
                }
                if (!empty($errors)) {
                    echo "Errors: " . implode(', ', $errors);
                }
            }
        } else {
            $destination = "Not Uploaded";
        }

        $caller_data = PeerToPeerVideoCall::where('Channel_Id', '=', $chanelIdd)->get();
        $chandel_creator_email = "noset";
        if (count($caller_data) > 0) {
            foreach ($caller_data as $rowwData) {
                if ($rowwData['Caller_Email'] == $session_emailId) {
                    PeerToPeerVideoCallChat::create([
                        'sender_email' => $session_emailId,
                        'receiver_email' => $rowwData['Receiver_Email'],
                        'sended_text' => $chat_text,
                        'full_name_sender' => $rowwData['Caller_Full_Name'],
                        'profile_pic_sender' => $rowwData['Caller_Profile_Pic'],
                        'full_name_receiver' => $rowwData['Receiver_Full_Name'],
                        'profile_pic_receiver' => $rowwData['Receiver_Profile_Pic'],
                        'images_path' => $pathSaveToDb,
                        'channel_id' => $chanelIdd,

                    ]);

                    Chat_History::create([
                        'sender_email' => $session_emailId,
                        'receiver_email' => $rowwData['Receiver_Email'],
                        'sended_text' => $chat_text,
                        'full_name' => $rowwData['Caller_Full_Name'],
                        'profile_img' => $rowwData['Caller_Profile_Pic'],
                        'full_name_sender' => $rowwData['Receiver_Full_Name'],
                        'profile_img_sender' => $rowwData['Receiver_Profile_Pic'],
                        'images_path' => $pathSaveToDb,
                        'chat_group_id' => $chanelIdd,
                    ]);

                } else {
                    PeerToPeerVideoCallChat::create([
                        'sender_email' => $session_emailId,
                        'receiver_email' => $rowwData['Caller_Email'],
                        'sended_text' => $chat_text,
                        'full_name_sender' => $rowwData['Receiver_Full_Name'],
                        'profile_pic_sender' => $rowwData['Receiver_Profile_Pic'],
                        'full_name_receiver' => $rowwData['Caller_Full_Name'],
                        'profile_pic_receiver' => $rowwData['Caller_Profile_Pic'],
                        'images_path' => $pathSaveToDb,
                        'channel_id' => $chanelIdd,

                    ]);


                    Chat_History::create([
                        'sender_email' => $session_emailId,
                        'receiver_email' => $rowwData['Caller_Email'],
                        'sended_text' => $chat_text,
                        'full_name' => $rowwData['Receiver_Full_Name'],
                        'profile_img' => $rowwData['Receiver_Profile_Pic'],
                        'full_name_sender' => $rowwData['Caller_Full_Name'],
                        'profile_img_sender' => $rowwData['Caller_Profile_Pic'],
                        'images_path' => $pathSaveToDb,
                        'chat_group_id' => $chanelIdd,
                    ]);
                }

            }
        }

        $data = array("chatGroupId" => 'noset');
        print_r(json_encode($data));
    }

    public function checkMessageForVideoCallPeerToPeer(Request $request)
    {
        $session_emailId = Session::get('emailId');
        $channelId = $request->channelId;
        //  $mailCount = Video_Chat::where('receiver_email', '=', $session_emailId)->get();
        $latestMessage = PeerToPeerVideoCallChat::where('receiver_email', '=', $session_emailId)->where('channel_id', '=', $channelId)->orderBy('id', 'DESC')->get();
        // PeerToPeerVideoCallChat::where('receiver_email', '=', $session_emailId)->where('channel_id','=',$channelId)->delete();
        $IsMessageFound = false;
        $folderPath = "";
        if (count($latestMessage) > 0) {
            $IsMessageFound = true;
            foreach ($latestMessage as $roww) {
                $folderPath = $roww["images_path"];
            }
        }

        $fileNames = [];
        if ($folderPath != "Not Uploaded") {
            if (strlen($folderPath) != 0) {
                $path = public_path($folderPath);
                $files = array_slice(scandir($path), 2);
                // Initialize an array to hold the file names
                // Loop through the scanned files
                foreach ($files as $file) {
                    // Exclude the current and parent directory references ('.' and '..')
                    if ($file !== '.' && $file !== '..') {
                        // Add the file name to the array
                        $fileNames[] = $file;
                    }
                }
            }
        }

        // Keep Saving about caller information that this caller is busy in doing call
        $record = VideoCallStatus::where('email_id', $session_emailId)->first();
        if ($record) {
            $record->updated_at = Carbon::now();
            $record->save();
        } else {
            VideoCallStatus::create([
                'email_id' => $session_emailId,
                'updated_at' => Carbon::now(),
            ]);
        }
        //.......................................................................................



        $data = array("latestMessage" => $latestMessage, "photoList" => $fileNames, "ImagePath" => $folderPath, "IsMessageFound" => $IsMessageFound);
        print_r(json_encode($data));
    }

    public function deleteReadedChatMessagePeerToPeer(Request $request)
    {
        PeerToPeerVideoCallChat::where('id', '=', (int) $request->messageId)->delete();
    }
    public function returnUserInfo($emailAdd)
    {
        $infoArray = [];
        $resultProfile = UserModel::where('email_id', $emailAdd)->get();
        $num_rows = count($resultProfile);
        if ($num_rows > 0) {
            foreach ($resultProfile as $row) {
                $infoArray[] = $row["profile_picture"];
                $infoArray[] = $row["first_name"] . " " . $row["second_name"];
            }
        }

        // else {
        //     $resultProfile = Organisation::where('email_id', $emailAdd)->get();
        //     $num_rows = count($resultProfile);
        //     if ($num_rows > 0) {
        //         foreach ($resultProfile as $row) {
        //             $infoArray[] = $row["profile_picture"];
        //             $infoArray[] = $row["first_name"] . " " . $row["second_name"];
        //         }
        //     } else {
        //         $resultProfile = Education::where('email_id', $emailAdd)->get();
        //         $num_rows = count($resultProfile);
        //         if ($num_rows > 0) {
        //             foreach ($resultProfile as $row) {
        //                 $infoArray[] = $row["profile_picture"];
        //                 $infoArray[] = $row["first_name"] . " " . $row["second_name"];
        //             }
        //         } else {

        //             $resultProfile = MeetingLinks::where('participant_email', $emailAdd)->get();
        //             foreach ($resultProfile as $row) {
        //                 $infoArray[] = $row["participant_profile_pic"];
        //                 $infoArray[] = $row["participant_name"];
        //             }

        //         }
        //     }
        // }
        return $infoArray;
    }

}