<?php
ini_set('display_errors', 1);
require_once '../../../resources/base_path_include.php';
require_once $base_path_to_learning_resources  . "includes/connect.php";
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';
//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
//dynemic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning_resources . 'lib/task_schedule/task_scheduler_functions.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$postdata = $_POST;

$requiredFields = [
    'institution_id' => 'Institution ID',
    'subject_id' => 'Subject ID',
    'class_id' => 'Class ID',
    'lesson_number' => 'Lesson number',
    'lesson_name' => 'Lesson name',
    'author' => 'Author',
    'description' => 'Description',
    'lesson_category_id' => 'Lesson category ID',
    'api_signature' => 'API signature',
    'function_type' => 'Function type',
    'jwt_token' => 'JWT token'
];

foreach ($requiredFields as $field => $label) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("$label is required.");
    }
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is iin decodede data of jwt use from there
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["principal"], null);;
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning, $conn_rjllearning_specific,$version, $updated_time, $userid, $institution_id);

$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
}
$section_id = $postdata['section_id'];

$class_id = $postdata['class_id'];
$subject_id = trim($postdata['subject_id']);
$lesson_number = trim($postdata['lesson_number']);
$lesson_name = ucwords(trim($postdata['lesson_name']));
$author = trim($postdata['author']);
$description = trim($postdata['description']);
// $type = trim($postdata['type']);
$type = trim($postdata['type']);

// $currenttime = time();

$publish_date = (isset($postdata['publish_date']) and !empty($postdata['publish_date'])) ? trim(date('Y-m-d', strtotime($postdata['publish_date']))) : date('Y-m-d');
$publish_times = (isset($postdata['publish_time']) and !empty($postdata['publish_time'])) ? trim($postdata['publish_time']) : date('H:i');
$terminate_date = (isset($postdata['terminate_date']) and !empty($postdata['terminate_date'])) ? trim(date('Y-m-d', strtotime($postdata['terminate_date']))) : null;
$termination_time = (isset($postdata['termination_time']) and !empty($postdata['termination_time'])) ? trim($postdata['termination_time']) : null;
$link = (isset($postdata['link']) and !empty($postdata['link'])) ? trim($postdata['link']) : null;
$lesson_category_id = trim($postdata['lesson_category_id']);

$audio_attachment = (isset($_FILES['audio_attachment']) and !empty($_FILES['audio_attachment'])) ? $_FILES['audio_attachment'] : null;
$primary_attachment = (isset($_FILES['primary_attachment']) and !empty($_FILES['primary_attachment'])) ? $_FILES['primary_attachment'] : null;
$cover_image = (isset($_FILES['cover_image']) and !empty($_FILES['cover_image'])) ? $_FILES['cover_image'] : null;

if($publish_date and $publish_times == null){
    $lesson_status==1;
} else{
    $lesson_status=0;
}

// checkClassInstitutionBranch($conn_rjllearning_specific,$institution_id,$branch_id,$class_id);
// SQL to check if the lesson category exists
$sql_query = "SELECT id FROM lesson_categories WHERE institution_id = ? AND class_id = ? AND subject_id = ?";
$params = [$institution_id,$class_id,$subject_id];
// Check by ID if it's numeric, otherwise check by topic_name
if (is_numeric($lesson_category_id)) {
    $sql_query .= " AND id = ?";
    $params[] = $lesson_category_id;
} else {
    $sql_query .= " AND topic_name = ?";
    $params[] = $lesson_category_id;
}

// Prepare and execute the query
$sql_check = $conn_rjllearning_specific->prepare($sql_query);
$sql_check->execute($params);
$existing_category_id = $sql_check->fetchColumn();

