1

1
mail@pastecode.io avatar
unknown
php
2 years ago
58 kB
1
Indexable
Never
    public function uploadStudentDataModal($data)
    {
        # DECLARE VARIABEL
        # =======================================
        $userSystemList = [];
        $userTenantList = [];
        $userParentSystemList = [];
        $userParentTenantList = [];
        $studentParentRelationData = [];

        $emails = [];
        $parentEmails = [];
        $usernameEmails = [];
        $usernameParentEmails = [];

        $allStudents = [];
        $allParents = [];
        $usernames = [];
        $usernameParents = [];

        $customer = getTenantWebsite();
        $customerId = $customer->customer_id;

        $rollback = [
            'student_parent_relation_ids' => [],
            'user_ids'                    => [],
        ];
        #=========================================

        try {
            # username
            $usernameData = CustomerSetting::getSettingValue($customerId, 'generate_username');
            $usernameSetting = $usernameData ? $usernameData : 'standard';

            # find role
            $studentRole = Role::findOrFail(Role::ROLE_ID_STUDENT);
            $studentRoleId = $studentRole->id;
            $parentRole = Role::findOrFail(Role::ROLE_ID_PARENT);
            $parentRoleId = $parentRole->id;

            $students = $data['student'];
            $parents = $data['parent'];

            # CARI SCHOOL LOCATION
            $masterSchoolLocations = MsSchoolLocation::select('school_location_id', 'school_short_address')
                ->whereNull('deleted_at')
                ->get()
                ->keyBy('school_location_id')
                ->map(function ($item) {
                    return $item['school_short_address'];
                });

            # CARI SCHOOL LEVEL
            $masterSchoolLevels = MsSchoolLevel::select('school_level_id', 'abbreviation')
                ->whereNull('deleted_at')
                ->get()
                ->keyBy('school_level_id')
                ->map(function ($item) {
                    return $item['abbreviation'];
                });

            # CARI YEAR LEVEL
            $masterYearLevel = MsYearLevel::select('year_level_id', 'description')
                ->whereNull('deleted_at')
                ->get()
                ->keyBy('year_level_id')
                ->map(function ($item) {
                    return $item['description'];
                });

            # CARI AGAMA
            $masterReligion = MsReligion::select('religion_id', 'religion_name')
                ->whereNull('deleted_at')
                ->get()
                ->keyBy('religion_id')
                ->map(function ($item) {
                    return $item['religion_name'];
                });

            # CARI NATIONALITY
            $masterNationality = MsNationality::select('nationality_id', 'nationality_name')
                ->whereNull('deleted_at')
                ->get()
                ->keyBy('nationality_id')
                ->map(function ($item) {
                    return $item['nationality_name'];
                });

            # CARI PROVINCE
            $masterProvince = MsProvince::select('province_id', 'province_name')
                ->whereNull('deleted_at')
                ->get()
                ->keyBy('province_id')
                ->map(function ($item) {
                    return $item['province_name'];
                });

            # CARI COUNTRY
            $masterCountry = MsCountry::select('country_id', 'country_name')
                ->whereNull('deleted_at')
                ->get()
                ->keyBy('country_id')
                ->map(function ($item) {
                    return $item['country_name'];
                });

            $passwordSetting = 'standard';

            try {
                $website = getTenantWebsite();
                useSystemEnvironment();
                $passwordDate = CustomerSetting::getSettingValue($website->customer_id, 'generate_password');
                if ($passwordDate !== null) {
                    $passwordSetting = $passwordDate;
                }
            } catch (Exception $exception) {
                // do nothing
            } finally {
                useTenantEnvironment($website);
            }

            # CARI USERNAME DI DB YG TERAKHIR
            $usernameMax = MsStudent::select([
                'f.username',
            ])
                ->join('t_user as f', function ($q) {
                    $q->on('f.user_id', '=', 'ms_student.user_id');
                    $q->whereNull('f.deleted_at');
                })
                ->whereRaw("f.username ~ '[0-9]+$'")
                ->whereNull('ms_student.deleted_at')
                ->orderByRaw("SUBSTRING(f.username FROM '([0-9]+)')::BIGINT DESC, f.username")
                ->first();

            if ($usernameMax) {
                if (strpos(strtolower($usernameMax->username), 'p_') !== false) {
                    $usernameMax = substr($usernameMax->username, 2);
                } else {
                    $usernameMax = $usernameMax->username ? (string)((int)$usernameMax->username) : null;
                }
            } else {
                $usernameMax = 0;
            }

            try {
                if ($students) {

                    $getMaxSiblingGroup = MsStudent::max('student_sibling_group');

                    if (! $getMaxSiblingGroup) {
                        $setStudentSiblingGroup = 0;
                    } else {
                        $setStudentSiblingGroup = ($getMaxSiblingGroup);
                    }

                    foreach ($students as $studentKey => $student) {
                        $setStudentSiblingGroup++;

                        $schoolLocation = null;
                        if (isset($student[4])) {
                            $schoolLocation = $masterSchoolLocations->filter(function ($item) use ($student) {
                                return $item === $student[4];
                            })->keys()
                                ->first();
                        }

                        $schoolLevel = null;
                        if (isset($student[5])) {
                            $schoolLevel = $masterSchoolLevels->filter(function ($item) use ($student) {
                                return $item === $student[5];
                            })->keys()
                                ->first();
                        }

                        $yearLevel = null;
                        if (isset($student[6])) {
                            $yearLevel = $masterYearLevel->filter(function ($item) use ($student) {
                                return $item === $student[6];
                            })->keys()
                                ->first();
                        }

                        $religion = null;
                        if (isset($student[13])) {
                            $religion = $masterReligion->filter(function ($item) use ($student) {
                                return $item === $student[13];
                            })->keys()
                                ->first();
                        }

                        $nationality = null;
                        if (isset($student[16])) {
                            $nationality = $masterNationality->filter(function ($item) use ($student) {
                                return $item === $student[16];
                            })->keys()
                                ->first();
                        }

                        $province = null;
                        if (isset($student[30])) {
                            $province = $masterProvince->filter(function ($item) use ($student) {
                                return $item === $student[30];
                            })->keys()
                                ->first();
                        }

                        $country = null;
                        if (isset($student[31])) {
                            $country = $masterCountry->filter(function ($item) use ($student) {
                                return $item === $student[31];
                            })->keys()
                                ->first();
                        }

                        $livingwith = null;
                        if (isset($student[32])) {
                            if ($student[32] == 'Bersama orang tua') {
                                $livingwith = 'Both Parent';
                            } else {
                                $livingwith = $student[32];
                            }
                        }

                        $familyIdentificationCardNumber = null;
                        if (isset($student[36])) {
                            $familyIdentificationCardNumber = $student[36];
                        }

                        $studentId = null;
                        if (isset($student[37])) {
                            $studentId = $student[37];
                        }

                        $studentJoinDate = null;
                        if (isset($student[7])) {
                            if ($student[7]) {
                                $studentJoinDate = str_replace('/', '-', $student[7]);
                                $studentJoinDate = date('Y-m-d', strtotime($studentJoinDate));
                            }
                        }

                        $studentDOB = null;
                        if (isset($student[10])) {
                            if ($student[10]) {
                                $studentDOB = str_replace('/', '-', $student[10]);
                                $studentDOB = date('Y-m-d', strtotime($studentDOB));
                            }
                        }

                        $studentPassport = null;
                        if (isset($student[19])) {
                            if ($student[19]) {
                                $studentPassport = str_replace('/', '-', $student[19]);
                                $studentPassport = date('Y-m-d', strtotime($studentPassport));
                            }
                        }

                        $studentKitas = null;
                        if (isset($student[21])) {
                            if ($student[21]) {
                                $studentKitas = str_replace('/', '-', $student[21]);
                                $studentKitas = date('Y-m-d', strtotime($studentKitas));
                            }
                        }

                        # ASSIGN KE VARIABEL
                        $studentData['student_id'] = $studentId;
                        $studentData['student_name'] = isset($student[0]) ? $student[0] : '-';
                        $studentData['student_nickname'] = isset($student[1]) ? $student[1] : '-';
                        $studentData['nis'] = isset($student[2]) ? $student[2] : '-';
                        $studentData['enrollment_status'] = isset($student[3]) ? $student[3] : 'Normal';
                        $studentData['enroll_school_location_id'] = ($schoolLocation) ? $schoolLocation : null;
                        $studentData['enroll_school_level_id'] = ($schoolLevel) ? $schoolLevel : null;
                        $studentData['enroll_year_level_id'] = ($yearLevel) ? $yearLevel : null;
                        $studentData['join_date_school'] = ($studentJoinDate) ? $studentJoinDate : '1900-01-01';
                        $studentData['gender'] = ($student[8] === 'Male') ? 'M' : 'F';
                        $studentData['religion_id'] = ($religion) ? $religion : null;
                        $studentData['place_of_birth'] = isset($student[9]) ? $student[9] : '-';
                        $studentData['date_of_birth'] = ($studentDOB) ? $studentDOB : '1900-01-01';
                        $studentData['email'] = isset($student[11]) ? strtolower($student[11]) : '-';
                        $studentData['address_line1'] = isset($student[12]) ? $student[12] : '-';
                        $studentData['nisn'] = isset($student[14]) ? $student[14] : null;
                        $studentData['admission_form_id'] = isset($student[15]) ? $student[15] : null;
                        $studentData['nationality_id'] = ($nationality) ? $nationality : null;
                        $studentData['identification_number'] = isset($student[17]) ? $student[17] : null;
                        $studentData['passport_no'] = isset($student[18]) ? $student[18] : null;
                        $studentData['passport_expired_date'] = $studentPassport;
                        $studentData['kitas_no'] = isset($student[20]) ? $student[20] : null;
                        $studentData['kitas_expired_date'] = $studentKitas;
                        $studentData['most_used_lang'] = isset($student[22]) ? $student[22] : null;
                        $studentData['phone_number'] = isset($student[23]) ? $student[23] : null;
                        $studentData['cellular_number'] = isset($student[24]) ? $student[24] : null;
                        $studentData['postal_code'] = isset($student[25]) ? $student[25] : null;
                        $studentData['village'] = isset($student[26]) ? $student[26] : null;
                        $studentData['sub_district'] = isset($student[27]) ? $student[27] : null;
                        $studentData['city'] = isset($student[28]) ? $student[28] : null;
                        $studentData['districts'] = isset($student[29]) ? $student[29] : null;
                        $studentData['province_id'] = ($province) ? $province : null;
                        $studentData['country_id'] = ($country) ? $country : null;
                        $studentData['living_with'] = $livingwith;
                        $studentData['distance_to_school'] = isset($student[33]) ? $student[33] : null;
                        $studentData['transport_to_school'] = isset($student[34]) ? $student[34] : null;
                        $studentData['child_status'] = isset($student[35]) ? $student[35] : null;
                        $studentData['family_identification_card_number'] = isset($student[36]) ? $student[36] : null;
                        $studentData['student_sibling_group'] = $setStudentSiblingGroup;
                        $studentData['created_at'] = date('Y-m-d H:i:s');
                        $studentData['updated_at'] = date('Y-m-d H:i:s');

                        # KALO STUDENT BARU YA BIKIN USERNAME DLL
                        if (! isset($studentData['student_id'])) {

                            // Generate email
                            $email = SystemUser::generateUniqueEmail($studentData['email'], $studentData['student_name'], 0, null, $emails, $usernameEmails);
                            if (! isset($emails[$email])) {
                                $emails[$email] = 1;
                            } else {
                                $emails[$email]++;
                            }
                            $studentData['email'] = strtolower($email);

                            // Generate username
                            if ($usernameSetting === 'custom') {
                                $usernameMax = (string)((int)$usernameMax + 1);
                                $username = SystemUser::generateFirstnameSecondname($usernameMax, $usernames, null, true);
                            } else {
                                $username = SystemUser::generateFirstnameSecondname($studentData['student_name'], $usernames);
                            }

                            $username = strtok($username, " ");
                            if (! isset($usernames[$username])) {
                                $usernames[$username] = 1;
                            } else {
                                $usernames[$username]++;
                            }
                            $studentData['username'] = strtolower($username);

                            // Generate password
                            switch ($passwordSetting) {
                                case 'birthdate':
                                    $birthdate = $studentData['date_of_birth'] ? date('y-m-d', strtotime($studentData['date_of_birth'])) : null;
                                    if ($birthdate !== null) {
                                        $split = explode("-", $birthdate);
                                        krsort($split);
                                        $password = implode($split);
                                    }
                                    break;
                                case 'standard':
                                    $password = 'password';
                                    break;
                                default:
                                    $password = $passwordSetting;
                                    break;
                            }
                            $studentData['password'] = Hash::make($password);

                            $studentData['uuid'] = Uuid::uuid4()->toString();
                            $studentData['user_uuid'] = $studentData['uuid'];
                            $studentData['upload_status'] = 'create';
                        } else {
                            $studentDetail = MsStudent::select([
                                't_user.username',
                                't_user.email',
                                't_user.password',
                                't_user.uuid',
                            ])->join('t_user', function ($i) {
                                $i->on('t_user.user_id', '=', 'ms_student.user_id');
                                $i->whereNull('t_user.deleted_at');
                            })->where('ms_student.student_id', '=', $studentData['student_id'])
                                ->whereNull('ms_student.deleted_at')
                                ->first();


                            // $studentData['email'] = $studentDetail['email'];
                            $studentData['password'] = $studentDetail['password'];
                            $studentData['username'] = $studentDetail['username'];
                            $studentData['uuid'] = $studentDetail['uuid'];
                            $studentData['user_uuid'] = $studentDetail['uuid'];
                            $studentData['upload_status'] = 'update';
                        }

                        $studentData['school_location_id'] = $studentData['enroll_school_location_id'];
                        $studentData['school_level_id'] = $studentData['enroll_school_level_id'];
                        $studentData['sokrates_old'] = true;
                        $studentData['role_id'] = $studentRoleId;
                        $studentData['customer_id'] = $customerId;
                        $studentData['created_at'] = date('Y-m-d H:i:s');
                        $studentData['updated_at'] = date('Y-m-d H:i:s');

                        # VARIABEL BUAT NAMPUNG USER DI TENANT
                        $userTenantList[] = [
                            'student_id' => $studentId,
                            'username'   => $studentData['username'],
                            'fullname'   => $studentData['student_name'],
                            'email'      => $studentData['email'],
                            'uuid'       => $studentData['uuid'],
                            'password'   => $studentData['password'],
                            'created_at' => $studentData['created_at'],
                            'updated_at' => $studentData['updated_at'],
                        ];

                        # VARIABEL BUAT NAMPUNG USER DI SYSTEM
                        $userSystemList[] = [
                            'student_id'   => $studentId,
                            'name'         => $studentData['student_name'],
                            'email'        => $studentData['email'],
                            'password'     => $studentData['password'],
                            'uuid'         => $studentData['uuid'],
                            'username'     => $studentData['username'],
                            'customer_id'  => $studentData['customer_id'],
                            'sokrates_old' => $studentData['sokrates_old'],
                            'created_at'   => $studentData['created_at'],
                            'updated_at'   => $studentData['updated_at'],
                        ];

                        $allStudents[] = $studentData;
                    }
                }

                # AMBIL STUDENT ID NYA AJA
                $studentIds = collect($allStudents)->map(function ($student) {
                    return $student['student_id'];
                })->values()->toArray();


                # INI UNTUK BAGIAN PARENT, CHECK ADA GA STUDENT DENGAN YG BRU DI INSERT
                $studentParentsData = MsStudentParents::select([
                    'ms_student_parents.student_parent_id',
                    'ms_student_parents.user_id',
                    'ms_student_parents.parent_type',
                    'ms_student_parents.student_id',
                ])->whereIn('ms_student_parents.student_id', $studentIds)
                    ->whereNull('ms_student_parents.deleted_at')
                    ->get()
                    ->toArray();


                $checkStudentParents = [];
                $checkStudentUserParents = [];

                if ($parents) {

                    $parents = collect($parents)->groupBy(function ($parent, $key) {
                        return $parent[3];
                    })->collapse()->values()->toArray();

                    foreach ($parents as $parentKey => $parent) {
                        $religion = null;
                        if (isset($parent[8])) {
                            $religion = $masterReligion->filter(function ($item) use ($parent) {
                                return $item === $parent[8];
                            })->keys()
                                ->first();
                        }

                        $nationality = null;
                        if (isset($parent[9])) {
                            $nationality = $masterNationality->filter(function ($item) use ($parent) {
                                return $item === $parent[9];
                            })->keys()
                                ->first();
                        }

                        $province = null;
                        if (isset($parent[22])) {
                            $province = $masterProvince->filter(function ($item) use ($parent) {
                                return $item === $parent[22];
                            })->keys()
                                ->first();
                        }

                        $country = null;
                        if (isset($parent[23])) {
                            $country = $masterCountry->filter(function ($item) use ($parent) {
                                return $item === $parent[23];
                            })->keys()
                                ->first();
                        }

                        # NYOCOKIN DENGAN ANTARA STUDENT DGN PARENT NYA
                        $studentData = collect($allStudents)->filter(function ($item) use ($parent) {
                            return $item['nis'] === $parent[0] && $item['student_name'] === $parent[1];
                        })->first();


                        $studentNis = $studentData ? $studentData['nis'] : null;
                        $studentName = $studentData ? $studentData['student_name'] : null;
                        $studentUsername = $studentData ? $studentData['username'] : null;
                        $studentPassword = $studentData ? $studentData['password'] : Hash::make('password');
                        $studentId = $studentData ? $studentData['student_id'] : null;
                        $enrollSchoolLocationId = $studentData ? $studentData['enroll_school_location_id'] : null;
                        $enrollSchoolLevelId = $studentData ? $studentData['enroll_school_level_id'] : null;

                        $parentDOB = null;

                        if (isset($parent[7])) {
                            if ($parent[7]) {
                                $parentDOB = str_replace('/', '-', $parent[7]);
                                $parentDOB = date('Y-m-d', strtotime($parentDOB));
                            }
                        }

                        $parentPassport = null;
                        if (isset($parent[12])) {
                            if ($parent[12]) {
                                $parentPassport = str_replace('/', '-', $parent[12]);
                                $parentPassport = date('Y-m-d', strtotime($parentPassport));
                            }
                        }

                        $parentKitas = null;
                        if (isset($parent[14])) {
                            if ($parent[14]) {
                                $parentKitas = str_replace('/', '-', $parent[14]);
                                $parentKitas = date('Y-m-d', strtotime($parentKitas));
                            }
                        }

                        # ASSIGN KE VARIABEL
                        $parentData['student_nis'] = $studentNis;
                        $parentData['student_name'] = $studentName;
                        $parentData['enroll_school_location_id'] = $enrollSchoolLocationId;
                        $parentData['enroll_school_level_id'] = $enrollSchoolLevelId;
                        $parentData['parent_type'] = isset($parent[2]) ? $parent[2] : null;
                        $parentData['parent_name'] = isset($parent[3]) ? $parent[3] : '-';
                        $parentData['place_of_birth'] = isset($parent[6]) ? $parent[6] : '-';
                        $parentData['date_of_birth'] = ($parentDOB) ? $parentDOB : '1900-01-01';
                        $parentData['address_line1'] = isset($parent[4]) ? $parent[4] : '-';
                        $parentData['religion_id'] = ($religion) ? $religion : null;
                        $parentData['gender'] = ($parent[2] === 'Mother') ? 'F' : 'M';
                        $parentData['nationality_id'] = ($nationality) ? $nationality : null;
                        $parentData['identification_number'] = isset($parent[10]) ? $parent[10] : null;
                        $parentData['passport_no'] = isset($parent[11]) ? $parent[11] : null;
                        $parentData['passport_expired_date'] = $parentPassport;
                        $parentData['kitas_no'] = isset($parent[13]) ? $parent[13] : null;
                        $parentData['kitas_expired_date'] = $parentKitas;
                        $parentData['phone_number'] = isset($parent[15]) ? $parent[15] : null;
                        $parentData['cellular_number'] = isset($parent[16]) ? $parent[16] : null;
                        $parentData['email'] = isset($parent[17]) ? $parent[17] : null;
                        $parentData['postal_code'] = isset($parent[18]) ? $parent[18] : null;
                        $parentData['village'] = isset($parent[19]) ? $parent[19] : null;
                        $parentData['sub_district'] = isset($parent[20]) ? $parent[20] : null;
                        $parentData['city'] = isset($parent[21]) ? $parent[21] : null;
                        $parentData['province_id'] = ($province) ? $province : null;
                        $parentData['country_id'] = ($country) ? $country : null;
                        $parentData['employment_company'] = isset($parent[24]) ? $parent[24] : null;
                        $parentData['office_address_line1'] = isset($parent[25]) ? $parent[25] : null;
                        $parentData['job_title'] = isset($parent[26]) ? $parent[26] : null;
                        $parentData['salary_range'] = isset($parent[27]) ? $parent[27] : null;
                        $parentData['relationship_to_student'] = isset($parent[28]) ? $parent[28] : null;
                        $parentData['last_education'] = isset($parent[29]) ? $parent[29] : null;
                        $parentData['student_id'] = $studentId;
                        $parentData['role_id'] = $parentRoleId;


                        # Check student parent data - MsStudentParents
                        $studentParentDetail = collect($studentParentsData)->filter(function ($item) use ($parentData) {
                            return $item['student_id'] === $parentData['student_id'] && $item['parent_type'] === $parentData['parent_type'];
                        })->first();

                        $userParentDetail = collect($studentParentsData)->filter(function ($item) use ($parentData) {
                            return $item['student_id'] === $parentData['student_id'];
                        })->values()->toArray();


                        # Check student parent user
                        $parentData['student_parent_id'] = $studentParentDetail ? $studentParentDetail['student_parent_id'] : null;
                        $parentData['user_id'] = $studentParentDetail ? $studentParentDetail['user_id'] : null;

                        if ($parentData['user_id']) {
                            $checkStudentUserParents[$studentNis] = true;
                        }

                        $parentData['customer_id'] = $customerId;
                        $parentData['sokrates_old'] = true;
                        $parentData['created_at'] = date('Y-m-d H:i:s');
                        $parentData['updated_at'] = date('Y-m-d H:i:s');

                        // check student_parent_id dan user_id
                        // Jika student_parent_id = null, maka insert data parent
                        // Jika student_parent_id != null, maka update data parent
                        // Jika salah satu data user_id dari parent === null, maka copy ke yang satu nya
                        // Jika dua2nya user_id dari parent === null, maka create 1 user baru

                        if (! $studentParentDetail && $userParentDetail) {
                            // Salah satu parent sudah punya user_id
                            // Tidak perlu bikin user baru
                            // Cuma perlu insert data ke ms_student_parents
                            $userParent = collect($userParentDetail)->first();
                            $parentData['user_id'] = $userParent['user_id'];
                            $parentData['upload_status'] = 'insert_parents';


                            $findUserParent = User::findOrFail($userParent['user_id']);
                            $parentData['email'] = $findUserParent->email;
                            $parentData['username'] = $findUserParent->username;
                            $parentData['fullname'] = $findUserParent->fullname;
                            $parentData['uuid'] = $findUserParent->uuid;
                            $parentData['user_uuid'] = $findUserParent->uuid;
                            $parentData['password'] = $findUserParent->password;
                            $checkStudentUserParents[$studentNis] = true;
                        }

                        if (! $studentParentDetail && ! $userParentDetail) {
                            // Semua parent belum punya user_id
                            // Perlu insert salah satu data parent ke t_user
                            // Dan perlu insert semua data ke ms_student_parents

                            # Generate password
                            $parentData['password'] = $studentPassword;


                            # Generate email
                            $parentEmail = SystemUser::generateUniqueEmail($parentData['email'], $parentData['student_name'], 0, 'p_', $parentEmails, $usernameParentEmails, $parent);

                            if (! isset($parentEmails[$parentEmail])) {
                                $parentEmails[$parentEmail] = 1;
                            } else {
                                $parentEmails[$parentEmail] += 1;
                            }

                            $parentData['email'] = strtolower($parentEmail);
//                            _dd('email', $parentData['email']);
                            $parentDetail = MsStudentParents::findOrCreateUserStudentParentForUploadModal($usernameSetting, $studentName, $studentUsername, $usernameParents);

//                            _dd('parentDetail', $parentDetail);
                            // if($parent[2] == 'Mother') {
                            //     _dd($parentDetail, $parentData, $parentEmails);
                            // }
                            # Retrieve Username Parents

                            $usernameParent = $parentDetail['username'];
                            $usernameParent = strtok($usernameParent, " ");

                            if (!isset($usernameParents[$usernameParent])) {
                                $usernameParents[$usernameParent] = 1;
                            } else {
                                $usernameParents[$usernameParent]++;
                            }

                            $parentData['username'] = strtolower($usernameParent);

                            $parentData['fullname'] = $parentDetail['fullname'];
                            $parentData['uuid'] = $parentDetail['uuid'];
                            $parentData['user_uuid'] = $parentDetail['uuid'];

                            if (! isset($checkStudentUserParents[$studentNis])) {
                                $userParentTenantList[] = [
                                    'username'   => $parentData['username'],
                                    'fullname'   => $studentName,
                                    'email'      => $parentData['email'],
                                    'uuid'       => $parentData['user_uuid'],
                                    'password'   => $parentData['password'],
                                    'created_at' => $parentData['created_at'],
                                    'updated_at' => $parentData['updated_at'],
                                ];

                                $userParentSystemList[] = [
                                    'username'     => $parentData['username'],
                                    'password'     => $parentData['password'],
                                    'name'         => $studentName,
                                    'email'        => $parentData['email'],
                                    'customer_id'  => $parentData['customer_id'],
                                    'uuid'         => $parentData['user_uuid'],
                                    'sokrates_old' => $parentData['sokrates_old'],
                                    'created_at'   => $parentData['created_at'],
                                    'updated_at'   => $parentData['updated_at'],
                                ];
                                $checkStudentUserParents[$studentNis] = true;
                            }
                            $parentData['upload_status'] = 'create';
                        }

                        if ($studentParentDetail) {
                            $findUserParent = User::findOrFail($studentParentDetail['user_id']);
                            // $parentData['email'] = $findUserParent->email; // jangan ganti ms_student_parent_email pake use remail
                            $parentData['username'] = $findUserParent->username;
                            $parentData['fullname'] = $findUserParent->fullname;
                            $parentData['uuid'] = $findUserParent->uuid;
                            $parentData['user_uuid'] = $findUserParent->uuid;
                            $parentData['password'] = $findUserParent->password;
                            $parentData['upload_status'] = 'update';
                            $checkStudentUserParents[$studentNis] = true;


                        }
                        $parentData['user_parents'] = $checkStudentUserParents[$studentNis];

                        $studentParentRelationData[] = [
                            'user_uuid_parent' => $parentData['user_uuid'],
                            'student_id'       => $parentData['student_id'],
                        ];
                        $allParents[] = $parentData;
                    }
                }

                try {
                    useSystemEnvironment();
                    DB::beginTransaction();

                    // Filter System User By Student Id
                    // Kalo udah punya student_id ga perlu insert ke user system lagi
                    $userSystemList = collect($userSystemList)
                        ->filter(function ($item) {
                            return (! isset($item['student_id']));
                        })->map(function ($item) {
                            $data = collect($item)->forget('student_id');
                            return $data;
                        })->unique()->values()->toArray();

                    if (collect($userSystemList)->count() > 0) {
                        SystemUser::insert($userSystemList);
                    }

                    // Insert parent to system user
                    $userParentSystemList = collect($userParentSystemList)
                        ->unique()->values()->toArray();
                    if (collect($userParentSystemList)->count() > 0) {
                        SystemUser::insert($userParentSystemList);
                    }

                    DB::commit();
                } catch (Exception $exception) {
                    DB::rollBack();
                    throw $exception;
                } finally {
                    useTenantEnvironment($website);
                }

                try {

                    DB::beginTransaction();

                    // Filter Tenant User By StudentId
                    // Kalo udah punya student_id ga perlu insert ke user tenant lagi
                    $filteredTenantUser = collect($userTenantList)
                        ->filter(function ($item) {
                            return (! isset($item['student_id']));
                        })->map(function ($item) {
                            $data = collect($item)->forget('student_id');
                            return $data;
                        })->unique()->values()->toArray();
                    if (collect($filteredTenantUser)->count() > 0) {
                        User::insert($filteredTenantUser);
                    }

                    // Get and map user id to student array
                    $allStudents = collect($allStudents)->map(function ($student) {
                        $studentUser = User::where('uuid', $student['user_uuid'])
                            ->whereNull('deleted_at')
                            ->first();

                        $student['user_id'] = $studentUser ? $studentUser['user_id'] : null;
                        return $student;
                    })->filter(function ($item) {
                        return ($item['user_id']);
                    })->values()
                        ->toArray();

                    $userIds = collect($allStudents)->map(function ($item) {
                        return $item['user_id'];
                    });

                    // Filter student insert
                    $tableStudentList = collect($allStudents)->map(function ($student) {
                        $studentData = MsStudent::getStudentAttributes($student);
                        $studentData['upload_status'] = $student['upload_status'];
                        return $studentData;
                    })->unique()->values()->toArray();
                    // Insert Students
                    $insertBatchStudents = collect($tableStudentList)
                        ->filter(function ($item) {
                            return ($item['upload_status'] === 'create');
                        })->unique()->values()->toArray();
                    if (collect($insertBatchStudents)->count() > 0) {
                        // Remove upload status column
                        $insertBatchStudents = collect($insertBatchStudents)->map(function ($item) {
                            $data = collect($item)->forget('upload_status');
                            return $data;
                        })->values()->toArray();
                        // Insert batch student - BreakPoint
                        MsStudent::insert($insertBatchStudents);
                    }

                    // Update Students
                    $updateStudents = collect($tableStudentList)
                        ->filter(function ($item) {
                            return ($item['upload_status'] === 'update');
                        })->unique()->values()->toArray();

                    // Update students on t_user
                    for ($i = 0; $i < count($updateStudents); $i++) {
                        $updateStudent = User::findOrFail($updateStudents[$i]['user_id']);
                        $updateStudent->fullname = $updateStudents[$i]['student_name'];
                        $updateStudent->email = $updateStudents[$i]['email'];
                        $updateStudent->save();

                        if ($updateStudents !==  null) {
                            useSystemEnvironment();
                            $website = getTenantWebsite();
                            // UPDATE STUDENT FULLNAME DI SOKRATES USERS
                            $studentSystem = SystemUser::where('uuid', '=', $updateStudent->uuid)->first();

                            if ($studentSystem !== null) {

                                $studentSystem->name = $updateStudent->fullname;
                                $studentSystem->email = $updateStudent->email;
                                $studentSystem->save();
                            }

                            useTenantEnvironment($website);

                            $studentParent = MsStudentParents::where('student_id', '=', $updateStudents[$i]['student_id'])->first();


                            if ($studentParent !== null) {
                                // UPDATE PARENT NAME DI T_USER
                                $studentParentUser = User::where('uuid', '=', $studentParent->user_uuid)->first();

                                if ($studentParentUser !== null) {
                                    $studentParentUser->fullname = $updateStudents[$i]['student_name'];
                                    $studentParentUser->save();
                                }

                                $website = getTenantWebsite();
                                useSystemEnvironment();

                                $studentParentSystem = SystemUser::where('uuid', '=', $studentParent->user_uuid)->first();
                                // UPDATE PARENT NAME DI USERS
                                if ($studentParentSystem !== null) {
                                    $studentParentSystem->name = $updateStudents[$i]['student_name'];
                                    // $studentParentSystem->email = ($studentParent->email !== null && $studentParent->email !== '-') ? $studentParent->email : '-';
                                    $studentParentSystem->save();
                                }

                                useTenantEnvironment($website);
                            }

                        }
                    }


                    MsStudent::updateBatch($updateStudents);

                    $year = date("Y");


                    // Get and map student id to student array
                    $allStudents = collect($allStudents)->map(function ($student) use ($year) {
                        $studentData = MsStudent::where('nis', $student['nis'])
                            ->where('date_of_birth', $student['date_of_birth'])
                            ->where('student_name', $student['student_name'])
                            ->where(db::raw("to_char(created_at, 'YYYY')"), $year)
                            ->whereNull('deleted_at')
                            ->first();

                        $parentIsExist = false;
                        if ($studentData != null) {
                            $parentData = MsStudentParents::where('student_id', $studentData['student_id'])
                            ->whereNull('deleted_at')
                            ->first();

                            $parentIsExist = $parentData ? true : false;
                        }

                        $student['student_id'] = $studentData ? $studentData['student_id'] : null;
                        return $student;
                    })->filter(function ($item) {
                        return ($item['student_id']);
                    })->values()
                    ->toArray();


                    $roleDataList = collect($allStudents)->filter(function ($item) {
                        return ($item['upload_status'] === 'create');
                    })->map(function ($item) {
                        return [
                            'user_id'            => $item['user_id'],
                            'role_id'            => $item['role_id'],
                            'school_location_id' => $item['enroll_school_location_id'],
                            'school_level_id'    => $item['enroll_school_level_id'],
                            'created_at'         => date('Y-m-d H:i:s'),
                        ];
                    })->unique()->values()->toArray();
                    if (collect($roleDataList)->count() > 0) {
                        TUserRole::insert($roleDataList);
                    }
                    $roleAssignedDataList = collect($allStudents)->filter(function ($item) {
                        return ($item['upload_status'] === 'create');
                    })->map(function ($item) {
                        return [
                            'role_id'     => $item['role_id'],
                            'entity_id'   => $item['user_id'],
                            'entity_type' => User::class,
                        ];
                    })->unique()->values()->toArray();
                    if (collect($roleAssignedDataList)->count() > 0) {
                        DB::table('assigned_roles')->insert($roleAssignedDataList);
                    }

                    // Insert parent to tenant user
                    $filteredTenantUserParent = collect($userParentTenantList)
                        ->unique()->values()->toArray();
                    if (collect($filteredTenantUserParent)->count() > 0) {
                        User::insert($filteredTenantUserParent);
                    }


                    // Get and map user id to parent array
                    $allParents = collect($allParents)
                        ->map(function ($parent) use ($allStudents) {
                            $parentUser = User::where('uuid', $parent['user_uuid'])
                                ->whereNull('deleted_at')
                                ->first();

                            $studentData = collect($allStudents)
                                ->filter(function ($item) use ($parent) {
                                    return $item['nis'] === $parent['student_nis'] && $item['student_name'] === $parent['student_name'];
                                })
                                ->first();

                            $parent['student_id'] = $studentData['student_id'];
                            $parent['user_id'] = $parentUser ? $parentUser['user_id'] : null;
                            return $parent;
                        })
                        ->values()
                        ->toArray();


                    // Map Father and Mother StudentId
                    $allParents = collect($allParents)->map(function ($parent) use ($allParents) {
                        if (! $parent['user_id']) {
                            $findParent = collect($allParents)->filter(function ($item) use ($parent) {
                                return ($item['user_id'] && ($item['student_nis'] === $parent['student_nis']));
                            })->first();
                            $parent['user_id'] = $findParent['user_id'];
                            $parent['user_uuid'] = $findParent['user_uuid'];
                        }
                        return $parent;
                    })->values()
                        ->toArray();


                    // Filter parent insert
                    $tableParentList = collect($allParents)->map(function ($parent) {
                        $parentData = MsStudentParents::getParentAttributes($parent);
                        return $parentData;
                    })->unique()->values()->toArray();

                    // Insert Parents
                    $insertBatchParents = collect($tableParentList)
                        ->filter(function ($item) {
                            return (! isset($item['student_parent_id']));
                        })->unique()->values()->toArray();
                    if (collect($insertBatchParents)->count() > 0) {
                        // Insert batch parent
                        MsStudentParents::insert($insertBatchParents);
                    }


                    // Update Parents
                    $updateParents = collect($tableParentList)
                        ->filter(function ($item) {
                            return (isset($item['student_parent_id']));
                        })->unique()->values()->toArray();
                    if (collect($updateParents)->count() > 0) {
                        $updatedParents = collect($updateParents)->each(function ($parent) {
                            $parentDetail = MsStudentParents::findOrFail($parent['student_parent_id']);
                            $parentDetail->setAttributesFromJson($parent);
                            $parentDetail->save();
                        });
                    }

                    $allParents = collect($allParents)->filter(function ($item) {
                        return ($item['user_id']);
                    })->values()
                        ->toArray();
                    $roleParentDataList = collect($allParents)->filter(function ($item) {
                        return ($item['upload_status'] === 'create');
                    })->map(function ($item) {
                        return [
                            'user_id'            => $item['user_id'],
                            'role_id'            => $item['role_id'],
                            'school_location_id' => $item['enroll_school_location_id'],
                            'school_level_id'    => $item['enroll_school_level_id'],
                            'created_at'         => date('Y-m-d H:i:s'),
                        ];
                    })->unique()->values()->toArray();
                    if (collect($roleParentDataList)->count() > 0) {
                        TUserRole::insert($roleParentDataList);
                    }
                    $roleAssignedParentDataList = collect($allParents)->filter(function ($item) {
                        return ($item['upload_status'] === 'create');
                    })->map(function ($item) {
                        return [
                            'role_id'     => $item['role_id'],
                            'entity_id'   => $item['user_id'],
                            'entity_type' => User::class,
                        ];
                    })->unique()->values()->toArray();
                    if (collect($roleAssignedParentDataList)->count() > 0) {
                        DB::table('assigned_roles')->insert($roleAssignedParentDataList);
                    }

                    // Student - Parent Relation
                    if (collect($studentParentRelationData)->count() > 0) {
                        collect($studentParentRelationData)->each(function ($student) use (&$rollback) {
                            // Student Parent Relation - Sibling
                            $checkSibling = MsStudentSibling::select([
                                'sibling_id',
                                'sibling_nis',
                            ])->where('student_id', $student['student_id'])
                                ->whereNull('deleted_at');
                            $checkSiblingCount = $checkSibling->count();
                            $checkSiblingData = $checkSibling->get();

                            if ($checkSiblingCount > 0) {
                                foreach ($checkSiblingData as $siblingData) {
                                    $siblingStudentData = MsStudent::where('nis', $siblingData->sibling_nis)
                                        ->whereNull('deleted_at')
                                        ->first();
                                    $siblingStudentId = $siblingStudentData ? $siblingStudentData->student_id : null;
                                    if ($siblingStudentId) {
                                        $checkStudentParentRelationSibling = MsStudentParentRelation::select([
                                            'student_parent_relation_id',
                                        ])->where('user_uuid_parent', $student['user_uuid_parent'])
                                            ->where('student_id', $siblingStudentId)
                                            ->whereNull('deleted_at')
                                            ->first();

                                        if (! $checkStudentParentRelationSibling) {
                                            $studentParentRelationSiblingData = [
                                                'user_uuid_parent' => $student['user_uuid_parent'],
                                                'student_id'       => $siblingStudentId,
                                            ];

                                            $studentParentRelationSibling = new MsStudentParentRelation;
                                            $studentParentRelationSibling->setAttributesFromJson($studentParentRelationSiblingData);
                                            $studentParentRelationSibling->save();

                                            $rollback['student_parent_relation_ids'][] = $studentParentRelationSibling->student_parent_relation_id;
                                        }
                                    }
                                }

                                $checkStudentParentRelation = MsStudentParentRelation::select([
                                    'student_parent_relation_id',
                                ])->where('user_uuid_parent', $student['user_uuid_parent'])
                                    ->where('student_id', $student['student_id'])
                                    ->whereNull('deleted_at')
                                    ->first();

                                if (! $checkStudentParentRelation) {
                                    $studentParentRelation = new MsStudentParentRelation;
                                    $studentParentRelation->setAttributesFromJson($student);
                                    $studentParentRelation->save();

                                    $rollback['student_parent_relation_ids'][] = $studentParentRelation->student_parent_relation_id;
                                }
                            }
                        });
                    }

                    DB::commit();
                } catch (Exception $exception) {
                    DB::rollBack();

                    SystemUser::query()
                        ->whereIn('uuid', collect($userSystemList)->pluck('uuid')->toArray())
                        ->forceDelete();

                    SystemUser::query()
                        ->whereIn('uuid', collect($userParentSystemList)->pluck('uuid')->toArray())
                        ->forceDelete();

                    throw $exception;
                }

            } catch (Exception $exception) {
                throw $exception;
            } finally {
                useTenantEnvironment($website);
            }

            $result = null;
        } catch (Exception $e) {
            throw $e;
        }

        return $result;
    }