<?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';

//db access function
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 . 'user_management/faculty/functions.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'admin_api/modules/staff/staff_details/staff_functions.php';
require_once $base_path_to_learning . 'functions/staff_logs.php';
require_once $base_path_to_learning.'user_management/user_versioning.php';

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

// $postdata = json_decode(file_get_contents("php://input"), true);
$postdata  = $_POST;
// checkIfNoPhpContentsReceive();
// print_R($postdata);die();
if (
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type'])  or
    !isset($postdata['jwt_token']) or  !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    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;

if ($role == 'principal' or $role == 'teacher') {
    $institution_id = $jwt_validate->data->institution_id;
    $branch_id = $jwt_validate->data->branch_id;
}
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id, ["superadmin", "admin", "principal", "teacher"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

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

    if (
        // !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
        !isset($postdata['father_name']) or !checkIfIssetAndNotEmpty($postdata['father_name']) or
        !isset($postdata['mother_name']) or !checkIfIssetAndNotEmpty($postdata['mother_name'])  or
        !isset($postdata['nationality']) or !checkIfIssetAndNotEmpty($postdata['nationality']) or

        !isset($postdata['dob']) or !checkIfIssetAndNotEmpty($postdata['dob']) or
        !isset($postdata['address']) or !checkIfIssetAndNotEmpty($postdata['address']) or
        !isset($postdata['city']) or !checkIfIssetAndNotEmpty($postdata['city'])  or
        !isset($postdata['pincode']) or  !checkIfIssetAndNotEmpty($postdata['pincode']) or
        !isset($postdata['country']) or  !checkIfIssetAndNotEmpty($postdata['country'])  or
        !isset($postdata['name']) or  !checkIfIssetAndNotEmpty($postdata['name']) or
        !isset($postdata['gender']) or  !checkIfIssetAndNotEmpty($postdata['gender']) or
        // !isset($postdata['email']) or !checkIfIssetAndNotEmpty($postdata['email']) or
        !isset($postdata['role']) or !checkIfIssetAndNotEmpty($postdata['role']) or
        !isset($postdata['state']) or !checkIfIssetAndNotEmpty($postdata['state']) or
        !isset($postdata['date_of_joining']) or !checkIfIssetAndNotEmpty($postdata['date_of_joining']) or
        !isset($postdata['mobile']) or  !checkIfIssetAndNotEmpty($postdata['mobile'])
    ) {
        errorreturn("All * fields are required .");
    }

    if ($role == 'admin' or $role == 'superadmin') {
        if (
            !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
            !isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id'])
        ) {
            errorreturn("institution field is required.");
        } else {
            $institution_id = $postdata['institution_id'];
            $branch_id = trim($postdata['branch_id']);
        }
    }

    $father_name = ucwords(strtolower(trim($postdata['father_name'])));
    $mother_name = ucwords(strtolower(trim($postdata['mother_name'])));
    $spouse_name = ucwords(strtolower(trim($postdata['spouse_name'])));
    $nationality = ucwords(strtolower(trim($postdata['nationality'])));

    $dob = trim($postdata['dob']);
    $address = ucwords(strtolower(trim($postdata['address'])));
    $city = trim($postdata['city']);
    $state = trim($postdata['state']);
    $pincode = trim($postdata['pincode']);
    $country = trim($postdata['country']);
    $name = ucwords(strtolower(trim($postdata['name']))); // use trim and ucwords here
    $gender = trim($postdata['gender']);
    $email = trim($postdata['email']);
    $mobile = trim($postdata['mobile']);
    $designation = (isset($postdata['designation']) and !empty($postdata['designation'])) ? trim($postdata['designation']) : null;
    $faculty_role = trim($postdata['role']); //teacher,principal,other
    $profile_image = (isset($_FILES['profile_image']) and !empty($_FILES['profile_image'])) ? ($_FILES['profile_image']) : null;
    $other_staff_group_id = (isset($postdata['other_staff_group_id']) and !empty($postdata['other_staff_group_id'])) ? trim($postdata['other_staff_group_id']) : null;
    $date_of_joining = (date('Y-m-d', strtotime($postdata['date_of_joining'])));
    $registered_bool_epf_esi = (isset($postdata['registered_bool_epf_esi'])) ? trim($postdata['registered_bool_epf_esi']) : 0;
    $date_of_joining_as_per_registration = isset($postdata['date_of_joining_as_per_registration']) && 
    !empty($postdata['date_of_joining_as_per_registration']) ? date('Y-m-d', strtotime($postdata['date_of_joining_as_per_registration'])): null;

    if ($date_of_joining_as_per_registration && $date_of_joining_as_per_registration < $date_of_joining) {
        errorreturn("Date of joining as per registration cannot be earlier than the date of joining");
    }
    
    $date_of_termination = isset($postdata['date_of_termination']) && !empty($postdata['date_of_termination'])
        ? date('Y-m-d', strtotime($postdata['date_of_termination']))
        : null;
    $print_bank_details = (isset($postdata['print_bank_details']) and !empty($postdata['print_bank_details'])) ? trim($postdata['print_bank_details']) : null;
    $account_name = (isset($postdata['account_name']) and !empty($postdata['account_name'])) ? ucwords(trim($postdata['account_name'])) : null;
    $account_holder_name = (isset($postdata['account_holder_name']) and !empty($postdata['account_holder_name'])) ? trim($postdata['account_holder_name']) : null;
    $account_no = (isset($postdata['account_no']) and !empty($postdata['account_no'])) ? trim($postdata['account_no']) : null;
    $ifsc_code = (isset($postdata['ifsc_code']) and !empty($postdata['ifsc_code'])) ? trim($postdata['ifsc_code']) : null;
    $branch_address = (isset($postdata['branch_address']) and !empty($postdata['branch_address'])) ? trim($postdata['branch_address']) : null;
    $account_type = (isset($postdata['account_type']) and !empty($postdata['account_type'])) ? trim($postdata['account_type']) : null;
    $adhar_card = (isset($_FILES['adhar_card']) and !empty($_FILES['adhar_card'])) ? ($_FILES['adhar_card']) : null;
    $pan_card = (isset($_FILES['pan_card']) and !empty($_FILES['pan_card'])) ? ($_FILES['pan_card']) : null;
    $driving_licence = (isset($_FILES['driving_licence']) and !empty($_FILES['driving_licence'])) ? ($_FILES['driving_licence']) : null;
    $driving_expiry_date = (isset($postdata['driving_expiry_date']) and !empty($postdata['driving_expiry_date'])) ? trim($postdata['driving_expiry_date']) : null; {

        if ($faculty_role === 'teacher' || $faculty_role === 'principal') {
            if (empty($postdata['email'])) {
                errorreturn("Email is required for teachers and principals.");
            }

            $email = trim($postdata['email']); // Assign before using

            if (!CheckEMailIsValidOrNot($email)) {
                errorreturn('Enter valid Email Id');
            }
        } elseif ($faculty_role === 'other') {
            // Email is optional — validate only if provided
            $email = (!empty($postdata['email'])) ? trim($postdata['email']) : null;

            // Optionally validate email format if not null
            if ($email !== null && !CheckEMailIsValidOrNot($email)) {
                errorreturn('Enter valid Email Id');
            }
        }



        // $res = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE  institution_id = ? and branch_id = ? and (name = ? OR email = ? OR mobile = ?)");
        // $res->execute(array($institution_id, $branch_id, $name, $email, $mobile));
        // $result1 = $res->fetchAll();
        // if (count($result1) >= 1) {
        //     errorreturn("Faculty info already exists.");
        // }
        // Prepare & run the query once
        // $stmt = $conn_rjllearning_specific->prepare("SELECT name, email, mobile FROM faculty_info WHERE  institution_id = ? AND branch_id = ? 
        //     AND (name = ? OR email = ? OR mobile = ?)");
        // $stmt->execute([$institution_id, $branch_id, $name, $email, $mobile]);
        // $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // if ($rows) {
        //     // There may be more than one match; check which columns collide
        //     $duplicates = [];

        //     foreach ($rows as $row) {
        //         if (strcasecmp($row['name'],   $name)   === 0) $duplicates['name']   = $name;
        //         if (strcasecmp($row['email'],  $email)  === 0) $duplicates['email']  = $email;
        //         if (strcasecmp($row['mobile'], $mobile) === 0) $duplicates['mobile'] = $mobile;
        //     }

        //     // Create a readable error like “Name, email already exist.”
        //     $fields = implode(', ', array_keys($duplicates));
        //     errorreturn(ucfirst($fields) . ' already exist' . (count($duplicates) > 1 ? '.' : 's.'));
        // }
        
        $stmt = $conn_rjllearning_specific->prepare("SELECT email, mobile FROM faculty_info 
            WHERE institution_id = ? AND branch_id = ? 
            AND (email = ? OR mobile = ?)");
        $stmt->execute([$institution_id, $branch_id, $email, $mobile]);
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        if ($rows) {
            $duplicates = [];

            foreach ($rows as $row) {
                if (strcasecmp($row['email'], $email) === 0) $duplicates['email'] = true;
                if (strcasecmp($row['mobile'], $mobile) === 0) $duplicates['mobile'] = true;
            }

            if (!empty($duplicates)) {
                $fields = implode(', ', array_keys($duplicates));
                $plural = count($duplicates) > 1 ? '' : 's';
                errorreturn(ucfirst($fields) . ' already exist' . $plural . '.', $conn_rjllearning_specific);
            }
        }


        $sql_codes = $conn_rjllearning_specific->prepare("Select count(*) as total from  branch WHERE id = ? and institution_id = ? and status =? ");
        $sql_codes->execute(array($branch_id, $institution_id, '1'));
        $result_branch = $sql_codes->fetchAll()[0]['total'];
        if ($result_branch != 1) {
            errorreturn("Branch Not Found.");
        }

        // $res = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE  institution_id = ? and branch_id = ? and (name = ? or email = ? or mobile = ?)");
        // $res->execute(array( $institution_id,$branch_id, $name, $email, $mobile));
        // $result1 = $res->fetchAll();
        // if (count($result1) >= 1) {
        //     errorreturn("Teacher already exists.");
        // }

        $sql_country = "SELECT id FROM country_info WHERE id = ?";
        $stmt_country = $conn_rjllearning->prepare($sql_country);
        $stmt_country->execute(array($country));
        $result_country = $stmt_country->fetchAll();
        if (count($result_country) < 1) {
            errorreturn("Country not found.");
        }
        //$country_id = $result_country['id'];

        $sql_codes = $conn_rjllearning->prepare("Select count(*) as total from  state_info WHERE id = ? and country_id = ? and status =? ");
        $sql_codes->execute(array($state, $country, '1'));
        $result_state = $sql_codes->fetchAll()[0]['total'];
        if ($result_state != 1) {
            errorreturn("state Not Found.");
        }

        if (!CheckAlphabetssWithSpace($father_name)) {
            //eg House Name, Street Name
            errorreturn('Invalid Father Name');
        }
        if (!CheckAlphabetssWithSpace($mother_name)) {
            //eg House Name, Street Name
            errorreturn('Invalid Mother Name');
        }
        if (!CheckAlphabetssWithSpace($spouse_name)) {
            //eg House Name, Street Name
            errorreturn('Invalid Spouse Name');
        }
        if (!CheckAddressValidation($address)) {
            //eg House Name, Street Name
            errorreturn('Invalid address');
        }
        if (!PinCodeValidation($pincode)) { // 6 digit only
            //eg House Name, Street Name
            errorreturn('Invalid Pin Code');
        }

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

        // 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 = 18; // 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.");
            }
        }

        $date_now = date("Y-m-d");
        if (!CheckDob($dob) or $dob >= $date_now) {
            errorreturn('Invalid DOB formats');
        }
        if ($dob > $date_now) {
            errorreturn('Invalid DOB formats');
        }

        if ($driving_licence != null && $driving_expiry_date == null) {
            errorreturn("Driving expiry date is required.");
        }
        if ($print_bank_details ==  '1' and $print_bank_details != null) {
            if (empty($account_name) || !preg_match('/^[A-Za-z\s]+$/', $account_name)) {
                errorreturn("Account holder name should only contain letters and spaces.");
            }

            // if (empty($account_no) ||  isset($account_no) && !preg_match('/^\d{11}$/', $account_no)) {
            //     errorreturn("Account number should be 11 digits.");
            // }
            // Account number validation: must be alphanumeric and 6-18 characters long
            if (empty($account_no) || !preg_match('/^[a-zA-Z0-9]{6,18}$/', $account_no)) {
                errorreturn("Account number should be alphanumeric and 6 to 18 characters long.");
            }

            if (empty($account_no) ||  isset($account_no) && !preg_match('/^\d{11}$/', $account_no)) {
                errorreturn("Account number should be 11 digits.");
            }
            // if (empty($ifsc_code) || isset($ifsc_code) && !preg_match('/^[A-Z]{4}0[A-Z0-9]{6}$/', $ifsc_code)) {
            //     errorreturn("IFSC code format is incorrect.");
            // }

            // IFSC code validation: specific format of 11 characters (4 letters, 1 zero, and 6 alphanumeric characters)
            if (empty($ifsc_code) || !preg_match('/^[A-Z]{4}0[A-Z0-9]{6}$/', $ifsc_code)) {
                errorreturn("IFSC code format is incorrect.");
            }
            if (empty($account_holder_name) || isset($account_holder_name) && !preg_match('/^[A-Za-z\s]+$/', $account_holder_name)) {
                errorreturn("Account holder name should only contain letters and spaces.");
            }
            if (empty($branch_address) || isset($branch_address) && !preg_match('/^[A-Za-z0-9\s\-.,#\/]+$/', $branch_address)) {
                errorreturn("Branch address contains invalid characters.");
            }
            // if (empty($account_type) || isset($account_type) && $account_type !== "savings" && $account_type !== "current") {
            //     errorreturn("Invalid account type. Allowed types are 'savings' or 'current'.");
            // }
            if (empty($account_type) || isset($account_type) && !in_array(ucwords(strtolower($account_type)), ['Savings Account', 'Current Account', 'Salary Account'])) {
                errorreturn("Invalid account type. Allowed types are 'Savings Account', 'Current Account', or 'Salary Account'.");
            }
        }
    }

    //check ledger categries exists or not
    if ($other_staff_group_id != null) {
        $sql_staff_groups = "Select group_name from   other_staff_groups where id = ? AND institution_id = ? AND branch_id like ? ";
        $stmt_staff_groups = $conn_rjllearning_specific->prepare($sql_staff_groups);
        $stmt_staff_groups->execute(array($other_staff_group_id, $institution_id, '%' . $branch_id . '%'));
        if (count($stmt_staff_groups->fetchAll()) != 1) {

            errorreturn('Staff groups not exists.');
        }
    }

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

        $directoryPathMain = "user_uploads/" . $workspace_id .  "/" . $institution_id . "/profile/" . $currentYear . "/" . $currentMonth . "/";

        $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', 'gif', 'png', 'heic', 'jpeg'];
        $maxFileSize = 2 * 1024 * 1024; // Maximum file size (2MB)
        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
    }
    // echo $faculty_role;
    if ($faculty_role === 'teacher' || $faculty_role === 'principal') {
        // echo $faculty_role;die();
        $user_id = $name;
    } elseif ($faculty_role === 'other') {
        $user_id = null;
    }


    try {
        $conn_rjllearning_specific->beginTransaction();

        // Step 1: Insert into faculty_info
        $sql = "INSERT INTO faculty_info (
        institution_id, branch_id, userid, name, gender, email, mobile, designation, role, 
        father_name, mother_name, spouse_name, nationality, dob, address, city, state, 
        pincode, country, status, lock_status, profile_image, other_staff_group_id, 
        date_of_joining, registered_bool_epf_esi, date_of_joining_as_per_registration, date_of_termination
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute([
            $institution_id,
            $branch_id,
            $user_id,
            $name,
            $gender,
            $email,
            $mobile,
            $designation,
            $faculty_role,
            $father_name,
            $mother_name,
            $spouse_name,
            $nationality,
            $dob,
            $address,
            $city,
            $state,
            $pincode,
            $country,
            '1',
            '1',
            null,
            $other_staff_group_id,
            $date_of_joining,
            $registered_bool_epf_esi, 
            $date_of_joining_as_per_registration,
            $date_of_termination
        ]);

        // Immediately get the last insert ID
        $faculty_id = $conn_rjllearning_specific->lastInsertId();

        // Step 2: Upload profile image
        if ($profile_image != null) {
            $image_name = "faculty_" . $faculty_id . "." . $file_extension;
            $faculty_path = $directoryPathMain . $image_name;

            awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $profile_image, $faculty_path, false, 0);

            $attachment_image = json_encode([
                "filepath" => $faculty_path,
                "original_name" => $file_name
            ]);

            $sql_logo = "UPDATE faculty_info SET profile_image = ? WHERE id= ?";
            $conn_rjllearning_specific->prepare($sql_logo)->execute([$attachment_image, $faculty_id]);
        }

        // Step 3: Store salary/bank details (before user creation)
        $success = createStaff(
            $conn_rjllearning,
            $conn_rjllearning_specific,
            $workspace_id,
            $institution_id,
            $branch_id,
            $print_bank_details,
            $account_holder_name,
            $account_name,
            $account_no,
            $ifsc_code,
            $branch_address,
            $account_type,
            $adhar_card,
            $pan_card,
            $driving_licence,
            $driving_expiry_date,
            $username,
            $faculty_id
        );
        

        // Step 4: Create user if teacher/principal
        if ($faculty_role == 'teacher' || $faculty_role == 'principal') {

            // Generate username
            $institution_info = getInstitution($conn_rjllearning, $institution_id);
            $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $branch_id, ['branch_code']);
            $faculty_username = $branch_info['branch_code'] . "_" . $faculty_id . "_F@" . $institution_info['institution_code'];

            $check_availability = checkUsernameAvailabilty($conn_rjllearning, $faculty_username);
            if (!$check_availability) {
                errorreturn('Username already exists. Please try another username.');
            }

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

            $user = storeUser(
                $conn_rjllearning,
                $workspace_id,
                $institution_id,
                $name,
                $dob,
                $gender,
                $faculty_username,
                $email,
                $mobile,
                $hashed_password,
                $faculty_role,
                $branch_id
            );

            // Finalize username with user ID
            $updated_faculty_username = $branch_info['branch_code'] . "_" . $user . "@" . $institution_info['institution_code'];
            $conn_rjllearning->prepare("UPDATE users SET username = ? WHERE id = ? AND institution_id = ?")
                ->execute([$updated_faculty_username, $user, $institution_id]);

            $conn_rjllearning_specific->prepare("UPDATE faculty_info SET userid = ? WHERE id = ? AND institution_id = ?")->execute([$user, $faculty_id, $institution_id]);
        }

        // Step 5: Insert into staff_log
        $basic_salary = "5000";
        insertStaffLog(
            $conn_rjllearning_specific,
            $institution_id,
            $branch_id,
            $faculty_id,
            $account_holder_name,
            $account_no,
            $ifsc_code,
            $branch_address,
            $account_type,
            $basic_salary,
            $designation,
            1
        );

        // Step 6: Update other_staff_details (should exist beforehand)
        if (!empty($date_of_joining)) {
            $conn_rjllearning_specific->prepare("UPDATE other_staff_details 
            SET joining_date = ? 
            WHERE institution_id = ? AND faculty_id = ?")
                ->execute([$date_of_joining, $institution_id, $faculty_id]);
        }

        if ($faculty_role == 'teacher' or $faculty_role == 'principal') {
            // $url = 'https://faculty.rejoicelearning.in';

            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 $url or <a href='$url'>Click Here<a>. </p>
            // <p>
            // Name : <b>$name</b><br>
            // Username : <b>$updated_faculty_username</b><br>
            // Password : <b>$password</b>
            // </p>";
            // Fetch white label values from institution
            $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://faculty.' . $base_domain;
            } else {
                $url = 'https://faculty.' . $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>$updated_faculty_username</b><br>
            Password : <b>$password</b>
            </p>";
            
            if ($faculty_role === 'teacher' || $faculty_role === 'principal') {
                updateUserRoleTimestamp($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $faculty_id);
            }

            // Send Email
            sendMailTemplate1($conn_rjllearning, $from_email, $email, $subject, $message, $workspace_id, $institution_id, $branch_id, $user, null, 'real_time');
            // sendMailTemplate1($conn_rjllearning, 'Rejoice Learning <no-reply@rejoicelearning.in>', $email, $subject, $message, $workspace_id, $institution_id, $branch_id, $user, null, 'real_time');
        }
          $conn_rjllearning_specific->commit();
    } catch (Exception $e) {
        if($conn_rjllearning_specific->inTransaction()) {
            $conn_rjllearning_specific->rollBack();
        }
        errorreturn("Error: " . $e->getMessage());
    }

    successreturn("Successfully $faculty_role added. Kindly check your registered email id for your login credentials.");

    //successreturn(array('id' => $id, 'successmsg' => "Successfully Faculty  added."));

} else if ($postdata['function_type'] == "alter_faculty") {

    if (
        !isset($postdata['state']) or !checkIfIssetAndNotEmpty($postdata['state']) or
        !isset($postdata['father_name']) or !checkIfIssetAndNotEmpty($postdata['father_name']) or
        !isset($postdata['mother_name']) or !checkIfIssetAndNotEmpty($postdata['mother_name'])  or
        !isset($postdata['nationality']) or !checkIfIssetAndNotEmpty($postdata['nationality']) or
        //  !isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id']) or 
        !isset($postdata['dob']) or !checkIfIssetAndNotEmpty($postdata['dob']) or
        !isset($postdata['address']) or !checkIfIssetAndNotEmpty($postdata['address']) or
        !isset($postdata['city']) or !checkIfIssetAndNotEmpty($postdata['city'])  or
        !isset($postdata['pincode']) or  !checkIfIssetAndNotEmpty($postdata['pincode']) or
        !isset($postdata['country']) or  !checkIfIssetAndNotEmpty($postdata['country']) or
        !isset($postdata['name']) or  !checkIfIssetAndNotEmpty($postdata['name']) or
        !isset($postdata['gender']) or  !checkIfIssetAndNotEmpty($postdata['gender']) or
        // !isset($postdata['email']) or !checkIfIssetAndNotEmpty($postdata['email']) or
        !isset($postdata['date_of_joining']) or !checkIfIssetAndNotEmpty($postdata['date_of_joining']) or
        !isset($postdata['mobile']) or  !checkIfIssetAndNotEmpty($postdata['mobile'])
    ) {
        errorreturn("All * fields are required.");
    }

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

    if ($role == 'admin' or $role == 'superadmin') {
        if (!isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id'])) {
            errorreturn("institution field is required.");
        } else {
            $institution_id = $postdata['institution_id'];
            $branch_id = trim($postdata['branch_id']);
        }
    }

    $father_name = trim($postdata['father_name']);
    $mother_name = trim($postdata['mother_name']);
    $spouse_name = trim($postdata['spouse_name']);
    $nationality = trim($postdata['nationality']);

    $dob = trim($postdata['dob']);
    $address = trim($postdata['address']);
    $city = trim($postdata['city']);
    $state = trim($postdata['state']);
    $pincode = trim($postdata['pincode']);
    $country = trim($postdata['country']);
    //  $faculty_id = trim($postdata['faculty_id']);
    $name = ucwords(strtolower(trim($postdata['name']))); // use trim and ucwords here
    $gender = trim($postdata['gender']);
    // $email = trim($postdata['email']);
    $mobile = trim($postdata['mobile']);
    $designation = (isset($postdata['designation']) and !empty($postdata['designation'])) ? trim($postdata['designation']) : null;
    $profile_image = (isset($_FILES['profile_image']) and !empty($_FILES['profile_image'])) ? ($_FILES['profile_image']) : null;
    $remove_bool = (isset($postdata['remove_bool']) and !empty($postdata['remove_bool'])) ? trim($postdata['remove_bool']) : 0; //if 

    $profile_image = (isset($_FILES['profile_image']) and !empty($_FILES['profile_image'])) ? ($_FILES['profile_image']) : null;
    $other_staff_group_id = (isset($postdata['other_staff_group_id']) and !empty($postdata['other_staff_group_id'])) ? trim($postdata['other_staff_group_id']) : null;
    $date_of_joining = (date('Y-m-d', strtotime($postdata['date_of_joining'])));
    $date_of_termination = isset($postdata['date_of_termination']) && !empty($postdata['date_of_termination'])
        ? date('Y-m-d', strtotime($postdata['date_of_termination']))
        : null;
    $print_bank_details = (isset($postdata['print_bank_details']) and !empty($postdata['print_bank_details'])) ? trim($postdata['print_bank_details']) : null;
    $account_name = (isset($postdata['account_name']) and !empty($postdata['account_name'])) ? ucwords(trim($postdata['account_name'])) : null;
    $account_holder_name = (isset($postdata['account_holder_name']) and !empty($postdata['account_holder_name'])) ? trim($postdata['account_holder_name']) : null;
    $account_no = (isset($postdata['account_no']) and !empty($postdata['account_no'])) ? trim($postdata['account_no']) : null;
    $ifsc_code = (isset($postdata['ifsc_code']) and !empty($postdata['ifsc_code'])) ? trim($postdata['ifsc_code']) : null;
    $branch_address = (isset($postdata['branch_address']) and !empty($postdata['branch_address'])) ? trim($postdata['branch_address']) : null;
    $account_type = (isset($postdata['account_type']) and !empty($postdata['account_type'])) ? trim($postdata['account_type']) : null;
    $adhar_card = (isset($_FILES['adhar_card']) and !empty($_FILES['adhar_card'])) ? ($_FILES['adhar_card']) : null;
    $remove_bool_adhar = (isset($postdata['remove_bool_adhar']) and !empty($postdata['remove_bool_adhar'])) ? trim($postdata['remove_bool_adhar']) : 0;
    $pan_card = (isset($_FILES['pan_card']) and !empty($_FILES['pan_card'])) ? ($_FILES['pan_card']) : null;
    $remove_bool_pan = (isset($postdata['remove_bool_pan']) and !empty($postdata['remove_bool_pan'])) ? trim($postdata['remove_bool_pan']) : 0;
    $driving_licence = (isset($_FILES['driving_licence']) and !empty($_FILES['driving_licence'])) ? ($_FILES['driving_licence']) : null;
    $remove_bool_driving = (isset($postdata['remove_bool_driving']) and !empty($postdata['remove_bool_driving'])) ? trim($postdata['remove_bool_driving']) : 0;
    $driving_expiry_date = (isset($postdata['driving_expiry_date']) and !empty($postdata['driving_expiry_date'])) ? trim($postdata['driving_expiry_date']) : null;
    $faculty_role = trim($postdata['role']); //teacher,principal,other
    $registered_bool_epf_esi = (isset($postdata['registered_bool_epf_esi'])) ? trim($postdata['registered_bool_epf_esi']) : 0;
    $date_of_joining_as_per_registration = isset($postdata['date_of_joining_as_per_registration']) && 
    !empty($postdata['date_of_joining_as_per_registration']) ? date('Y-m-d', strtotime($postdata['date_of_joining_as_per_registration'])): null;

    if ($faculty_role === 'teacher' || $faculty_role === 'principal') {
        if (empty($postdata['email'])) {
            errorreturn("Email is required for teachers and principals.");
        }

        $email = trim($postdata['email']); // Assign before using

        if (!CheckEMailIsValidOrNot($email)) {
            errorreturn('Enter valid Email Id');
        }
    } elseif ($faculty_role === 'other') {
        // Email is optional — validate only if provided
        $email = (!empty($postdata['email'])) ? trim($postdata['email']) : null;

        // Optionally validate email format if not null
        if ($email !== null && !CheckEMailIsValidOrNot($email)) {
            errorreturn('Enter valid Email Id');
        }
    } {
        // $res = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE  institution_id = ? and branch_id = ? and userid = ?");
        // $res->execute(array($institution_id,$branch_id,$userid));
        // $result1 = $res->fetchAll();
        // if (count($result1) >= 1) {
        //     errorreturn("Faculty info already exists.");
        // }

        // $sql_codes = $conn_rjllearning_specific->prepare("Select count(*) as total from  branch WHERE id = ? and institution_id = ? and status =? ");
        // $sql_codes->execute(array($branch_id,$institution_id,'1'));
        // $result_branch = $sql_codes->fetchAll()[0]['total'];
        // if ($result_branch != 1) {
        //     errorreturn("Branch Not Found.");
        // }

        // $res = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE id != ? and institution_id = ? and (name = ? or email = ? or mobile = ?)");
        // $res->execute(array($faculty_id, $institution_id, $name, $email, $mobile));
        // $result1 = $res->fetchAll();
        // if (count($result1) >= 1) {
        //     errorreturn("Name / Email / Mobile already exists.");
        // }

        if (!CheckAlphabetssWithSpace($father_name)) {
            //eg House Name, Street Name
            errorreturn('Invalid Father Name');
        }
        if (!CheckAlphabetssWithSpace($mother_name)) {
            //eg House Name, Street Name
            errorreturn('Invalid Mother Name');
        }
        if (!CheckAlphabetssWithSpace($spouse_name)) {
            //eg House Name, Street Name
            errorreturn('Invalid Spouse Name');
        }
        if (!CheckAddressValidation($address)) {
            //eg House Name, Street Name
            errorreturn('Invalid address');
        }
        if (!PinCodeValidation($pincode)) { // 6 digit only
            //eg House Name, Street Name
            errorreturn('Invalid Pin Code');
        }
        // if (!CheckEMailIsValidOrNot($email)) {
        //     errorreturn('Enter valid Email Id');
        // }
        //user validation
        if (!checkOnlyCharacters($name)) { // 6 digit only
            //eg House Name, Street Name
            errorreturn('Name must only contain letters!"');
        }
        // 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');
        }

        $date_now = date("Y-m-d");
        if (!CheckDob($dob) or $dob >= $date_now) {
            errorreturn('Invalid DOB formats');
        }
        if ($dob > $date_now) {
            errorreturn('Invalid DOB formats');
        }

        if ($driving_licence != null && $driving_expiry_date == null) {
            errorreturn("Driving expiry date is required.");
        }
        if ($print_bank_details ==  '1' and $print_bank_details != null) {
            if (empty($account_name) || !preg_match('/^[A-Za-z\s]+$/', $account_name)) {
                errorreturn("Account holder name should only contain letters and spaces.");
            }

            if (empty($account_no) ||  isset($account_no) && !preg_match('/^\d{11}$/', $account_no)) {
                errorreturn("Account number should be 11 digits.");
            }

            if (empty($account_no) ||  isset($account_no) && !preg_match('/^\d{11}$/', $account_no)) {
                errorreturn("Account number should be 11 digits.");
            }
            if (empty($ifsc_code) || isset($ifsc_code) && !preg_match('/^[A-Z]{4}0[A-Z0-9]{6}$/', $ifsc_code)) {
                errorreturn("IFSC code format is incorrect.");
            }
            if (empty($account_holder_name) || isset($account_holder_name) && !preg_match('/^[A-Za-z\s]+$/', $account_holder_name)) {
                errorreturn("Account holder name should only contain letters and spaces.");
            }
            if (empty($branch_address) || isset($branch_address) && !preg_match('/^[A-Za-z0-9\s\-.,#\/]+$/', $branch_address)) {
                errorreturn("Branch address contains invalid characters.");
            }
            if (empty($account_type) || isset($account_type) && $account_type !== "savings" && $account_type !== "current") {
                errorreturn("Invalid account type. Allowed types are 'savings' or 'current'.");
            }
        }
    }

    //check ledger categries exists or not
    if ($other_staff_group_id != null) {
        $sql_staff_groups = "Select group_name from   other_staff_groups where id = ? AND institution_id = ? AND branch_id like ? ";
        $stmt_staff_groups = $conn_rjllearning_specific->prepare($sql_staff_groups);
        $stmt_staff_groups->execute(array($other_staff_group_id, $institution_id, '%' . $branch_id . '%'));
        if (count($stmt_staff_groups->fetchAll()) != 1) {

            errorreturn('Staff groups not exists.');
        }
    }

    $sql = $conn_rjllearning_specific->prepare("SELECT userid,profile_image FROM faculty_info WHERE id = ? and institution_id=?");
    $sql->execute(array($faculty_id, $institution_id));
    $result = $sql->fetchAll();
    if (count($result) != 1) {
        errorreturn("Faculty not found.");
    } else {
        $user_id = $result[0]['userid'];
        $existing_profile_image = $result[0]['profile_image'];
        if ($existing_profile_image !=  null) {
            $data_attachment = json_decode($existing_profile_image, true);
            $filePath = $data_attachment['filepath'];
        }
    }

    // $res = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE id != ?  and institution_id = ? and (name = ? or email = ? or mobile = ?)");
    // $res->execute(array($faculty_id,$institution_id,$name,$email,$mobile));
    // $result1 = $res->fetchAll();
    // if (count($result1) >= 1) {
    //     errorreturn("Faculty info already exists.");
    // }


    if ($remove_bool == 1 and $profile_image != null) {

        if ($existing_profile_image === null) {

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

            $directoryPathMain =  "user_uploads/" . $workspace_id .  "/" . $institution_id . "/profile/" . $currentYear . "/" . $currentMonth . "/";
        } else {

            $directoryPathMain = substr($filePath, 0, strrpos($filePath, '/') + 1);
        }
        $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', 'gif', 'png', 'heic', 'jpeg'];
        $maxFileSize = 2; // Maximum file size (2MB)

        checkFileValidation($fileSize, $fileType, $file_extension, $maxFileSize, $allowedTypes, $allowed_extensions);
        $image_name = $name . "-" . date('d-m-Y') . "." . $file_extension;
        $profile = $directoryPathMain . $image_name;

        //move_uploaded_file($fileTmpName, $GLOBALS['base_path_to_learning'] . $icon);
        try {
            $s3_learning_bucket->putObject([
                'Bucket' => $learning_bucketName,
                'Key' => $profile,
                'SourceFile' => $fileTmpName,

            ]);
        } catch (Exception $e) {
            errorreturn($e->getMessage());
        }
        $data = json_encode(array("filepath" => $profile, "original_name" => $file_name));
        $sql_users = "UPDATE faculty_info SET profile_image =? WHERE id=? and institution_id=?";
        $conn_rjllearning_specific->prepare($sql_users)->execute(array($data, $faculty_id, $institution_id));
    }


    $sql = "UPDATE faculty_info SET date_of_joining = ?, registered_bool_epf_esi = ? , date_of_joining_as_per_registration = ?,branch_id= ?,name=?,gender=?,email=?,mobile=?,designation=?,father_name=?,mother_name=?,spouse_name=?,nationality=?,dob=?,address=?,city=?,state=?,pincode=?,country=?
     WHERE id = ? and institution_id=? ";
    $conn_rjllearning_specific->prepare($sql)->execute(array($date_of_joining, $registered_bool_epf_esi, $date_of_joining_as_per_registration, $branch_id, $name, $gender, $email, $mobile, $designation, $father_name, $mother_name, $spouse_name, $nationality, $dob, $address, $city, $state, $pincode, $country, $faculty_id, $institution_id));

    if ($faculty_role == 'teacher' or $faculty_role == 'principal') {
        $user = updateUsers($conn_rjllearning, $workspace_id, $institution_id, $name, $dob, $gender, $email, $mobile, $user_id);
    }


    if ($remove_bool == 1 and $existing_profile_image != null) {
        $sql_image = $conn_rjllearning_specific->prepare("SELECT profile_image FROM  faculty_info  where id = ? and institution_id = ?");
        $sql_image->execute(array($faculty_id, $institution_id));
        $result_image = $sql_image->fetchAll();
        if (count($result_image) == 1) {
            $existing_profile_image = $result[0]['profile_image'];
            if ($existing_profile_image !=  null) {
                $data_attachment = json_decode($existing_profile_image, true);
                $filePath = $data_attachment['filepath'];
            }
            //$existing_image = $result_image[0]['profile_image'];
            awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $filePath, null, null);
            $sql = "UPDATE faculty_info SET profile_image = ? WHERE id = ? and institution_id= ?";
            $conn_rjllearning_specific->prepare($sql)->execute(array(null, $faculty_id, $institution_id));
        }
    }

    if ($profile_image !=  null) {
        $image_name = "faculty_" . $faculty_id . "." . $file_extension; // Define the image name dynamically
        $faculty_path = $directoryPathMain . $image_name; // Create the full path for the logo
        awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName, $profile_image, $faculty_path, $multiple_files_bool = false, $multiple_file_index = 0);
        $attachment_image = json_encode(array("filepath" => $faculty_path, "original_name" => $file_name));
        $sql_logo = "UPDATE faculty_info SET profile_image = ? WHERE id= ?";
        $conn_rjllearning_specific->prepare($sql_logo)->execute(array($attachment_image, $faculty_id));
    }

    $success = alterStaff($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $branch_id, $print_bank_details, $account_holder_name, $account_name, $account_no, $ifsc_code, $branch_address, $account_type, $adhar_card, $pan_card, $driving_licence, $driving_expiry_date, $username, $faculty_id,  $remove_bool_adhar, $remove_bool_pan, $remove_bool_driving);
    $basic_salary = "6000";
    insertStaffLog($conn_rjllearning_specific, $institution_id, $branch_id, $faculty_id, $account_holder_name, $account_no, $ifsc_code, $branch_address, $account_type, $basic_salary, $designation, 1);
    if (!empty($date_of_joining)) {
        $query = "UPDATE other_staff_details 
              SET joining_date = ? 
              WHERE institution_id = ? 
              AND faculty_id = ?";

        $stmt = $conn_rjllearning_specific->prepare($query);
        $stmt->execute([$date_of_joining, $institution_id, $faculty_id]);
    }
    // if ($faculty_role == 'teacher' or $faculty_role == 'principal') {
    //     updateUserRoleTimestamp($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $faculty_id);
    // }

    successreturn("Successfully faculty updated.");
} else if ($postdata['function_type'] == "faculty_status") {

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

    $res = $conn_rjllearning->prepare("SELECT status, role FROM faculty_info WHERE id = ? and institution_id=? ");
    $res->execute(array($faculty_id, $institution_id));
    $result1 = $res->fetch();
    $status = $result1['status'];
    $faculty_role = $result1['role'];
    //echo $lock_status;die();

    if ($status == '1') {
        $status = '0';
        $sql = "UPDATE faculty_info SET status=?  WHERE id = ? and institution_id=? ";
        $conn_rjllearning_specific->prepare($sql)->execute(array($status, $faculty_id, $institution_id));
    } else if ($status == '0') {
        $status = '1';
        $sql = "UPDATE faculty_info SET status=?  WHERE id = ? and institution_id=?";
        $conn_rjllearning_specific->prepare($sql)->execute(array($status, $faculty_id, $institution_id));
    }

    if ($faculty_role == 'teacher' or $faculty_role == 'principal') {
        updateUserRoleTimestamp($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $faculty_id);
    }

    successreturn("faculty status updated Successfully");
} else if ($postdata['function_type'] == "unlock_faculty") {
    if (!isset($postdata['faculty_id']) or !checkIfIssetAndNotEmpty($postdata['faculty_id'])) {
        errorreturn('Error in updating the faculty.');
    } else {
        $faculty_id = $postdata['faculty_id'];
    }

    $res = $conn_rjllearning_specific->prepare("SELECT id, role, lock_status FROM faculty_info WHERE id = ? and institution_id =? and branch_id = ?");
    $res->execute(array($faculty_id, $institution_id, $branch_id));
    $result1 = $res->fetchAll();
    $lockstatus = $result1[0]['lock_status'];
    $faculty_role = $result1[0]['role'];

    if ($lockstatus == '1') {
        $lock_status = '0';
        $sql = "UPDATE faculty_info SET lock_status=?  WHERE id=?  and institution_id= ? and branch_id=?";
        $conn_rjllearning_specific->prepare($sql)->execute(array($lock_status, $faculty_id, $institution_id, $branch_id));
    } else if ($lockstatus == '0') {
        $lock_status = '1';
        $sql = "UPDATE faculty_info SET lock_status=?  WHERE id = ?  and institution_id =? and branch_id=?";
        $conn_rjllearning_specific->prepare($sql)->execute(array($lock_status, $faculty_id, $institution_id, $branch_id));
    }
    
    if ($faculty_role == 'teacher' or $faculty_role == 'principal') {
        updateUserRoleTimestamp($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $faculty_id);
    }
    successreturn("Faculty status updated Successfully");
}