<?php
ini_set('display_errors', 1);
ini_set('memory_limit', '512M');
ini_set('max_execution_time', 300);
date_default_timezone_set('Asia/Kolkata'); // Set your timezone

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 . 'admin_api/modules/student_registration/functions/functions.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';

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

use PhpOffice\PhpSpreadsheet\IOFactory;

// $postdata = file_get_contents("php://input");
$postdata = $_POST;


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, ['principal'], 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);

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

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

    if (isset($_FILES['file'])) {
        $insert_data = [];

        $fileName = $_FILES['file']['name'];
        $fileSize = $_FILES['file']['size'];
        $fileTemp = $_FILES['file']['tmp_name'];
        $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);

        // Define allowed file extensions
        $allowedExtensions = ["xlsx", "xls"];
        if (!in_array($fileExtension, $allowedExtensions)) {
            errorreturn("Only XLSX and XLS files are allowed.");
        }

        // File size validation (max 10MB)
        $maxFileSize = 10 * 1024 * 1024;
        if ($fileSize > $maxFileSize) {
            errorreturn('File size exceeds the maximum allowed limit (10 MB).');
        }


        try {
            $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($fileTemp);
            $worksheet = $spreadsheet->getSheet(0);

            foreach ($worksheet->getRowIterator() as $rowNumber => $row) {
                if ($rowNumber >= 1) {  // Process rows starting from row 8
                    if ($rowNumber == 1) continue; // Skip the header row (column names)

                    $cellIterator = $row->getCellIterator();
                    $cellIterator->setIterateOnlyExistingCells(false); // Read all cells

                    $rowData = [];
                    foreach ($cellIterator as $cell) {
                        $rowData[] = $cell->getValue();
                    }

                    // Debugging Output: Check Row Data


                    // Ensure there is valid data in the row
                    if (empty(array_filter($rowData))) continue; // Skip empty rows

                    // Now, $rowData[0] should contain actual branch name
                    $branch = trim($rowData[0]); // Example: "Chandigarh"

                    $requiredFields = [
                        'branch' => $rowData[0] ?? null,
                        'reg_no' => $rowData[1] ?? null,
                        'name' => strtolower($rowData[2] ?? null),
                        'fathername' => strtolower($rowData[3] ?? null),
                        'mothername' => $rowData[4] ?? null,
                        'mobile' => $rowData[5] ?? null,
                        'email' => strtolower($rowData[6] ?? null),
                        'address_line_1' => $rowData[7] ?? null,
                        'city' => $rowData[8] ?? null,
                        'pincode' => $rowData[9] ?? null,
                        'dob' => $rowData[10] ?? null,
                        'gender' => $rowData[11] ?? null,
                        'for_class' => $rowData[16] ?? null,
                        'last_school_name' => $rowData[17] ?? null,
                        'current_class_name' => $rowData[18] ?? null,
                    ];

                    // Check for null values in required fields
                    foreach ($requiredFields as $field => $value) {
                        if (is_null($value) || $value === '') {
                            errorreturn("Error: The field '$field' cannot be null or empty.");
                        }
                    }


                    // Extract values from the row
                    $branch = $rowData[0];
                    $reg_no = $rowData[1];
                    $name = strtoupper($rowData[2]);
                    $fathername = strtoupper($rowData[3]);
                    $mothername = $rowData[4];
                    $mobile = $rowData[5];
                    $email = strtolower($rowData[6]);
                    $address_line_1 = $rowData[7];
                    $city = $rowData[8];
                    $pincode = $rowData[9];
                    $dob = $rowData[10];
                    $gender = $rowData[11];
                    $reg_fees = $rowData[12] ?? null;
                    $paid_through = $rowData[13] ?? null;
                    $payment_mode = $rowData[14] ?? null;
                    $reference_number = $rowData[15] ?? null;
                    $for_class_name = $rowData[16];
                    $last_school = $rowData[17];
                    $current_class_name = $rowData[18];
                    $section_admitted_name = $rowData[19];
                    $country_name = $rowData[20];
                    $caste = $rowData[21];
                    $nationality = $rowData[22];
                    $nationality_proof_number = $rowData[23];
                    $blood_group = $rowData[24];




                    $stmt = $conn_rjllearning->prepare("SELECT id FROM country_info WHERE name = ?");
                    $stmt->execute([$country_name]); // Bind the value inside an array
                    $country = $stmt->fetch(PDO::FETCH_COLUMN); // Fetch the single column value

                    // // Fetch Branch ID
                    // $stmt = $conn_rjllearning_specific->prepare("SELECT id FROM branch WHERE name = ? AND institution_id = ?");
                    // $stmt->execute([$branch, $institution_id]);
                    // $branchData = $stmt->fetch(PDO::FETCH_ASSOC);
                    // if (!$branchData) {
                    //     errorreturn("Branch not found for the given institution.");
                    // }
                    // $branch_id = $branchData['id'];

                    $stmt = $conn_rjllearning_specific->prepare("
                        SELECT id 
                        FROM section_info 
                        WHERE section_name = ? 
                        AND institution_id = ? 
                        AND (branch_id LIKE ? OR branch_id = 'all')
                    ");

                    $branch_id_like = '%' . $branch_id . '%'; // Add wildcard before binding

                    $stmt->execute([$section_admitted_name, $institution_id, $branch_id_like]);

                    $sectionData = $stmt->fetch(PDO::FETCH_ASSOC);

                    if (!$sectionData) {
                        errorreturn("Section not found for the given institution and branch.");
                    }

                    $section_admitted = $sectionData['id'];

                    // Fetch Last School Class ID
                    $stmt = $conn_rjllearning_specific->prepare("
                        SELECT id 
                        FROM class_info 
                        WHERE classname = ? 
                        AND institution_id = ? 
                        AND (branch_id LIKE ? OR branch_id = 'all')
                    ");

                    $params = [$for_class_name, $institution_id, '%' . $branch_id . '%'];

                    $stmt->execute($params);
                    $forclassname = $stmt->fetch(PDO::FETCH_ASSOC);

                    if (!$forclassname) {
                        errorreturn("New class not found for the given institution and branch.");
                    }

                    $for_class = $forclassname['id'];

                    // Fetch Current Class ID
                    $stmt = $conn_rjllearning_specific->prepare("
                        SELECT id 
                        FROM class_info 
                        WHERE classname = ? 
                        AND institution_id = ? 
                        AND (branch_id LIKE ? OR branch_id = 'all')
                    ");
                    $stmt->execute([$current_class_name, $institution_id, '%' . $branch_id . '%']);
                    $currentClassData = $stmt->fetch(PDO::FETCH_ASSOC);

                    if (!$currentClassData) {
                        errorreturn("Current class not found for the given institution and branch.");
                    }

                    $current_class = $currentClassData['id'];

                    // Mobile validation
                    if (!preg_match('/^\d{10}$/', $mobile)) {
                        errorreturn("Invalid mobile number at row: $rowNumber");
                    }
                    $mobile = "+91" . $mobile;

                    // Validate Email
                    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                        errorreturn('Enter a valid Email Id.');
                    }

                    // Validate Gender
                    if (!in_array($gender, ['M', 'F'])) {
                        errorreturn('Invalid gender details.');
                    }

                    // Validate DOB
                    $date_now = date("Y-m-d");
                    if (is_numeric($dob)) {
                        // Handle as Excel serial date
                        $excelBaseDate = 25569; // Excel's base date is January 1, 1900
                        $unixTimestamp = ($dob - $excelBaseDate) * 86400; // Convert to Unix timestamp
                        $dob = date("Y-m-d", $unixTimestamp);
                    } else {
                        // Handle as dd-mm-yyyy format
                        if (!strtotime($dob)) {
                            errorreturn('Invalid date format. Expected format: dd-mm-yyyy. Received: ' . $dob);
                            return;
                        }
                        $dob = date('Y-m-d', strtotime($dob));
                    }
                    //  echo $dob;die();
                    // Validate DOB is in the past
                    if (!CheckDob($dob) or $dob >= $date_now) {
                        errorreturn('Invalid DOB format or DOB cannot be today/future date.');
                    }
                    // if ($dob >= $date_now) {
                    //     errorreturn('Invalid DOB format.');
                    // }

                    // Check for Duplicate Student
                    $stmt = $conn_rjllearning_specific->prepare("SELECT id FROM students WHERE institution_id = ? AND branch_id = ? AND (name = ? OR email = ? OR mobile = ?)");

                    $params = [$institution_id,$branch_id,$name, $email, $mobile];

                    $stmt->execute($params);
                    if ($stmt->rowCount() > 0) {
                        errorreturn("Duplicate entry found at row: $rowNumber");
                    }

                    // Add valid data for batch insertion
                    $insert_data[] = [
                        $institution_id,
                        $branch_id,
                        $reg_no,
                        $name,
                        $fathername,
                        $mothername,
                        $mobile,
                        $email,
                        $address_line_1,
                        $city,
                        $pincode,
                        $dob,
                        $gender,
                        $reg_fees,
                        $paid_through,
                        $reference_number,
                        $for_class,
                        $last_school,
                        $current_class,
                        0,
                        null,
                        $date_now,
                        $username,
                        '1'
                    ];
                }
            }



            // Debug Admission Number Query
            $sql = "SELECT MAX(admission_number) AS max_admission_no FROM student_admission 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);

            // echo "<pre>";
            // echo "Max Admission Number Row: ";
            // print_r($max_admission_no_row);
            // echo "</pre>";

            if ($max_admission_no_row['max_admission_no'] !== null) {
                // Extract numeric part from max admission number and increment
                preg_match('/(\d+)/', $max_admission_no_row['max_admission_no'], $matches);
                $max_admission_no = isset($matches[0]) ? intval($matches[0]) : 0;
                $admission_no_without_branch = $max_admission_no + 1;
            } else {
                $admission_no_without_branch = 1;
            }

            $incremented_admission_no = $admission_no_without_branch;


            // echo "<pre>";
            // echo "Incremented Admission No: $admission_no_without_branch\n";
            // echo "</pre>";

            // Debug Unique Admission Number Check
            $sql_check = "SELECT COUNT(*) AS num_rows FROM student_admission 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();

            // echo "<pre>";
            // echo "Initial Admission No Check - Count: $num_rows\n";
            // echo "</pre>";

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

                // echo "<pre>";
                // echo "Incremented Admission No (While Loop): $admission_no_without_branch, Count: $num_rows\n";
                // echo "</pre>";
            }

            // Debug Roll Number Query
            $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);

            if ($stmt_roll->execute(array($institution_id, $branch_id))) {
                $max_roll_no_row = $stmt_roll->fetch(PDO::FETCH_ASSOC);

                // echo "<pre>";
                // echo "Max Roll Number Row: ";
                // print_r($max_roll_no_row);
                // echo "</pre>";

                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']);
                    $incremented_roll_no = $max_roll_no + 1;
                    $admission_roll_no = $incremented_roll_no;
                } else {
                    $admission_roll_no = 1;
                }
            }

            // echo "<pre>";
            // echo "Final Admission Roll No: $admission_roll_no\n";
            // echo "</pre>";


            $date_admission = date('Y-m-d');

            try {
                // Start transaction
                $conn_rjllearning_specific->beginTransaction();



                if (!empty($insert_data)) {
                    // Prepare SQL statements
                    $stmt_insert_registration = $conn_rjllearning_specific->prepare("
                        INSERT INTO student_registration (
                            institution_id, branch_id, reg_no, name, fathername, mothername, mobile, email,
                            address_line_1, city, pincode, dob, gender, reg_fees, paid_through, refrence_number,
                            for_class, last_school, current_class, sibling_bool, sibling, date_added, added_by, status
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");

                    $stmt_insert_student_admission = $conn_rjllearning_specific->prepare("
                        INSERT INTO student_admission (
                            institution_id, branch_id, reg_no, date_admission, admission_number, class_admitted,
                            section_admitted, last_tc, last_school, date_added, added_by, profile_image, sibling_bool,
                            sibling, student_id
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");

                    $stmt_insert_students = $conn_rjllearning_specific->prepare("
                        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
                        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");

                    $stmt_update_student_admission = $conn_rjllearning_specific->prepare("UPDATE student_admission SET student_id = ? WHERE institution_id = ? AND student_id = ?");

                    $stmt_update_students = $conn_rjllearning_specific->prepare(" UPDATE students SET user_id = ? WHERE id = ? AND institution_id = ?");

                    $stmt_update_users = $conn_rjllearning_specific->prepare("
                        UPDATE student_registration SET name=?, fathername=?, mothername=?, mobile=?, email=?, 
                        address_line_1=?, city=?, pincode=?, dob=?, gender=?, status=?, student_id=? 
                        WHERE id=? AND institution_id=?
                    ");

                    $reg_ids = []; // Store registration IDs for debugging

                    foreach ($insert_data as $index => $rowAdd) {
                        // Insert into student_registration
                        $stmt_insert_registration->execute($rowAdd);
                        $reg_id = $conn_rjllearning_specific->lastInsertId();

                        if ($rowAdd[13] !== null) {
                            registerStudent($conn_rjllearning_specific, $institution_id, $branch_id, $rowAdd[3], 'Student_Registration', $rowAdd[13], $date_now, 'receipt', 1, $rowAdd[14], $username, $rowAdd[15]);
                        }

                        // Assign variables
                        $name = $rowAdd[3];
                        $fathername = $rowAdd[4];
                        $mothername = $rowAdd[5];
                        $mobile = $rowAdd[6];
                        $email = $rowAdd[7];
                        $address_line_1 = $rowAdd[8];
                        $city = $rowAdd[9];
                        $pincode = $rowAdd[10];
                        $dob = $rowAdd[11];
                        $gender = $rowAdd[12];
                        $blood_group = null;

                        // Insert into student_admission
                        $stmt_insert_student_admission->execute([
                            $institution_id,
                            $branch_id,
                            $rowAdd[2],
                            $date_admission,
                            $admission_no_without_branch,
                            $rowAdd[16],
                            $section_admitted,
                            null,
                            $rowAdd[17],
                            date('Y-m-d'),
                            $username,
                            null,
                            0,
                            null,
                            $institution_id . '_' . $branch_id . '_' . $reg_id
                        ]);
                        $admission_id = $conn_rjllearning_specific->lastInsertId();

                        // Generate Unique Username
                        $institution_info = getInstitution($conn_rjllearning, $institution_id);
                        $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $branch_id, ['branch_code']);
                        $student_username = ($branch_info['branch_code']) . $admission_no_without_branch . "@" . ($institution_info['institution_code']);

                        while (!checkUsernameAvailabilty($conn_rjllearning, $student_username)) {
                            $admission_no_without_branch++;
                            $student_username = ($branch_info['branch_code']) . $admission_no_without_branch . "@" . ($institution_info['institution_code']);
                        }

                        // Insert into students
                        $stmt_insert_students->execute([
                            $institution_id,
                            $branch_id,
                            $admission_id,
                            $academic_id,
                            'Indian',
                            'General',
                            $admission_no_without_branch,
                            $rowAdd[16],
                            $section_admitted,
                            rand(1, 100),
                            $student_username,
                            null,
                            null,
                            null,
                            null,
                            $name,
                            $fathername,
                            $mothername,
                            $mobile,
                            $email,
                            $address_line_1,
                            $city,
                            $pincode,
                            $dob,
                            $gender,
                            $blood_group,
                            $date_admission,
                            date('Y-m-d'),
                            $username,
                            $username,
                            1,
                            1
                        ]);
                        $student_id = $conn_rjllearning_specific->lastInsertId();

                        // Update student_admission table
                        $stmt_update_student_admission->execute([$student_id, $institution_id, $institution_id . '_' . $branch_id . '_' . $reg_id]);

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

                        // Create User
                        $userid = storeUser($conn_rjllearning, $workspace_id, $institution_id, $name, $dob, $gender, $student_username, $email, $mobile, $hashed_password, 'student', $branch_id);

                        // Update students table with user_id
                        $stmt_update_students->execute([$userid, $student_id, $institution_id]);

                        // Update student registration
                        $stmt_update_users->execute([$name, $fathername, $mothername, $mobile, $email, $address_line_1, $city, $pincode, $dob, $gender, 2, $student_id, $reg_id, $institution_id]);

                        // Cache Student Data
                        cacheAcademicStudentData($conn_rjllearning_specific, $institution_id, $branch_id, $rowAdd[16], $section_admitted, $student_id, $date_admission);

                        // Retrieve branch details
                        $branch = getBranchDetails($conn_rjllearning_specific, $branch_id, $institution_id);
                        if ($branch) {
                            // Generate ledger name based on parent's name
                            if (!empty($fathername)) {
                                $ledger_name = "$name S/o $fathername - $admission_no_without_branch";
                            } elseif (!empty($mothername)) {
                                $ledger_name = "$name D/o $mothername - $admission_no_without_branch";
                            } else {
                                $ledger_name = "$name - $admission_no_without_branch";
                            }

                            // Sanitize inputs
                            $ledger_address = sanitizeInput($address_line_1);
                            $ledger_name = sanitizeInput($ledger_name);

                            // Create student financial ledger data
                            $formattedData[] = [
                                'product_connection_id' => $userid,
                                'ledger_address' => $ledger_address,
                                'ledger_name' => $ledger_name,
                                'ledger_main_ledgerhead' => 'Sundry Debtors',
                                'mobile' => $mobile,
                                'email' => $email,
                                'class' => $rowAdd[16],
                                'section' => $section_admitted,
                                "function_type" => "add"
                            ];

                            $students_data = [
                                "workspace_id" => $workspace_id,
                                "branch" => $branch,
                                "student_learning" => $formattedData,
                                "created_by" => $username
                            ];

                            // Send data to financial system
                            curlAddAlterStudentLedgersFinware($students_data);
                        }

                        // Send Welcome Email
                        if (isset($email) && isset($name) && isset($student_username) && isset($password)) {
                            $students_list[] = [
                                "user_id" => $userid,
                                "email" => $email,
                                "name" => $name,
                                "username" => $student_username,
                                "password" => $password
                            ];
                        }
                    }

                    if (!empty($students_list)) {
                        require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/mail_system/mail_Template1.php';
                        
                        $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>';
                        $subject = 'Welcome to ' . $white_label_app_name;

                        $subject = 'Welcome to ' . $app_name;
                        // $url = 'https://students.rejoicelearning.in';

                        // Process each student and send welcome email
                        foreach ($students_list as $emailDetail) {
                            // Create personalized message for each student
                            $message = "
                                                <h1>Welcome To <span class='web_app_title'>" . htmlspecialchars($app_name) . "</span></h1>
                                                <p>Thank you for creating a user account on " . htmlspecialchars($app_name) . ". 
                                                   You can now sign in at <a href='" . htmlspecialchars($url) . "'>" . htmlspecialchars($url) . "</a>.</p>
                                                <p>
                                                    Name: <b>" . htmlspecialchars($emailDetail['name']) . "</b><br>
                                                    Username: <b>" . htmlspecialchars($emailDetail['username']) . "</b><br>
                                                    Password: <b>" . htmlspecialchars($emailDetail['password']) . "</b>
                                                </p>";

                            // Send email using template
                            sendMailTemplate1(
                                $conn_rjllearning,
                                $from_email,
                                $emailDetail['email'],
                                $subject,
                                $message,
                                $workspace_id,
                                $institution_id,
                                $branch_id,
                                $emailDetail['user_id'],
                                null,
                                'real_time'
                            );
                        }
                    }

                    // Commit transaction after successful execution
                    $conn_rjllearning_specific->commit();
                    successreturn(['successmsg' => "Student(s) added successfully."]);
                } else {
                    erroreturn("No student data to insert.");
                }
            } catch (Exception $e) {
                // Rollback in case of any error
                $conn_rjllearning_specific->rollBack();
                errorreturn("Error: " . $e->getMessage());
            }
        } catch (Exception $e) {
            $conn_rjllearning_specific->rollBack();
            errorreturn("Error: " . $e->getMessage());
        }
    } else {
        errorreturn('No file was uploaded.');
    }
}
