<?php
ini_set('display_errors', 1);

require_once '../../../resources/base_path_include.php';
require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
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/check_username_availability.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'admin_api/academic_session/functions/registration_functions.php';
require_once $base_path_to_learning . 'admin_api/modules/student_admission/upload_admission_certificate_functions.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 . 'external_requests/finware_curl/groups_ledgers/curl_add_alter_student_ledgers_finware.php';
require_once $base_path_to_learning_resources . 'external_requests/finware_curl/groups_ledgers/curl_function_branch_students.php';
require_once $base_path_to_learning . 'user_management/faculty/functions.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/cache_student_academic_function.php';
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";
require_once $base_path_to_learning . "principal_api/principal_function/principal_function.php";

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

$postdata = $_POST;
// print_R($postdata);
// die();
if (
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type']) or
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['jwt_token']) or !checkIfIssetAndNotEmpty($postdata['jwt_token']) or
    !isset($postdata['student_id']) or !checkIfIssetAndNotEmpty($postdata['student_id']) or
    !isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id']) or
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['class_id']) or !checkIfIssetAndNotEmpty($postdata['class_id']) or
    !isset($postdata['section_id']) or !checkIfIssetAndNotEmpty($postdata['section_id']) or
    !isset($postdata['name']) or !checkIfIssetAndNotEmpty($postdata['name']) or
    !isset($postdata['fathername']) or !checkIfIssetAndNotEmpty($postdata['fathername']) or
    !isset($postdata['mothername']) or !checkIfIssetAndNotEmpty($postdata['mothername']) or
    !isset($postdata['mobile']) or !checkIfIssetAndNotEmpty($postdata['mobile']) or
    !isset($postdata['email']) or !checkIfIssetAndNotEmpty($postdata['email']) or
    !isset($postdata['address_line_1']) or !checkIfIssetAndNotEmpty($postdata['address_line_1']) or
    !isset($postdata['city']) or !checkIfIssetAndNotEmpty($postdata['city']) or
    !isset($postdata['pincode']) or !checkIfIssetAndNotEmpty($postdata['pincode']) or
    !isset($postdata['dob']) or !checkIfIssetAndNotEmpty($postdata['dob']) or
    !isset($postdata['gender']) or !checkIfIssetAndNotEmpty($postdata['gender']) or
    !isset($postdata['father_occupation']) or !checkIfIssetAndNotEmpty($postdata['father_occupation']) or
    !isset($postdata['mother_occupation']) or !checkIfIssetAndNotEmpty($postdata['mother_occupation'])
    
) {
    errorreturn("All * fields are required.");
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$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, ['teacher'], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

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);

$nationality = trim($postdata['nationality']);
$caste = ucwords(trim($postdata['caste']));
$class = trim($postdata['class_id']);
$section = trim($postdata['section_id']);
$name = ucwords(trim($postdata['name']));
$fathername = ucwords(trim($postdata['fathername']));
$mothername = ucwords(trim($postdata['mothername']));
$mobile = trim($postdata['mobile']);
$email = trim($postdata['email']);
$address_line_1 = ucwords(trim($postdata['address_line_1']));
$city = ucwords(trim($postdata['city']));
$pincode = trim($postdata['pincode']);
$dob = trim($postdata['dob']);
$gender = trim($postdata['gender']);
$father_occupation = trim($postdata['father_occupation']);
$mother_occupation = trim($postdata['mother_occupation']);
$student_profile_image = (isset($_FILES['student_profile_image']) and !empty($_FILES['student_profile_image'])) ? (($_FILES['student_profile_image'])) : null;
$nationality_proof =  (isset($_FILES['nationality_proof']) and !empty($_FILES['nationality_proof'])) ? $_FILES['nationality_proof'] : null;
$birth_certificate = (isset($_FILES['birth_certificate']) and !empty($_FILES['birth_certificate'])) ? $_FILES['birth_certificate'] : null;
$nationality_proof_number = trim($postdata['nationality_proof_number']);
$profile_image = (isset($_FILES['profile_image']) and !empty($_FILES['profile_image'])) ? $_FILES['profile_image'] : null;
$remove_certificate = (isset($postdata['remove_certificate']) and !empty($postdata['remove_certificate'])) ? trim($postdata['remove_certificate']) : 0;
$remove_nationality = (isset($postdata['remove_nationality']) and !empty($postdata['remove_nationality'])) ? trim($postdata['remove_nationality']) : 0;
$remove_profile_image = (isset($postdata['remove_profile_image']) and !empty($postdata['remove_profile_image'])) ? trim($postdata['remove_profile_image']) : 0;
$blood_group =  (isset($postdata['blood_group']) and !empty($postdata['blood_group'])) ? $postdata['blood_group'] : null;
$can_activate = 1;
// $can_active = trim($postdata['can_active']);
$bus_id =  (isset($postdata['bus_id']) and !empty($postdata['bus_id'])) ? $postdata['bus_id'] : null;
$route_id =  (isset($postdata['route_id']) and !empty($postdata['route_id'])) ? $postdata['route_id'] : null;
$stop_id =  (isset($postdata['stop_id']) and !empty($postdata['stop_id'])) ? $postdata['stop_id'] : null; 
$last_tc = (isset($_FILES['last_tc']) and !empty($_FILES['last_tc'])) ? $_FILES['last_tc'] : null;
$remove_last_tc = (isset($postdata['remove_last_tc']) and !empty($postdata['remove_last_tc'])) ? trim($postdata['remove_last_tc']) : 0;
$class_admitted = trim($postdata['class_admitted']);
$section_admitted = trim($postdata['section_admitted']);
$sibling_bool =  trim($postdata['sibling_bool']);
$sibling = (isset($postdata['sibling']) && is_array($postdata['sibling']) && !empty($postdata['sibling'])) ? $postdata['sibling'] : null;
$last_school = trim($postdata['last_school']);
$date_admission = isset($postdata['date_admission']) && !empty($postdata['date_admission']) 
    ? $postdata['date_admission'] 
    : null;
    
$teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
$class_section_subjects  = $teacher_data['class_section_subjects'];
$class_incharge_roles = $teacher_data['class_incharge_roles'];
$staff_access_modules = $teacher_data['staff_access_modules'];
$check_faculty_status = checkFacultyModuleGranted($postdata['function_type'], $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class, $section, null, $conn_rjllearning);
if ($check_faculty_status == false) {
    errorreturn("Access denied: You do not have the required permissions.");
}


if ($sibling_bool == 1) {
    if (!is_array($sibling) || empty($sibling)) {
        errorreturn("Select at least one sibling.");
    }
        $imploded_siblings = "('" . implode("','", $sibling) . "')";
        $count_siblings = count($sibling);
    
        $sql_student = $conn_rjllearning_specific->prepare("SELECT COUNT(*) as total FROM students WHERE admission_number IN $imploded_siblings AND institution_id = ? AND branch_id = ?");
        $sql_student->execute([$institution_id, $branch_id]);
        $result_student = $sql_student->fetchAll()[0]['total'];
        if ($result_student != $count_siblings) {
            $sibling_bool = 0;
            $sibling = null;
        } else {
            $sibling = "'" . implode("','", $sibling) . "'";
        }
}

{
    $sql = $conn_rjllearning_specific->prepare("SELECT branch_code FROM  branch WHERE id = ? AND institution_id = ?");
    $sql->execute(array($branch_id, $institution_id));
    $result = $sql->fetchAll();
    if (count($result) >= 1) {
        $branch_code = $result[0]['branch_code'];
    } else {
        errorreturn("Branch  not exists.");
    }

    if (!checkOnlyCharacters($name)) { // 6 digit only
        //eg House Name, Street Name
        errorreturn('Name must only contain letters!"');
    }

    if (!CheckEMailIsValidOrNot($email)) {
        errorreturn('Enter valid Email Id');
    }

    if (strlen($mobile) != 13 or $mobile <= 0) {
        errorreturn('Enter valid 12 digit mobile number ' . $mobile);
    }

    if ($gender != 'M' && $gender != 'F') {
        errorreturn('Invalid gender details');
    }

    $date_now = date("Y-m-d");
    if (!CheckDob($dob) or $dob >= $date_now) {
        errorreturn('Invalid DOB formats');
    }
    //student address
    if (!CheckAddressValidation($address_line_1)) {
        //eg House Name, Street Name
        errorreturn('Invalid Address');
    }

    //Branch Pin Code Validation 
    if (!PinCodeValidation($pincode)) { // 6 digit only
        //eg House Name, Street Name
        errorreturn('Invalid Pin Code');
    }
}

