<?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/modules/students/student_functions.php';
require_once $base_path_to_learning . 'user_management/faculty/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 . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/cache_student_academic_function.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_resources . 'lib/cron_jobs/function/function.php';

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

$postdata = $_POST;

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['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id']) or
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['class_admitted']) or !checkIfIssetAndNotEmpty($postdata['class_admitted']) or
    !isset($postdata['section_admitted']) or !checkIfIssetAndNotEmpty($postdata['section_admitted'])
) {
    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;



$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ['superadmin', 'admin'], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
    
}
require_once $base_path_to_learning . 'admin_api/modules/student_admission/upload_admission_certificate_functions.php';

$date_admission = trim(date('Y-m-d', strtotime($postdata['date_admission'])));
$branch_id = trim($postdata['branch_id']);
$institution_id = trim($postdata['institution_id']);
$class_admitted = trim($postdata['class_admitted']);
$section_admitted = trim($postdata['section_admitted']);
//student registration
$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']));

$father_occupation = isset($postdata['father_occupation']) ? ucwords(trim($postdata['father_occupation'])) : null;
$mother_occupation = isset($postdata['mother_occupation']) ? ucwords(trim($postdata['mother_occupation'])) : null;

$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']);
// $ledgerhead = trim($postdata['ledgerhead']);
// $opening_balance = 0.00;
// $current_balance = 0.00;
// $opening_balance_type=trim($postdata['opening_balance_type']);
// $current_balance_type=trim($postdata['current_balance_type']);
// $address = isset($postdata['address_line_1']) ? trim($postdata['address_line_1']) : null;
// $gst = isset($postdata['gst']) ? trim($postdata['gst']) : null;
// $pan = isset($postdata['pan']) ? trim($postdata['pan']) : null;
//validation for ledger
$blood_group =   null;
$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;
// print_r($birth_certificate);
$last_tc = (isset($_FILES['last_tc']) and !empty($_FILES['last_tc'])) ? $_FILES['last_tc'] : null;
$sibling_bool =  trim($postdata['sibling_bool']);
// $sibling = (isset($postdata['sibling']) and !empty($postdata['sibling'])) ? ($postdata['sibling']) : null;
$sibling = (isset($postdata['sibling']) && is_array($postdata['sibling']) && !empty($postdata['sibling'])) ? $postdata['sibling'] : null;

