<?php

namespace App\Http\Controllers\Admin\LMS;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\Batch;
use App\Models\Admin;
use App\Models\Address;
use App\Models\Classes;
use App\Models\Slot;
use Illuminate\Support\Facades\DB;
use App\Models\IeltsMockTest;
use App\Models\ExamCategory;
use App\Models\Attendance;
use Firebase\JWT\JWT;
use App\Helpers\AdminHelper;
use App\Models\Task;
use App\Models\UsersMockTest;
use Illuminate\Validation\Rule;



class ClassController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:admin');
    }
    public function index(Request $request)
    {

        abort_if(!userCan('class.view'), 403);
        $datetimeD = $request->input('datetimeD');
        $query = Classes::query()->with(['batch','batch.plans', 'tutor']);
        if (userCan('candidate.assignedTutor')) {
        } else if (checkTutorRole()) {
            $query->whereNotNull('classes.tutor_id')
            ->where('classes.tutor_id', Auth::user()->id);
           
        }
         // Filter batches status here
     

        $query->whereHas('batch', function ($q){
            $q->where('status', 1);
        });
       
        $query->searchQuery($query);

        if (!empty($request->batch_id)) {
            $query->where('classes.batch_id', $request->input('batch_id'));
        }

        if (!empty($request->tutor_id)) {
            $query->where('classes.tutor_id', $request->input('tutor_id'));
        }

        $nowDate = Carbon::now();
       
        if ($request->list_by == 'all') {
         
        }else if($request->list_by == 'complete'){
          
            // $query->whereDate('start_date', '<=', $nowDate);
            $query->whereRaw("DATE_ADD(start_date, INTERVAL class_duration MINUTE) <= ?", [$nowDate->subMinutes(90)]);
        }else{
           
            // $query->whereDate('start_date', '>=', $nowDate);

            $query->whereRaw("DATE_ADD(start_date, INTERVAL class_duration MINUTE) >= ?", [$nowDate->subMinutes(90)]);
        } 

        if ($datetimeD) {
            $dates = explode(' - ', $datetimeD);
            $startDate = Carbon::createFromFormat('m/d/Y', $dates[0])->startOfDay()->format('Y-m-d H:i:s');
            $endDate = Carbon::createFromFormat('m/d/Y', $dates[1])->endOfDay()->format('Y-m-d H:i:s');

            $query->whereBetween('start_date', [$startDate, $endDate]);
        }


        $totalCount = $query->count();

        $datas = $query->oldest('start_date')->paginate(10)->withQueryString();

        $role_AVAILABLE_TUTOR_ROLES = explode(',', env('AVAILABLE_TUTOR_ROLES', 'Tutor'));
        $admin_list_tutor = Admin::where('id', '!=', 1)
            ->whereHas('roles', function ($query) use ($role_AVAILABLE_TUTOR_ROLES) {
                $query->whereIn('name', $role_AVAILABLE_TUTOR_ROLES);
            })
            ->get()
            ->toArray();

        $batches = Batch::where('status', 1)->select('batch_name', 'id')->get()->toArray();

        return view('admin.LMS.class.index', compact('datas', 'totalCount', 'batches', 'admin_list_tutor'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        abort_if(!userCan('class.create'), 403);

        $role_AVAILABLE_TUTOR_ROLES = explode(',', env('AVAILABLE_TUTOR_ROLES', 'Tutor'));
        $admin_list_tutor = Admin::where('id', '!=', 1)
            ->whereHas('roles', function ($query) use ($role_AVAILABLE_TUTOR_ROLES) {
                $query->whereIn('name', $role_AVAILABLE_TUTOR_ROLES);
            })
            ->get()
            ->toArray();

        $batches = Batch::get(['id', 'batch_name', 'batch_code']);

        $mock_test_list = IeltsMockTest::select('id')->get()->toArray();
        $mock_test_list_category = ExamCategory::select('id', 'name')->get()->toArray();

        return view('admin.LMS.class.create', compact('admin_list_tutor', 'batches', 'mock_test_list', 'mock_test_list_category'));
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        abort_if(!userCan('class.create'), 403);
        // dd($request->all());
        $batches = Batch::withTrashed()->find($request->input('batch_id'));

        $start_date = Carbon::parse($request->input('start_date'))->tz(env('APP_TIMEZONE', 'UTC'))->format('Y-m-d H:i:s');
        $end_date = Carbon::parse($request->input('start_date'))
            ->addMinutes($request->input('class_duration'))
            ->tz(env('APP_TIMEZONE', 'UTC'))->format('Y-m-d H:i:s');

        $tutor_id = $request->input('tutor_id');
        
        $request['day'] = @$batches->number_of_classes  + 1;
        $rules = [
            'class_mode' => 'required|in:0,1',
            'status' => 'required',
            'batch_id' => 'required|exists:batches,id',
            'class_name' => 'required|string|max:50',
            'class_code' => 'required|string|unique:classes,class_code|max:50',
            'tutor_id' => 'required|integer',
            'class_duration' => 'required|integer',
            'start_date' => [
                'required',
                'date',
                'after_or_equal:'.now(),
                function ($attribute, $value, $fail) use ($tutor_id, $start_date) {
                    $exists = DB::table('classes')
                        ->where('tutor_id', $tutor_id)
                        ->whereRaw("? BETWEEN start_date AND DATE_ADD(start_date, INTERVAL class_duration MINUTE)", [$start_date])
                        ->exists();
        
                    if ($exists) {
                        $fail('The selected start date is not unique or conflicts with an existing class.');
                    }
                },
           
            ],
        ];



        $validatedData = $request->validate($rules);
       
        try {

            DB::beginTransaction(); // Start transaction
            $userId =  Auth::user()->id;


            $validatedData['created_by'] = $userId;
            $validatedData['updated_by'] = $userId;

            $validatedData['class_duration'] = $request->class_duration;
            $validatedData['module_name'] = $request->module_name;
            $validatedData['recording_status'] = $request->recording_status;
            $validatedData['task_module'] = $request->task_module;
            $validatedData['task_name'] = $request->task_name;






            if (isset($request["class_des"])) {
                $classDetails = $request["class_des"];
                $description = json_encode($classDetails);
                // Do something with the JSON data

            } else {
                $description = null;
            }



            if (isset($request["task_des"])) {
                $task_des1 = $request["task_des"];

                foreach ($task_des1 as &$task) {
                    if (!isset($task['mock_test'])) {
                        $task['mock_test'] = null;
                    }
                    if (!isset($task['mock_test_type'])) {
                        $task['mock_test_type'] = null;
                    }
                }

                // Using $task_des1 instead of $classDetails
                $task_description = json_encode($task_des1);
            } else {
                $task_description = null;
            }

            if (isset($request["study_material"])) {
                $study_material = $request["study_material"];



                // Using $task_des1 instead of $classDetails
                $study_material = json_encode($study_material);
            } else {
                $study_material = null;
            }
            $validatedData['day'] =  $request["day"];
            $validatedData['description'] =  $description;
            $validatedData['task_description'] =  $task_description;
            $validatedData['study_material'] = $study_material;



            $class = Classes::create($validatedData);

            $batches->update(['number_of_classes', $class->day]);


            if ($class && $batches->user_ids) {
                $userIds = explode(",", $batches->user_ids);

                foreach ($userIds as $userId) {

                    $decodedDescription = json_decode($class->task_description, true);
                    if (!empty($decodedDescription)) {
                        // First, delete existing tasks for the current user and class

                        $tasks = Task::where('class_id', $class->id)
                            ->where('user_id', $userId)
                            ->get();

                        if ($tasks->isNotEmpty()) {
                            $tasks->each(function ($task) {
                                $task->delete();
                            });
                        }

                        // Then, create new tasks based on the decoded description
                        foreach ($decodedDescription as $description) {
                            $taskdata = [
                                'task_module' => $class->task_module ?? null,
                                'assign_date' => $class->start_date,
                                'class_id' => $class->id ?? null,
                                'created_by' => $batches->created_by,
                                'updated_by' => Auth::user()->id,
                                'user_id' => $userId,
                                'task_name' => $description['name'] ?? null,
                                'task_links' => $description['link'] ?? null,
                                'task_duration' => $description['duration'] ?? null,
                                'task_type' => $description['type'] ?? null,
                                'mock_test' => $description['mock_test'] ?? null,
                                'mock_test_type' => $description['mock_test_type'] ?? null,
                                'test_type' => @$description['test_type'] ?? null,
                            ];
                            // Create a new Task record
                            $taskGet = Task::create($taskdata);

                            // Check if the task type is "Mock test"
                            if (!empty($taskGet) && @$taskGet->task_type == "Mock test" || @$taskGet->task_type == "Practice test") {

                                $usersMockTests = UsersMockTest::where('class_id', $class->id)
                                    ->where('user_id', $userId)
                                    ->where('ielts_test_ids',  $taskGet->mock_test)
                                    ->get();
                                if ($usersMockTests->isNotEmpty()) {
                                    $usersMockTests->each(function ($userMockTest) {
                                        $userMockTest->delete();
                                    });
                                }
                                // Create a new UsersMockTest record
                                $mockTest = [
                                    'test_type' => $taskGet->mock_test_type,
                                    'available_at' => $class->start_date,
                                    'class_id' => $class->id,
                                    'user_id' => $userId,
                                    'ielts_test_ids' => $taskGet->mock_test,
                                    'category' => $taskGet->task_type == "Mock test" ? "M" : ($taskGet->task_type == "Practice test" ? "P" : "M"),
                                ];

                                UsersMockTest::create($mockTest);
                            }
                        }
                    }
                }
            }


            DB::commit();
            flashSuccess("Class created successfully!");
            return redirect()->route('admin.class.index');
        } catch (\Exception $e) {
            DB::rollBack(); // Roll back transaction if an exception occurs
            flashError(__('something_went_wrong' . $e->getMessage()));
            return back()->withInput();
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        // dd($id);
        abort_if(!userCan('class.view'), 403);
        $class = Classes::find($id);
        if ($class) {
           


            $role_AVAILABLE_TUTOR_ROLES = explode(',', env('AVAILABLE_TUTOR_ROLES', 'Tutor'));
            $admin_list_tutor = Admin::where('id', '!=', 1)
                ->whereHas('roles', function ($query) use ($role_AVAILABLE_TUTOR_ROLES) {
                    $query->whereIn('name', $role_AVAILABLE_TUTOR_ROLES);
                })
                ->get()
                ->toArray();

            $batch = Batch::select('id', 'batch_name', 'batch_code', 'meeting_id', 'meeting_password', 'user_ids')
                ->where('id', $class->batch_id)
                ->first();


            $batchUserIds = @$batch->user_ids ?? null;

            $batchUserIdsArray = explode(",", $batchUserIds);

            $users = User::leftJoin('attendances', function ($join) use ($class) {
                $join->on('users.id', '=', 'attendances.user_id')
                    ->where('attendances.class_id', '=', $class->id);
            })
                ->whereIn('users.id', $batchUserIdsArray)
                ->select('users.id', 'users.name', 'attendances.id as attendance_id', 'attendances.attend as attend')
                ->groupBy('users.id')
                ->get();
            $mock_test_list = IeltsMockTest::select('id')->get()->toArray();
            $mock_test_list_category = ExamCategory::select('id', 'name')->get()->toArray();

            return view('admin.LMS.class.show', compact('class', 'admin_list_tutor', 'batch', 'users', 'mock_test_list_category', 'mock_test_list'));
            
        } else {
            flashError("Class not found.");
            return back();
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        abort_if(!userCan('class.update'), 403);


        $class = Classes::where('id', $id)->first();
        if ($class) {
           

            $role_AVAILABLE_TUTOR_ROLES = explode(',', env('AVAILABLE_TUTOR_ROLES', 'Tutor'));
            $admin_list_tutor = Admin::where('id', '!=', 1)
                ->whereHas('roles', function ($query) use ($role_AVAILABLE_TUTOR_ROLES) {
                    $query->whereIn('name', $role_AVAILABLE_TUTOR_ROLES);
                })
                ->get()
                ->toArray();
            $batches = Batch::withTrashed()->get(['id', 'batch_name', 'batch_code']);


            $mock_test_list = IeltsMockTest::select('id')->get()->toArray();
            $mock_test_list_category = ExamCategory::select('id', 'name')->get()->toArray();

            return view('admin.LMS.class.edit', compact('class', 'admin_list_tutor', 'batches', 'mock_test_list', 'mock_test_list_category'));
        } else {
            flashError("Class not found.");
            return back();
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {


       
        abort_if(!userCan('class.update'), 403);

        $rules = [
            'class_mode' => 'required|in:0,1',
            'status' => 'required',
            'batch_id' => 'required|exists:batches,id',
            'class_name' => 'required|string|max:50',
             'class_code' => 'required|string|unique:classes,class_code,' . $id,
            'start_date' => 'required|date',
            'tutor_id' => 'required|integer',


        ];

        $validatedData = $request->validate($rules);

        $userId = Auth::user()->id;

        $validatedData['updated_by'] = $userId;

        $class = Classes::findOrFail($id);
        try {

            DB::beginTransaction(); // Start transaction
            if ($class) {
                $batches = Batch::withTrashed()->find($request->input('batch_id'));

                $validatedData['updated_by'] = $userId;

                $validatedData['class_duration'] = $request->class_duration;
                $validatedData['module_name'] = $request->module_name;
                $validatedData['recording_status'] = $request->recording_status;
                $validatedData['task_module'] = $request->task_module;
                $validatedData['task_name'] = $request->task_name;





                if (isset($request["class_des".$class->id])) {
                    $classDetails = $request["class_des".$class->id];
                    $description = json_encode($classDetails);
                    // Do something with the JSON data
                    
                }else{
                    $description = null;
                }



                if (isset($request["task_des".$class->id])) {
                    $task_des1 = $request["task_des".$class->id];
                
                    foreach ($task_des1 as &$task) {
                        if (!isset($task['mock_test'])) {
                            $task['mock_test'] = null;
                        }
                        if (!isset($task['mock_test_type'])) {
                            $task['mock_test_type'] = null;
                        }
                    }
                
                    // Using $task_des1 instead of $classDetails
                    $task_description = json_encode($task_des1);
                } else {
                    $task_description = null;
                }
    
                if (isset($request["study_material".$class->id])) {
                    $study_material = $request["study_material".$class->id];
                
                    
                
                    // Using $task_des1 instead of $classDetails
                    $study_material = json_encode($study_material);
                } else {
                    $study_material = null;
                }

                $validatedData['description'] =  $description;
                $validatedData['task_description'] =  $task_description;
                $validatedData['study_material'] = $study_material;

              

                $class->update($validatedData);



                if ($class && @$batches->user_ids) {
                    $userIds = explode(",", $batches->user_ids);

                    foreach ($userIds as $userId) {

                        $decodedDescription = json_decode($class->task_description, true);
                        if (!empty($decodedDescription)) {
                            // First, delete existing tasks for the current user and class

                            $tasks = Task::where('class_id', $class->id)
                                ->where('user_id', $userId)
                                ->get();

                            if ($tasks->isNotEmpty()) {
                                $tasks->each(function ($task) {
                                    $task->delete();
                                });
                            }

                            // Then, create new tasks based on the decoded description
                            foreach ($decodedDescription as $description) {
                                $taskdata = [
                                    'task_module' => $class->task_module ?? null,
                                    'assign_date' => $class->start_date,
                                    'class_id' => $class->id ?? null,
                                    'created_by' => $batches->created_by,
                                    'updated_by' => Auth::user()->id,
                                    'user_id' => $userId,
                                    'task_name' => $description['name'] ?? null,
                                    'task_links' => $description['link'] ?? null,
                                    'task_duration' => $description['duration'] ?? null,
                                    'task_type' => $description['type'] ?? null,
                                    'mock_test' => $description['mock_test'] ?? null,
                                    'mock_test_type' => $description['mock_test_type'] ?? null,
                                    'test_type' => @$description['test_type'] ?? null,
                                ];
                                // Create a new Task record
                                $taskGet = Task::create($taskdata);

                                // Check if the task type is "Mock test"
                                if (!empty($taskGet) && @$taskGet->task_type == "Mock test" || @$taskGet->task_type == "Practice test") {

                                    $usersMockTests = UsersMockTest::where('class_id', $class->id)
                                        ->where('user_id', $userId)
                                        ->where('ielts_test_ids',  $taskGet->mock_test)
                                        ->get();
                                    if ($usersMockTests->isNotEmpty()) {
                                        $usersMockTests->each(function ($userMockTest) {
                                            $userMockTest->delete();
                                        });
                                    }
                                    // Create a new UsersMockTest record
                                    $mockTest = [
                                        'test_type' => $taskGet->mock_test_type,
                                        'available_at' => $class->start_date,
                                        'class_id' => $class->id,
                                        'user_id' => $userId,
                                        'ielts_test_ids' => $taskGet->mock_test,
                                        'category' => $taskGet->task_type == "Mock test" ? "M" : ($taskGet->task_type == "Practice test" ? "P" : "M"),
                                    ];

                                    UsersMockTest::create($mockTest);
                                }
                            }
                        }
                    }
                }
            } else {
                flashError("Class not found!");
                return redirect()->route('admin.class.index');
            }

            DB::commit();
            flashSuccess("Class Update successfully!");
            return redirect()->route('admin.class.index');
        } catch (\Exception $e) {
            DB::rollBack(); // Roll back transaction if an exception occurs
            flashError(__('something_went_wrong' . $e->getMessage()));
            return back()->withInput();
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function calendarEvent(Request $request)
    {

        $searchName = $request->input('keyword');
        $batch_id = $request->input('batch_id');
        $query = Classes::query();
        if (!empty($batch_id)) {
            $query->where('classes.batch_id', $request->input('batch_id'));
        }
        if (!empty($request->tutor_id)) {
            $query->where('classes.tutor_id', $request->input('tutor_id'));
        }
     

        if (userCan('candidate.assignedTutor')) {
        } else if (checkTutorRole()) {
            $query->whereNotNull('classes.tutor_id')
            ->where('classes.tutor_id', Auth::user()->id);
           
        }
         // Filter batches status here
     

        $query->whereHas('batch', function ($q){
            $q->where('status', 1);
        });
       
        
      
        $query->select([
            'classes.id',
            'classes.class_name AS title',
            'classes.class_code AS class_code',
            'classes.class_mode',
            'classes.status AS class_status',
            'classes.created_at',
            'classes.created_by',
            'classes.tutor_id',
            'classes.class_duration AS classDuration',
            'classes.day AS classDay',
            'classes.start_date AS start',
            DB::raw("CONCAT(DATE(classes.start_date), ' ', TIME(CAST(classes.start_date AS TIME) + INTERVAL classes.class_duration * 60 SECOND)) AS end"),
            'classes.batch_id',
            'batches.batch_name AS batch_name',
            'batches.batch_code AS batch_code',
            'batches.batch_mode',

        ]);

        $query->leftJoin('batches', function ($join) {
            $join->on('batches.id', '=', 'classes.batch_id');
        });



        if (request('start')) {
            $startDate = Carbon::parse(request('start'));
            $query->whereDate('classes.start_date', '>=', $startDate->format('Y-m-d'));
        }

        if (request('end')) {
            $toDate = Carbon::parse(request('end'));
            $query->whereDate('classes.start_date', '<=', $toDate->format('Y-m-d'));
        }

        if (!empty($searchName)) {
            // $query->whereHas('user', function ($userQuery) use ($searchName) {
            //     $userQuery->where('name', 'LIKE', "%$searchName%")
            //     ->orWhere('email', 'LIKE', "%$searchName%")
            //     ->orWhere('id', $searchName)
            //     ->orWhere('phone', 'LIKE', "%$searchName%");
            // });
        }




        $data = $query->get()->toArray();

        $formattedData = [];

        foreach ($data as $item) {
            $formattedItem = [
                'id' => $item['id'],
                'title' => $item['title'],
                'class_code' => $item['class_code'] ?? null,
                'class_mode' => $item['class_mode'] == 1 ? 'Online' : 'Offline',
                'batch_id' => $item['batch_id'] ?? null,
                'batch_name' => $item['batch_name'] ?? null,
                'batch_code' => $item['batch_code'] ?? null,
                'batch_mode' => $item['batch_mode'] ?? null,
                'created_at' => dateMonthTimeFormat($item['created_at']) ?? null,
                'created_by' => adminIdToNameGet($item['created_by']) ?? null,
                'tutor_id' => adminIdToNameGet($item['tutor_id']) ?? null,
                'class_date' => dateMonthTimeFormat($item['start']) ?? null,
                'start' => $item['start'],
                'end' => $item['end'],
                'classDuration' => $item['classDuration'],
                'classDay' => $item['classDay'],
                'class_status' => $item['class_status'] == 1 ? 'Active' : 'Inactive',


            ];

            // Push the formatted item into the result array
            $formattedData[] = $formattedItem;
        }


        return response()->json($formattedData);
    }

    function change_attendees_status(Request $request)
    {
        // dd($request->all());
        if (empty($request->attendance_id)) {
            // Create a new Attendance record
            if (empty($request->user_id) || empty($request->class_id)) {
                return response()->json(['error' => 'Both user_id and class_id are required'], 400);
            }

            $newAttendance = new Attendance();
            $newAttendance->user_id = $request->user_id;
            $newAttendance->class_id = $request->class_id;
            $newAttendance->attend = $request->status ?? null;
            $newAttendance->save();
        } else {
            // Update existing record if attendance_id is provided
            $attendance = Attendance::find($request->attendance_id);

            if (!$attendance) {
                return response()->json(['error' => 'Attendance record not found'], 404);
            }

            if ($request->type == 'attend_status') {
                $attendance->attend = $request->status;
                $attendance->save();
            }
        }

        $message = $request->status == 1 ? __('Activated successfully') : __('Deactivated successfully');
        return response()->json(['message' => $message]);
    }
    public function attendeesTable($id)
    {
        $class = Classes::find($id);
        $users = [];

        if ($class) {
            $batchUserIds = Batch::where('id', $class->batch_id)
                ->pluck('user_ids')
                ->first();

            $batchUserIdsArray = explode(",", $batchUserIds);

            $users = User::leftJoin('attendances', function ($join) use ($class) {
                $join->on('users.id', '=', 'attendances.user_id')
                    ->where('attendances.class_id', '=', $class->id);
            })
                ->whereIn('users.id', $batchUserIdsArray)
                ->select('users.id', 'users.name', 'attendances.id as attendance_id', 'attendances.attend as attend')
                ->groupBy('users.id')
                ->get();
        }

        // Render the attendees table HTML using a Blade view
        $html = view('admin.LMS.class.partials.attendees_table', compact('users', 'class'))->render();
        // Return the HTML response
        return response()->json(['html' => $html]);
    }


    // public function hostZoomMeeting(Request $request)
    // {
    //     $meetingId = $request->get('meeting_id');
    //     $meetingPassword = $request->get('password');

    //     // Redirect users to Zoom join meeting page with meeting ID and password
    //     return redirect()->away("https://zoom.us/j/{$meetingId}?pwd={$meetingPassword}");
    // }

    // public function hostZoomMeeting(Request $request)
    // {
    //     $meetingId = $request->get('meeting_id');
    //     $meetingPassword = $request->get('password');
    //     $sdkJWT = $this->generateZoomJWT($meetingId);
    //     // dd($sdkJWT);
    //     // Pass the token to the view.
    //     dd("w,dfnwbdjk");
    //     return view('admin.LMS.zoomHOST.index', compact('sdkJWT','meetingId', 'meetingPassword'));
    // }

    // private function generateZoomJWT($meetingNumber)
    // {

    //     $iat = time();
    //     $exp = $iat + (60 * 60 * 2); // Expire after 2 hours
    //     $role = 1; // Host role is 1, attende

    //     $oHeader = [
    //         "alg" => "HS256",
    //         "typ" => "JWT"
    //     ];

    //     $oPayload = [
    //         "appKey" => env('NEXT_PUBLIC_ZOOM_API_KEY'),
    //         "sdkKey" => env('NEXT_PUBLIC_ZOOM_API_KEY'),
    //         "mn" => $meetingNumber,
    //         "role" => $role,
    //         "iat" => $iat,
    //         "exp" => $exp,
    //         "tokenExp" => $exp
    //     ];

    //     $sdkJWT = JWT::encode($oPayload, env('ZOOM_MEETING_SDK_SECRET'), 'HS256');

    //     return $sdkJWT;
    // }

    public function hostZoomMeeting(Request $request)
    {
        $meetingId = $request->get('meeting_id');
        $meetingPassword = $request->get('password');
        // Your meeting settings
        $meetingNumber = $meetingId;
        $topic = $request->input('topic', 'Zoom Meeting'); // Meeting topic, default: "Zoom Meeting"
        $role = $request->input('role', 1); // Role: 1 for host, 0 for participant
        $duration = $request->input('duration', 60); // Meeting duration in minutes, default: 60 minutes

        // Generate JWT token
        $jwt = $this->generateZoomSDKJWT($meetingNumber, $role);

        // Return meeting details and JWT token
        return view('admin.LMS.zoomHOST.index', [
            'meetingNumber' => $meetingNumber,
            'meetingPassword' => $meetingPassword,
            'role' => $role,
            'jwt' => $jwt,
        ]);
    }

    function generateZoomSDKJWT($meetingNumber, $role)
    {
        $iat = time();
        $exp = $iat + (60 * 60 * 2); // Expire after 2 hours

        $payload = [
            'appKey' => env('NEXT_PUBLIC_ZOOM_API_KEY'),
            'sdkKey' => env('NEXT_PUBLIC_ZOOM_API_KEY'),
            'mn' => $meetingNumber,
            'role' => $role,
            'iat' => $iat,
            'exp' => $exp,
            'tokenExp' => $exp
        ];

        // Encode JWT with the appropriate key
        $jwt = JWT::encode($payload, env('ZOOM_MEETING_SDK_SECRET'), 'HS256');

        return $jwt;
    }

    public function hostZoomMeetingLeave()
    {
        // Perform any cleanup tasks here, such as logging or updating database records
        // For example, you might want to log the user's exit from the meeting

        // Redirect the user to a specific page after leaving the meeting
        return redirect()->route('admin.class.index');
    }


    public function getClassCode(Request $request)
    {

        $batchId = $request->input('batchId');

        // Call the helper function to get the batch code
        $class_code = AdminHelper::getClassCode($batchId);
        if ($request->ajax()) {
            // Return the batch code as JSON response
            return response()->json($class_code);
        } else {
            return $class_code;
        }
    }

    public function getBatchClassData(Request $request)
    {

        $batchId = $request->input('batchId');

        // Call the helper function to get the batch code
        $batch = Batch::where('id', $batchId)->first();
        $data = [];
        if(!empty($batch)){
            $start_date = Carbon::parse($batch->start_date)->tz(env('APP_TIMEZONE', 'UTC'));

            // Get the next working day
            $start_date = AdminHelper::getNextWorkingDay($start_date)->toDateString();
            
            // Check if class time and start date are not empty
            if (!empty($batch->class_time) && !empty($start_date)) {
                // Set the time from the class time string
                $start_date = Carbon::parse($start_date)->tz(env('APP_TIMEZONE', 'UTC'))->setTimeFromTimeString($batch->class_time);
            }
            
            // Format the date in the desired format
            $formatted_date = $start_date->format('Y-m-d\TH:i');
            
            // Assign the formatted date to $data['start_date']
            $data['start_date'] = $formatted_date;
           
            $data['class_mode'] = $batch->batch_mode;
            $data['class_duration'] = $batch->class_duration;
            $data['tutor_id'] = $batch->tutor_id;
        }

        if ($request->ajax()) {
            // Return the batch code as JSON response
            return response()->json($data);
        } else {
            return $data;
        }
    }

    
}