if ($postdata['function_type'] == "alter_student") {

    if (!isset($postdata['student_id']) or !checkIfIssetAndNotEmpty($postdata['student_id'])) {
        errorreturn('Error in updating the student.');
    } else {
        $student_id = $postdata['student_id'];
    }

    $current_time = date('Y-m-d H:i:s');

    // $existing_birth_certificate = null;
    // $existing_nationality_proof = null;
    // $existing_student_profile_image = null;
    // $admission_number = null;
    $conn_rjllearning_specific->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
    $conn_rjllearning_specific->beginTransaction();
    try {
        
        $res = $conn_rjllearning_specific->prepare("SELECT id,admission_number,institution_id,birth_certificate,nationality_proof,student_profile_image,user_id FROM  students WHERE id = ? and institution_id=? and branch_id =?  ");
        $res->execute(array($student_id, $institution_id, $branch_id));
        $result1 = $res->fetchAll();
        if (count($result1) == 1) {
            $existing_birth_certificate = $result1[0]['birth_certificate'];
            if ($existing_birth_certificate !=  null) {
                $birth_certificate_data = json_decode($existing_birth_certificate, true);
                $birth_certificate_path = $birth_certificate_data['filepath'];
            }
            $existing_nationality_proof = $result1[0]['nationality_proof'];
            if ($existing_nationality_proof !=  null) {
                $data_attachment_proof = json_decode($existing_nationality_proof, true);
                $nationality_file_path = $data_attachment_proof['filepath'];
            }
            $existing_student_profile_image = $result1[0]['student_profile_image'];
            if ($existing_student_profile_image !=  null) {
                $data_attachment = json_decode($existing_student_profile_image, true);
                $profile_image_path = $data_attachment['filepath'];
            }
            $admission_number = $result1[0]['admission_number'];
            $user_id = $result1[0]['user_id'];
        }

        if ($birth_certificate != null) {
            if ($existing_birth_certificate == null) {

                $currentYear = date('Y');
                $currentMonth = date('m');
                $currentDay =  date('d');
                $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/" . $branch_id .  "/students/" . $admission_number .  "/" . $currentYear . "/" . $currentMonth . "/";
            } else {

                $directoryPathMain = substr($birth_certificate_path, 0, strrpos($birth_certificate_path, '/') + 1);
            }
            $file_name = $_FILES['birth_certificate']['name'];
            $fileTmpName = $_FILES['birth_certificate']["tmp_name"];
            $fileSize = $_FILES['birth_certificate']["size"];
            $fileType = $_FILES['birth_certificate']["type"];
            $fileError = $_FILES['birth_certificate']["error"];
            $birth_certification_file_extension = strtolower(pathinfo($_FILES['birth_certificate']['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, $birth_certification_file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
        }

        if ($nationality_proof != null) {
            if ($existing_nationality_proof == null) {
                $currentYear = date('Y');
                $currentMonth = date('m');
                $currentDay =  date('d');
                $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/" . $branch_id .  "/students/" . $admission_number .  "/" . $currentYear . "/" . $currentMonth . "/";
            } else {
                $directoryPathMain = substr($nationality_file_path, 0, strrpos($nationality_file_path, '/') + 1);
            }

            $file_name = $_FILES['nationality_proof']['name'];
            $fileTmpName = $_FILES['nationality_proof']["tmp_name"];
            $fileSize = $_FILES['nationality_proof']["size"];
            $fileType = $_FILES['nationality_proof']["type"];
            $fileError = $_FILES['nationality_proof']["error"];
            $nationality_proof_file_extension = strtolower(pathinfo($_FILES['nationality_proof']['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, $nationality_proof_file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
        }

        if ($student_profile_image != null) {
            if ($existing_student_profile_image == null) {
                $currentYear = date('Y');
                $currentMonth = date('m');
                $currentDay =  date('d');
                //$directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/admission_documents/" . "/student_uploads/" . $currentYear . "/" . $currentMonth . "/";
                $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/" . $branch_id .  "/students/" . $admission_number .  "/" . $currentYear . "/" . $currentMonth . "/";
            } else {
                $directoryPathMain = substr($profile_image_path, 0, strrpos($profile_image_path, '/') + 1);
            }

            $file_name = $_FILES['student_profile_image']['name'];
            $fileTmpName = $_FILES['student_profile_image']["tmp_name"];
            $fileSize = $_FILES['student_profile_image']["size"];
            $fileType = $_FILES['student_profile_image']["type"];
            $fileError = $_FILES['student_profile_image']["error"];
            $student_file_extension = strtolower(pathinfo($_FILES['student_profile_image']['name'], PATHINFO_EXTENSION));
            $size = filesize($fileTmpName);
            // Check if it's a valid image
            $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/heic']; // Allowed image types
            $allowed_extensions = ['jpg', 'png', 'heic', 'jpeg', 'pdf'];
            $maxFileSize = 2 * 1024 * 1024; // Maximum file size (2MB)

            checkFileValidation($fileSize, $fileType, $student_file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
        }
        
        if ($last_tc != null) {
            $currentYear = date('Y');
            $currentMonth = date('m');
            $currentDay =  date('d');

            $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/" . $branch_id .  "/students/" . $admission_number .  "/" . $currentYear . "/" . $currentMonth . "/";
            $file_name = $_FILES['last_tc']['name'];
            $fileTmpName = $_FILES['last_tc']["tmp_name"];
            $fileSize = $_FILES['last_tc']["size"];
            $fileType = $_FILES['last_tc']["type"];
            $fileError = $_FILES['last_tc']["error"];
            $lasttc_file_extension = strtolower(pathinfo($_FILES['last_tc']['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.wordprocessingml.document',]; // Allowed image types
            $allowed_extensions = ['jpg', 'png', 'heic', 'jpeg', 'pdf', 'doc', 'docx'];
            $maxFileSize = 2 * 1024 * 1024; // Maximum file size (2MB)

            checkFileValidation($fileSize, $fileType, $lasttc_file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
        }
        
        //get student_admission
        $sql_student_admission = $conn_rjllearning_specific->prepare("
        SELECT last_tc FROM student_admission 
        WHERE admission_number = ? AND institution_id = ?");
        $sql_student_admission->execute([$admission_number, $institution_id]);
        $result_student_admission = $sql_student_admission->fetchAll();
        
        $existing_last_tc = null;
        $last_tc_path = null;
        
        if (!empty($result_student_admission[0]['last_tc'])) {
        $existing_last_tc = $result_student_admission[0]['last_tc'];
        $last_tc_data = json_decode($existing_last_tc, true);
        $last_tc_path = $last_tc_data['filepath'] ?? null;
        }


        
        updateUsers($conn_rjllearning, $workspace_id, $institution_id, $name, $dob, $gender, $email, $mobile, $user_id);
        $sql_users = "UPDATE  students SET  date_admission = COALESCE(?, date_admission) ,nationality=?,caste=?,class_id=?,section_id= ?,nationality_proof_number=?,name= ?, fathername=?, mothername=?,mobile=?,email=?,address_line_1= ?,city=?,pincode=?,dob=?,gender=?,blood_group = ?,can_activate= ? ,mother_occupation = ?,father_occupation = ? WHERE id=? and institution_id=? ";
        $conn_rjllearning_specific->prepare($sql_users)->execute(array($date_admission,$nationality, $caste, $class, $section, $nationality_proof_number, $name, $fathername, $mothername, $mobile, $email, $address_line_1, $city, $pincode, $dob, $gender, $blood_group, $can_activate,$mother_occupation,$father_occupation, $student_id, $institution_id));

        //student admission
        $sql_users = "UPDATE student_admission SET  date_admission = COALESCE(?, date_admission) ,class_admitted=?,section_admitted=?,sibling_bool=?,sibling= ?,last_school = ? WHERE admission_number = ? and institution_id=? ";
        $conn_rjllearning_specific->prepare($sql_users)->execute(array($date_admission,$class_admitted, $section_admitted,$sibling_bool, $sibling,$last_school, $admission_number, $institution_id));
        
        if ($remove_last_tc == 1 && $existing_last_tc !== null) {
            if (!empty($last_tc_path)) {
                awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, 
                    $conn_rjllearning_specific, $institution_id, $last_tc_path, null, null);
            }
            
            // Step 3: Update last_tc as NULL in DB
            $sql = "UPDATE student_admission SET last_tc = NULL 
                    WHERE admission_number = ? AND institution_id = ?";
            $conn_rjllearning_specific->prepare($sql)->execute([$admission_number, $institution_id]);
        }
        
        // Step 4: Insert new last_tc if remove_last_tc == 1 and file is uploaded
        if ($remove_last_tc == 1 && isset($_FILES['last_tc'])) {
            $student_file_extension = pathinfo($_FILES['last_tc']['name'], PATHINFO_EXTENSION);
            $image_name = "student_last_tc" . $student_id . "." . $student_file_extension;
            $last_tc_aws = $directoryPathMain . $image_name;
        
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $last_tc, $last_tc_aws, $multiple_files_bool = false, $multiple_file_index = 0);
            // Step 5: Update last_tc path in DB
            $attachment_image = json_encode([
                "filepath" => $last_tc_aws,
                "original_name" => $_FILES['last_tc']['name']
            ]);
        
            $sql_logo = "UPDATE student_admission SET last_tc = ? 
                         WHERE admission_number = ? AND institution_id = ?";
            $conn_rjllearning_specific->prepare($sql_logo)->execute([$attachment_image, $admission_number, $institution_id]);
        }
        
        $check_query = "SELECT * FROM student_stops WHERE student_id = ? AND institution_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($check_query);
        $stmt->execute([$student_id, $institution_id]);
        $result = $stmt->fetch();

        if (is_null($bus_id)) {
            if ($result) {
                // If bus_id is null and the row exists, delete the row
                $delete_query = "DELETE FROM student_stops WHERE student_id = ? AND institution_id = ?";
                $stmt = $conn_rjllearning_specific->prepare($delete_query);
                $stmt->execute([$student_id, $institution_id]);
            }
        } else {
            if ($result) {
                // Row exists, perform update
                $stop_id_to_update = is_null($route_id) ? null : $stop_id;
                $update_query = "UPDATE student_stops SET bus_id = ?, route_id = ?, stop_id = ?, last_modified_by = ?, last_modified_at = ? WHERE institution_id = ? AND branch_id = ? AND student_id = ?";
                $stmt = $conn_rjllearning_specific->prepare($update_query);
                $stmt->execute([$bus_id, $route_id, $stop_id, $username, $current_time, $institution_id, $branch_id, $student_id]);
            } else {
                // No row exists, perform insert
                $stop_id_to_insert = is_null($route_id) ? null : $stop_id;
                $insert_query = "INSERT INTO student_stops (institution_id, branch_id, student_id, bus_id, route_id, stop_id, created_by, created_time) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                $stmt_insert = $conn_rjllearning_specific->prepare($insert_query);
                $stmt_insert->execute([$institution_id, $branch_id, $student_id, $bus_id, $route_id, $stop_id, $username, $current_time]);
            }
        }

        if ($remove_profile_image == 1 and $existing_student_profile_image != null) {
            $sql_image = $conn_rjllearning_specific->prepare("SELECT student_profile_image FROM  students  where id = ? and institution_id = ? ");
            $sql_image->execute(array($student_id, $institution_id));
            $result_image = $sql_image->fetchAll();
            if (count($result_image) == 1) {
                $profileimage = $result_image[0]['student_profile_image'];
                if ($profileimage !=  null) {
                    $data_attachment = json_decode($profileimage, true);
                    $filePath = $data_attachment['filepath'];
                }
                awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $filePath, null, null);
                $sql = "UPDATE students SET student_profile_image = ? WHERE  id = ? and institution_id = ? ";
                $conn_rjllearning_specific->prepare($sql)->execute(array(null, $student_id, $institution_id));
            }
        }

        if ($remove_profile_image == 1 and $student_profile_image !=  null) {
            $image_name = "student_profile_image_" . $student_id . "." . $student_file_extension; // Define the image name dynamically
            $profile_image_aws = $directoryPathMain . $image_name; // Create the full path for the logo
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $student_profile_image, $profile_image_aws, $multiple_files_bool = false, $multiple_file_index = 0);
            $attachment_image = json_encode(array("filepath" => $profile_image_aws, "original_name" => $_FILES['student_profile_image']['name']));
            $sql_logo = "UPDATE students SET student_profile_image = ? WHERE id= ?";
            $conn_rjllearning_specific->prepare($sql_logo)->execute(array($attachment_image, $student_id));
        }

        if ($remove_nationality == 1 and $existing_nationality_proof != null) {
            $sql_image = $conn_rjllearning_specific->prepare("SELECT nationality_proof FROM  students  where id = ? and institution_id = ? ");
            $sql_image->execute(array($student_id, $institution_id));
            $result_image = $sql_image->fetchAll();
            if (count($result_image) == 1) {
                $nationalityproof = $result_image[0]['nationality_proof'];
                if ($nationalityproof !=  null) {
                    $data_attachment_proof = json_decode($nationalityproof, true);
                    $nationality_file_path = $data_attachment_proof['filepath'];
                }
                awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $nationality_file_path, null, null);
                $sql = "UPDATE students SET nationality_proof = ? WHERE  id = ? and institution_id = ? ";
                $conn_rjllearning_specific->prepare($sql)->execute(array(null, $student_id, $institution_id));
            }
        }

        if ($remove_nationality == 1 and $nationality_proof !=  null) {
            $image_name1 = "nationality_proof_" . $student_id . "." . $nationality_proof_file_extension; // Define the image name dynamically
            $nationality_proof_aws = $directoryPathMain . $image_name1; // Create the full path for the logo
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $nationality_proof, $nationality_proof_aws, $multiple_files_bool = false, $multiple_file_index = 0);
            $attachment_image1 = json_encode(array("filepath" => $nationality_proof_aws, "original_name" => $_FILES['nationality_proof']['name']));
            $sql_logo = "UPDATE students SET nationality_proof = ? WHERE id= ?";
            $conn_rjllearning_specific->prepare($sql_logo)->execute(array($attachment_image1, $student_id));
        }

        if ($remove_certificate == 1 and $existing_birth_certificate != null) {
            $sql_image = $conn_rjllearning_specific->prepare("SELECT birth_certificate FROM  students  where id = ? and institution_id = ?");
            $sql_image->execute(array($student_id, $institution_id));
            $result_image = $sql_image->fetchAll();
            if (count($result_image) == 1) {
                $existing_birthcertificate = $result_image[0]['birth_certificate'];
                if ($existing_birthcertificate !=  null) {
                    $birth_certificate_data = json_decode($existing_birthcertificate, true);
                    $birth_certificate_path = $birth_certificate_data['filepath'];
                }
                awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $birth_certificate_path, null, null);
                $sql = "UPDATE students SET birth_certificate = ? WHERE  id = ? and institution_id = ? ";
                $conn_rjllearning_specific->prepare($sql)->execute(array(null, $student_id, $institution_id));
            }
        }

        if ($remove_certificate == 1 and $birth_certificate !=  null) {
            $image_name1 = "birth_certificate_" . $student_id . "." . $birth_certification_file_extension; // Define the image name dynamically
            $ationality_proof_aws = $directoryPathMain . $image_name1; // Create the full path for the logo
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $birth_certificate, $ationality_proof_aws, $multiple_files_bool = false, $multiple_file_index = 0);
            $attachment_image2 = json_encode(array("filepath" => $ationality_proof_aws, "original_name" => $_FILES['birth_certificate']['name']));
            $sql_logo = "UPDATE students SET birth_certificate = ? WHERE id= ?";
            $conn_rjllearning_specific->prepare($sql_logo)->execute(array($attachment_image2, $student_id));
        }

        $branch = getBranchDetails($conn_rjllearning_specific, $branch_id, $institution_id);
        if (!empty($branch)) {
            if (!empty($fathername)) {
                $relation = ($gender === 'M') ? 'S/o' : 'D/o';
                $ledger_name = "$name $relation $father_name - $admission_number";
            } elseif (!empty($mothername)) {
                $relation = ($gender === 'M') ? 'S/o' : 'D/o';
                $ledger_name = "$name $relation $mother_name - $admission_number";
            } else {
                // If both father's and mother's names are null, handle as needed (e.g., just the name and admission number)
                $ledger_name = "$name - $admission_number";
            }

            $ledger_address = sanitizeInput($address_line_1);
            $ledger_name = sanitizeInput($ledger_name);
            $class_info = getClass($conn_rjllearning_specific, $institution_id, $class);
            // print_r($class_info);die();
            $section_data = getSection($conn_rjllearning_specific, $institution_id, $section);
            // Create array with student and branch details for formattedData
            $formattedData[] = array(
                'product_connection_id' => $student_id,
                'ledger_address' => $ledger_address,
                'ledger_name' => $ledger_name,
                'ledger_main_ledgerhead' => 'Sundry Debtors',
                'mobile' => $mobile,
                'email' => $email,
                'class' => $class_info['class_name'],
                'section' => $section_data['section_name'],
                "function_type" => "alter"
            );
            $students_data  = array("workspace_id" => $workspace_id, "branch" => $branch, "student_learning" => $formattedData, "created_by" => $username);
            curlAddAlterStudentLedgersFinware($students_data);
        }
        cacheAcademicStudentData($conn_rjllearning_specific, $institution_id, $branch_id, $class, $section, $student_id, $date_now);
        $conn_rjllearning_specific->commit();
        
        successreturn("Updated student Successfully");
    } catch (Exception $e) {
        $conn_rjllearning_specific->rollBack();
        errorreturn("Error : " . $e->getMessage());
    }
}