if ($sibling_bool == 1 && is_array($sibling)) {
    if (!is_array($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) {
        // If student count does not match, reset sibling details
        $sibling_bool = 0;
        $sibling = null;
    } else {
        $sibling = "'" . implode("','", $sibling) . "'";
        // $sibling = implode(',', $sibling);
    }
}

// $last_school = trim($postdata['last_school']);
$last_school = (isset($postdata['last_school']) and !empty($postdata['last_school'])) ? ($postdata['last_school']) : null;
$academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if ($academic_id == false) {
    errorreturn("Access denied. Academic session not active.");
} {
    if (!CheckStartDate($date_admission)) {
        //eg House Name, Street Name
        errorreturn('Invalid Date Format');
    }
    $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');
    }

    $dobDate = DateTime::createFromFormat('Y-m-d', $dob);
    $currentDate = new DateTime();
    $minimumAge = 2; // Minimum age in years to allow registration

    if ($dobDate && $dobDate <= $currentDate) {
        $age = $dobDate->diff($currentDate)->y; // Calculate age in years

        if ($age < $minimumAge) {
            errorreturn("Registration denied. Student must be at least $minimumAge years old.");
        }
    }

    //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'] == "create_students_admission") {
        // $branch = getBranchDetails($conn_rjllearning_specific, $branch_id, $institution_id);
        // print_r($branch);
        // die();

    $conn_rjllearning_specific->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
    $conn_rjllearning_specific->beginTransaction();
    try {
        $sql = "SELECT MAX(admission_number) AS max_admission_no FROM students WHERE institution_id = ? AND branch_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute(array($institution_id, $branch_id));
        $max_admission_no_row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($max_admission_no_row['max_admission_no'] !== null) {
            $max_admission_no = intval($max_admission_no_row['max_admission_no']);
            // Increment the maximum admission number
            $incremented_admission_no = $max_admission_no + 1;
            $admission_no_without_branch = $incremented_admission_no;
        } else {
            // If no existing records, start from 1
            $admission_no_without_branch = "1";
        }

        //   // Check if the admission roll no is already used
        $sql_check = "SELECT COUNT(*) AS num_rows FROM students WHERE institution_id = ? AND branch_id = ? AND admission_number = ?";
        $stmt_check = $conn_rjllearning_specific->prepare($sql_check);
        $stmt_check->execute(array($institution_id, $branch_id, $admission_no_without_branch));
        $num_rows = $stmt_check->fetchColumn();
        // Keep incrementing the admission number until it's unique
        while ($num_rows > 0) {
            $incremented_admission_no++;
            $admission_no_without_branch = $incremented_admission_no;
            $stmt_check->execute(array($institution_id, $branch_id, $admission_no_without_branch));
            $num_rows = $stmt_check->fetchColumn();
        }

        $sql_roll = "SELECT MAX(roll_no) AS max_roll_no FROM students WHERE institution_id = ? AND branch_id = ?";
        $stmt_roll = $conn_rjllearning_specific->prepare($sql_roll);

        // Execute the statement with the institution_id and branch_id as parameters
        if ($stmt_roll->execute(array($institution_id, $branch_id))) {
            $max_roll_no_row = $stmt_roll->fetch(PDO::FETCH_ASSOC);

            if ($max_roll_no_row !== false && $max_roll_no_row['max_roll_no'] !== null) {
                $max_roll_no = intval($max_roll_no_row['max_roll_no']);
                // Increment the maximum admission number
                $incremented_roll_no = $max_roll_no + 1;
                $admission_roll_no = $incremented_roll_no;
            } else {
                // If no existing records, start from 1
                $admission_roll_no = 1;
            }
        }



        if ($birth_certificate !=  null) {
            $currentYear = date('Y');
            $currentMonth = date('m');
            $currentDay =  date('d');

            $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/" . $branch_id .  "/students/" . $branch_code . $admission_no_without_branch;
            $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"];
            $certificate_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.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, $certificate_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/" . $branch_code . $admission_no_without_branch;
            $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);
        }

        if ($nationality_proof != null) {
            $currentYear = date('Y');
            $currentMonth = date('m');
            $currentDay =  date('d');

            $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/" . $branch_id .  "/students/" . $branch_code . $admission_no_without_branch;
            $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"];
            $file_extension_of_nationality = 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.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, $file_extension_of_nationality, $maxFileSize, $allowedTypes, $allowed_extensions);
        }

        if ($profile_image != null) {
            $currentYear = date('Y');
            $currentMonth = date('m');
            $currentDay =  date('d');
            $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id .  "/" . $branch_id .  "/students/" . $branch_code . $admission_no_without_branch;
            $file_name = $_FILES['profile_image']['name'];
            $fileTmpName = $_FILES['profile_image']["tmp_name"];
            $fileSize = $_FILES['profile_image']["size"];
            $fileType = $_FILES['profile_image']["type"];
            $fileError = $_FILES['profile_image']["error"];
            $file_extension = strtolower(pathinfo($_FILES['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, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
        }


        $reg_no = trim($postdata['reg_no']);

        $sql_check = $conn_rjllearning_specific->prepare("SELECT id  FROM  student_registration WHERE institution_id = ? AND branch_id = ? AND reg_no = ?");
        $sql_check->execute(array($institution_id, $branch_id, $reg_no));
        $num_rows = $sql_check->fetchAll();
        // Check if there are any existing records with the same combination of admission number and registration number
        if (count($num_rows) != 1) {
            // Handle error - Student already exists with the given registration number and admission number
            errorreturn("Student registration number not exists: registration number $reg_no");
        }
        $reg_id = $num_rows[0]['id'];
        //echo $admission_no_without_branch;die();

        $sql = "INSERT INTO student_admission(institution_id,branch_id,reg_no,date_admission,admission_number,class_admitted,section_admitted,last_tc,last_school
        ,nationality,nationality_proof_number,caste,birth_certificate,nationality_proof,dob,gender,blood_group,address_line_1,city,pincode,date_added,added_by,profile_image,sibling_bool,sibling, student_id)
                             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt =  $conn_rjllearning_specific->prepare($sql);
        $stmt->execute(array(
            $institution_id,
            $branch_id,
            $reg_no,
            $date_admission,
            $admission_no_without_branch,
            $class_admitted,
            $section_admitted,
            null,
            $last_school,
            $nationality,
            $nationality_proof_number,
            $caste,
            null,
            null,
            $dob,
            $gender,
            $blood_group,
            $address_line_1,
            $city,
            $pincode,
            date('Y-m-d'),
            $username,
            null,
            $sibling_bool,
            $sibling,
            $institution_id . '_' . $branch_id . '_' . $reg_id
        ));

        $admission_id = $conn_rjllearning_specific->lastInsertId();

        if ($last_tc !=  null) {
            $image_name = "student_last_tc_" . $admission_id . "." . $lasttc_file_extension; // Define the image name dynamically
            $student_lasttc_path = $directoryPathMain . $image_name; // Create the full path for the logo
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $last_tc, $student_lasttc_path, $multiple_files_bool = false, $multiple_file_index = 0);
            $last_tc_image = json_encode(array("filepath" => $student_lasttc_path, "original_name" => $_FILES['last_tc']['name']));
            $sql_logo = "UPDATE student_admission SET last_tc = ? WHERE id= ?";
            $conn_rjllearning_specific->prepare($sql_logo)->execute(array($last_tc_image, $admission_id));
        }

        $institution_info = getInstitution($conn_rjllearning, $institution_id);
        // print_r($institution_info['institution_code']);die();
        $additional_data = ['branch_code'];
        $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $branch_id, $additional_data);
        // echo $branch_info['branch_code'];die();

        $student_username = ($branch_info['branch_code']) . "" . $admission_no_without_branch . "@" . ($institution_info['institution_code']);
        // echo $student_username;die();
        $check_availability = checkUsernameAvailabilty($conn_rjllearning, $student_username);
        if (!$check_availability) {
            errorreturn('Username already exists. Please try another username.' .$student_username);
        }

        //student registration
        $sql = "INSERT INTO students(
                    institution_id, branch_id, admission_id, academic_id, nationality, caste, admission_number, class_id, section_id, roll_no, username, student_profile_image, birth_certificate, nationality_proof, nationality_proof_number, name, fathername, mothername, mobile, email, address_line_1, city, pincode, dob, gender, blood_group, date_admission, date_added, added_by, user_id, can_activate, status, father_occupation, mother_occupation
                ) 
                VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?)";

        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute(array(
            $institution_id,
            $branch_id,
            $admission_id,
            $academic_id,
            $nationality,
            $caste,
            $admission_no_without_branch,
            $class_admitted,
            $section_admitted,
            $admission_roll_no,
            $student_username,
            null,
            null,
            null,
            $nationality_proof_number,
            $name,
            $fathername,
            $mothername,
            $mobile,
            $email,
            $address_line_1,
            $city,
            $pincode,
            $dob,
            $gender,
            $blood_group,
            $date_admission,
            date('Y-m-d'),
            $username,
            $username,
            1,
            1,
            $father_occupation,  // Add father occupation
            $mother_occupation   // Add mother occupation
        ));

        $student_id = $conn_rjllearning_specific->lastInsertId();


        $sql = "UPDATE student_admission set student_id = ? where institution_id = ? and student_id = ?";
        $update = $conn_rjllearning_specific->prepare($sql)->execute(array($student_id, $institution_id, $institution_id . '_' . $branch_id . '_' . $reg_id));

        $chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@#$%&*_";
        $password = substr(str_shuffle($chars), 0, 8);
        //encrypt password
        $hashed_password = password_hash($password, PASSWORD_DEFAULT);

        if ($birth_certificate !=  null) {
            $image_name1 = "birth_certificate_" . $admission_id . "." . $certificate_extension;
            $admission_student_certificate_path = $directoryPathMain . $image_name1;
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $birth_certificate, $admission_student_certificate_path, $multiple_files_bool = false, $multiple_file_index = 0);
            $admission_attachment_certificate = json_encode(array("filepath" => $admission_student_certificate_path, "original_name" => $_FILES['birth_certificate']['name']));
            $sql_logo = "UPDATE student_admission SET birth_certificate = ? WHERE id= ?";
            $conn_rjllearning_specific->prepare($sql_logo)->execute(array($admission_attachment_certificate, $admission_id));
        }

        if ($nationality_proof !=  null) {
            $image_name2 = "nationality_proof_" . $admission_id . "." . $file_extension_of_nationality;
            $admission_student_nationality_path = $directoryPathMain . $image_name2;
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $nationality_proof, $admission_student_nationality_path, $multiple_files_bool = false, $multiple_file_index = 0);
            $admission_attachment_nationality = json_encode(array("filepath" => $admission_student_nationality_path, "original_name" => $_FILES['nationality_proof']['name']));
            $sql_logo = "UPDATE student_admission SET nationality_proof = ? WHERE id= ?";
            $conn_rjllearning_specific->prepare($sql_logo)->execute(array($admission_attachment_nationality, $admission_id));
        }

        if ($profile_image !=  null) {
            $image_name3 = "profile_image_" . $admission_id . "." .  $file_extension; // Define the image name dynamically
            $student_profile_path = $directoryPathMain . $image_name3; // Create the full path for the logo
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $profile_image, $student_profile_path, $multiple_files_bool = false, $multiple_file_index = 0);
            $attachment_image = json_encode(array("filepath" => $student_profile_path, "original_name" => $_FILES['profile_image']['name']));
            $sql_logo = "UPDATE student_admission SET profile_image = ? WHERE id= ?";
            $conn_rjllearning_specific->prepare($sql_logo)->execute(array($attachment_image, $admission_id));
        }

        if ($profile_image !=  null) {
            $image_name3 = "profile_image_" . $student_id . "." .  $file_extension; // Define the image name dynamically
            $student_profile_path = $directoryPathMain . $image_name3; // Create the full path for the logo
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $profile_image, $student_profile_path, $multiple_files_bool = false, $multiple_file_index = 0);
            $attachment_image = json_encode(array("filepath" => $student_profile_path, "original_name" => $_FILES['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 ($birth_certificate !=  null) {
            $image_name1 = "birth_certificate_" . $student_id . "." . $certificate_extension; // Define the image name dynamically
            $student_certificate_path = $directoryPathMain . $image_name1; // Create the full path for the logo
            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $birth_certificate, $student_certificate_path, $multiple_files_bool = false, $multiple_file_index = 0);
            $attachment_certificate = json_encode(array("filepath" => $student_certificate_path, "original_name" => $_FILES['birth_certificate']['name']));
            $sql_logo = "UPDATE students SET birth_certificate = ? WHERE id= ?";
            $conn_rjllearning_specific->prepare($sql_logo)->execute(array($attachment_certificate, $student_id));
        }

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

        // Update student registration
        $registation_status = 2;
        // Call updateStudentRegistration function with new data
        $sql_users = "UPDATE student_registration SET  name=?, fathername=?, mothername=?,mobile=?,email=?,address_line_1= ?,city=?,pincode=?,dob=?,gender=?,status = ?, student_id = ? WHERE id=? and institution_id=?";
        $conn_rjllearning_specific->prepare($sql_users)->execute(array($name, $fathername, $mothername, $mobile, $email, $address_line_1, $city, $pincode, $dob, $gender, $registation_status, $student_id, $reg_id, $institution_id));

        //curl api for students
        // get branch data - Rejoice Learning company id, branch id and finware book id function
        $branch = getBranchDetails($conn_rjllearning_specific, $branch_id, $institution_id);
        if (!empty($branch)) {
            if (!empty($fathername)) {
                // Use father's name if it's not null
                // Use "S/o" for males and "D/o" for females
                $relation = ($gender === 'M') ? 'S/o' : 'D/o';
                $ledger_name = "$name $relation $fathername - $admission_no_without_branch";
                //$ledger_name = "$name S/o $father_name - $admission_no_without_branch";
            } elseif (!empty($mothername)) {
                // Use mother's name if father's name is null
                //$ledger_name = "$name D/o $mother_name - $admission_no_without_branch";
                $relation = ($gender === 'M') ? 'S/o' : 'D/o';
                $ledger_name = "$name $relation $mothername - $admission_no_without_branch";
            } 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_no_without_branch";
            }

            $ledger_address = sanitizeInput($address_line_1);
            $ledger_name = sanitizeInput($ledger_name);
            $class_info = getClass($conn_rjllearning_specific, $institution_id, $class_admitted);
            $section = getSection($conn_rjllearning_specific, $institution_id, $section_admitted);
            // Create array with student and branch details for formattedData
            $formattedData[] = array(
                // 'product_connection_id' => $userid,
                '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['section_name'],
                'admission_number' => $admission_no_without_branch,
                "function_type" => "add"
            );
            $students_data  = array("workspace_id" => $workspace_id, "branch" => $branch, "student_learning" => $formattedData, "created_by" => $username);
            curlAddAlterStudentLedgersFinware($students_data);
        }
        
        $userid = storeUser($conn_rjllearning, $workspace_id, $institution_id, $name, $dob, $gender, $student_username, $email, $mobile, $hashed_password, $role = 'student', $branch_id);

        $sql = "Update students set user_id = ? where id  = ? AND institution_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute(array($userid, $student_id, $institution_id));
        

        require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/mail_system/mail_Template1.php';
        //     $subject = 'Welcome to ' . $web_app_title;
        //     $message = 'Welcome to ';
    
        //     $message = "
        // <h1>Welcome To <span class='web_app_title'>$web_app_title</span></h1>
        // <p>Thank you for creating a user account on $web_app_title. You can now sign in at <a href='https://students.rejoicelearning.in'>https://students.rejoicelearning.in</a> or <a href='https://students.rejoicelearning.in'>Click Here</a>.</p>
        // <p>
        //     Name: <b>$name</b><br>
        //     Username: <b>$student_username</b><br>
        //     Password: <b>$password</b>
        // </p>";
        $institution_info = getInstitution($conn_rjllearning, $institution_id);
        $white_label_url = $institution_info['white_label_url'] ?? '';
        $white_label_email = $institution_info['white_label_email'] ?? '';
        $white_label_message_header = $institution_info['white_label_message_header'] ?? '';
        $white_label_app_name = $institution_info['white_label_app_name'] ?? '';

        // Set default domain
        $default_domain = 'rejoicelearning.in';

        // Build faculty subdomain-based URL dynamically
        if (!empty($white_label_url)) {
            $domain = str_replace(['http://', 'https://', 'www.'], '', $white_label_url);
            $domain_parts = explode('/', $domain); // remove any path
            $base_domain = $domain_parts[0];

            $url = 'https://students.' . $base_domain;
        } else {
            $url = 'https://students.' . $default_domain;
        }

        // Use white label values if provided, otherwise fallback to default
        $app_name = !empty($white_label_app_name) ? $white_label_app_name : $web_app_title;
        $app_url = $url;
        $from_email = !empty($white_label_email) ? $white_label_email : 'Rejoice Learning <no-reply@rejoicelearning.in>';

        // Email Subject
        $subject = 'Welcome to ' . $app_name;

        // Email Body
        $message = "
         <h1>Welcome To <span class='web_app_title'>$app_name</span></h1>
            <p>Thank you for creating a user account on $app_name. You can now sign in at $app_url or <a href='$app_url'>Click Here<a>. </p>
            Name : <b>$name</b><br>
            Username : <b>$student_username</b><br>
            Password : <b>$password</b>
        </p>";
        $conn_rjllearning_specific->commit();
        sendMailTemplate1($conn_rjllearning,$from_email,$email,$subject,$message,$workspace_id,$institution_id,$branch_id,$userid,null,'real_time');
       // sendMailTemplate1($conn_rjllearning, 'Rejoice Learning <no-reply@rejoicelearning.in>', $email, $subject, $message, $workspace_id, $institution_id, $branch_id, $userid, null, 'real_time');
        cacheAcademicStudentData($conn_rjllearning_specific, $institution_id, $branch_id, $class_admitted, $section_admitted, $student_id, $date_admission);
        successreturn("Successfully student admission completed. Kindly check your registered email id for your login credentials.");
    } catch (Exception $e) {
        $conn_rjllearning_specific->rollBack();
        errorreturn("Error : " . $e->getMessage());
    }
    //successreturn(array('id' => $admission_id, 'successmsg' => "Successfully student admission completed."));
}