// If the category does not exist, insert it
if (!$existing_category_id) {
    $sql_insert_category = "INSERT INTO lesson_categories 
        (institution_id, branch_id, academic_id, subject_id, class_id, topic_name, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?)";
    $stmt_insert_category = $conn_rjllearning_specific->prepare($sql_insert_category);
    $stmt_insert_category->execute([$institution_id, $branch_id, $academic_id, $subject_id, $class_id, $lesson_category_id, 1 // Default status
    ]);
    // Fetch the last inserted ID
    $lesson_category_id = $conn_rjllearning_specific->lastInsertId();
} else {
    // Use the existing ID if found
    $lesson_category_id = $existing_category_id;
}

// Get today's date
$today_date = date('Y-m-d');
$currenttime = time();
// if ($publish_time != null) {
//     if (!CheckValidateTimeWithHyphen($publish_time)) {
//         errorreturn('Invalid publish time');
//     }
// }
$publish_time = convertTimeFormat($publish_times);
if ($type == 'youtube_embed') {
    if ($link !=  null) {
        if (!validateYouTubeUrl($link)) {
            errorreturn('Invalid youtube link');
        }
    }
}

$check_branch_class = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, $class_id, $subject_id, $institution_id);
if ($check_branch_class == false) {
    errorreturn("Access denied");
}
validateBranchClassSection($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $support_branch_all = 1, $checkClass = 0 , $support_class_all = 0, $checkSection = 1,  $support_section_all = 1);

$function_type = trim($postdata['function_type']);
$Faculty_Codes = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?");
$Faculty_Codes->execute(array($userid, $institution_id, $branch_id));
// Fetch a single row instead of all
$result_faculty = $Faculty_Codes->fetch(PDO::FETCH_ASSOC);
// Check if the faculty exists
if ($result_faculty === false) {
    errorreturn("Faculty Not Found.");
}
// Retrieve the faculty_id from the result
$faculty_id = $result_faculty['id'];
if (isset($postdata['section_id']) && is_array($postdata['section_id'])) {
    $section_id = $postdata['section_id']; // Use it directly
    if (count($section_id) === 1 && $section_id[0] === 'all') {
        // If 'all' is present, no need for further checks
        $json_section_id = 'all';
    } else {
        // Handle the case when 'all' is not present
        if (count($section_id) <= 0) {
            errorreturn("Select at least one section.");
        }
        // Prepare the section IDs for SQL query
        $imploded_section_ids = "('" . implode("','", $section_id) . "')";
        // Encode the valid section IDs
        $json_section_id = json_encode($section_id);
    }
} else {
    errorreturn("Select at least one section.");
}


