<?php

namespace App\Http\Controllers\Api;

use App\Http\Resources\UserShortResource;
use App\Models\User;
use App\Models\Livestream;
use Illuminate\Http\Request;
use App\Models\LivestreamMember;
use App\Models\LivestreamComment;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use App\Http\Resources\LivestreamResource;
use App\Classes\AgoraDynamicKey\RtcTokenBuilder;
// include ("./../app/Classes/AgoraDynamicKey/RtcTokenBuilder.php");
class LivestreamController extends Controller
{
    public function create(Request $request)
    {
        $user = $request->user();
        $appID = setting('agora_app_id');
        $appCertificate = setting('agora_app_cert');
        $channelName = $user->username . date('md');
        Livestream::where('user_id', $user->id)->update(['status' => 'completed']);
        $role = RtcTokenBuilder::RolePublisher;
        $expireTimeInSeconds = 7200;
        $currentTimestamp = now()->getTimestamp();
        $privilegeExpiredTs = $currentTimestamp + $expireTimeInSeconds;
        $token = RtcTokenBuilder::buildTokenWithUid($appID, $appCertificate, $channelName, 0, $role, $privilegeExpiredTs);
        $livestream  = new Livestream();
        $livestream->user_id = $request->user()->id;
        $livestream->agora_channel_name = $channelName;
        $livestream->agora_token = $token;
        $livestream->save();
        $livestreamdata = Livestream::find($livestream->id);
        $livestreamdata =  new LivestreamResource($livestreamdata);
        return response()->json(['status' => 200, 'message' => "Livestream  generated successfully", 'data' => $livestreamdata]);
    }
    public function joinLiveStream(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'livestream_id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['status' => 400, 'message' => $validator->errors()], 200);
        }
        $checkExistLivestream =  Livestream::find($request->livestream_id);
        $user = $request->user();
        if (empty($checkExistLivestream)) {
            return response()->json(['status' => 400, 'message' => 'Livestream not found '], 200);
        }
        if ($checkExistLivestream->status == 'completed') {
            return response()->json(['status' => 400, 'message' => 'Livestream is completed'], 200);
        }
        if ($checkExistLivestream->user_id == $user->id) {
            return response()->json(['status' => 400, 'message' => 'Cannot join your own livestream'], 200);
        }
        $alreadyJoined = LivestreamMember::where(['user_id' => $user->id, 'livestream_id' => $request->livestream_id])->first();
        if (!empty($alreadyJoined)) {
            return response()->json(['status' => 400, 'message' => 'Already Join Livestream'], 200);
        }
        LivestreamMember::create(['user_id' => $user->id, 'livestream_id' => $request->livestream_id]);
        // $membercount = LivestreamMember::where('livestream_id', $request->livestream_id)->count();
        return response()->json(['status' => '200', 'message' => 'Livestream joined successfully', 'data' => new LivestreamResource($checkExistLivestream)], 200);
    }
    public function endLiveStream(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'livestream_id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['status' => 400, 'message' => $validator->errors()], 200);
        }
        $checkExistLivestream =  Livestream::find($request->livestream_id);
        $user = $request->user();
        if (empty($checkExistLivestream)) {
            return response()->json(['status' => 400, 'message' => 'Livestream not found '], 200);
        }
        if ($checkExistLivestream->status == 'completed') {
            return response()->json(['status' => 400, 'message' => 'Livestream is completed'], 200);
        }
        if ($checkExistLivestream->user_id == $user->id) {
            $checkExistLivestream->status = 'completed';
            $checkExistLivestream->update();
            return response()->json(['status' => 200, 'message' => 'Admin closed the livestream'], 200);
        }
        LivestreamMember::where(['user_id' => $user->id, 'livestream_id' => $request->livestream_id])->delete();
        return response()->json(['status' => 200, 'message' => 'Livestream is completed'], 200);
    }
    public function liveStreamMembers(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'livestream_id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['status' => 400, 'message' => $validator->errors()], 200);
        }
        $livestream =  Livestream::find($request->livestream_id);
        $user = $request->user();
        if (empty($livestream)) {
            return response()->json(['status' => 400, 'message' => 'Livestream not found '], 200);
        }
        if ($livestream->status == 'completed') {
            return response()->json(['status' => 400, 'message' => 'Livestream is completed'], 200);
        }
        if ($user->id != $livestream->user_id) {
            return response()->json(['status' => 400, 'message' => 'UnAuthenticated'], 200);
        }
        $users = [];
        $stream_id = $request->livestream_id;
        $livestreamviewers = LivestreamMember::where('livestream_id', $stream_id)->with('user')->get();
        if (count($livestreamviewers) > 0) {
            $userModel = new User();
            foreach ($livestreamviewers as $singleUser) {
                $userdata = $userModel->getUserData($singleUser);
                if (!empty($userdata)) {
                    $users[] = $userdata;
                }
            }
            return response()->json(['status' => '200', 'message' => 'User fetch successfully', 'data' => $users], 200);
        }
        return response()->json(['status' => 400, 'message' => 'User fetch successfully', 'data' => $users], 200);
    }
    public function addComment(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'livestream_id' => 'required',
            'comment' => 'required',

        ]);
        if ($validator->fails()) {
            return response()->json(['status' => 400, 'message' => $validator->errors()], 200);
        }
        $livestream_id = $request->livestream_id;
        $livestream = LiveStream::find($livestream_id);

        if (empty($livestream)) {
            return response()->json(['status' => 400, 'message' => 'Livestream not found',], 200);
        }
        if ($livestream->status != 'active') {
            return response()->json(['status' => 400, 'message' => 'Livestream not active',], 200);
        }
        $user_id = $request->user()->id;
        $commentModel = new LivestreamComment;
        $commentModel->user_id = $user_id;
        $commentModel->livestream_id = $livestream_id;
        $commentModel->comment = $request->comment;
        $commentModel->save();
        return response()->json(['status' => 200, 'message' => 'comment successfully'], 200);
    }
    public function getCmment(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'livestream_id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['status' => 400, 'message' => $validator->errors()], 200);
        }
        $limit = $request->limit ?? 10;
        $offset = $request->offset ?? 0;

        $comments = LivestreamComment::where('livestream_id', $request->livestream_id)->limit($limit)->offset($offset)->get();
        if (count($comments) > 0) {
            $userModel = new User();
            foreach ($comments as $comment) {
                $comment['user'] = $userModel->usershortInfo($comment->user_id);
            }
        }
        return response()->json(['status' => 200, 'message' => 'comment fetch successfully', 'data' => $comments], 200);
    }
    public function liveStreamViewCount(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'livestream_id' => 'required',
        ]);
        if ($validator->fails()) {
            return response()->json(['status' => 400, 'message' => $validator->errors()], 200);
        }
        $livestream = LiveStream::find($request->livestream_id);

        if (empty($livestream)) {
            return response()->json(['status' => 400, 'message' => 'livestream not found'], 200);
        }
        $member = LivestreamMember::where('livestream_id', $request->livestream_id)->count();
        return response()->json(['status' => 200, 'message' => 'Viewer count fetch successfully', 'data' => $member], 200);
    }
    public function getLivestreams(Request $request)
    {
        $limit = $request->limit ?? 10;
        $user_id = $request->user()->id;
        $offset = $request->offset ?? 0;
        $livestreams = Livestream::where('status', 'active')->where('user_id', '!=', $user_id)->limit($limit)->offset($offset)->get();
        return response()->json([
            'status' => 200,
            'message' => 'Recommendations found',
            'data' => LivestreamResource::collection($livestreams),
        ]);
    }
}