if ($postdata['function_type'] == "create_lesson") {
    
    // if ($type == 0 && $primary_attachment != null) {
    //     errorreturn("Cannot upload file attachment when using YouTube embed type.");
    // }
    
    // if ($type != 0 && $link != null) {
    //     errorreturn("YouTube link can only be used with 'youtube_embed' type.");
    // }
    
    $res = $conn_rjllearning_specific->prepare("SELECT id FROM lessons WHERE institution_id =? AND academic_id= ? AND class_id= ? AND subject_id =?  AND lesson_name =? ");
    $res->execute(array($institution_id, $academic_id, $class_id, $subject_id, $lesson_name));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("Lesson already exists.");
    }

    if ($audio_attachment == null) {
        $audio_attachment = null;
    } else {

        $currentYear = date('Y');
        $currentMonth = date('n');
        $currentDay =  date('d');

        $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/lesson/" . $currentYear . "/" . $currentMonth . "/";
        
        $file_name = $_FILES['audio_attachment']['name'];
        $fileTmpName = $_FILES['audio_attachment']["tmp_name"];
        $fileSize = $_FILES['audio_attachment']["size"];
        $fileType = $_FILES['audio_attachment']["type"];
        $fileError = $_FILES['audio_attachment']["error"];
        $file_extension = strtolower(pathinfo($_FILES['audio_attachment']['name'], PATHINFO_EXTENSION));
        $size = filesize($fileTmpName);
        // Check if it's a valid image
        $allowedTypes = [
            'audio/mpeg',     // for mp3
            'audio/wav',      // for wav
            'audio/aac',      // for aac
            'audio/flac',     // for flac
            'audio/ogg',   
              'video/mp4', 'video/avi', 'video/mkv', 'video/mov', 'video/webm', // Videos
                'audio/mpeg', 'audio/wav', 'audio/aac', 'audio/flac', 'audio/ogg', // Audios// for ogg
        ]; // Allowed audio types
        $allowed_extensions = ['mp3', 'wav', 'aac', 'flac', 'ogg','mp4', 'avi', 'mkv', 'mov', 'webm'];
        $maxFileSize = 500 * 1024 * 1024; // Maximum file size (2MB)

        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }


    if ($primary_attachment == null) {
        $primary_attachment = null;
    } else {
        $currentYear = date('Y');
        $currentMonth = date('m');
        $currentDay =  date('d');

        $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/lesson/" . $currentYear . "/" . $currentMonth . "/";
        $file_name = $_FILES['primary_attachment']['name'];
        $fileTmpName = $_FILES['primary_attachment']["tmp_name"];
        $fileSize = $_FILES['primary_attachment']["size"];
        $fileType = $_FILES['primary_attachment']["type"];
        $fileError = $_FILES['primary_attachment']["error"];
        $file_extension = strtolower(pathinfo($_FILES['primary_attachment']['name'], PATHINFO_EXTENSION));
        $size = filesize($fileTmpName);
        // Check if it's a valid image

        $allowedTypes = [
            'image/jpeg',
            'image/png',
            'image/gif',
            'image/heic',
            'application/pdf',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.ms-excel',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'video/mp4',
            'video/avi',
            'video/mkv',
            'video/mov',
            'video/webm'
        ];
        $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx', 'mp4', 'avi', 'mkv', 'mov', 'webm'];
        $maxFileSize = 500 * 1024 * 1024; // Maximum file size (500MB)
        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }

    if ($cover_image == null) {
        $cover_image = null;
    } else {

        $currentYear = date('Y');
        $currentMonth = date('m');
        $currentDay =  date('d');

        $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/lesson/" . $currentYear . "/" . $currentMonth . "/";
        
        $file_name = $_FILES['cover_image']['name'];
        $fileTmpName = $_FILES['cover_image']["tmp_name"];
        $fileSize = $_FILES['cover_image']["size"];
        $fileType = $_FILES['cover_image']["type"];
        $fileError = $_FILES['cover_image']["error"];
        $file_extension = strtolower(pathinfo($_FILES['cover_image']['name'], PATHINFO_EXTENSION));
        $size = filesize($fileTmpName);
        // Check if it's a valid image
        $allowedTypes = [
            'image/jpeg',
            'image/png',
            'image/gif',
            'image/heic',
            'application/pdf',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.ms-excel',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        ]; // Allowed image types
        $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
        $maxFileSize = 2;

        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }


    try {
        $sql = "INSERT INTO lessons(institution_id,branch_id,academic_id,class_id,section_id,subject_id,publish_date,publish_time,terminate_date,termination_time,lesson_category_id,lesson_number,lesson_name,author,description,
    type,audio_attachment,primary_attachment,cover_image,link,added_by,date_created,time_created,status)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ,? ,? ,? ,? ,? ,?, ? ,? ,?)";

        $stmt = $conn_rjllearning_specific->prepare($sql);

        $stmt->execute(array(
            $institution_id,
            $branch_id,
            $academic_id,
            $class_id,
            $json_section_id,
            $subject_id,
            $publish_date,
            $publish_time,
            $terminate_date,
            $termination_time,
            $lesson_category_id,
            $lesson_number,
            $lesson_name,
            $author,
            $description,
            $type,
            null,
            null,
            null,
            $link,
            $username,
            date('Y-m-d'),
            time(),
            $lesson_status
        ));
    } catch (Exception $e) {
        echo "Error: " . $e->getMessage();
    }

    $id = $conn_rjllearning_specific->lastInsertId();
    
    if ($primary_attachment !=  null) {
            $image_name1 = "primary_attachment_" . $id . "." . $file_extension; // Define the image name dynamically
            $primary_attachment_path = $directoryPathMain . $image_name1; // Create the full path for the logo
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $primary_attachment, $primary_attachment_path, $multiple_files_bool = false, $multiple_file_index = 0);
            $primary_attachment_image = json_encode(array("filepath" => $primary_attachment_path, "original_name" => $_FILES['primary_attachment']['name']));
            $sql_logo = "UPDATE lessons SET primary_attachment = ? WHERE id= ?";
            $conn_rjllearning_specific->prepare($sql_logo)->execute(array($primary_attachment_image, $id));
    }
    
    if($cover_image !=  null) {
            $image_name2 = "coverimage_" . $id . "." . $file_extension; // Define the image name dynamically
            $cover_image_path = $directoryPathMain . $image_name2; // Create the full path for the logo
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $cover_image, $cover_image_path, $multiple_files_bool = false, $multiple_file_index = 0);
            $cover_image_new = json_encode(array("filepath" => $cover_image_path, "original_name" => $_FILES['cover_image']['name']));
            $sql_logo = "UPDATE lessons SET cover_image = ? WHERE id= ?";
            $conn_rjllearning_specific->prepare($sql_logo)->execute(array($cover_image_new, $id));
    }
    
     if($audio_attachment !=  null) {
            $image_name3 = "audio_attachment_" . $id . "." . $file_extension; // Define the image name dynamically
            $audio_attachment_path = $directoryPathMain . $image_name3; // Create the full path for the logo
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $audio_attachment, $audio_attachment_path, $multiple_files_bool = false, $multiple_file_index = 0);
            $audio_attachment_image = json_encode(array("filepath" => $audio_attachment_path, "original_name" =>  $_FILES['audio_attachment']['name']));
            $sql_logo = "UPDATE lessons SET audio_attachment = ? WHERE id= ?";
            $conn_rjllearning_specific->prepare($sql_logo)->execute(array($audio_attachment_image, $id));
    }
    
    $timestamp = strtotime("$publish_date $publish_time");
    if (date('H:i') == strtotime($publish_time)) {
        // scheduled right now
        manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'lesson', $id, $publish_date, (time() + 120), 1, $process_type = 'create');
    } else {
        // scheduled for later
        manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'lesson', $id, $publish_date, $timestamp, 1, $process_type = 'create');
    }
    
    // if ($currenttime == strtotime($publish_time)) {
    //         // Task scheduled for publish date right now
    //         manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'lesson', $id, $publish_date, (time() + 120), 1, $process_type = 'create');
    //     } else {
    //         // Task scheduled for publish date later
    //         manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'lesson', $id, $publish_date, $timestamp, 1, $process_type = 'create');
    //     }

    successreturn(array('id' => $id, 'successmsg' => "Successfully Lesson  added."));
} else if ($postdata['function_type'] == "alter_lesson") {
    
    // if ($type == 0 && $primary_attachment != null) {
    //     errorreturn("Cannot upload file attachment when using YouTube embed type. Choose either YouTube link or file upload.");
    // }
    
    // if ($type != 0 && $link != null) {
    //     errorreturn("YouTube link can only be used with 'youtube_embed' type.");
    // }

    if (!isset($postdata['lesson_id']) or !checkIfIssetAndNotEmpty($postdata['lesson_id'])) {
        errorreturn('Error in updating the lesson.');
    } else {
        $id = $postdata['lesson_id'];
    }
    $remove_audio = (isset($postdata['remove_audio']) and !empty($postdata['remove_audio'])) ? trim($postdata['remove_audio']) : 0;
    $remove_bool = (isset($postdata['remove_bool']) and !empty($postdata['remove_bool'])) ? trim($postdata['remove_bool']) : 0;
    $cover_bool = (isset($postdata['cover_bool']) and !empty($postdata['cover_bool'])) ? trim($postdata['cover_bool']) : 0;

    $res = $conn_rjllearning_specific->prepare("SELECT primary_attachment,cover_image,audio_attachment,publish_date  FROM lessons WHERE id = ? and institution_id=? ");
    $res->execute(array($id, $institution_id));
    $result1 = $res->fetchAll();
    if (count($result1) != 1) {
        errorreturn("Lesson not exists. ");
    }
    
    if (count($result1) == 1) {
        $existing_audio = $result1[0]['audio_attachment'];
        if($existing_audio !=  null){
            $old_audio_attachment = json_decode($existing_audio, true);
            $audio_path = $old_audio_attachment['filepath'];
        }
        $existing_attachment = $result1[0]['primary_attachment'];
        if($existing_attachment !=  null){
            $old_primary_attachment = json_decode($existing_attachment, true);
            $primary_path = $old_primary_attachment['filepath'];
        }
        $existing_cover_image = $result1[0]['cover_image'];
        if($existing_cover_image !=  null){
            $old_cover_attachment = json_decode($existing_cover_image, true);
            $cover_path = $old_cover_attachment['filepath'];
        }
    }

    $res = $conn_rjllearning_specific->prepare("SELECT primary_attachment,cover_image,audio_attachment FROM lessons WHERE id != ? and institution_id=? and class_id = ? and subject_id = ? and ( lesson_name = ?) ");
    $res->execute(array($id, $institution_id, $class_id, $subject_id, $lesson_name));
    $result1 = $res->fetchAll();
    if (count($result1) >= 1) {
        errorreturn("This Lesson already exits.");
    }

    if ($audio_attachment != null) {
     
        if ($existing_audio === null) {
            $currentYear = date('Y');
            $currentMonth = date('m');
            $currentDay =  date('d');
            $directoryAudioPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/lesson/" . $currentYear . "/" . $currentMonth . "/";
        } else {

            $directoryAudioPathMain = substr($audio_path, 0, strrpos($audio_path, '/') + 1);
        }

        $file_name = $_FILES['audio_attachment']['name'];
        $fileTmpName = $_FILES['audio_attachment']["tmp_name"];
        $fileSize = $_FILES['audio_attachment']["size"];
        $fileType = $_FILES['audio_attachment']["type"];
        $fileError = $_FILES['audio_attachment']["error"];
        $audio_file_extension = strtolower(pathinfo($_FILES['audio_attachment']['name'], PATHINFO_EXTENSION));
        $size = filesize($fileTmpName);
        // Check if it's a valid image
        $allowedTypes = [
            'audio/mpeg',     // for mp3
            'audio/wav',      // for wav
            'audio/aac',      // for aac
            'audio/flac',     // for flac
            'audio/ogg',      // for ogg
        ]; // Allowed audio types

        $allowed_extensions = ['mp3', 'wav', 'aac', 'flac', 'ogg']; // Allowed audio extensions
        $maxFileSize = 10 * 1024 * 1024; // Maximum file size (2MB)

        checkFileValidation($fileSize, $fileType, $audio_file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }

    if ($primary_attachment != null) {
        // echo 'here';
        if ($existing_attachment === null) {

            $currentYear = date('Y');
            $currentMonth = date('m');
            $currentDay =  date('d');

            $directoryPrimaryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/lesson/" . $currentYear . "/" . $currentMonth . "/";
        } else {

            $directoryPrimaryPathMain = substr($primary_path, 0, strrpos($primary_path, '/') + 1);
        }

        $file_name = $_FILES['primary_attachment']['name'];
        $fileTmpName = $_FILES['primary_attachment']["tmp_name"];
        $fileSize = $_FILES['primary_attachment']["size"];
        $fileType = $_FILES['primary_attachment']["type"];
        $fileError = $_FILES['primary_attachment']["error"];
        $primary_file_extension = strtolower(pathinfo($_FILES['primary_attachment']['name'], PATHINFO_EXTENSION));
        $size = filesize($fileTmpName);
        // Check if it's a valid image
        $allowedTypes = [
            'image/jpeg',
            'image/png',
            'image/gif',
            'image/heic',
            'application/pdf',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.ms-excel',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'video/mp4',
            'video/avi',
            'video/mkv',
            'video/mov',
            'video/webm'
        ];
        $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx', 'mp4', 'avi', 'mkv', 'mov', 'webm'];
        $maxFileSize = 500 * 1024 * 1024; // Maximum file size (2MB)

        checkFileValidation($fileSize, $fileType, $primary_file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }

    if ( $cover_image != null) {
        // echo 'here';
        if ($existing_cover_image === null) {

            $currentYear = date('Y');
            $currentMonth = date('m');
            $currentDay =  date('d');
            $directoryCoverPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/lesson/" . $currentYear . "/" . $currentMonth . "/";
        } else {
            $directoryCoverPathMain = substr($cover_path, 0, strrpos($cover_path, '/') + 1);
        }

        $file_name = $_FILES['cover_image']['name'];
        $fileTmpName = $_FILES['cover_image']["tmp_name"];
        $fileSize = $_FILES['cover_image']["size"];
        $fileType = $_FILES['cover_image']["type"];
        $fileError = $_FILES['cover_image']["error"];
        $cover_file_extension = strtolower(pathinfo($_FILES['cover_image']['name'], PATHINFO_EXTENSION));
        $size = filesize($fileTmpName);
        // Check if it's a valid image
        $allowedTypes = [
            'image/jpeg',
            'image/png',
            'image/gif',
            'image/heic',
            'application/pdf',
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'application/vnd.ms-excel',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        ]; // Allowed image types
        $allowed_extensions = ['jpg', 'gif', 'png', 'heic', 'jpeg', 'pdf', 'xlsx', 'xls', 'doc', 'docx'];
        $maxFileSize = 2; // Maximum file size (2MB)

        checkFileValidation($fileSize, $fileType, $cover_file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }

    $sql_users = "UPDATE lessons SET branch_id = ?,class_id =?,section_id = ?,subject_id =?,publish_date=?,publish_time = ?,terminate_date= ?,termination_time= ?,lesson_category_id = ?,lesson_number = ?,lesson_name=?,author = ?,description= ?,type= ?,link = ? WHERE id=? and institution_id=?";
    $conn_rjllearning_specific->prepare($sql_users)->execute(array($branch_id, $class_id, $json_section_id, $subject_id, $publish_date, $publish_time, $terminate_date, $termination_time, $lesson_category_id, $lesson_number, $lesson_name, $author, $description, $type, $link, $id, $institution_id));

        // Aadhaar Card
    if ($existing_audio != null && $remove_audio == 1) {
        deleteExistingFile($conn_rjllearning_specific, $id, $institution_id, 'audio_attachment', 'lessons', $GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName']);
    }
    if ($audio_attachment !== null && $remove_audio == 1) {
        uploadNewFile('audio_attachment', $id, $audio_attachment, 'lessons', $directoryAudioPathMain, $audio_file_extension, $conn_rjllearning_specific, $GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName']);
    }

    // PAN Card
    if ($remove_bool == 1 && $existing_attachment != null) {
        deleteExistingFile($conn_rjllearning_specific, $id, $institution_id, 'primary_attachment', 'lessons', $GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName']);
    }
    if ($remove_bool == 1 and $primary_attachment !== null) {
        uploadNewFile('primary_attachment', $id, $primary_attachment, 'lessons', $directoryPrimaryPathMain, $primary_file_extension, $conn_rjllearning_specific, $GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName']);
    }

    // Driving Licence
    if ($cover_bool == 1 && $existing_cover_image != null) {
        deleteExistingFile($conn_rjllearning_specific, $id, $institution_id, 'cover_image', 'lessons', $GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName']);
    }
    if ($cover_bool == 1 and $cover_image !== null) {
        uploadNewFile('cover_image', $id, $cover_image, 'lessons', $directoryCoverPathMain, $cover_file_extension, $conn_rjllearning_specific, $GLOBALS['s3_learning_bucket'], $GLOBALS['learning_bucketName']);
    }

    if (date('h-i') == strtotime($publish_time)) {
        // scheduled right now
        manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'lesson', $id, $publish_date, (time() + 120), 1, $process_type = 'alter');
    } else {
        // scheduled for later
        manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'lesson', $id, $publish_date, strtotime($publish_time), 1, $process_type = 'alter');
    }
    
    // if ($currenttime == strtotime($publish_time)) {
    //     // scheduled right now
    //     manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'lessons', $id, $publish_date, (time() + 120), 1, $process_type = 'alter');
    // } else {
    //     // scheduled for later
    //     manageSchedulerTask($conn_rjllearning, $workspace_id, $institution_id, 'lessons', $id, $publish_date, strtotime($publish_time), 1, $process_type = 'alter');
    // }
    
    successreturn("Updated lesson Successfully");
}

 // Helper function to delete existing file
function deleteExistingFile($conn, $lesson_id, $institution_id, $field, $table, $s3_bucket, $bucket_name)
    {
        $sql_image = $conn->prepare("SELECT $field FROM $table WHERE id = ? AND institution_id = ?");
        $sql_image->execute(array($lesson_id, $institution_id));
        $result_image = $sql_image->fetch();

        if ($result_image && $result_image[$field] !== null) {
            $existing_file = json_decode($result_image[$field], true);
            $file_path = $existing_file['filepath'];
            awsS3UserUploadDelete($s3_bucket, $bucket_name, $conn, $institution_id, $file_path, null, null);

            $sql = "UPDATE $table SET $field = ? WHERE id = ? AND institution_id = ?";
            $conn->prepare($sql)->execute(array(null, $lesson_id, $institution_id));
        }
}

function uploadNewFile($file_key, $lesson_id, $field, $table, $directory_path, $file_extension, $conn, $s3_bucket, $bucket_name)
{
    // Define allowed file keys to prevent unauthorized uploads
    $allowed_file_keys = ['audio_attachment', 'primary_attachment', 'cover_image'];
    
    if (!in_array($file_key, $allowed_file_keys)) {
        errorreturn("Invalid file key: $file_key");
    }

    // Build the file name and path dynamically
    $file_name = $file_key . "_" . $lesson_id . "." . $file_extension;
    $file_path = $directory_path . $file_name;

    // Check if the file exists in the $_FILES array
    if (!isset($_FILES[$file_key]) || $_FILES[$file_key]['error'] !== UPLOAD_ERR_OK) {
        errorreturn("File upload error for key: $file_key");
    }

    // Retrieve the original file name
    $tmp_name = $_FILES[$file_key]['name'];

    // Upload to AWS S3
    awsS3UserUploadInsert($s3_bucket, $bucket_name, $field, $file_path, false, 0);

    // Encode file metadata as JSON
    $attachment_image = json_encode([
        "filepath" => $file_path,
        "original_name" => $tmp_name
    ]);

    // Update the database
    $sql = "UPDATE `$table` SET `$file_key` = ? WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$attachment_image, $lesson_id]);

}



function convertTimeFormat($time) {
    // Replace the hyphen (-) with a colon (:)
    $convertedTime = str_replace('-', ':', $time);

    // Validate the converted time format
    if (preg_match("/^(2[0-3]|[01]?[0-9]):[0-5][0-9]$/", $convertedTime)) {
        return $convertedTime; // Valid time in HH:mm format
    }
    return false; // Invalid time
}
