Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 300
CRAP
0.00% covered (danger)
0.00%
0 / 10207
StudentService
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 300
2354690.00
0.00% covered (danger)
0.00%
0 / 10201
 __construct
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 4
 __clone
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 2
 getInstance
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 7
 createStudent
0.00% covered (danger)
0.00%
0 / 1
600.00
0.00% covered (danger)
0.00%
0 / 179
 updateStudent
0.00% covered (danger)
0.00%
0 / 1
1406.00
0.00% covered (danger)
0.00%
0 / 196
 updateStudentExtraFields
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 searchStudent
0.00% covered (danger)
0.00%
0 / 1
1190.00
0.00% covered (danger)
0.00%
0 / 274
 getAllStudents
0.00% covered (danger)
0.00%
0 / 1
1560.00
0.00% covered (danger)
0.00%
0 / 47
 getAllStudentsForApi
0.00% covered (danger)
0.00%
0 / 1
420.00
0.00% covered (danger)
0.00%
0 / 102
 getStudentDetailsByIds
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 40
 getStudentDetailsById
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 168
 getStudentDetailsByIdForMultiIDCard
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 156
 getStudentDetailsByIdConcessionNumbers
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 139
 getHisCorrectBatchId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getStudentDetailsByIdForApi
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 86
 searchStudents
0.00% covered (danger)
0.00%
0 / 1
552.00
0.00% covered (danger)
0.00%
0 / 85
 searchMigrationStudents
0.00% covered (danger)
0.00%
0 / 1
462.00
0.00% covered (danger)
0.00%
0 / 89
 getFailedStudentById
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 57
 isFailed
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 24
 deleteStudent
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 14
 deleteStudentFile
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 13
 unlinkStudentProfilePic
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 8
 removeStudentSignature
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 16
 removeStudentProfilePic
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 16
 getStudentBatchIdBySubject
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 getStudentDetailsForMakeAttendance
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 27
 searchCancelStudents
0.00% covered (danger)
0.00%
0 / 1
462.00
0.00% covered (danger)
0.00%
0 / 74
 updateFailedStudentStatus
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 32
 updateFailedStudentStatusWithRemarks
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 34
 deleteStudentDir
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 18
 getStudentsCountByBatch
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 22
 getStudentIdByAdmissionNo
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 getStudentDetailsByRegNo
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 getStudentByRollNo
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 14
 getStudentBankSId
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 14
 getStudentDetailsBybankSID
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 updateStudentPhoto
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 moveStudentToFailedList
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 29
 moveStudentToFailedListByAdmissionNo
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 29
 moveBackFromFailedList
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 32
 moveBackFromFailedListWithRollNoAssigned
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 77
 moveBackFromFailedListByAdmissionNo
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 26
 getStudentDetailsByEmailId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 updateStudentPassword
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 getStudentDetailsByAdmissionNo
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 updateStudentsTcIssuedByStudentIds
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 getAllStudentsByBatchIdSemIdSubjectId
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 29
 updateStudentBatch
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 updateCampusTypesOfBatch
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 getStudentsAssignedToApseudoSub
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 18
 getStudentData
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 searchFailedStudents
0.00% covered (danger)
0.00%
0 / 1
342.00
0.00% covered (danger)
0.00%
0 / 79
 getStudentDetails
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 45
 getStudentsByBatch
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 24
 verifyAllStudentsByBatchId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 unVerifyAllStudentsByBatchId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 blockStudentByBatch
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 getFullStudentList
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 updatePhdStudentDetails
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 getStudentOpenCourseDetails
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 getStudentsCountBySubbatchId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 8
 updateStudentDetails
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 17
 getCoachingTypes
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 14
 getScholarshipTypes
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 14
 insertStudentDataFromExcel
0.00% covered (danger)
0.00%
0 / 1
18360.00
0.00% covered (danger)
0.00%
0 / 514
 getDepartmentByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getBatchByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getNationalityByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getsecondLangaugeByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getReligionByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getStudentReservationByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getStudentCasteByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getStudentSeatReservationByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getStudentFeeCategoryByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getStudentSubCasteByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getStudentQuotaByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getStudentPovertyLineByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getStudentDistrictByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getStudentStateByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getStudentTalukByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getCoachingTypeByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getScholarshipTypeByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getStaffDetailsByName
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 approveStudentPaymentStatus
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 18
 updateStudentApproveStatus
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 16
 getStudentMcNo
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 getMaxMcNo
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 addStudentMcNo
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 30
 getStudentCancelCertificateNo
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 getMinCancelNo
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getMaxCancelNo
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getStudentRegisteredExamDetails
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getExamSemId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 updateCancelNo
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 addStudentCancelNo
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 30
 getStudentDetailsByBatchSemIdAndSubbatchId
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 25
 addStudentExtras
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 81
 updateStudentExtras
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 105
 getStudentExtrasByStudentId
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 38
 addStudentEducationDetails
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 14
 removeStudentEducationDetailsByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 getStudentEducationDetailsByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 getStudentEducationDetailsByStudentIdURLEncodedFormat
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 addStudentSportsDetails
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 14
 removeStudentSportsDetailsByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 getStudentSportsDetailsByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 getAllStudentsOfABatchByBatchIdSemIdAndSubbatchId
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 28
 getStudentsBySubjectId
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 26
 moveStudentToFailedListByBatch
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 26
 getStudentSecondLanguageByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 getStudentOptionalSubjectsByStudentId
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 16
 batchChangeAssinc
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getCourseTypeByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 getStudentFailedBatches
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 17
 getStudentDetailOnTheBasesOfGenderAndBatchId
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 17
 getStudentDetailWithSecondLanguageID
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 34
 getStudentsBatchIDBySemIDandStudentID
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 23
 getFailedStudentBatchs
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 21
 updateStudentsForBatchTransfer
0.00% covered (danger)
0.00%
0 / 1
90.00
0.00% covered (danger)
0.00%
0 / 57
 getPassedStudentsCountInMinimumStipulatedTimeInDepartmentAndYear
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 getCourseTypeByRegisterNumber
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 getStudentBasicDetailsById
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 36
 getStudentsByBatches
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 25
 getExamRegisteredStudents
0.00% covered (danger)
0.00%
0 / 1
420.00
0.00% covered (danger)
0.00%
0 / 117
 getStudentSpecialization
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 getFailedStudentDetails
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 15
 getStudentsInRangeByBatches
0.00% covered (danger)
0.00%
0 / 1
132.00
0.00% covered (danger)
0.00%
0 / 76
 getGenders
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 addStudentSpecialization
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 getStudentsSpecializationDetail
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 26
 assignSpecializationToStudent
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 15
 updateSpecializationToStudent
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 27
 getSpecializationDetail
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 getStudentDetailsBySubBatch
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 23
 getStudentDetailsByRequestWithInternalMark
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 89
 getDomiciles
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 studentTransportaionId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 getStudentNameById
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 getStudentListByBatchIdAndDeptId
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 16
 isStudentInFinalSemester
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 21
 getStudentDetailsByBatchAndCampusType
0.00% covered (danger)
0.00%
0 / 1
156.00
0.00% covered (danger)
0.00%
0 / 105
 getStudentBatchIdByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 getStudentList
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 74
 getAllStudentsForFormways
0.00% covered (danger)
0.00%
0 / 1
380.00
0.00% covered (danger)
0.00%
0 / 69
 getStudentGenderList
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 8
 getStudentDetailsForPrintForm
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 123
 getStudentEducationDetailsByStudentIdAndQualification
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 searchStudenttByString
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 19
 getPreviousBatch
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 12
 getStudentsMarksCardSerialNoInBatch
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 48
 getStudentsInBatch
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 22
 getSupplyRegisteredStudentsInBatch
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 25
 getStudentsForEnrolmentByBatch
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 39
 getStudentIdByStudentRegId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 getblockReasons
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 16
 getblockedReasonByStudentSubject
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 24
 getSubjectsDetailsByStudentDetails
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 43
 getStudentDetailsByRegNoForFailedStudents
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 updateStudentFailedList
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 45
 getFailedStudentDetailsList
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 deleteStudentFailedList
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 getAllStudentMailIdByRequest
0.00% covered (danger)
0.00%
0 / 1
342.00
0.00% covered (danger)
0.00%
0 / 40
 getStudentSubBatchIdBySubjectAndBatchID
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 37
 getStudentsByBatchIdSemIdSubjectIdStaffId
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 29
 updateChallanStatusByChallanNo
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 21
 updateChallanStatusByChallanNoForSupply
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 21
 getSupplyStudentDetails
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 32
 getStudentCountBySbsId
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 38
 getStudentsInBatchBySubjectId
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 30
 getStudentOpenCourse
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 36
 searchStudentList
0.00% covered (danger)
0.00%
0 / 1
90.00
0.00% covered (danger)
0.00%
0 / 527
 updateStudentProfile
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 17
 updateStudentExtrasProfile
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 24
 getExamBlockedStudentsByBatch
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 33
 getReAdmissionDetails
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 updateReAdmissionDetails
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 44
 deleteReAdmissionDetails
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 getStudentBatchBySemId
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 12
 getPreviousSemestersOfThisBatch
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 15
 getStudentRegNoById
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 getHostelStudents
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 11
 getFailedStudentDetailsByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 getStudentsAssignedToPseudoSubject
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 38
 getStudentPreviousBatchBySemId
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 11
 resetStudentFields
0.00% covered (danger)
0.00%
0 / 1
182.00
0.00% covered (danger)
0.00%
0 / 51
 getStudentField
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 18
 getDynamicFromStudentDetailsForPrint
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 16
 getStudentSpecializationByBatchId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getStudentHourNote
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 saveStudentHourNote
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 updateStudentHourNote
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 getStudentDetailsForEditProfileFromStudentPortal
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 43
 getStudentIsPgOrNot
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 getAllStudentsOfABatchByBatchIdOrExamRegistrationId
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 50
 getStudentsByBatchId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 14
 getStudentPhotoByStudentId
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 17
 getTcIssuedStudentDetails
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 42
 updateStudentFailedDate
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 12
 updateStudentTcIssueDate
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 12
 getExamBlockedStudentsByBatchSupply
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 33
 getStudentHallTicketBlockedStatus
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 21
 getExamRegisteredStudentDetailsByDeptartment
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 30
 getStudentDetailsByRollNo
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 updateStudentProfileImageResource
0.00% covered (danger)
0.00%
0 / 1
240.00
0.00% covered (danger)
0.00%
0 / 76
 updateStudentSignatureImageResource
0.00% covered (danger)
0.00%
0 / 1
240.00
0.00% covered (danger)
0.00%
0 / 73
 updateParentSignatureImageResource
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 getStudentProfilePic
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 25
 getStudentSignPic
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 25
 searchStudentForListDown
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 26
 getParentSignPic
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 21
 getFailedStudentDetailsByBatchIdAndSemId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 15
 getExamRegisteredStudentDetailsByExamRegIdAndSubjectId
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 35
 createCompanyForPlacement
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 getAllPlacementCompanies
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 8
 getAllPlacementCompaniesByRequest
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 14
 updatePlacementCompanyDetails
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 deletePlacementCompanyById
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 7
 fetchStudentsPlacementDetails
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 fetchStudentsForPlacementDetails
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 saveStudentPlacementDetails
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 27
 updatePlacementProperties
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 checkPlacementProperty
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 28
 getStudentDetailsByRequest
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 getStudentAddonCourse
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 getRegularExamRegistrationsOfStudent
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 30
 getStudentReservationForDatImport
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 8
 getStudentSeatReservationForDatImport
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 8
 getStudentByRequestForPseudoSubjectImport
0.00% covered (danger)
0.00%
0 / 1
110.00
0.00% covered (danger)
0.00%
0 / 20
 getStudentsForExportShow
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 generateAsyncStudentPhotoDownload
0.00% covered (danger)
0.00%
0 / 1
210.00
0.00% covered (danger)
0.00%
0 / 128
 generateAsyncStudentPhotoDownloadCourseType
0.00% covered (danger)
0.00%
0 / 1
240.00
0.00% covered (danger)
0.00%
0 / 129
 getMoocExamRegistrationStudents
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 28
 getSupplyExamsRegistrationOfStudent
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 22
 blockStudentExamResultByExamRegistration
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 32
 searchStudentBasicDetails
0.00% covered (danger)
0.00%
0 / 1
930.00
0.00% covered (danger)
0.00%
0 / 139
 isExistAnEntryForAdvancedProfile
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 5
 submitFormAdvancedProfile
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 23
 getDataForAdvancedProfile
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 14
 getStudentDataforAdvanceProfile
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 31
 getMentorMenteeForAdvancedProfile
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 57
 getStudentMarkHtmlResponse
0.00% covered (danger)
0.00%
0 / 1
756.00
0.00% covered (danger)
0.00%
0 / 156
 getSemesterDetailsForAdvanceProfile
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 8
 updatePublishStatus
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 3
 getPublishStatus
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 7
 togglePublishStatus
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 3
 addStudentToV4
0.00% covered (danger)
0.00%
0 / 1
506.00
0.00% covered (danger)
0.00%
0 / 96
 updateStudentToV4
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 16
 getStudentPreviousBatchDetailsBySemId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 15
 getV4StudentDetails
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 17
 createV4MoveStudentFailedRequest
0.00% covered (danger)
0.00%
0 / 1
156.00
0.00% covered (danger)
0.00%
0 / 33
 getV4MoveStudentFailedRequest
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 15
 deleteV4Request
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 11
 updateV4RequestAsFailer
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 12
 getStudentSubjectAttendanceBlockStatus
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 23
 getAllStudentDetailsByRequest
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 146
 getStudentCertificates
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 32
 getStudentsByBatchForCustomReport
0.00% covered (danger)
0.00%
0 / 1
1406.00
0.00% covered (danger)
0.00%
0 / 162
 getStudentDetailsForSsp
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 49
 getStudentDetailsForSspAndSingleStudent
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 49
 getStudentPreviousDetailsForSsp
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 32
 getStudentPreviousDetailsForSspForSingleStudent
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 33
 getbatchDetailsForSsp
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 16
 createSppLog
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 27
 updateSppLog
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 26
 selectSppLog
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 21
 getStudentLastQualification
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 31
 getPreviousCollegeWithSspData
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 17
 getPreviousCourseWithSspData
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 14
 getStudentPhotosByBatches
0.00% covered (danger)
0.00%
0 / 1
342.00
0.00% covered (danger)
0.00%
0 / 64
 getStudentBulkZip
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 14
 createZipWithStructure
0.00% covered (danger)
0.00%
0 / 1
210.00
0.00% covered (danger)
0.00%
0 / 54
 checkPathAndAddIt
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 25
 getStudentDetailsForApi
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 20
 getMultipleStudentDetails
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 8
 InsertStudentMarkAcknowledgement
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 28
 getStudentMarkAcknowledgement
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 studentDetailsForCollege
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 30
 getStudentDetailsBystudentAccount
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 7
 updateStudentMarkAcknowledgement
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 getStudentGradeWithExamIdAndStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 33
 getStudentAdmissionYear
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 13
 getDynamicDataForDossier
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 48
 getFailedStudentDetailsWithDiscontinuedStateByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 25
 getFailedBatchAndSemester
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 checkStudentCBEApplicationExists
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 getAllDomicileForStudent
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 checkForDuplicateUUCMS
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 17
 getSupplyRegisteredStudentsInBatchSemDetails
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 28
 getUserResidenceDetails
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 28
 getFeCommunityStudentAttendanceAndInternal
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 34
 getStudentDetailsByRegNoSem
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 37
 addStudentAutomatcallyToSubjectCommunity
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 73
 studentAssignmentToCbe
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 39
 removeStudentFromAllCbeApplication
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 109
 getWeekStudentsDetails
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 51
 getStudentDetailsForApiSecond
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 33
 getFailedStudentForMigrationById
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 57
 updateFormToAccesscardConf
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 14
 getStudentRegNoByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 updateStudentAccountExtraAdditionalDetails
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 77
<?php
namespace com\linways\core\ams\professional\service;
use com\linways\base\helper\ResultHandler;
use stdClass;
use com\linways\base\util\StringUtil;
use com\linways\base\util\TwigRenderer;
use com\linways\base\hooks\LinwaysHooks;
use com\linways\base\util\SecurityUtils;
use linways\cfb\classes\components\Select;
use com\linways\core\ams\professional\dto\Batch;
use com\linways\core\ams\professional\dto\Student;
use com\linways\core\ams\professional\dto\Semester;
use com\linways\core\ams\professional\util\PdfUtil;
use com\linways\core\ams\professional\util\S3Utils;
use com\linways\core\ams\professional\logging\Events;
use com\linways\core\ams\professional\util\CommonUtil;
use com\linways\core\ams\professional\constant\ExamType;
use com\linways\core\ams\professional\constant\UserType;
use com\linways\core\ams\professional\dto\StudentExtras;
use com\linways\core\ams\professional\logging\AMSLogger;
use com\linways\core\ams\professional\queue\AMSTaskQueue;
use com\linways\core\ams\professional\service\BatchService;
use com\linways\core\ams\professional\constant\BackendTypes;
use com\linways\core\ams\professional\constant\FailedReason;
use com\linways\core\ams\professional\dto\SettingsConstents;
use com\linways\core\ams\professional\service\CommonService;
use com\linways\core\ams\professional\constant\BatchConstants;
use com\linways\core\ams\professional\service\ResourceService;
use com\linways\core\ams\professional\constant\ResourceContext;
use com\linways\core\ams\professional\constant\SettingsConstants;
use com\linways\core\ams\professional\service\AsyncReportService;
use com\linways\core\ams\professional\mapper\StudentServiceMapper;
use com\linways\core\ams\professional\request\AddUserToRoleRequest;
use com\linways\core\ams\professional\request\SearchStudentRequest;
use com\linways\core\ams\professional\service\report\ReportService;
use com\linways\core\ams\professional\request\GetAsyncReportRequest;
use com\linways\core\ams\professional\request\UploadResourceRequest;
use com\linways\core\ams\professional\request\api\GetStudentsRequest;
use com\linways\core\ams\professional\request\GetPreSignedUrlRequest;
use com\linways\core\ams\professional\response\SearchStudentResponse;
use com\linways\core\ams\professional\service\AmsCustomFieldsService;
use com\linways\core\ams\professional\exception\ProfessionalException;
use com\linways\core\ams\professional\constant\AmsCustomFieldsEntities;
use com\linways\core\ams\professional\constant\apiendpoints\ApiEndpoints;
use com\linways\core\ams\professional\constant\examcontroller\MarkList;
use com\linways\core\ams\professional\request\api\GetAllStudentsRequest;
use com\linways\core\ams\professional\request\SearchFailedStudentRequest;
use com\linways\core\ams\professional\request\StudentHourWiseNoteRequest;
use com\linways\core\ams\professional\response\SearchFailedStudentResponse;
use com\linways\core\ams\professional\request\academic\FailedStudentRequest;
use com\linways\core\ams\professional\request\SaveAmsCustomFieldsValueRequest;
use com\linways\core\ams\professional\service\report\AdvancedStudentReportService;
use com\linways\core\ams\professional\request\GetStudentForAdmissionRegisterRequest;
use com\linways\core\ams\professional\constant\examcontroller\ExamSubjectTypeConstants;
use com\linways\core\ams\professional\constant\StatusConstants;
use com\linways\core\ams\professional\request\academic\AutoAssignmentCbeTermRegistration;
use com\linways\core\ams\professional\request\RemoveStudentFromAllCbeApplicationsRequest;
$foreignStudentsAdditionalInformation = json_decode(CommonService::getInstance()->getSettings(SettingsConstants::FOREIGN_STUDENT_INFORMATION_SETTINGS, SettingsConstants::FOREIGN_STUDENT_INFORMATION_SETTINGS));
global $settings;
$settings = $foreignStudentsAdditionalInformation->show;
/**Settings for TC to filter by batchStartYear**/
$tcSettings = json_decode(CommonService::getInstance()->getSettings(SettingsConstants::TC_BY_BATCH_START_YEAR, SettingsConstants::TC_BY_BATCH_START_YEAR));
$enableTCSettings = $tcSettings->enable;
$tcBatchStartYear = $tcSettings->batchYear;
class StudentService extends BaseService
{
    // /Condition 1 - Presence of a static member variable
    private static $_instance = null;
    private $mapper = [];
    private $logger = null;
    // /Condition 2 - Locked down the constructor
    private function __construct()
    {
        $this->logger = AMSLogger::getLogger();
        $this->mapper = StudentServiceMapper::getInstance()->getMapper();
    }
    // Prevent any outside instantiation of this class
    // /Condition 3 - Prevent any object or instance of that class to be cloned
    private function __clone()
    {
    }
    // Prevent any copy of this object
    // /Condition 4 - Have a single globally accessible static method
    public static function getInstance()
    {
        if (!is_object(self::$_instance))// or if( is_null(self::$_instance) ) or if( self::$_instance == null )
        {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
    /**
     * create student
     * @param Student $student
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     */
    public function createStudent($student)
    {
        $student = $this->realEscapeObject($student);
        $userBirthDay = !empty($student->studentBirthday) ? " \"$student->studentBirthday\"," : 'null,';
        $student->quotaId = !empty($student->quotaId) ? $student->quotaId : 'NULL';
        $student->religion = !empty($student->religion) ? $student->religion : 'NULL';
        $student->casteId = !empty($student->casteId) ? $student->casteId : 'NULL';
        $student->subCasteId = !empty($student->subCasteId) ? $student->subCasteId : 'NULL';
        // $student->feeReservationId = !empty($student->feeReservationId)? $student->feeReservationId: 'NULL';
        $student->nationalityId = !empty($student->nationalityId) ? $student->nationalityId : 'NULL';
        $student->povertyLineId = !empty($student->povertyLineId) ? $student->povertyLineId : 'NULL';
        $student->stateId = !empty($student->stateId) ? $student->stateId : 'NULL';
        $student->districtId = !empty($student->districtId) ? $student->districtId : 'NULL';
        $student->talukId = !empty($student->talukId) ? $student->talukId : 'NULL';
        $student->campusTypeId = !empty($student->campusTypeId) ? $student->campusTypeId : 'NULL';
        $student->secondLanguageId = !empty($student->secondLanguageId) ? $student->secondLanguageId : 'NULL';
        $student->secondLanguage2Id = !empty($student->secondLanguage2Id) ? $student->secondLanguage2Id : 'NULL';
        $student->guideId = !empty($student->guideId) ? $student->guideId : 'NULL';
        $student->reservID = !empty($student->reservID) ? $student->reservID : 'NULL';
        $student->studentReservationID = !empty($student->studentReservationID) ? $student->studentReservationID : 'NULL';
        $student->capID = !empty($student->capID) ? $student->capID : 'NULL';
        $student->domicileId = !empty($student->domicileId) ? "'" . $student->domicileId . "'" : 'NULL';
        $sql = "INSERT INTO studentaccount
        (studentAccount,
        studentPassword,
        parentPassword,
        rollNo,
        regNo,
        deptID,
        batchID,
        studentName,
        studentEmail,
        studentEmail2,
        studentGender,
        studentBirthday,
        studentAddress,
        studentPhone,
        parentPhone,
        religion,
        casteID,
        student_subcaste_id,
        category,
        bloodGroup,
        admissionType,
        quotaID,
        `lateral`,
        NRI,
        studentSurname,
        studentFather,
        studentMother,
        studentJoindate,
        sslc,
        plustwo,
        hosteller,
        feewaiverScheme,
        admissionNo,
        nationality_id,
        previousSchool,
        highestExamPassed,
        prev_institute_dateofpassing,
        prev_institute_regiNo,
        admissionTCNo,
        busroute,
        state_id,
        district_id,
        taluk_id,
        annualIncome,
        aadhaar_no,
        poverty_line,
        campus_type_id,
        secondlangaugeID,
        joiningSemId,
        reservID,
        reservationID,
        phdTopicName,
        phdCurrentStatus,
        guideId,
        ugPercentage,
        parentAddress1,
        parentAddress2,
        parentCity,
        parentZipCode,
        parentCountry,
        parentState,
        applicationNo,
        entranceTest,
        MATScore,
        cap_id,
        domicile_id,
        admission_entry_type,
        my_image_resource_id,
        my_sign_img_resource_id,
        secondLanguage2ID,
        phdExpiry
        )
        VALUES(
        \"$student->studentAccount\",
        md5(\"$student->studentPassword\"),
        md5(\"$student->parentPassword\"),
        \"$student->rollNo\",
        \"$student->regNo\",
        \"$student->deptID\",
        \"$student->batchID\",
        \"$student->studentName\",
        \"$student->studentEmail\",
        \"$student->studentEmail2\",
        \"$student->studentGender\",
$userBirthDay
        \"$student->studentAddress\",
        \"$student->studentPhone\",
        \"$student->parentPhone\",
        $student->religion,
        $student->casteId,
        $student->subCasteId,
        \"$student->category\",
        \"$student->bloodGroup\",
        \"$student->admissionType\",
        $student->quotaId,
        \"$student->lateral\",
        \"$student->nri\",
        \"$student->studentSurname\",
        \"$student->studentFather\",
        \"$student->studentMother\",
        \"$student->studentJoindate\",";
        $sql .= $student->sslc == "" ? "NULL," : "'$student->sslc',";
        $sql .= $student->plustwo == "" ? "NULL," : "'$student->plustwo',";
        $sql .= "\"$student->hosteller\",
        \"$student->feewaiverScheme\",
        \"$student->admissionNo\",
        $student->nationalityId,
        '$student->previousSchool',
        '$student->highestExamPassed',
        '$student->previousPassDate',
        '$student->prevRegNo',
        '$student->admissionTCNo',
        '$student->busroute',
        $student->stateId,
        $student->districtId,
        $student->talukId,
        '$student->annualIncome',
        '$student->aadharNo',
        $student->povertyLineId,
        $student->campusTypeId,
        $student->secondLanguageId,
        $student->joiningSemId,
        $student->reservID,
        $student->studentReservationID,
        '$student->phpTopicName',
        '$student->currentStatus',
        $student->guideId,";
        $sql .= $student->ugPercentage == "" ? "NULL," : "'$student->ugPercentage',";
        $sql .= "'$student->parentAddress1',
        '$student->parentAddress2',
        '$student->parentCity',
        '$student->parentZipCode',
        '$student->parentCountry',
        '$student->parentState',
        '$student->applicationNo',
        '$student->entranceTest',
        '$student->matScore',
        '$student->capID',
        $student->domicileId,
        '$student->admissionEntryType',
        '$student->myImageResourceId',
        '$student->studentSignImgResourceId',
        $student->secondLanguage2Id,
        \"$student->phdExpiry\"
        )";
        try {
            $student->studentId = $this->executeQueryForObject($sql, true);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        try {
            $this->addStudentToV4($student->studentId);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        $this->updateStudentExtraFields($student);
        return $student->studentId;
    }
    /**
     * update student
     * @param Student $student
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     */
    public function updateStudent($student)
    {
        if (!empty($student->customFields))
            $customFields = clone $student->customFields;
        $student = $this->realEscapeObject($student);
        $student->customFields = $customFields;
        unset($customFields);
        $updateexitType = "";
        $faileBatchId = BatchService::getInstance()->getFailedBatchId();
        $failed = 0;
        $student->quotaId = !empty($student->quotaId) ? $student->quotaId : 'NULL';
        $student->religion = !empty($student->religion) ? $student->religion : 'NULL';
        $student->casteId = !empty($student->casteId) ? $student->casteId : 'NULL';
        $student->subCasteId = !empty($student->subCasteId) ? $student->subCasteId : 'NULL';
        $student->povertyLineId = !empty($student->povertyLineId) ? $student->povertyLineId : 'NULL';
        $student->nationalityId = !empty($student->nationalityId) ? $student->nationalityId : 'NULL';
        $student->stateId = !empty($student->stateId) ? $student->stateId : 'NULL';
        $student->districtId = !empty($student->districtId) ? $student->districtId : 'NULL';
        $student->talukId = !empty($student->talukId) ? $student->talukId : 'NULL';
        $student->campusTypeId = !empty($student->campusTypeId) ? $student->campusTypeId : 'NULL';
        $student->reservID = !empty($student->reservID) ? $student->reservID : 'NULL';
        $student->studentReservationID = !empty($student->studentReservationID) ? $student->studentReservationID : 'NULL';
        $student->guideId = !empty($student->guideId) ? $student->guideId : 'NULL';
        $student->secondLanguageId = !empty($student->secondLanguageId) ? $student->secondLanguageId : 'NULL';
        $student->secondLanguage2Id = !empty($student->secondLanguage2Id) ? $student->secondLanguage2Id : 'NULL';
        $student->domicileId = !empty($student->domicileId) ? "'" . $student->domicileId . "'" : 'NULL';
        $sql = "select sa.batchID, ba.semID, sa.joiningSemId,sem.type,sem.orderNo ,sa.student_lock
        from studentaccount sa
        inner join batches ba on sa.batchID = ba.batchID
        left join semesters sem on sem.semID = ba.semID
        where studentID =$student->studentId";
        $batchDetails = $this->executeQueryForObject($sql);
        $batchId = $batchDetails->batchID;
        $semID = $batchDetails->semID;
        $currentJoiningSemId = $batchDetails->joiningSemId;
        $student->joiningSemId = ($student->joiningSemId) ? $student->joiningSemId : $currentJoiningSemId;
        $shouldAttendanceBatchIdBeChanged = true;
        if ($student->batchID == $faileBatchId) {
            if ($batchId != $faileBatchId) {
                $updateexitType = ", exitType = '$student->exitType";
                $sql = "call move_failedstudents(\"$student->studentId\",$semID,0)";
                //echo $sql;
                $this->executeQuery($sql);
                $failed = 1;
                $student_lock = 1;
                $studentPreviousSemesters = $this->getPreviousSemestersOfThisBatch($student->studentId,$batchDetails);
                $previousBatchId = $batchId;
                $sqlForUpdatingFailedStudents = "UPDATE  failed_students SET reason ='" . FailedReason::FAILED . "',hisSemestersInThisbatch = '$studentPreviousSemesters',updated_by = '".$student->updatedBy."',userType = '".$student->updatedByUserType."'  WHERE studentID=$student->studentId AND previousBatch = '$previousBatchId'";
                $this->executeQuery($sqlForUpdatingFailedStudents);
            }
        } else {
            if ($student->isBatchShuffle == "true") {
                $shouldAttendanceBatchIdBeChanged = false;
                $sqlForBatchShuffle = "call move_failedstudents(\"$student->studentId\",$semID,0)";
                $this->executeQuery($sqlForBatchShuffle);
                $studentPreviousSemesters = $this->getPreviousSemestersOfThisBatch($student->studentId,$batchDetails);
                $previousBatchId = $batchId;
                $sqlForUpdatingReason = "UPDATE  failed_students SET reason ='" . FailedReason::BATCH_SHUFFLE . "',hisSemestersInThisbatch = '$studentPreviousSemesters',updated_by = '".$student->updatedBy."',userType = '".$student->updatedByUserType."'  WHERE studentID=$student->studentId AND previousBatch = '$previousBatchId'";
                $this->executeQuery($sqlForUpdatingReason);
            }
            $updateexitType = ", exitType = '' ";
            $sql_update = "UPDATE failed_students SET isFailNow = 0 WHERE studentID = \"$student->studentId\"";
            $this->executeQuery($sql_update);
        }
        if ($batchId != $student->batchID && $failed == 0 && $shouldAttendanceBatchIdBeChanged) {
            /*
            * 09-01-2023
            * Comments : Attendance updation has been removed in V4 code
             $sql = "UPDATE attendance SET batchID=\"" . $student->batchID . "\" WHERE studentID=\"" . $student->studentId . "\" AND batchID=\"" . $batchId . "\"";
             $this->executeQuery($sql);
            */
            $sql = "INSERT INTO admin_who_migarte_batch (adminID, studentID) VALUES(\"" . $student->updatedBy . "\", \"" . $student->studentId . "\")";
            $this->executeQuery($sql);
        }
        $student_lock = $batchDetails->student_lock;
        $userBirthDay = !empty($student->studentBirthday) ? " studentBirthday=\"$student->studentBirthday\"," : 'studentBirthday=null,';
        // $feeReservations = !empty($student->feeReservationId)?"fee_reservations_id=\"$student->feeReservationId\",":"";
        $showCapID = CommonService::getInstance()->getSettings(SettingsConstents::STUDENT_PROFILE_EDIT, SettingsConstents::SHOW_CAP_ID);
        $admissionEntryTypes =json_decode(CommonService::getInstance()->getSettings(SettingsConstents::STUDENT_DETAILS, SettingsConstents::STUDENT_ADMISSION_TYPE));
        $condition = "";
        $condition = $showCapID?",cap_id='$student->capID'":"";
        $condition = $admissionEntryTypes->isAdmissionQuotaEnabled? ",admission_entry_type = '$student->admissionEntryType'":"";
        $sql = "UPDATE studentaccount SET
        studentAccount='$student->studentAccount',
        rollNo='$student->rollNo',
        regNo='$student->regNo',
        deptID='$student->deptID',
        batchID='$student->batchID',
        studentName='$student->studentName',
        studentEmail='$student->studentEmail',
        studentEmail2='$student->studentEmail2',
        studentGender='$student->studentGender',
        studentAddress='$student->studentAddress',
        studentPhone='$student->studentPhone',
        parentPhone='$student->parentPhone',
        religion=$student->religion,
        casteID=$student->casteId,
        student_subcaste_id=$student->subCasteId,
        category='$student->category',
        bloodGroup='$student->bloodGroup',
        quotaID = $student->quotaId,
        admissionType='$student->admissionType',
        `lateral`='$student->lateral',
        NRI='$student->nri',
        studentSurname='$student->studentSurname',
        studentFather='$student->studentFather',
        studentMother='$student->studentMother',
        studentJoindate='$student->studentJoindate',
        phdExpiry='$student->phdExpiry',
        sslc =";
        $sql .= $student->sslc == "" ? "NULL,plustwo=" : "'$student->sslc',plustwo=";
        $sql .= $student->plustwo == "" ? "NULL," : "'$student->plustwo',";
        $sql .="admissionIndexMark = ";
        $sql .= $student->admissionIndexMark == "" ? "NULL," : "'$student->admissionIndexMark',";
        $sql .= "feewaiverScheme='$student->feewaiverScheme',
        student_lock = '$student_lock',
        admissionNo='$student->admissionNo$updateexitType,
        rfId = '$student->rfId',
        $userBirthDay
        nationality_id = $student->nationalityId,
        previousSchool =  '$student->previousSchool',
        highestExamPassed =  '$student->highestExamPassed',
        prev_institute_dateofpassing =  '$student->previousPassDate',
        prev_institute_regiNo = '$student->prevRegNo',
        admissionTCNo = '$student->admissionTCNo',
        ugPercentage = ";
        $sql .= $student->ugPercentage == "" ? "NULL," : "'$student->ugPercentage',";
        $sql .= "busroute = '$student->busroute',
        state_id = $student->stateId,
        district_id = $student->districtId,
        taluk_id = $student->talukId,
        annualIncome = '$student->annualIncome',
        aadhaar_no = '$student->aadharNo',
        student_aadhar_name = '$student->aadharName',
        ssp_id = '$student->sspId',
        poverty_line = $student->povertyLineId,
        campus_type_id = $student->campusTypeId,
        secondlangaugeID = $student->secondLanguageId,
        secondlanguage2ID = $student->secondLanguage2Id,
        joiningSemId = $student->joiningSemId,
        reservID = $student->reservID,
        reservationID = $student->studentReservationID,
        phdTopicName='$student->phpTopicName',
        phdCurrentStatus='$student->currentStatus',
        guideId=$student->guideId,
        parentAddress1='$student->parentAddress1',
        parentAddress2='$student->parentAddress2',
        parentCity='$student->parentCity',
        parentZipCode='$student->parentZipCode',
        parentCountry='$student->parentCountry',
        parentState='$student->parentState',
        applicationNo='$student->applicationNo',
        entranceTest='$student->entranceTest',
        MATScore='$student->matScore',
        domicile_id=$student->domicileId $condition,
        my_image_resource_id='$student->myImageResourceId',
        my_sign_img_resource_id='$student->studentSignImgResourceId',
        uucmsid='$student->uucmsId',
        candidateIsFrom='$student->candidateIsFrom',
        candidateCountryCode='$student->candidateCountryCode',
        village='$student->village',
        abcId='$student->abcId'
        WHERE studentID='$student->studentId'";
        try {
            $secondLangQuery= "SELECT secondlangaugeID , spa.current_batch_id, spa.current_term_id   FROM studentaccount s
                                INNER JOIN student_program_account spa ON spa.student_id = s.studentID
                                where studentID = '$student->studentId'";
            $oldSecondLang = $this->executeQueryForObject($secondLangQuery);
            $this->executeQuery($sql);
            if($oldSecondLang->secondlangaugeID != $student->secondLanguageId){
                if($oldSecondLang->secondlangaugeID){
                    $sql = "UPDATE v4_ams_subject vas
                            INNER JOIN cm_academic_paper_subjects caps ON caps.ams_subject_id = vas.id
                            INNER JOIN `groups` sg ON sg.paperSubjectId = caps.id
                            INNER JOIN groups_relations gr ON gr.child_groups_id = sg.id
                            INNER JOIN group_members gm ON gm.groups_id = sg.id
                            INNER JOIN student_program_account spa ON spa.id = gm.student_id
                            INNER JOIN studentaccount s ON s.studentID = spa.student_id
                            INNER JOIN `groups` g ON g.id = gr.parent_groups_id
                            SET gm.properties = json_set(gm.properties, '$.academicStatus', 'REMOVED')
                            WHERE vas.secondLanguage = '$oldSecondLang->secondlangaugeID' AND g.id = '$oldSecondLang->current_batch_id'
                            AND sg.academic_term_id  = '$oldSecondLang->current_term_id' AND s.studentID = '$student->studentId'";
                    $this->executeQuery($sql);
                }
            }
            if (!empty($student->customFields)) {
                $saveCustomFieldsRequest = new SaveAmsCustomFieldsValueRequest();
                $saveCustomFieldsRequest->entityId = $student->studentId;
                $saveCustomFieldsRequest->entity = AmsCustomFieldsEntities::STUDENT;
                $saveCustomFieldsRequest->fieldValues = $student->customFields;
                $saveCustomFieldsRequest->createdBy = $student->createdBy;
                $saveCustomFieldsRequest->updatedBy = $student->updatedBy;
                AmsCustomFieldsService::getInstance()->saveAmsCustomFieldValue($saveCustomFieldsRequest);
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        try {
            $this->updateStudentToV4($student->studentId);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        $this->updateStudentExtraFields($student);
        return true;
    }
    /**
     * Undocumented function
     *
     * @param [Student] $student
     * @return void
     */
    public function updateStudentExtraFields($student)
    {
        $sql = "INSERT INTO `studentaccount_extras` (`studentID`, `parentPincode`) VALUES ('$student->studentId', '$student->parentPincode') ON DUPLICATE KEY UPDATE parentPincode = '$student->parentPincode'";
        try {
            $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $student->studentId;
    }
    /**
     * Search Student
     * @param SearchStudentRequest $searchStudentRequest
     * @return \com\linways\core\ams\professional\response\SearchStudentResponse
     */
    public function searchStudent($searchStudentRequest, $exact = false)
    {
        $studentDetails = new SearchStudentResponse();
        $sql_cond = "";
        if (!$searchStudentRequest == NULL) {
            $method = $searchStudentRequest->method ? $searchStudentRequest->method : 'AND';
            // $sql_count = "SELECT count(sa.studentID) AS totalRecord  FROM studentaccount sa INNER JOIN department dept ON sa.deptID=dept.deptID INNER JOIN batches bth ON sa.batchID=bth.batchID AND dept.deptID=bth.deptID WHERE sa.batchID is not null AND sa.batchID <> (select batchID from batches where batchName = 'failed') ";
            $sql_count = "SELECT count(sa.studentID) AS totalRecord ";
            $sql = "SELECT sa.*, dept.deptName, bth.batchName, aq.quotaName, bth.semID, sec.secondLangaugeName, sec2.secondLangaugeName as secondLangauge2Name,se.currentAddress1, 
                    se.currentAddress2, se.permanentAddress1, se.permanentAddress2, se.placeofBirth, se.motherTongue, 
                    se.extraAcitivites, se.stateOfBirth, se.countryOfBirth, se.passportNo, se.passportIssuingCountry, 
                    se.passportValidUpto,re.religionName,sc.casteName,ssc.subcaste_name as subCasteName ,se.permanentState, se.permanentCity, se.permanentCountry, 
                    se.permanentZipCode, se.currentState, se.currentCity, se.currentCountry, se.currentZipCode, se.fatherEducation, 
                    se.annualIncome AS fatherIncome, se.parentOccupation, se.fatherEmail, se.motherEducation, se.motherIncome, se.motherOccupation, 
                    se.motherEmail,se.motherPhone, se.residentCategory, se.belongsTo, se.isHandicapped, povlin.poverty_line ,se.handicappedDesc,
                    ds.districtName,ta.talukName,sa.previousSchool,sa.yearOfPassing,sr.reservName AS reservationName,
                    st.state_name AS stateName,se.admisssion_genrl_mngmnt_weight AS admittedCategory,
                    (SELECT CONCAT(SUM(mark),'/',SUM(max_mark)) FROM student_marks_tenth WHERE studentID=sa.studentID) AS tenthMarks,
                    (SELECT CONCAT(SUM(mark),'/',SUM(max_mark)) FROM student_marks_eleventh WHERE studentID=sa.studentID) AS eleventhMarks,
                    (SELECT CONCAT(SUM(mark),'/',SUM(max_mark)) FROM student_marks_twelfth WHERE studentID=sa.studentID) AS twelfthMarks,
                    (SELECT CONCAT(SUM(mark),'/',SUM(max_mark)) FROM student_marks_ug WHERE studentID=sa.studentID) AS ugMarks,
                    (SELECT SUM(mark)/SUM(max_mark)*100 FROM student_marks_tenth WHERE studentID=sa.studentID) AS tenthPercent,
                    (SELECT SUM(mark)/SUM(max_mark)*100 FROM student_marks_eleventh WHERE studentID=sa.studentID) AS eleventhPercent,
                    (SELECT SUM(mark)/SUM(max_mark)*100 FROM student_marks_twelfth WHERE studentID=sa.studentID) AS twelfthPercent,
                    (SELECT SUM(mark)/SUM(max_mark)*100 FROM student_marks_ug WHERE studentID=sa.studentID) AS ugPercent,
                    sa.admissionIndexMark as admissionIndexMark,
                    ad.name as domicile_name,n.nationalityName ";
            if ($searchStudentRequest->item2_val) {
                $sql .= ",GROUP_CONCAT(si." . $searchStudentRequest->item1[2] . ") as " . $searchStudentRequest->item1[2];
            }
            $sql .= "
                FROM studentaccount sa
                    INNER JOIN batches bth ON sa.batchID=bth.batchID
                    INNER JOIN department dept ON bth.deptID=dept.deptID
                    INNER JOIN course_type ct on bth.courseTypeID = ct.courseTypeID
                    LEFT JOIN admission_quotas aq ON sa.quotaID=aq.quotaID
                    LEFT JOIN secondLangauge sec ON sec.secondlangaugeID = sa.secondlangaugeID
                    LEFT JOIN secondLangauge sec2 ON sec2.secondlangaugeID = sa.secondlanguage2ID
                    LEFT JOIN studentaccount_extras se ON se.studentID=sa.studentID
                    LEFT JOIN districts ds ON ds.id=sa.district_id
                    LEFT JOIN taluks ta ON ta.id=sa.taluk_id
                    LEFT JOIN religion re on re.religionID=sa.religion
                    LEFT JOIN student_reservation sr ON sa.reservID = sr.reservID
                    left join admission_domicile ad on ad.id=sa.domicile_id
                    left join nationality n on sa.nationality_id=n.id
                    LEFT JOIN poverty_line povlin on povlin.id = sa.poverty_line ";
            $sql_count .= "
                FROM studentaccount sa
                    INNER JOIN batches bth ON sa.batchID=bth.batchID
                    INNER JOIN department dept ON dept.deptID=bth.deptID
                    INNER JOIN course_type ct on bth.courseTypeID = ct.courseTypeID
                    LEFT JOIN admission_quotas aq ON sa.quotaID=aq.quotaID
                    LEFT JOIN secondLangauge sec ON sec.secondlangaugeID = sa.secondlangaugeID
                    LEFT JOIN secondLangauge sec2 ON sec2.secondlangaugeID = sa.secondlanguage2ID
                    LEFT JOIN studentaccount_extras se ON se.studentID=sa.studentID
                    LEFT JOIN districts ds ON ds.id=sa.district_id
                    LEFT JOIN taluks ta ON ta.id=sa.taluk_id
                    LEFT JOIN religion re on re.religionID=sa.religion
                    LEFT JOIN student_reservation sr ON sa.reservID = sr.reservID ";
            if ($searchStudentRequest->item2_val) {
                if ($searchStudentRequest->item2_val > 0) {
                    $sql .= " left Join " . $searchStudentRequest->item1[0] . " si on si." . $searchStudentRequest->item1[1] . " = sa." . $searchStudentRequest->item2_field;
                    $sql_count .= " left Join " . $searchStudentRequest->item1[0] . " si on si." . $searchStudentRequest->item1[1] . " = sa." . $searchStudentRequest->item2_field;
                }
            }
            $sql .= "
                    LEFT JOIN student_caste sc on sa.casteID=sc.casteID
                    LEFT JOIN student_subcaste ssc on sa.student_subcaste_id=ssc.id
                    LEFT JOIN state st ON st.id=sa.state_id
                    WHERE sa.batchID is not null AND sa.batchID <> (select batchID from batches where batchName = 'failed') ";
            $sql_count .= "
                    LEFT JOIN student_caste sc on sa.casteID=sc.casteID
                    LEFT JOIN student_subcaste ssc on sa.student_subcaste_id=ssc.id
                    LEFT JOIN state st ON st.id=sa.state_id
                    WHERE sa.batchID is not null AND sa.batchID <> (select batchID from batches where batchName = 'failed') ";
            if ($searchStudentRequest->name) {
                $sql_cond .= "$method sa.studentName like '%" . $searchStudentRequest->name . "%' ";
            }
            if ($searchStudentRequest->batchId) {
                $sql_cond .= "$method sa.batchID = '" . $searchStudentRequest->batchId . "' ";
            }
            if (!empty($searchStudentRequest->batchIds)) {
                $sql_cond .= "$method sa.batchID IN ('" . implode("','",$searchStudentRequest->batchIds) . "') ";
            }
            if ($searchStudentRequest->feewaiverScheme) {
                $sql_cond .= "$method sa.feewaiverScheme = $searchStudentRequest->feewaiverScheme ";
            }
            if ($searchStudentRequest->deptId) {
                $sql_cond .= "$method sa.deptID = '" . $searchStudentRequest->deptId . "' ";
            }
            if ($searchStudentRequest->account) {
                $sql_cond .= "$method sa.studentAccount like '%" . $searchStudentRequest->account . "%' ";
            }
            if ($searchStudentRequest->email) {
                $sql_cond .= "$method sa.studentEmail like '%" . $searchStudentRequest->email . "%' ";
            }
            if ($searchStudentRequest->rollNo) {
                if (!$exact) {
                    $sql_cond .= "$method sa.rollNo like '%" . $searchStudentRequest->rollNo . "%' ";
                } else {
                    $sql_cond .= "$method sa.rollNo = '" . $searchStudentRequest->rollNo . "' ";
                }
            }
            if ($searchStudentRequest->admissionNo) {
                if (!$exact) {
                    $sql_cond .= "$method sa.admissionNo like '%" . $searchStudentRequest->admissionNo . "%' ";
                } else {
                    $sql_cond .= "$method sa.admissionNo = '" . $searchStudentRequest->admissionNo . "' ";
                }
            }
            if ($searchStudentRequest->proxyNo) {
                $sql_cond .= "$method sa.proxyNo = '" . $searchStudentRequest->proxyNo . "' ";
            }
            if ($searchStudentRequest->regNo) {
                if (!$exact) {
                    $sql_cond .= "$method sa.regNo like '%" . $searchStudentRequest->regNo . "%' ";
                } else {
                    $sql_cond .= "$method sa.regNo = '" . $searchStudentRequest->regNo . "' ";
                }
            }
            if ($searchStudentRequest->studentIds) {
                $sql_cond .= " $method sa.studentID IN (" . $searchStudentRequest->studentIds . ")";
            }
            if ($searchStudentRequest->seatReservation) {
                $sql_cond .= " $method sr.reservID IN (".$searchStudentRequest->seatReservation.")";
            }
            if ($searchStudentRequest->coursePattern) {
                $sql_cond .= " $method ct.courseTypeID IN (".$searchStudentRequest->coursePattern.")";
            }
            if ($searchStudentRequest->year) {
                $sql_cond .= " $method bth.batchStartYear IN (".$searchStudentRequest->year.")";
            }
            if ($searchStudentRequest->coursePatternId) {
                $sql_cond .= " $method bth.patternID IN (".$searchStudentRequest->coursePatternId.")";
            }
            if ($searchStudentRequest->secondLanguageId) {
                $sql_cond .= " $method sa.secondLangaugeID = $searchStudentRequest->secondLanguageId ";
            }
            if ($searchStudentRequest->applicationNo) {
                if (!$exact) {
                    $sql_cond .= "$method sa.applicationNo like '%" . $searchStudentRequest->applicationNo . "%' ";
                } else {
                    $sql_cond .= "$method sa.applicationNo = '" . $searchStudentRequest->applicationNo . "' ";
                }
            }
            if ($searchStudentRequest->sortBy) {
                $sql_order .= " order by $searchStudentRequest->sortBy $searchStudentRequest->sortOrder ";
            }
            $sql_count .= $sql_cond;
            $sql .= $sql_cond;
            if (!$searchStudentRequest->excludeFaildStudent) {
                // $sql_count2 = "SELECT count(sa.studentID) AS totalRecord FROM studentaccount sa INNER JOIN department dept ON sa.deptID=dept.deptID INNER JOIN batches bth ON dept.deptID=bth.deptID INNER JOIN failed_students fs ON fs.studentID=sa.studentID AND fs.previousBatch=bth.batchID LEFT JOIN admission_quotas aq ON sa.quotaID=aq.quotaID LEFT JOIN secondLangauge sec ON sec.secondlangaugeID = sa.secondlangaugeID LEFT JOIN studentaccount_extras se ON se.studentID=sa.studentID LEFT JOIN districts ds ON ds.id=sa.district_id LEFT JOIN taluks ta ON ta.id=sa.taluk_id  left join religion re on re.religionID=sa.religion left join student_caste sc on sa.casteID=sc.casteID  WHERE sa.batchID is not null " . $sql_cond;
                $sql_count2 = "SELECT count(sa.studentID) AS totalRecord ";
                $sql2 = "SELECT sa.*,
                                 dept.deptName,
                                 bth.batchName,
                                 aq.quotaName,
                                 bth.semID,
                                 sec.secondLangaugeName,
                                sec2.secondLangaugeName as secondLangauge2Name,
                                 se.currentAddress1,
                                 se.currentAddress2,
                                 se.permanentAddress1,
                                 se.permanentAddress2,
                                 se.placeofBirth,
                                 se.motherTongue,
                                 se.extraAcitivites,
                                 se.stateOfBirth,
                                 se.countryOfBirth,
                                 se.passportNo,
                                 se.passportIssuingCountry,
                                 se.passportValidUpto,
                                re.religionName,
                                sc.casteName,
                                ssc.subcaste_name as subCasteName ,
                                se.permanentState,
                                 se.permanentCity,
                                 se.permanentCountry,
                                 se.permanentZipCode,
                                 se.currentState,
                                 se.currentCity,
                                 se.currentCountry,
                                 se.currentZipCode,
                                  se.fatherEducation,
                                  se.father_income AS fatherIncome,
                                  se.parentOccupation,
                                  se.fatherEmail,
                                  se.motherEducation,
                                   se.motherIncome,
                                   se.motherOccupation,
                                   se.motherEmail,
                                  se.motherPhone,
                                   se.residentCategory,
                                   se.belongsTo,
                                   se.isHandicapped,
                                   povlin.poverty_line ,
                                  se.handicappedDesc,
                                  ds.districtName,
                                  ta.talukName,
                                  sa.previousSchool,
                                  sa.yearOfPassing,
                                  sr.reservName AS reservationName,
                                  st.state_name AS stateName,
                                  se.admisssion_genrl_mngmnt_weight AS admittedCategory,
                                  (SELECT CONCAT(SUM(mark),'/',SUM(max_mark)) FROM student_marks_tenth WHERE studentID=sa.studentID) AS tenthMarks,
                                  (SELECT CONCAT(SUM(mark),'/',SUM(max_mark)) FROM student_marks_eleventh WHERE studentID=sa.studentID) AS eleventhMarks,
                                  (SELECT CONCAT(SUM(mark),'/',SUM(max_mark)) FROM student_marks_twelfth WHERE studentID=sa.studentID) AS twelfthMarks,
                                  (SELECT CONCAT(SUM(mark),'/',SUM(max_mark)) FROM student_marks_ug WHERE studentID=sa.studentID) AS ugMarks,  
                                  sa.admissionIndexMark as admissionIndexMark, 
                                  (SELECT SUM(mark)/SUM(max_mark)*100 FROM student_marks_tenth WHERE studentID=sa.studentID) AS tenthPercent,
                                  (SELECT SUM(mark)/SUM(max_mark)*100 FROM student_marks_eleventh WHERE studentID=sa.studentID) AS eleventhPercent,
                                  (SELECT SUM(mark)/SUM(max_mark)*100 FROM student_marks_twelfth WHERE studentID=sa.studentID) AS twelfthPercent,
                                  (SELECT SUM(mark)/SUM(max_mark)*100 FROM student_marks_ug WHERE studentID=sa.studentID) AS ugPercent,
                                  ad.name as domicile_name,n.nationalityName ";
                if ($searchStudentRequest->item2_val) {
                    $sql2 .= ",GROUP_CONCAT(si." . $searchStudentRequest->item1[2] . ") as " . $searchStudentRequest->item1[2];
                }
                $sql2 .= " FROM studentaccount sa
                    INNER JOIN failed_students fs ON fs.studentID=sa.studentID
                    INNER JOIN batches bth ON fs.previousBatch=bth.batchID
                    INNER JOIN department dept ON bth.deptID=dept.deptID
                    INNER JOIN course_type ct on bth.courseTypeID = ct.courseTypeID
                    LEFT JOIN admission_quotas aq ON sa.quotaID=aq.quotaID
                    LEFT JOIN secondLangauge sec ON sec.secondlangaugeID = sa.secondlangaugeID
                    LEFT JOIN secondLangauge sec2 ON sec2.secondlangaugeID = sa.secondlanguage2ID
                    LEFT JOIN student_reservation sr ON sa.reservID = sr.reservID
                    LEFT JOIN admission_domicile ad on ad.id=sa.domicile_id
                    LEFT JOIN nationality n on sa.nationality_id=n.id
                    LEFT JOIN poverty_line povlin on povlin.id = sa.poverty_line";
                $sql_count2 .= "
                    FROM studentaccount sa
                    INNER JOIN failed_students fs ON fs.studentID=sa.studentID
                    INNER JOIN batches bth ON fs.previousBatch=bth.batchID
                    INNER JOIN department dept ON bth.deptID=dept.deptID
                    INNER JOIN course_type ct on bth.courseTypeID = ct.courseTypeID
                    LEFT JOIN admission_quotas aq ON sa.quotaID=aq.quotaID
                    LEFT JOIN secondLangauge sec ON sec.secondlangaugeID = sa.secondlangaugeID
                    LEFT JOIN secondLangauge sec2 ON sec2.secondlangaugeID = sa.secondlanguage2ID
                    LEFT JOIN student_reservation sr ON sa.reservID = sr.reservID";
                if ($searchStudentRequest->item2_val) {
                    if ($searchStudentRequest->item2_val > 0) {
                        $sql2 .= " left Join " . $searchStudentRequest->item1[0] . " si on si." . $searchStudentRequest->item1[1] . " = sa." . $searchStudentRequest->item2_field;
                        $sql_count2 .= " left Join " . $searchStudentRequest->item1[0] . " si on si." . $searchStudentRequest->item1[1] . " = sa." . $searchStudentRequest->item2_field;
                    }
                }
                $sql2 .= "
                    LEFT JOIN studentaccount_extras se ON se.studentID=sa.studentID
                    LEFT JOIN districts ds ON ds.id=sa.district_id
                    LEFT JOIN taluks ta ON ta.id=sa.taluk_id
                    left join religion re on re.religionID=sa.religion
                    left join student_caste sc on sa.casteID=sc.casteID
                    LEFT JOIN student_subcaste ssc on sa.student_subcaste_id=ssc.id
                    LEFT JOIN state st ON st.id=sa.state_id
                    WHERE sa.batchID is not null AND fs.isFailNow='1'" . $sql_cond . "GROUP BY sa.studentID";
                $sql_count2 .= "
                    LEFT JOIN studentaccount_extras se ON se.studentID=sa.studentID
                    LEFT JOIN districts ds ON ds.id=sa.district_id
                    LEFT JOIN taluks ta ON ta.id=sa.taluk_id
                    left join religion re on re.religionID=sa.religion
                    left join student_caste sc on sa.casteID=sc.casteID
                    LEFT JOIN student_subcaste ssc on sa.student_subcaste_id=ssc.id
                    LEFT JOIN state st ON st.id=sa.state_id
                    WHERE sa.batchID is not null AND fs.isFailNow='1'" . $sql_cond . "GROUP BY sa.studentID";
                $sql .= "GROUP BY sa.studentID UNION " . $sql2;
                // $sql_count .= " UNION " . $sql_count2;
                $sql_count .= "GROUP BY sa.studentID UNION " . $sql_count2;
            }
            $sql .= $sql_order;
            $studentCount = $this->executeQueryForObject($sql_count)->totalRecord;
            $studentDetails->totalRecords = $studentCount;
            if ($searchStudentRequest->export) {
                $searchStudentRequest->endIndex = $studentDetails->totalRecords;
            }
            $sql .= " LIMIT $searchStudentRequest->startIndex,$searchStudentRequest->endIndex";
            $studentDetails->students = $this->executeQueryForList($sql);
        }
        return $studentDetails;
    }
    /**
     * get all student
     * @param SearchStudentRequest $studentRequest
     * @return array|object|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author gadheyan
     */
    public function getAllStudents($studentRequest)
    {
        $studentDetails = [];
        if ($studentRequest) {
            $isCurrentSem = true;
            if (!empty($studentRequest->semId) && !empty($studentRequest->batchId)) {
                $isCurrentSem = SemesterService::getInstance()->isCurrentSemester($studentRequest->batchId, $studentRequest->semId);
            }
            if(is_array($studentRequest->deptId) && count($studentRequest->deptId)) {
                $studentRequest->deptId = implode(",",$studentRequest->deptId);
            }
            if ($isCurrentSem) {
                if (!$studentRequest->deptId && !$studentRequest->batchId && !$studentRequest->subbatchId) {
                    $sqlStudents = "SELECT studentID as id, studentName as name FROM studentaccount sa inner join batches ba on  ba.batchID = sa.batchID inner join semesters sem on sem.semID = ba.semID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID WHERE  joinedSem.orderNo <= sem.orderNo and student_lock=0";
                } else if ($studentRequest->deptId && !$studentRequest->batchId && !$studentRequest->subbatchId) {
                    $sqlStudents = "SELECT studentID as id, studentName as name FROM studentaccount sa inner join batches ba on  ba.batchID = sa.batchID inner join semesters sem on sem.semID = ba.semID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID WHERE  joinedSem.orderNo <= sem.orderNo and student_lock=0 AND sa.deptID  IN ($studentRequest->deptId)";
                } else if ($studentRequest->deptId && $studentRequest->batchId && !$studentRequest->subbatchId) {
                    $sqlStudents = "SELECT studentID as id, studentName as name FROM studentaccount sa inner join batches ba on  ba.batchID = sa.batchID inner join semesters sem on sem.semID = ba.semID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID WHERE  joinedSem.orderNo <= sem.orderNo and student_lock=0 AND sa.batchID=$studentRequest->batchId AND sa.deptID  IN ($studentRequest->deptId)";
                } else if (!$studentRequest->deptId && $studentRequest->batchId && !$studentRequest->subbatchId) {
                    $sqlStudents = "SELECT studentID as id, studentName as name FROM studentaccount sa inner join batches ba on  ba.batchID = sa.batchID inner join semesters sem on sem.semID = ba.semID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID WHERE  joinedSem.orderNo <= sem.orderNo and student_lock=0 AND sa.batchID=$studentRequest->batchId";
                } else if ($studentRequest->deptId && $studentRequest->batchId && $studentRequest->subbatchId) {
                    $sqlStudents = "SELECT sa.studentID as id, sa.studentName as name FROM studentaccount sa INNER JOIN subbatches sub ON sub.batchID =sa.batchID INNER JOIN subbatch_student ss ON sub.subbatchID=ss.subbatchID AND sa.studentID =ss.studentID inner join batches ba on  ba.batchID = sa.batchID inner join semesters sem on sem.semID = ba.semID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID WHERE  joinedSem.orderNo <= sem.orderNo and sub.subbatchID=$studentRequest->subbatchId";
                }
            } else {
                $semDetails = SemesterService::getInstance()->getSemDetailsBySemId($studentRequest->semId);
                if (!$studentRequest->deptId && !$studentRequest->batchId && !$studentRequest->subbatchId) {
                    $sqlStudents = "SELECT sa.studentID as id, studentName as name, joinedSem.orderNo, fsem.orderNo FROM studentaccount sa left join failed_students fs on sa.studentID = fs.studentID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID left join semesters fsem on fsem.semID = fs.failedInSemester  WHERE  joinedSem.orderNo <= $semDetails->orderNo and (fsem.orderNo > $semDetails->orderNo or fsem.orderNo is null) and student_lock=0";
                } else if ($studentRequest->deptId && !$studentRequest->batchId && !$studentRequest->subbatchId) {
                    $sqlStudents = "SELECT sa.studentID as id, studentName as name, joinedSem.orderNo, fsem.orderNo FROM studentaccount sa left join failed_students fs on sa.studentID = fs.studentID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID left join semesters fsem on fsem.semID = fs.failedInSemester  WHERE  joinedSem.orderNo <= $semDetails->orderNo and (fsem.orderNo > $semDetails->orderNo or fsem.orderNo is null) and student_lock=0 AND sa.deptID    IN ($studentRequest->deptId)";
                } else if ($studentRequest->deptId && $studentRequest->batchId && !$studentRequest->subbatchId) {
                    $sqlStudents = "SELECT sa.studentID as id, studentName as name, joinedSem.orderNo, fsem.orderNo FROM studentaccount sa left join failed_students fs on sa.studentID = fs.studentID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID left join semesters fsem on fsem.semID = fs.failedInSemester  WHERE  joinedSem.orderNo <= $semDetails->orderNo and (fsem.orderNo > $semDetails->orderNo or fsem.orderNo is null) and student_lock=0 AND (sa.batchID=$studentRequest->batchId or previousBatch = $studentRequest->batchId) AND sa.deptID  IN ($studentRequest->deptId)";
                } else if (!$studentRequest->deptId && $studentRequest->batchId && !$studentRequest->subbatchId) {
                    $sqlStudents = "SELECT sa.studentID as id, studentName as name, joinedSem.orderNo, fsem.orderNo FROM studentaccount sa left join failed_students fs on sa.studentID = fs.studentID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID left join semesters fsem on fsem.semID = fs.failedInSemester  WHERE  joinedSem.orderNo <= $semDetails->orderNo and (fsem.orderNo > $semDetails->orderNo or fsem.orderNo is null) and student_lock=0 AND (sa.batchID=$studentRequest->batchId or previousBatch = $studentRequest->batchId)";
                } else if ($studentRequest->deptId && $studentRequest->batchId && $studentRequest->subbatchId) {
                    $sqlStudents = "SELECT sa.studentID as id, sa.studentName as name FROM studentaccount sa INNER JOIN subbatches sub ON sub.batchID =sa.batchID INNER JOIN subbatch_student ss ON sub.subbatchID=ss.subbatchID AND sa.studentID =ss.studentID left join failed_students fs on sa.studentID = fs.studentID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID left join semesters fsem on fsem.semID = fs.failedInSemester  WHERE  joinedSem.orderNo <= $semDetails->orderNo and (fsem.orderNo > $semDetails->orderNo or fsem.orderNo is null) and sub.subbatchID = $studentRequest->subbatchId";
                }
            }
            if (!empty($studentRequest->sortBy)) {
                $sqlStudents .= " ORDER BY $studentRequest->sortBy $studentRequest->sortOrder";
            }
            try {
                $studentDetails = $this->executeQueryForList($sqlStudents);
            } catch (\Exception $e) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        }
        return $studentDetails;
    }
    /**
     * get all student for api with total count
     * @param GetStudentsRequest $request
     * @return object|array|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author gadheyan
     */
    public function getAllStudentsForApi(GetStudentsRequest $request)
    {
        $responseList = [];
        $request = $this->realEscapeObject($request);
        $columnsForData = "sa.studentID AS id,
                    sa.studentName AS name,
                    sa.admissionNo AS admissionNumber,sa.regNo as RegisterNo,
                    sa.studentBirthday as DOB, pc.patterncourseName as Course";
        $columnsForCount = "count(*) as count";
        $tables = "studentaccount sa
                    LEFT JOIN admission_quotas aq
                    ON sa.quotaID = aq.quotaID
                    LEFT JOIN religion r
                    ON sa.religion = r.religionID
                    LEFT JOIN student_caste c
                    ON sa.casteID = c.casteID
                    LEFT JOIN batches bt
                    ON bt.batchID = sa.batchID
                    LEFT JOIN pattern_deptcourses pc
                    ON pc.patterncourseID = bt.patterncourseID ";
        $filter = "1=1 ";
        if ($request) {
            if ($request->id) {
                $filter .= "AND sa.studentID = '$request->id'";
            }
            if ($request->deptId) {
                $filter .= "AND sa.deptID = '$request->deptId'";
            }
            if ($request->batchId) {
                $filter .= "AND sa.batchID = '$request->batchId'";
            }
            if ($request->studentLock) {
                $filter .= "AND sa.student_lock = '$request->studentLock'";
            }
            if ($request->username) {
                $filter .= "AND sa.studentAccount = '$request->username'";
            }
            if ($request->name) {
                $filter .= "AND sa.studentName like '%$request->name%'";
            }
            if ($request->email) {
                $filter .= "AND sa.studentEmail = '$request->email'";
            }
            if ($request->gender) {
                $filter .= "AND sa.studentGender = '$request->gender'";
            }
            if ($request->phoneNo) {
                $filter .= "AND sa.studentPhone = '$request->phoneNo'";
            }
            if ($request->category) {
                $filter .= "AND sa.category = '$request->category'";
            }
            if ($request->bloodGroup) {
                $filter .= "AND sa.bloodGroup = '$request->bloodGroup'";
            }
            if ($request->admissionNo) {
                $filter .= "AND sa.admissionNo = '$request->admissionNo'";
            }
            if ($request->regNo) {
                $filter .= "AND sa.regNo = '$request->regNo'";
            }
            if ($request->admissionQuota) {
                $filter .= "AND aq.quotaName = '$request->admissionQuota'";
            }
            if ($request->religion) {
                $filter .= "AND r.religionName = '$request->religion'";
            }
            if ($request->caste) {
                $filter .= "AND c.casteName = '$request->caste'";
            }
        }
        if ($request->sortBy) {
            $orderBy = " ORDER BY $request->sortBy $request->sortOrder";
        }
        $pagination = " LIMIT " .
            ((int)$request->_page - 1) * (int)$request->_pageSize . "," .
            (int)$request->_pageSize;
        try {
            $sqlForData = "SELECT " .
                $columnsForData .
                " FROM " .
                $tables .
                " WHERE " .
                $filter . $orderBy . $pagination;
            $sqlForCount = "SELECT " .
                $columnsForCount .
                " FROM " .
                $tables .
                " WHERE "
                . $filter;
            $response = [];
            $totalRecordsCount = $this->executeQueryForObject($sqlForCount)->count;
            $studentRecords = $this->executeQueryForList($sqlForData);
            $response['_meta'] = CommonUtil::prepareApiPaginationInfo($totalRecordsCount,
                $request->_page,
                $request->_pageSize,
                $studentRecords);
            $response['data'] = $studentRecords;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $response;
    }
    /**
     *
     * @param array $studentId
     * @return $studentDetails
     * @throws ProfessionalException
     */
    public function getStudentDetailsByIds($studentId)
    {
        $studentDetails = NULL;
        if(is_array($studentId)){
            $studentIds = implode(",",$studentId);
            $studentIds = rtrim($studentIds, ', ');
        }
        else{
            $studentIds = $studentId;
        }
        $sql = "SELECT sa.studentID as id,
                            sa.studentName as name,
                            sa.myImage,
                            bth.batchID,
                            bth.semID,
                            dept.deptID,
                            dept.deptName,
                            bth.batchName,
                            sa.regNo,
                            sa.studentFather,
                            sa.studentAddress,
                            sa.studentPhone,
                            sa.studentEmail,
                            sa.studentSignImage,
                        sa.parentPhone,
                        sa.studentMother,
                        sa.admissionNo,
                        sa.rollNo,
                            bth.courseTypeID
                        FROM studentaccount sa
                        INNER JOIN batches bth ON sa.batchID=bth.batchID
                        INNER JOIN department dept ON dept.deptID=bth.deptID
                        WHERE ";
        $sql .= " sa.studentID IN (" .$studentIds. ")";
        try {
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     *
     * @param int $studentId
     * @return $studentDetails
     * @throws ProfessionalException
     */
    public function getStudentDetailsById($studentId)
    {
        $studentDetails = NULL;
        $studentId = $this->realEscapeString($studentId);
        
        $sql="SELECT
        sa.studentID as id,
        sa.studentName as name,
        sa.studentAccount,
        sa.studentPassword,
        sa.regNo,
        sa.bloodGroup,
        sa.rollNo,
        sa.admissionNo,
        sa.applicationNo,
        sa.studentEmail,
        sa.studentPhone,
        sa.parentPhone,
        sa.tcIssued,
        sa.studentAddress,
        sa.studentEmail,
        sa.studentPhone,
        sa.parentAddress1,
        sa.parentAddress2,
        sa.parentCity,
        sa.parentZipCode,
        sa.parentCountry,
        sa.parentState,
        sa.studentJoindate,
        sa.exitType,
        sa.studentSignImage,
        sa.quotaID as quotaId,
        sa.student_lock,
        sa.nationality_id as nationalityId,
        sa.previousSchool as previousSchool,
        sa.highestExamPassed as highestExamPassed,
        sa.prev_institute_dateofpassing as previousPassDate,
        sa.prev_institute_regiNo as prevRegNo,
        sa.admissionTCNo as admissionTCNo,
        sa.busroute as busroute,
        sa.state_id as stateId,
        sa.district_id as districtId,
        sa.taluk_id as talukId,
        sa.annualIncome as annualIncome,
        sa.aadhaar_no as aadharNo,
        sa.poverty_line as povertyLineId,
        sa.campus_type_id as campusTypeId,
        sa.secondlangaugeID as secondLanguageId,
        sa.joiningSemId as joiningSemId,
        sa.reservID as reservID,
        sa.reservationID as studentReservationID,
        sa.phdTopicName as phpTopicName,
        sa.phdCurrentStatus as currentStatus,
        sa.guideId as guideId,
        sa.religion AS religion,
        sa.community,
        sa.category,
        sa.studentBirthday,
        sa.studentFather,
        sa.sslc,
        sa.plustwo,
        sa.parentOccupation,
        sa.studentGender,
        sa.myImage,
        sa.studentSignImage,
        sa.plustwo,
        sa.studentFather,
        sa.studentMother,
        sa.uucmsid,
        sa.candidateCountryCode,
        sa.candidateIsFrom,
        sa.phdExpiry,
        sa.placement_required as placement_required,
        sa.is_placed as is_placed,
        bth.batchName,
        bth.batchID,
        bth.patternID as courseTypeId,
        bth.courseTypeID,
        bth.batchStartYear as startYear,
        bth.batchEndYear as endYear,
        bth.final_semester as finalSem,
        bth.isPassOut,
        dept.deptName,
        dept.departmentDesc,
        dept.deptID,
        bct.type_name as typeName,
        bct.type_code AS coursePatternName,
        bct.is_pg AS isPG,
        sem.semID,
        sem.semName,
        sem.year,
        sem.orderNo,
        sem.type,
        sl.secondLangaugeName,
        pdc.patterncourseName,
        pdc.patterncourseCode,
        pdc.patterncourseID,
        pdc.patternAbbreviation,
        pdc.extraSettings,
        sc.subsiderycoursename,
        se.entranceRank,
        se.parentOccupation as fatherOccupation,
        se.motherOccupation,
        se.commuhouse,
        se.commupin,
        se.currentAddress1,
        se.currentAddress2,
        se.permahouse,
        se.permapin,
        se.permanentAddress1,
        se.permanentAddress2,
        se.currentCity,
        se.permanentCity,
        se.permanentZipCode,
        se.currentZipCode,
        aq.quotaName,
        sr.reservName as reservationName,
        re.religionName,
        re.religionID,
        state.state_name as stateName,
        cp.patternName,
        cp.patternDesc,
        caste.casteID,
        caste.casteName,
        rs.reservationID,
        rs.reservationName AS studentReservation,
        nat.nationalityName,
        nat.id as nationalityID,
        s.state_name AS state,
        s.id as stateID,
        spa.current_program_id,
        p.id as programId,
        p.stream_id,
        p.properties,
        p.name AS programName,
        vs.name AS schoolName,
        rt.remarks,spbl.remark_desc AS remarkDesc
        FROM studentaccount sa
        INNER JOIN batches bth ON sa.batchID = bth.batchID
        INNER JOIN department dept ON bth.deptID = dept.deptID
        LEFT JOIN batch_course_type bct ON bth.patternID = bct.id
        LEFT JOIN semesters sem ON sem.semID = bth.semID
        LEFT JOIN secondLangauge sl ON sl.secondlangaugeID = sa.secondlangaugeID
        LEFT JOIN pattern_deptcourses pdc ON bth.patterncourseID = pdc.patterncourseID
        LEFT JOIN subsiderycourse sc ON pdc.patterncourseID = sc.pattern_deptcourses_id
        LEFT JOIN studentaccount_extras se ON se.studentID = sa.studentID
        LEFT JOIN admission_quotas aq ON aq.quotaID = sa.quotaID
        LEFT JOIN student_reservation sr ON sr.reservID = sa.reservID
        LEFT JOIN religion re ON re.religionID=sa.religion
        LEFT JOIN `state` ON `state`.id = sa.state_id
        LEFT JOIN course_pattern cp on cp.patternID = bth.patternID
        LEFT JOIN student_caste caste ON caste.casteID=sa.casteID
        LEFT JOIN reservation_students rs ON rs.reservationID=sa.reservationID
        LEFT JOIN nationality nat ON nat.id = sa.nationality_id
        LEFT JOIN `state` s ON sa.state_id=s.id
        LEFT JOIN student_program_account spa on spa.student_id = sa.studentID
        LEFT JOIN program p on p.id = spa.current_program_id
        LEFT JOIN department batchDepartment ON bth.deptID=batchDepartment.deptID
        LEFT JOIN v4_school vs ON vs.id=batchDepartment.school_id
        LEFT JOIN student_program_batch_log spbl ON spbl.program_student_id = spa.id AND spbl.batch_group_id = spa.current_batch_id AND spbl.term_id=spa.current_term_id
        LEFT JOIN remarks_table rt ON spbl.remark_id=rt.id
        WHERE sa.studentID = $studentId";
        try {
            $studentDetails = $this->executeQueryForObject($sql);
        }
        catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
     /**
     *  Get Student Details For Bulk IDCard Printing
     * @param int $studentId
     * @return $studentDetails
     * @throws ProfessionalException
     */
    public function getStudentDetailsByIdForMultiIDCard($studentId)
    {
        $studentDetails = NULL;
        $studentId = $this->realEscapeString($studentId);
        $sql="SELECT
        sa.studentID as id,
        sa.studentName as name,
        sa.studentAccount,
        sa.studentPassword,
        sa.regNo,
        sa.bloodGroup,
        sa.rollNo,
        sa.admissionNo,
        sa.applicationNo,
        sa.studentEmail,
        sa.studentPhone,
        sa.parentPhone,
        sa.tcIssued,
        sa.studentAddress,
        sa.studentEmail,
        sa.studentPhone,
        sa.parentAddress1,
        sa.parentAddress2,
        sa.parentCity,
        sa.parentZipCode,
        sa.parentCountry,
        sa.parentState,
        sa.studentJoindate,
        sa.exitType,
        sa.studentSignImage,
        sa.quotaID as quotaId,
        sa.student_lock,
        sa.nationality_id as nationalityId,
        sa.previousSchool as previousSchool,
        sa.highestExamPassed as highestExamPassed,
        sa.prev_institute_dateofpassing as previousPassDate,
        sa.prev_institute_regiNo as prevRegNo,
        sa.admissionTCNo as admissionTCNo,
        sa.busroute as busroute,
        sa.state_id as stateId,
        sa.district_id as districtId,
        sa.taluk_id as talukId,
        sa.annualIncome as annualIncome,
        sa.aadhaar_no as aadharNo,
        sa.poverty_line as povertyLineId,
        sa.campus_type_id as campusTypeId,
        sa.secondlangaugeID as secondLanguageId,
        sa.joiningSemId as joiningSemId,
        sa.reservID as reservID,
        sa.reservationID as studentReservationID,
        sa.phdTopicName as phpTopicName,
        sa.phdCurrentStatus as currentStatus,
        sa.guideId as guideId,
        sa.religion AS religion,
        sa.community,
        sa.category,
        sa.studentBirthday,
        sa.studentFather,
        sa.sslc,
        sa.plustwo,
        sa.parentOccupation,
        sa.studentGender,
        sa.myImage,
        sa.studentSignImage,
        sa.plustwo,
        sa.studentFather,
        sa.studentMother,
        sa.uucmsid,
        sa.candidateCountryCode,
        sa.candidateIsFrom,
        sa.phdExpiry,
        bth.batchName,
        bth.batchID,
        bth.patternID as courseTypeId,
        bth.courseTypeID,
        bth.batchStartYear as startYear,
        bth.batchEndYear as endYear,
        bth.final_semester as finalSem,
        bth.isPassOut,
        dept.deptName,
        dept.departmentDesc,
        dept.deptID,
        bct.type_name as typeName,
        bct.type_code AS coursePatternName,
        bct.is_pg AS isPG,
        sem.semID,
        sem.semName,
        sem.year,
        sem.orderNo,
        sem.type,
        sl.secondLangaugeName,
        pdc.patterncourseName,
        pdc.patterncourseCode,
        pdc.patterncourseID,
        pdc.patternAbbreviation,
        pdc.extraSettings,
        sc.subsiderycoursename,
        se.entranceRank,
        se.parentOccupation as fatherOccupation,
        se.motherOccupation,
        se.commuhouse,
        se.commupin,
        se.currentAddress1,
        se.currentAddress2,
        se.permahouse,
        se.permapin,
        se.permanentAddress1,
        se.permanentAddress2,
        se.currentCity,
        se.permanentCity,
        se.permanentZipCode,
        se.currentZipCode,
        aq.quotaName,
        sr.reservName as reservationName,
        re.religionName,
        state.state_name as stateName,
        cp.patternName,
        cp.patternDesc,
        caste.casteID,
        caste.casteName,
        rs.reservationID,
        rs.reservationName AS studentReservation,
        nat.nationalityName,
        s.state_name AS state,
        spa.current_program_id,
        p.id as programId,
        p.stream_id,
        p.properties
        FROM studentaccount sa
        INNER JOIN batches bth ON sa.batchID = bth.batchID
        INNER JOIN department dept ON bth.deptID = dept.deptID
        LEFT JOIN batch_course_type bct ON bth.patternID = bct.id
        LEFT JOIN semesters sem ON sem.semID = bth.semID
        LEFT JOIN secondLangauge sl ON sl.secondlangaugeID = sa.secondlangaugeID
        LEFT JOIN pattern_deptcourses pdc ON bth.patterncourseID = pdc.patterncourseID
        LEFT JOIN subsiderycourse sc ON pdc.patterncourseID = sc.pattern_deptcourses_id
        LEFT JOIN studentaccount_extras se ON se.studentID = sa.studentID
        LEFT JOIN admission_quotas aq ON aq.quotaID = sa.quotaID
        LEFT JOIN student_reservation sr ON sr.reservID = sa.reservID
        LEFT JOIN religion re ON re.religionID=sa.religion
        LEFT JOIN `state` ON `state`.id = sa.state_id
        LEFT JOIN course_pattern cp on cp.patternID = bth.patternID
        LEFT JOIN student_caste caste ON caste.casteID=sa.casteID
        LEFT JOIN reservation_students rs ON rs.reservationID=sa.reservationID
        LEFT JOIN nationality nat ON nat.id = sa.nationality_id
        LEFT JOIN `state` s ON sa.state_id=s.id
        LEFT JOIN student_program_account spa on spa.student_id = sa.studentID
        LEFT JOIN program p on p.id = spa.current_program_id
        WHERE sa.studentID IN( $studentId)";
        try {
            $studentDetails = $this->executeQueryForObject($sql);
        }
        catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     *
     * @param int $studentId
     * @return $studentDetails
     * @throws ProfessionalException
     */
    public function getStudentDetailsByIdConcessionNumbers($studentId)
    {
        $studentDetails = NULL;
        $studentId = $this->realEscapeString($studentId);
        $sql = "SELECT sa.studentID as id,
            sa.studentName as name,
            sa.studentAccount,
            sa.studentPassword,
            sa.regNo,
            sa.rollNo,
            sa.admissionNo,
            sa.applicationNo,
            sa.studentEmail,
            sa.studentPhone,
            sa.parentPhone,
            sa.tcIssued,
            dept.deptName,
            bth.batchName,
            dept.deptID,
            bth.batchID,
            bth.patternID as courseTypeId,
            bth.courseTypeID,
            bct.type_name as typeName,
            bth.batchStartYear as startYear,
            bth.batchEndYear as endYear,
            bth.final_semester as finalSem,
            dept.departmentDesc,
            sa.tcIssued,
            sa.studentAddress,
            sa.studentEmail,
            sa.studentPhone,
            sem.semID,
            sem.semName,
            sem.year,
            sem.orderNo,
            sem.type,
            sa.parentAddress1,
            sa.parentAddress2,
            sa.parentCity,
            sa.parentZipCode,
            sa.parentCountry,
            sa.parentState,
            sa.studentJoindate,
            sa.exitType,
            sa.studentSignImage,
            sa.quotaID as quotaId,
            sa.student_lock,
            sa.nationality_id as nationalityId,
            sa.previousSchool as previousSchool,
            sa.highestExamPassed as highestExamPassed,
            sa.prev_institute_dateofpassing as previousPassDate,
            sa.prev_institute_regiNo as prevRegNo,
            sa.admissionTCNo as admissionTCNo,
            sa.busroute as busroute,
            sa.state_id as stateId,
            sa.district_id as districtId,
            sa.taluk_id as talukId,
            sa.annualIncome as annualIncome,
            sa.aadhaar_no as aadharNo,
            sa.poverty_line as povertyLineId,
            sa.campus_type_id as campusTypeId,
            sa.secondlangaugeID as secondLanguageId,
            sa.joiningSemId as joiningSemId,
            sa.reservID as reservID,
            sa.reservationID as studentReservationID,
            sa.phdTopicName as phpTopicName,
            sa.phdCurrentStatus as currentStatus,
            sa.guideId as guideId,
            sl.secondLangaugeName,
            pdc.patterncourseName,
            pdc.patterncourseCode,
            pdc.patterncourseID,
            pdc.patternAbbreviation AS patternAbbreviation,
            sa.religion AS religion,
            sa.community,
            sa.category,
            sa.studentBirthday,
            sa.studentFather,
            sa.sslc,
            sa.plustwo,
            sa.parentOccupation,
            sa.studentGender,
            sa.myImage,
            sa.studentSignImage,
            sc.subsiderycoursename AS subsideryCourseName,
            se.entranceRank,
            sa.plustwo,
            sa.studentFather,
            sa.studentMother,
            se.parentOccupation as fatherOccupation,
            se.motherOccupation,
            aq.quotaName,
            se.commuhouse,
            se.commupin,
            se.currentAddress1,
            se.currentAddress2,
            se.permahouse,
            se.permapin,
            se.permanentAddress1,
            se.permanentAddress2,
            se.currentCity,
            se.permanentCity,
            se.permanentZipCode,
            se.currentZipCode,
            bct.type_code AS coursePatternName,
            bct.is_pg AS isPG,sr.reservName as reservationName,
            sa.cap_id,
            sa.bloodGroup,
            re.religionName,
            CONCAT_WS(' ',se.commuhouse,se.currentAddress1,se.currentAddress2,se.currentCity,se.currentCountry,se.currentState,se.currentZipCode) as additional_info_currentAddress,
            CONCAT_WS(' ',se.permaHouse,se.permanentAddress1,se.permanentAddress2,se.permanentCity,se.permanentCountry,se.permanentState,se.permanentZipCode) as additional_info_permanentAddress,
            state.state_name as stateName,
            cp.patternName,cp.patternDesc,
            sa.admission_entry_type,
            caste.casteID,
            caste.casteName,
            rs.reservationID,
            rs.reservationName AS studentReservation,
            nat.nationalityName,
            s.state_name AS state,
            pdc.extraSettings,
            concess.concessionId,
            sa.busroute,
            sa.phdExpiry
            FROM studentaccount sa
            INNER JOIN department dept ON sa.deptID=dept.deptID INNER JOIN batches bth ON sa.batchID=bth.batchID LEFT JOIN batch_course_type bct ON bth.patternID = bct.id LEFT JOIN semesters sem ON sem.semID = bth.semID LEFT JOIN secondLangauge sl ON sl.secondlangaugeID = sa.secondlangaugeID LEFT JOIN pattern_deptcourses pdc ON bth.patterncourseID = pdc.patterncourseID LEFT JOIN subsiderycourse sc ON pdc.patterncourseID = sc.pattern_deptcourses_id LEFT JOIN studentaccount_extras se ON se.studentID = sa.studentID LEFT JOIN admission_quotas aq ON aq.quotaID = sa.quotaID LEFT JOIN student_reservation sr ON sr.reservID = sa.reservID LEFT JOIN religion re ON re.religionID=sa.religion LEFT JOIN state ON state.id = sa.state_id
            LEFT JOIN course_pattern cp on cp.patternID = bth.patternID
            LEFT JOIN student_caste caste ON caste.casteID=sa.casteID
            LEFT JOIN reservation_students rs ON rs.reservationID=sa.reservationID
            LEFT JOIN nationality nat ON nat.id = sa.nationality_id
            LEFT JOIN state s ON sa.state_id=s.id
            LEFT JOIN StudentConcessions concess on concess.studentId = sa.studentID
            WHERE sa.studentID = $studentId";
        try {
            $studentDetails = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /*
        Method for getting student correct batch if he/she in failed batch
        @author  Ranjith Balachandran
    */
    public function getHisCorrectBatchId($studentId)
    {
        $sql = "";
        $studentId = $this->realEscapeString($studentId);
        $studentBatchId = null;
        $sql = "SELECT previousBatch AS hisBatchId FROM failed_students WHERE studentID = $studentId";
        try {
            $studentBatchId = $this->executeQueryForObject($sql)->hisBatchId;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentBatchId;
    }
    /**
     * get student by id for api
     * @param int $id
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getStudentDetailsByIdForApi($id)
    {
        $sql = "";
        $id = $this->realEscapeString($id);
        $sql = "SELECT
        sa.studentID AS id,
        sa.admissionNo AS admissionNumber,
        sa.rollNo AS rollNumber,
        sa.regNo AS registerNumber,
        sa.studentName AS name,
        sa.studentSurname AS surName,
        sa.studentLastName AS lastName,
        sa.studentEmail AS email,
        sa.studentGender AS gender,
        sa.myImage AS profilePicture,
        sa.studentBirthday AS dob,
        sa.studentAddress AS address,
        sa.homeTown,
        sa.studentPhone AS phone,
        sa.studentFather AS father,
        sa.studentMother AS mother,
        sa.category,
        sa.religion,
        sa.community,
        sa.deptID AS departmentId,
        dpt.deptName AS departmentName,
        dpt.departmentDesc AS departmentDescription,
        sa.batchID AS batchId,
        btc.batchName,
        btc.semID,
        btc.batchDesc AS batchDescription,
        sa.bloodGroup,
        aq.quotaName as admissionType,
        sa.lateral AS isLateral,
        sa.NRI AS isNRI,
        sa.studentJoindate AS joinDate,
        sa.sslc AS isSSLC,
        sa.plustwo AS isPlusTwo,
        sa.hosteller AS isHosteller,
        sa.parentPhone,
        sa.feewaiverScheme AS feeWaiverScheme,
        sa.quotaID,
        sa.experience,
        sa.yearOfPassing,
        sa.qualification,
        sa.tcIssued,
        sa.transport,
        sa.exitType,
        sa.rfId,
        r.religionName,
        sa.casteID,
        sc.casteName,
        sa.parentPassword,
        p.name as currentProgramName,
        sa.studentAccount ,
        aq2.quotaName as admissionQuota,
        n.nationalityName,
        CONCAT(btc.batchStartYear,\" - \",btc.batchEndYear) as periodOfStudy,
        sl.secondLangaugeName,
        spa.properties->>'$.academicStatus' as studentStatus,
        sa.studentJoindate ,
        ct.typeName as courseType,
        ct2.name as campusTypeName,
        spa.properties->>'$.admitSemester' as admittedSemester
        FROM
        studentaccount sa
        INNER JOIN
        batches btc ON sa.batchID = btc.batchID AND sa.studentID = $id
        INNER JOIN
        department dpt ON dpt.deptID = sa.deptID AND sa.studentID = $id
        LEFT JOIN religion r ON r.religionID=sa.religion
        LEFT JOIN student_caste sc ON sc.casteID=sa.casteID AND sc.religionID=r.religionID
        left join admission_quotas aq on aq.quotaID = sa.quotaID
        left join student_program_account spa on spa.student_id = sa.studentID
        left join program p on p.id = spa.current_program_id and spa.student_id = $id
        left join admission_quotas aq2 on aq2.quotaID = sa.quotaID and sa.studentID = $id
        left join nationality n on n.id = sa.nationality_id and sa.studentID = $id
        left join secondLangauge sl on sl.secondlangaugeID = sa.secondlangaugeID and sa.studentID =$id
        left join course_type ct on ct.courseTypeID = btc.courseTypeID 
        left join campus_type ct2 on ct2.id = btc.campus_typeID ;
";
        try {
            return $this->executeQueryForObject($sql, FALSE, $this->mapper[StudentServiceMapper::GET_STUDENT_DETAILS_BY_ID_FOR_API]);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     *Search failed Student
     * @param SearchFailedStudentRequest $searchStudentRequest
     * @return \com\linways\core\ams\professional\response\SearchFailedStudentResponse
     */
    public function searchStudents($searchStudentRequest, $showAll = TRUE)
    {
        /**Settings for TC to filter by batchStartYear**/
        $tcSettings = json_decode(CommonService::getInstance()->getSettings(SettingsConstants::TC_BY_BATCH_START_YEAR, SettingsConstants::TC_BY_BATCH_START_YEAR));
        $enableTCSettings = $tcSettings->enable;
        $tcBatchStartYear = $tcSettings->batchYear;
        $sql_cond = "";
        
        $studentDetails = new SearchFailedStudentResponse();
        try {
            if (!$searchStudentRequest == NULL) {
                $sqlCourseCompleted = "";
                if (!$showAll) {
                    $sqlCourseCompleted = " and sem.semName = '" . Semester::COURSE_COMPLETED_SEM . "'";
                }
                $sql_count = "SELECT count(studentID) as totalRecord from( (SELECT sa.studentID, sa.studentName, sa.studentAccount, sa.studentEmail, sa.rollNo, sa.admissionNo, sa.tcIssued, dept.deptID, dept.deptName, bth.batchID, bth.batchName, bth.patternID as courseTypeId,fs.previousBatch,exitType, sa.batchID as batch, bth.campus_typeID,stc.issueDate,stc.tcNo,cp.prefix,cp.prefixYear,sa.regNo,stc.is_deleted,dept.deptShow, bth.batchStartYear, stc.reasonForLeave FROM studentaccount sa INNER JOIN failed_students fs ON fs.studentID=sa.studentID INNER JOIN batches bth ON bth.batchID=fs.previousBatch INNER JOIN department dept ON dept.deptID=bth.deptID left join studentTransferCertificate stc on stc.studentID = sa.studentID and stc.is_deleted = 0 LEFT JOIN certificatePrefixes cp ON cp.id = stc.tcPrefixId WHERE fs.studentID  >0 AND fs.isFailNow=1)
            UNION
            (SELECT sa.studentID, sa.studentName, sa.studentAccount, sa.studentEmail, sa.rollNo, sa.admissionNo, sa.tcIssued, dept.deptID, dept.deptName, bth.batchID, bth.batchName, bth.patternID as courseTypeId,null as previousBatch,exitType, sa.batchId as batch, bth.campus_typeID,stc.issueDate,stc.tcNo,cp.prefix,cp.prefixYear,sa.regNo,stc.is_deleted,dept.deptShow, bth.batchStartYear, stc.reasonForLeave FROM studentaccount sa  INNER JOIN batches bth ON bth.batchID=sa.batchID INNER JOIN department dept ON dept.deptID=bth.deptID INNER JOIN semesters sem ON sem.semID=bth.semID left join studentTransferCertificate stc on stc.studentID = sa.studentID and stc.is_deleted = 0 LEFT JOIN certificatePrefixes cp ON cp.id = stc.tcPrefixId WHERE sa.studentID  >0 " . $sqlCourseCompleted . ") )as tempStudentsCount WHERE studentID > 0 ";
                $sql = "SELECT * from( (SELECT sa.studentID, sa.studentName, sa.studentAccount, sa.studentEmail, sa.studentPhone, sa.rollNo, sa.admissionNo, sa.tcIssued, dept.deptID, dept.deptName, bth.batchID, bth.batchName, bth.patternID as courseTypeId,fs.previousBatch,exitType, sa.batchID as batch, bth.campus_typeID,stc.issueDate,stc.tcNo,cp.prefix,cp.prefixYear,sa.regNo,stc.is_deleted, stc.createdDate as generatedDate,dept.deptShow, bth.batchStartYear, stc.reasonForLeave FROM studentaccount sa INNER JOIN failed_students fs ON fs.studentID=sa.studentID INNER JOIN batches bth ON bth.batchID=fs.previousBatch INNER JOIN department dept ON dept.deptID=bth.deptID left join studentTransferCertificate stc on stc.studentID = sa.studentID and stc.is_deleted = 0 LEFT JOIN certificatePrefixes cp ON cp.id = stc.tcPrefixId WHERE fs.studentID  >0 AND fs.isFailNow=1)
            UNION
            (SELECT sa.studentID, sa.studentName, sa.studentAccount, sa.studentEmail, sa.studentPhone, sa.rollNo, sa.admissionNo, sa.tcIssued, dept.deptID, dept.deptName, bth.batchID, bth.batchName, bth.patternID as courseTypeId,null as previousBatch,exitType, sa.batchId as batch, bth.campus_typeID,stc.issueDate,stc.tcNo,cp.prefix,cp.prefixYear,sa.regNo,stc.is_deleted, stc.createdDate as generatedDate,dept.deptShow,bth.batchStartYear, stc.reasonForLeave FROM studentaccount sa  INNER JOIN batches bth ON bth.batchID=sa.batchID INNER JOIN department dept ON dept.deptID=bth.deptID INNER JOIN semesters sem ON sem.semID=bth.semID left join studentTransferCertificate stc on stc.studentID = sa.studentID and stc.is_deleted = 0 LEFT JOIN certificatePrefixes cp ON cp.id = stc.tcPrefixId WHERE sa.studentID  >0 " . $sqlCourseCompleted . ") )as tempStudents WHERE studentID > 0 ";
                if ($searchStudentRequest->name) {
                    $sql_cond .= "AND studentName like '%" . $searchStudentRequest->name . "%' ";
                }
                if ($searchStudentRequest->tcNo) {
                    $sql_cond .= "AND tcNo like '%" . $searchStudentRequest->tcNo . "%' ";
                }
                if ($searchStudentRequest->batchId) {
                    $sql_cond .= "AND batchID = '" . $searchStudentRequest->batchId . "' ";
                }
                if ($searchStudentRequest->deptId) {
                    $sql_cond .= "AND deptID = '" . $searchStudentRequest->deptId . "' ";
                }
                if ($searchStudentRequest->account) {
                    $sql_cond .= "AND studentAccount like '%" . $searchStudentRequest->account . "%' ";
                }
                if ($searchStudentRequest->email) {
                    $sql_cond .= "AND studentEmail like '%" . $searchStudentRequest->email . "%' ";
                }
                if ($searchStudentRequest->rollNo) {
                    $sql_cond .= "AND rollNo like '%" . $searchStudentRequest->rollNo . "%' ";
                }
                if ($searchStudentRequest->admissionNo) {
                    $sql_cond .= "AND admissionNo like '%" . $searchStudentRequest->admissionNo . "%' ";
                }
                if ($searchStudentRequest->campusTypeId) {
                    $sql_cond .= "AND campus_typeID = '" . $searchStudentRequest->campusTypeId . "' ";
                }
                if ($searchStudentRequest->fromDate) {
                    $sql_cond .= "AND issueDate >= '" . $searchStudentRequest->fromDate . "' ";
                }
                if ($searchStudentRequest->toDate) {
                    $sql_cond .= "AND issueDate <= '" . $searchStudentRequest->toDate . "' ";
                }
                if ($searchStudentRequest->regNo) {
                    $sql_cond .= "AND regNo = '" . $searchStudentRequest->regNo . "' ";
                }
                if ($searchStudentRequest->batchStartYear) {
                    $sql_cond .= "AND batchStartYear = '" . $searchStudentRequest->batchStartYear . "' ";
                }
                if ($enableTCSettings) {
                    $sql_cond .= " AND batchStartYear >= '" . $tcBatchStartYear . "' ";
                }
                       
                if ($searchStudentRequest->tcIssued) {
                    if ($searchStudentRequest->tcIssued == 'issued') {
                        $sql_cond .= "AND tcIssued = 1 ";
                    } elseif ($searchStudentRequest->tcIssued == 'notIssued') {
                        $sql_cond .= "AND tcIssued = 0 ";
                    }
                }
                $sql_cond .= " AND deptShow = 1 ";
                if ($searchStudentRequest->sortBy) {
                    $sql_cond .= "order by $searchStudentRequest->sortBy $searchStudentRequest->sortOrder ";
                }
                $sql_count .= $sql_cond;
                $studentDetails->totalRecords = $this->executeQueryForObject($sql_count)->totalRecord;
                if (!$searchStudentRequest->export) {
                    $sql .= $sql_cond . "LIMIT $searchStudentRequest->startIndex,$searchStudentRequest->endIndex";
                } else {
                    $sql .= $sql_cond;
                }
                $studentDetails->students = $this->executeQueryForList($sql);
            }
            return $studentDetails;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     *Search failed Student
     * @param SearchFailedStudentRequest $searchStudentRequest
     * @return \com\linways\core\ams\professional\response\SearchFailedStudentResponse
     */
    public function searchMigrationStudents($searchStudentRequest, $showAll = TRUE)
    {
        $studentDetails = new SearchFailedStudentResponse();
        try {
            if (!$searchStudentRequest == NULL) {
                $sqlCourseCompleted = "";
                if (!$showAll) {
                    $sqlCourseCompleted = " and sem.semName = '" . Semester::COURSE_COMPLETED_SEM . "'";
                }
                // We need to applly the filter conditions to subqueries also
                $subQueryCond = "";
                if ($searchStudentRequest->name) {
                    $sql_cond .= "AND studentName like '" . $searchStudentRequest->name . "%' ";
                    $subQueryCond .= "AND studentName like '" . $searchStudentRequest->name . "%' ";
                }
                if ($searchStudentRequest->cancellationCertificateNo) {
                    $sql_cond .= "AND cancellationCertificateNo = '" . $searchStudentRequest->cancellationCertificateNo . "' ";
                    $subQueryCond .= "AND cancellationCertificateNo = '" . $searchStudentRequest->cancellationCertificateNo . "' ";
                }
                if ($searchStudentRequest->batchId) {
                    $sql_cond .= "AND batchID = '" . $searchStudentRequest->batchId . "' ";
                    $subQueryCond .= "AND bth.batchID = '" . $searchStudentRequest->batchId . "' ";
                }
                if ($searchStudentRequest->deptId) {
                    $sql_cond .= "AND deptID = '" . $searchStudentRequest->deptId . "' ";
                    $subQueryCond .= "AND dept.deptID = '" . $searchStudentRequest->deptId . "' ";
                }
                if ($searchStudentRequest->account) {
                    $sql_cond .= "AND studentAccount like '%" . $searchStudentRequest->account . "%' ";
                    $subQueryCond .= "AND studentAccount like '%" . $searchStudentRequest->account . "%' ";
                }
                if ($searchStudentRequest->email) {
                    $sql_cond .= "AND studentEmail like '%" . $searchStudentRequest->email . "%' ";
                    $subQueryCond .= "AND studentEmail like '%" . $searchStudentRequest->email . "%' ";
                }
                if ($searchStudentRequest->rollNo) {
                    $sql_cond .= "AND rollNo like '%" . $searchStudentRequest->rollNo . "%' ";
                    $subQueryCond .= "AND rollNo like '%" . $searchStudentRequest->rollNo . "%' ";
                }
                if ($searchStudentRequest->admissionNo) {
                    $sql_cond .= "AND admissionNo like '%" . $searchStudentRequest->admissionNo . "%' ";
                    $subQueryCond .= "AND admissionNo like '%" . $searchStudentRequest->admissionNo . "%' ";
                }
                if ($searchStudentRequest->campusTypeId) {
                    $sql_cond .= "AND campus_typeID = '" . $searchStudentRequest->campusTypeId . "' ";
                    $subQueryCond .= "AND campus_typeID = '" . $searchStudentRequest->campusTypeId . "' ";
                }
                if ($searchStudentRequest->fromDate) {
                    $sql_cond .= "AND issueDate >= '" . $searchStudentRequest->fromDate . "' ";
                    $subQueryCond .= "AND issueDate >= '" . $searchStudentRequest->fromDate . "' ";
                }
                if ($searchStudentRequest->toDate) {
                    $sql_cond .= "AND issueDate <= '" . $searchStudentRequest->toDate . "' ";
                    $subQueryCond .= "AND issueDate <= '" . $searchStudentRequest->toDate . "' ";
                }
                if ($searchStudentRequest->regNo) {
                    $sql_cond .= "AND regNo = '" . $searchStudentRequest->regNo . "' ";
                    $subQueryCond .= "AND regNo = '" . $searchStudentRequest->regNo . "' ";
                }
                if ($searchStudentRequest->tcIssued) {
                    if ($searchStudentRequest->tcIssued == 'issued') {
                        $sql_cond .= "AND tcIssued = 1 ";
                        $subQueryCond .= "AND tcIssued = 1 ";
                    } elseif ($searchStudentRequest->tcIssued == 'notIssued') {
                        $sql_cond .= "AND tcIssued = 0 ";
                        $subQueryCond .= "AND tcIssued = 0 ";
                    }
                }
                if ($searchStudentRequest->sortBy) {
                    $sql_cond .= "order by $searchStudentRequest->sortBy $searchStudentRequest->sortOrder ";
                }
                //count of students
                    $sql_count = "SELECT count(studentID) as totalRecord from( (SELECT sa.studentID, sa.studentName, sa.studentAccount, sa.studentEmail, sa.rollNo, sa.admissionNo, sa.tcIssued, dept.deptID, dept.deptName, bth.batchID, bth.batchName, bth.patternID as courseTypeId,fs.previousBatch,exitType, sa.batchID as batch, bth.campus_typeID,smc.issueDate,smc.migrationCertificateNo,cp.prefix,cp.prefixYear,sa.regNo FROM studentaccount sa INNER JOIN failed_students fs ON fs.studentID=sa.studentID INNER JOIN batches bth ON bth.batchID=fs.previousBatch INNER JOIN department dept ON dept.deptID=bth.deptID left join studentMigrationCertificate smc on smc.studentId = sa.studentID LEFT JOIN certificatePrefixes cp ON cp.id = smc.prefixId WHERE fs.studentID  >0 AND fs.isFailNow=1 $subQueryCond )
                UNION
                (SELECT sa.studentID, sa.studentName, sa.studentAccount, sa.studentEmail, sa.rollNo, sa.admissionNo, sa.tcIssued, dept.deptID, dept.deptName, bth.batchID, bth.batchName, bth.patternID as courseTypeId,null as previousBatch,exitType, sa.batchId as batch, bth.campus_typeID,smc.issueDate,smc.migrationCertificateNo,cp.prefix,cp.prefixYear,sa.regNo FROM studentaccount sa  INNER JOIN batches bth ON bth.batchID=sa.batchID INNER JOIN department dept ON dept.deptID=bth.deptID INNER JOIN semesters sem ON sem.semID=bth.semID left join studentMigrationCertificate smc on smc.studentId = sa.studentID LEFT JOIN certificatePrefixes cp ON cp.id = smc.prefixId WHERE sa.studentID  >0 $subQueryCond " . $sqlCourseCompleted . ") )as tempStudentsCount WHERE studentID > 0 ";
                //sql for fetching students
                    $sql = "SELECT * from( (SELECT sa.studentID, sa.studentName, sa.studentAccount, sa.studentEmail, sa.rollNo, sa.admissionNo, sa.tcIssued, dept.deptID, dept.deptName, bth.batchID, bth.batchName, bth.patternID as courseTypeId,fs.previousBatch,exitType, sa.batchID as batch, bth.campus_typeID,smc.issueDate,smc.migrationCertificateNo,cp.prefix,cp.prefixYear,sa.regNo FROM studentaccount sa INNER JOIN failed_students fs ON fs.studentID=sa.studentID INNER JOIN batches bth ON bth.batchID=fs.previousBatch INNER JOIN department dept ON dept.deptID=bth.deptID left join studentMigrationCertificate smc on smc.studentId = sa.studentID LEFT JOIN certificatePrefixes cp ON cp.id = smc.prefixId WHERE fs.studentID  >0 AND fs.isFailNow=1 $subQueryCond)
                UNION
                (SELECT sa.studentID, sa.studentName, sa.studentAccount, sa.studentEmail, sa.rollNo, sa.admissionNo, sa.tcIssued, dept.deptID, dept.deptName, bth.batchID, bth.batchName, bth.patternID as courseTypeId,null as previousBatch,exitType, sa.batchId as batch, bth.campus_typeID,scc.issueDate,scc.cancellationCertificateNo,cp.prefix,cp.prefixYear,sa.regNo FROM studentaccount sa  INNER JOIN batches bth ON bth.batchID=sa.batchID INNER JOIN department dept ON dept.deptID=bth.deptID INNER JOIN semesters sem ON sem.semID=bth.semID left join studentCancellationCertificate scc on scc.studentId = sa.studentID LEFT JOIN certificatePrefixes cp ON cp.id = scc.prefixId WHERE sa.studentID  >0 $subQueryCond " . $sqlCourseCompleted . ") )as tempStudents WHERE studentID > 0 ";
                //count condition
                $sql_count .= $sql_cond;
                $studentDetails->totalRecords = $this->executeQueryForObject($sql_count)->totalRecord;
                if (!$searchStudentRequest->export) {
                    $sql .= $sql_cond . "LIMIT $searchStudentRequest->startIndex,$searchStudentRequest->endIndex";
                } else {
                    $sql .= $sql_cond;
                }
                $studentDetails->students = $this->executeQueryForList($sql);
            }
            return $studentDetails;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * get failed student details
     * @param int $studentId
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getFailedStudentById($studentId)
    {
        $studentDeatils = NULL;
        $sql = "SELECT sa.studentID as id,
        sa.studentName as name,
        sa.regNo, sa.rollNo,
        sa.studentGender,
        sa.admissionNo,
        dept.deptName,
        bth.batchName,
        dept.deptID,
        bth.batchID,
        bth.patternID as courseTypeId,
        bct.type_code as typeCode,
        bct.type_name as typeName,
        bth.batchStartYear as startYear,
        bth.batchEndYear as endYear,
        dept.departmentDesc,
        sa.studentAddress,
        pdc.patterncourseName,
        sl.secondLangaugeName,
        sem.semName,
        sem.orderNo as semOrderNo ,
        sa.studentMother,
        sa.studentJoindate,
        sa.parentAddress1,
        sa.parentAddress2,
        sa.parentCity,
        sa.parentZipCode,
        sa.parentCountry,
        sa.parentState,
        sa.studentFather,
        sa.myImage,
        state.state_name as stateName,
        sa.studentBirthday,
        CONCAT_WS(' ',se.commuhouse,se.currentAddress1,se.currentAddress2,se.currentCity,se.currentCountry,se.currentState,se.currentZipCode) as additional_info_currentAddress,
        CONCAT_WS(' ',se.permaHouse,se.permanentAddress1,se.permanentAddress2,se.permanentCity,se.permanentCountry,se.permanentState,se.permanentZipCode) as additional_info_permanentAddress,sa.tcIssued,nat.nationalityName,caste.casteID,caste.casteName,rs.reservationID,rs.reservationName AS studentReservation, fs.failedInSemester as lastSemId
        FROM studentaccount sa
        INNER JOIN failed_students fs ON fs.studentID=sa.studentID
        INNER JOIN batches bth ON bth.batchID=fs.previousBatch
        INNER JOIN department dept ON dept.deptID=bth.deptID
        LEFT JOIN batch_course_type bct ON bct.id=bth.patternID
        left join pattern_deptcourses pdc ON bth.patterncourseID = pdc.patterncourseID
        left join secondLangauge sl on sl.secondlangaugeID = sa.secondlangaugeID
        left join semesters sem on sem.semID = bth.semID
        left join studentaccount_extras se on se.studentID = sa.studentID
        LEFT JOIN state ON state.id = sa.state_id
        LEFT JOIN nationality nat ON nat.id = sa.nationality_id
        LEFT JOIN student_caste caste ON caste.casteID=sa.casteID
        LEFT JOIN reservation_students rs ON rs.reservationID=sa.reservationID
        WHERE fs.studentID =  $studentId";
        try {
            $studentDeatils = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDeatils;
    }
    /**
     * check student is failed or not
     * @param int $studentId
     */
    public function isFailed($studentId)
    {
        $isFailed = false;
        $studentId = $this->realEscapeString($studentId);
        $sql = "SELECT b.batchID
        FROM studentaccount sa
        INNER JOIN batches b on sa.batchID = b.batchID
        where sa.studentID='$studentId' and b.batchName  = '" . BATCH::BATCH_FAILED_NAME . "'";
        try {
            $failed = $this->executeQueryForObject($sql);
            if (!empty($failed)) {
                $isFailed = true;
            }else{
                $failed = $this->executeQueryForObject("SELECT v3.* FROM v3_v4_move_student_to_failed_request v3
                INNER JOIN student_program_account spa ON spa.id = v3.student_program_id
                WHERE spa.student_id = '$studentId' AND v3.status IN ('NOT_DONE');");
                if (!empty($failed)) {
                    $isFailed = true;
                }
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $isFailed;
    }
    /**
     * delete student by studentid
     * @param integer $studentIds
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     */
    public function deleteStudent($studentIds)
    {
        if ($studentIds != NULL && count($studentIds) > 0) {
            foreach ($studentIds as $studentId) {
                $this->deleteStudentDir($studentId);
                $this->unlinkStudentProfilePic($studentId);
            }
            $sql = "DELETE FROM studentaccount WHERE studentID IN (" . implode(',', $studentIds) . ")";
            try {
                return $this->executeQuery($sql);
            } catch (\Exception $e) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        }
    }
    /**
     * delete student files
     * @param string $user_dir
     */
    public function deleteStudentFile($user_dir)
    {
        if (is_dir($user_dir)) {
            if ($dh = opendir($user_dir)) {
                while (($file = readdir($dh)) !== false) {
                    if ($file != "." && $file != "..") {
                        unlink($user_dir . $file);
                    }
                }
                closedir($dh);
            }
            rmdir($user_dir);
        }
    }
    /**
     * delete student profile pic using student id
     * @param integer $studentId
     */
    public function unlinkStudentProfilePic($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        $studentDetails = $this->getStudentDetailsById($studentId);
        $path = DOCUMENT_ROOT . str_replace('../', '', $studentDetails->myImage);
        if (is_file("$studentDetails->myImage")) {
            unlink("$studentDetails->myImage");
        }
    }
    /**
     * delete student signature pic using student id
     * @param integer $studentId
     */
    public function removeStudentSignature($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        $studentDetails = $this->getStudentDetailsById($studentId);
        $path = DOCUMENT_ROOT . str_replace('../', '', $studentDetails->studentSignImage);
        if (is_file($path)) {
            $removeSignatureSql = "UPDATE studentaccount SET studentSignImage = null WHERE studentID = '$studentId'";
            try {
                $this->executeQuery($removeSignatureSql);
                unlink($path);
            } catch (\Exception $e) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        } else {
            throw new ProfessionalException(ProfessionalException::FILE_NOT_FOUND, "File not found in the specified path");
        }
    }
    /**
     * delete student signature pic using student id
     * @param integer $studentId
     */
    public function removeStudentProfilePic($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        $studentDetails = $this->getStudentDetailsById($studentId);
        $path = DOCUMENT_ROOT . str_replace('../', '', $studentDetails->myImage);
        if (is_file($path)) {
            $removeSignatureSql = "UPDATE studentaccount SET myImage = null WHERE studentID = '$studentId'";
            try {
                $this->executeQuery($removeSignatureSql);
                unlink($path);
            } catch (\Exception $e) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        } else {
            throw new ProfessionalException(ProfessionalException::FILE_NOT_FOUND, "File not found in the specified path");
        }
    }
    /**
     * Get student batch details by regNo and subjectCode
     * @param string $regNo
     * @param string $syllabusCode
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getStudentBatchIdBySubject($regNo, $syllabusCode)
    {
        $regNo = $this->realEscapeString($regNo);
        $syllabusCode = $this->realEscapeString($syllabusCode);
        $sql = "select sa.studentID, sr.batchID, ba.batchName,sr.semID, sr.subjectID from studentaccount sa left join failed_students fs on sa.studentID = fs.studentID and isFailNow=1 inner join  batches ba on ba.batchID = case when fs.studentID is not null then fs.previousBatch else sa.batchID end inner join sbs_relation sr on sr.batchID =case when fs.studentID is not null then fs.previousBatch else sa.batchID end inner join subjects sub on sub.subjectID = sr.subjectID  where regNo = \"$regNo\" and syllabusName = \"$syllabusCode\"";
        try {
            $studentBatch = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentBatch;
    }
    /**
     * get student details for mark attendance
     * @param SearchStudentRequest $studentRequest
     * @return object|array|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getStudentDetailsForMakeAttendance($studentRequest)
    {
        $studentRequest = $this->realEscapeObject($studentRequest);
        $studentDetails = null;
        $isCurrentSem = SemesterService::getInstance()->isCurrentSemester($studentRequest->batchId, $studentRequest->semId);
        if ($studentRequest->subbatchId) {
            if ($isCurrentSem) {
                $sql = "select sa.studentID, sa.studentName, sa.rollNo, sa.regNo, sa.admissionNo, at.isAbsent, if(sr.batchID !=$studentRequest->batchId,'1','0') as isMarkedOtherBatch, at.sbsID as markedSbsId, sa.myImage, sa.studentGender from  studentaccount sa INNER JOIN subbatch_student ss ON ss.studentID=sa.studentID  LEFT JOIN attendance at ON at.studentID=sa.studentID AND at.attendanceDate='" . (date('Y-m-d', strtotime($studentRequest->attendanceDate))) . "' AND at.hour=$studentRequest->hourId LEFT JOIN sbs_relation sr ON sr.sbsID=at.sbsID where sa.batchID=$studentRequest->batchId AND ss.subbatchID=$studentRequest->subbatchId  ORDER BY sa.$studentRequest->sortBy";
            } else {
                $sql = "select sa.studentID, sa.studentName, sa.rollNo, sa.regNo, sa.admissionNo, sa.myImage, sa.studentGender from studentaccount sa inner join department dep on sa.deptID = dep.deptID inner join batches ba on sa.deptID = ba.deptID inner join subbatch_student ss on sa.studentID = ss.studentID where ba.batchID = $studentRequest->batchId and subbatchID = $studentRequest->subbatchId and  sa.studentID in(select studentID from studentaccount sa inner join batches ba on sa.batchID = ba.batchID where ba.batchID = $studentRequest->batchId union select studentID from failed_students fs where previousBatch = $studentRequest->batchId and failedInSemester > $studentRequest->semId) order by sa.$studentRequest->sortBy";
            }
        } else {
            if ($isCurrentSem) {
                $sql = "select sa.studentID, sa.studentName, sa.rollNo, sa.regNo, sa.admissionNo, at.isAbsent, if(sr.batchID !=$studentRequest->batchId,'1','0') as isMarkedOtherBatch, at.sbsID as markedSbsId, sa.myImage, sa.studentGender from  studentaccount sa LEFT JOIN attendance at ON at.studentID=sa.studentID AND at.attendanceDate='" . (date('Y-m-d', strtotime($studentRequest->attendanceDate))) . "' AND at.hour=$studentRequest->hourId LEFT JOIN sbs_relation sr ON sr.sbsID=at.sbsID where sa.batchID=$studentRequest->batchId  ORDER BY sa.$studentRequest->sortBy";
            } else {
                $sql = "select sa.studentID, sa.studentName, sa.rollNo, sa.regNo, sa.admissionNo, sa.myImage, sa.studentGender from studentaccount sa inner join batches ba on sa.batchID =  ba.batchID where ba.batchID = $studentRequest->batchId  union select sa.studentID, sa.studentName, sa.rollNo, sa.regNo, sa.admissionNo, sa.myImage, sa.studentGender from failed_students fs left join studentaccount sa on fs.studentID= sa.studentID where previousBatch = $studentRequest->batchId and failedInSemester > $studentRequest->semId order by $studentRequest->sortBy";
            }
        }
        try {
            $studentDetails = $this->executeQueryForList($sql);
            foreach($studentDetails as $idx => $student){
                $studentDetails[$idx]->myImage = $this->getStudentProfilePic($student->studentID)->docpath;
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     *Search failed Student
     * @param SearchFailedStudentRequest $searchStudentRequest
     * @return \com\linways\core\ams\professional\response\SearchFailedStudentResponse
     */
    public function searchCancelStudents($searchStudentRequest, $showAll = TRUE)
    {
        $studentDetails = new SearchFailedStudentResponse();
        try {
            if (!$searchStudentRequest == NULL) {
                $sqlCourseCompleted = "";
                if (!$showAll) {
                    $sqlCourseCompleted = " and sem.semName = '" . Semester::COURSE_COMPLETED_SEM . "'";
                }
                $sql_count = "SELECT count(studentID) as totalRecord from( (SELECT sa.studentID, sa.studentName, sa.studentAccount, sa.studentEmail, sa.rollNo, sa.admissionNo, sa.tcIssued, dept.deptID, dept.deptName, bth.batchID, bth.batchName, bth.patternID as courseTypeId,fs.previousBatch,exitType, sa.batchID as batch, bth.campus_typeID,scc.issueDate,scc.cancellationCertificateNo,cp.prefix,cp.prefixYear,sa.regNo FROM studentaccount sa INNER JOIN failed_students fs ON fs.studentID=sa.studentID INNER JOIN batches bth ON bth.batchID=fs.previousBatch INNER JOIN department dept ON dept.deptID=bth.deptID left join studentCancellationCertificate scc on scc.studentId = sa.studentID LEFT JOIN certificatePrefixes cp ON cp.id = scc.prefixId WHERE fs.studentID  >0 AND fs.isFailNow=1)
            UNION
            (SELECT sa.studentID, sa.studentName, sa.studentAccount, sa.studentEmail, sa.rollNo, sa.admissionNo, sa.tcIssued, dept.deptID, dept.deptName, bth.batchID, bth.batchName, bth.patternID as courseTypeId,null as previousBatch,exitType, sa.batchId as batch, bth.campus_typeID,scc.issueDate,scc.cancellationCertificateNo,cp.prefix,cp.prefixYear,sa.regNo FROM studentaccount sa  INNER JOIN batches bth ON bth.batchID=sa.batchID INNER JOIN department dept ON dept.deptID=bth.deptID INNER JOIN semesters sem ON sem.semID=bth.semID left join studentCancellationCertificate scc on scc.studentId = sa.studentID LEFT JOIN certificatePrefixes cp ON cp.id = scc.prefixId WHERE sa.studentID  >0 " . $sqlCourseCompleted . ") )as tempStudentsCount WHERE studentID > 0 ";
                $sql = "SELECT * from( (SELECT sa.studentID, sa.studentName, sa.studentAccount, sa.studentEmail, sa.rollNo, sa.admissionNo, sa.tcIssued, dept.deptID, dept.deptName, bth.batchID, bth.batchName, bth.patternID as courseTypeId,fs.previousBatch,exitType, sa.batchID as batch, bth.campus_typeID,scc.issueDate,scc.cancellationCertificateNo,cp.prefix,cp.prefixYear,sa.regNo FROM studentaccount sa INNER JOIN failed_students fs ON fs.studentID=sa.studentID INNER JOIN batches bth ON bth.batchID=fs.previousBatch INNER JOIN department dept ON dept.deptID=bth.deptID left join studentCancellationCertificate scc on scc.studentId = sa.studentID LEFT JOIN certificatePrefixes cp ON cp.id = scc.prefixId WHERE fs.studentID  >0 AND fs.isFailNow=1)
            UNION
            (SELECT sa.studentID, sa.studentName, sa.studentAccount, sa.studentEmail, sa.rollNo, sa.admissionNo, sa.tcIssued, dept.deptID, dept.deptName, bth.batchID, bth.batchName, bth.patternID as courseTypeId,null as previousBatch,exitType, sa.batchId as batch, bth.campus_typeID,scc.issueDate,scc.cancellationCertificateNo,cp.prefix,cp.prefixYear,sa.regNo FROM studentaccount sa  INNER JOIN batches bth ON bth.batchID=sa.batchID INNER JOIN department dept ON dept.deptID=bth.deptID INNER JOIN semesters sem ON sem.semID=bth.semID left join studentCancellationCertificate scc on scc.studentId = sa.studentID LEFT JOIN certificatePrefixes cp ON cp.id = scc.prefixId WHERE sa.studentID  >0 " . $sqlCourseCompleted . ") )as tempStudents WHERE studentID > 0 ";
                if ($searchStudentRequest->name) {
                    $sql_cond .= "AND studentName like '%" . $searchStudentRequest->name . "%' ";
                }
                if ($searchStudentRequest->cancellationCertificateNo) {
                    $sql_cond .= "AND cancellationCertificateNo = '" . $searchStudentRequest->cancellationCertificateNo . "' ";
                }
                if ($searchStudentRequest->batchId) {
                    $sql_cond .= "AND batchID = '" . $searchStudentRequest->batchId . "' ";
                }
                if ($searchStudentRequest->deptId) {
                    $sql_cond .= "AND deptID = '" . $searchStudentRequest->deptId . "' ";
                }
                if ($searchStudentRequest->account) {
                    $sql_cond .= "AND studentAccount like '%" . $searchStudentRequest->account . "%' ";
                }
                if ($searchStudentRequest->email) {
                    $sql_cond .= "AND studentEmail like '%" . $searchStudentRequest->email . "%' ";
                }
                if ($searchStudentRequest->rollNo) {
                    $sql_cond .= "AND rollNo like '%" . $searchStudentRequest->rollNo . "%' ";
                }
                if ($searchStudentRequest->admissionNo) {
                    $sql_cond .= "AND admissionNo like '%" . $searchStudentRequest->admissionNo . "%' ";
                }
                if ($searchStudentRequest->campusTypeId) {
                    $sql_cond .= "AND campus_typeID = '" . $searchStudentRequest->campusTypeId . "' ";
                }
                if ($searchStudentRequest->fromDate) {
                    $sql_cond .= "AND issueDate >= '" . $searchStudentRequest->fromDate . "' ";
                }
                if ($searchStudentRequest->toDate) {
                    $sql_cond .= "AND issueDate <= '" . $searchStudentRequest->toDate . "' ";
                }
                if ($searchStudentRequest->regNo) {
                    $sql_cond .= "AND regNo = '" . $searchStudentRequest->regNo . "' ";
                }
                if ($searchStudentRequest->tcIssued) {
                    if ($searchStudentRequest->tcIssued == 'issued') {
                        $sql_cond .= "AND tcIssued = 1 ";
                    } elseif ($searchStudentRequest->tcIssued == 'notIssued') {
                        $sql_cond .= "AND tcIssued = 0 ";
                    }
                }
                if ($searchStudentRequest->sortBy) {
                    $sql_cond .= "order by $searchStudentRequest->sortBy $searchStudentRequest->sortOrder ";
                }
                $sql_count .= $sql_cond;
                $studentDetails->totalRecords = $this->executeQueryForObject($sql_count)->totalRecord;
                if (!$searchStudentRequest->export) {
                    $sql .= $sql_cond . "LIMIT $searchStudentRequest->startIndex,$searchStudentRequest->endIndex";
                } else {
                    $sql .= $sql_cond;
                }
                $studentDetails->students = $this->executeQueryForList($sql);
            }
            return $studentDetails;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * update failed student status
     * @param array $studentList
     * @param string $failedStatus
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     */
    public function updateFailedStudentStatus($studentList, $failedStatus)
    {
        $failedBatchId = 0;
        $adminId = $_SESSION['adminID'];
        if ($studentList != NULL && count($studentList) > 0) {
            try {
                $failedBatchId = BatchService::getInstance()->getFailedBatchId();
            } catch (\Exception $e) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
            foreach ($studentList as $studentId) {
                $sql = "select sa.batchID, ba.semID, sa.joiningSemId,sem.type,sem.orderNo ,sa.student_lock from studentaccount sa inner join batches ba on sa.batchID = ba.batchID left join semesters sem on sem.semID = ba.semID where sa.studentID='" . $studentId . "'";
                $batchDetails = $this->executeQueryForObject($sql);
                $batchID = $batchDetails->batchID;
                $semID = $batchDetails->semID;
                if ($batchID != 1) {
                    // $sql = "call move_failedstudents('$studentId','$semID',0)";
                    // $this->executeQuery($sql);
                    // $studentPreviousSemesters = $this->getPreviousSemestersOfThisBatch($studentId,$batchDetails);
                    // $previousBatchId = $batchID;
                    // $sqlForUpdatingFailedStudents = "UPDATE  failed_students SET reason ='" . FailedReason::FAILED . "',hisSemestersInThisbatch = '$studentPreviousSemesters',updated_by = '".$adminId."',userType = 'ADMIN'  WHERE studentID=$studentId AND previousBatch = '$previousBatchId'";
                    // $this->executeQuery($sqlForUpdatingFailedStudents);
                    // TAKEN V4 UPDATES
                    $failedStudentRequest = new FailedStudentRequest;
                    $failedStudentRequest->studentId = $studentId;
                    $failedStudentRequest->batchId = $batchDetails->batchID;
                    $failedStudentRequest->reason = trim($failedStatus);
                    $failedStudentRequest->remarks = trim($remarks);
                    $failedStudentRequest->academicSatus = StatusConstants::ACTIVE;
                    StudentService::getInstance()->createV4MoveStudentFailedRequest($failedStudentRequest);
                }
            }
            try {
                $sql_failed = "UPDATE studentaccount set exitType='$failedStatus', student_lock = 1 WHERE studentID IN (" . implode(',', $studentList) . ")";
                return $this->executeQuery($sql_failed);
            } catch (\Exception $e) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        }
    }
    /**
     * update failed student status with remarks
     * @param array $studentList
     * @param string $failedStatus
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     */
    public function updateFailedStudentStatusWithRemarks($studentList, $failedStatus,$failedDate = NULL,$remarks)
    {
        $enableRemarks = json_decode(CommonService::getInstance()->getSettings(SettingsConstants::ENABLE_REMARKS_ON_FAILURE, SettingsConstants::ENABLE_REMARKS_ON_FAILURE))->enable_remark;
        $failedBatchId = 0;
        $adminId = $_SESSION['adminID'];
        if ($studentList != NULL && count($studentList) > 0) {
            try {
                $failedBatchId = BatchService::getInstance()->getFailedBatchId();
            } catch (\Exception $e) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
            $updateFailedDateSql = !empty($failedDate)? ",failedDate = '".$failedDate."' ":"";
            foreach ($studentList as $studentId) {
                $sql = "select sa.batchID, ba.semID, sa.joiningSemId,sem.type,sem.orderNo ,sa.student_lock from studentaccount sa inner join batches ba on sa.batchID = ba.batchID left join semesters sem on sem.semID = ba.semID where sa.studentID='" . $studentId . "'";
                $batchDetails = $this->executeQueryForObject($sql);
                $batchID = $batchDetails->batchID;
                $semID = $batchDetails->semID;
                if ($batchID != 1) {
                    $failedStudentRequest = new FailedStudentRequest;
                    $failedStudentRequest->studentId = $studentId;
                    $failedStudentRequest->batchId = $batchDetails->batchID;
                    $failedStudentRequest->reason = trim($failedStatus);
                    $failedStudentRequest->remarks = trim($remarks);
                    $failedStudentRequest->academicSatus = StatusConstants::ACTIVE;
                    StudentService::getInstance()->createV4MoveStudentFailedRequest($failedStudentRequest);
                    // TAKEN V4 UPDATES
                    // $sql = "call move_failedstudents('$studentId','$semID',0)";
                    // $this->executeQuery($sql);
                    // $studentPreviousSemesters = $this->getPreviousSemestersOfThisBatch($studentId,$batchDetails);
                    // $previousBatchId = $batchID;
                    // $sqlForUpdatingFailedStudents = "UPDATE  failed_students SET reason ='" . FailedReason::FAILED . "',hisSemestersInThisbatch = '$studentPreviousSemesters',updated_by = '".$adminId."',userType = 'ADMIN'".$updateFailedDateSql."  WHERE studentID=$studentId AND previousBatch = '$previousBatchId'";
                    // $this->executeQuery($sqlForUpdatingFailedStudents);
                    // if($enableRemarks)
                    // {
                    //    $query=" UPDATE failed_students SET remarks = '$remarks' WHERE studentID=$studentId ";
                    //    $this->executeQuery($query);
                    // }
                }
            }
            try {
                $sql_failed = "UPDATE studentaccount set exitType='$failedStatus',student_lock = 1 WHERE studentID IN (" . implode(',', $studentList) . ")";
                return $this->executeQuery($sql_failed);
            } catch (\Exception $e) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        }
    }
    /**
     * delete student directory
     * @param int $studentId
     */
    public function deleteStudentDir($studentId)
    {
        global $STUDENT_FOLDER_PATH;
        $studentDetails = $this->getStudentDetailsById($studentId);
        $user_dir = $STUDENT_FOLDER_PATH . $studentDetails->studentAccount;
        $user_dir = str_replace('../', '', $user_dir);
        $user_dir = DOCUMENT_ROOT . $user_dir;
        if (is_dir($user_dir) && $user_dir != DOCUMENT_ROOT . "users/") {
            if ($dh = opendir($user_dir)) {
                while (($file = readdir($dh)) !== false) {
                    if ($file != "." && $file != "..") {
                        $this->deleteStudentFile($user_dir . "/" . $file . "/");
                    }
                }
                closedir($dh);
            }
            rmdir($user_dir);
        }
    }
    /**
     * Get count of students in a batch
     * @param int $batchId
     * @param int $isHosteler
     * @param string $gender
     * @return int
     * @throws ProfessionalException
     */
    public function getStudentsCountByBatch($batchId, $isHosteler = null, $gender = null)
    {
        $batchId = $this->realEscapeString($batchId);
        $isHosteler = $this->realEscapeString($isHosteler);
        $gender = $this->realEscapeString($gender);
        $sql_hosteler_cond = "";
        $sql_hosteler = "";
        $sql_gender = "";
        if ($isHosteler) {
            $sql_hosteler = " left join student_hosteler sh on sa.studentID = sh.studentID ";
            $sql_hosteler_cond = $isHosteler == 0 ? " and sh.studentID is null" : "  and sh.studentID is not null";
        }
        if ($gender) {
            $sql_gender = " and studentGender = '" . $gender . "'";
        }
        $sql = "SELECT COUNT(distinct(sa.studentID)) as count FROM studentaccount sa $sql_hosteler WHERE batchID=$batchId  $sql_hosteler_cond $sql_gender";
        try {
            $count = $this->executeQueryForObject($sql)->count;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $count;
    }
    /**
     * Get studentId by admission no
     * @param string $admissionNo
     * @param int $batchId
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getStudentIdByAdmissionNo($admissionNo, $batchId)
    {
        $admissionNo = $this->realEscapeString($admissionNo);
        $batchId = $this->realEscapeString($batchId);
        $sql = "select sa.studentID,sa.studentName from studentaccount sa left join failed_students fs on sa.studentID = fs.studentID where (sa.batchID = $batchId or previousBatch = $batchId)  and admissionNo = \"$admissionNo\"";
        try {
            $studentDetails = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * student details by reg no
     * @param string $regNo
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getStudentDetailsByRegNo($regNo)
    {
        $regNo = $this->realEscapeString($regNo);
        $sql = "SELECT sa.studentID as id, sa.studentName as name, dept.deptName, bth.batchName, sa.regNo, sa.rollNo, dept.deptName, bth.batchName, dept.deptID, bth.batchID, bth.patternID as courseTypeId, bth.batchStartYear as startYear, bth.batchEndYear as endYear, dept.departmentDesc, sa.tcIssued, sa.studentAddress, bth.courseTypeID FROM studentaccount sa INNER JOIN department dept ON sa.deptID=dept.deptID INNER JOIN batches bth ON sa.batchID=bth.batchID AND dept.deptID=bth.deptID WHERE regNo = \"$regNo\"";
        try {
            $studentDetails = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * get student details by rollno
     * @param string $rollNo
     * @param int $batchId
     * @param int $subbatchId
     * @return int
     * @throws ProfessionalException
     */
    public function getStudentByRollNo($rollNo, $batchId, $subbatchId)
    {
        $studentId = null;
        if ($subbatchId == 0) {
            $sql = "select studentID from studentaccount where batchID=\"" . $batchId . "\" and rollno=\"" . trim($rollNo) . "\"";
        } else {
            $sql = "select t1.studentID, t1.studentName, t1.rollNo from  studentaccount t1, subbatch_student t2 where t1.batchID=\"" . $batchId . "\" and t2.subbatchID=\"" . $subbatchId . "\" and t1.studentID=t2.studentID and t1.rollno=\"" . trim($rollNo) . "\"";
        }
        try {
            $studentId = $this->executeQueryForObject($sql)->studentID;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentId;
    }
    /**
     * Get Student Bank SID
     * @param int $studentId
     * @return string
     * @throws ProfessionalException
     */
    public function getStudentBankSId($studentId)
    {
        $bankSID = null;
        $studentId = $this->realEscapeString($studentId);
        $sql = "select bankSID from studentaccount WHERE studentID = $studentId";
        try {
            $response = $this->executeQueryForObject($sql);
            if (!empty($response)) {
                $bankSID = $response->bankSID;
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $bankSID;
    }
    public function getStudentDetailsBybankSID($bankSID)
    {
        $bankSID = $this->realEscapeString($bankSID);
        $studentDetails = NULL;
        $sql = "SELECT sa.studentID as id, sa.studentName as name, dept.deptName, bth.batchName, sa.regNo, sa.rollNo, dept.deptName, bth.batchName, dept.deptID, bth.batchID, bth.patternID as courseTypeId, bth.batchStartYear as startYear, bth.batchEndYear as endYear, dept.departmentDesc, sa.tcIssued, sa.studentAddress FROM studentaccount sa INNER JOIN department dept ON sa.deptID=dept.deptID INNER JOIN batches bth ON sa.batchID=bth.batchID WHERE ";
        $sql .= " sa.bankSID ='$bankSID'";
        try {
            $studentDetails = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * update student image
     * @param int $studentId
     * @param string $imagePath
     * @return \com\linways\base\dto\MySqlResult|null
     * @throws ProfessionalException
     */
    public function updateStudentPhoto($studentId, $imagePath)
    {
        $studentId = $this->realEscapeString($studentId);
        $sql = "UPDATE studentaccount SET myImage = '$imagePath' WHERE studentID = $studentId";
        try {
            return $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Move student to failed list by studentId
     * @param int $studentId
     * @param string $exitType
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     */
    public function moveStudentToFailedList($studentId, $exitType = SettingsConstants::EXIT_TYPE_FAILED)
    {
        $studentId = $this->realEscapeString($studentId);
        $exitType = $this->realEscapeString($exitType);
        $adminId = $_SESSION['adminID'];
        $faileBatchId = BatchService::getInstance()->getFailedBatchId();
        if (empty($studentId)) {
            throw new ProfessionalException("STUDENT_REQUIRED", "INVALID STUDENTID");
        } else {
            $sql_batch = "SELECT sa.batchID, semID FROM studentaccount sa INNER JOIN batches bat ON sa.batchID = bat.batchID WHERE studentID = $studentId";
        }
        if ($exitType != SettingsConstants::EXIT_TYPE_FAILED && $exitType != SettingsConstants::EXIT_TYPE_DISCONTINUED) {
            throw new ProfessionalException("INVALID_EXIT_TYPE", "INVALID EXIT_TYPE");
        }
        $studentBatch = $this->executeQueryForObject($sql_batch);
        if ($studentBatch->batchID == $faileBatchId) {
            throw new ProfessionalException("STUDENT_ALREADY_IN_FAILED_LIST", "STUDENT ALREADY EXISTS IN FAILED LIST");
        }
        $semesters = SemesterService::getInstance()->getPreviousSemsters($studentBatch->semID);
        $sql = "call move_failedstudents(\"$studentId\",$studentBatch->semID,\"$semesters\")";
        $updateSql = "UPDATE studentaccount SET batchID = $faileBatchId , exitType = '$exitType', student_lock = 1 WHERE studentID = $studentId";
        $sqlForUpdatingFailedStudents = "UPDATE  failed_students SET reason ='" . FailedReason::FAILED . "',updated_by = '".$adminId."',userType = 'ADMIN' WHERE studentID=$studentId AND previousBatch = '$studentBatch->batchID'";
        try {
            $this->executeQuery($sql);
            $this->executeQuery($sqlForUpdatingFailedStudents);
            return $this->executeQuery($updateSql);
        } catch (\Exception $e) {
            throw new ProfessionalException("UPDATE_ERROR", "UPDATION FAILED");
        }
    }
    /**
     * Move student to failed list by admission no
     * @param string $admissionNo
     * @param string $exitType
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     */
    public function moveStudentToFailedListByAdmissionNo($admissionNo, $exitType = SettingsConstants::EXIT_TYPE_FAILED)
    {
        $admissionNo = $this->realEscapeString($admissionNo);
        $exitType = $this->realEscapeString($exitType);
        $adminId = $_SESSION['adminID'];
        $faileBatchId = BatchService::getInstance()->getFailedBatchId();
        if (empty($admissionNo)) {
            throw new ProfessionalException("STUDENT_REQUIRED", "INVALID ADMISSION NUMBER");
        } else {
            $sql_batch = "SELECT sa.studentId, sa.batchID, semID FROM studentaccount sa INNER JOIN batches bat ON sa.batchID = bat.batchID WHERE admissionNo = '$admissionNo'";
        }
        if ($exitType != SettingsConstants::EXIT_TYPE_FAILED && $exitType != SettingsConstants::EXIT_TYPE_DISCONTINUED) {
            throw new ProfessionalException("INVALID_EXIT_TYPE", "INVALID EXIT_TYPE");
        }
        $studentBatch = $this->executeQueryForObject($sql_batch);
        if ($studentBatch->batchID == $faileBatchId) {
            throw new ProfessionalException("STUDENT_ALREADY_IN_FAILED_LIST", "STUDENT ALREADY EXISTS IN FAILED LIST");
        }
        $semesters = SemesterService::getInstance()->getPreviousSemsters($studentBatch->semID);
        $sql = "call move_failedstudents(\"$studentBatch->studentId\",$studentBatch->semID,\"$semesters\")";
        $updateSql = "UPDATE studentaccount SET batchID = $faileBatchId , exitType = '$exitType', student_lock = 1  WHERE studentID = $studentBatch->studentId";
        $sqlForUpdatingFailedStudents = "UPDATE  failed_students SET reason ='" . FailedReason::FAILED . "',updated_by = '".$adminId."',userType = 'ADMIN' WHERE studentID='".$studentBatch->studentId."' AND previousBatch = '$studentBatch->batchID'";
        try {
            $this->executeQuery($sql);
            $this->executeQuery($sqlForUpdatingFailedStudents);
            return $this->executeQuery($updateSql);
        } catch (\Exception $e) {
            throw new ProfessionalException("UPDATE_ERROR", "UPDATION FAILED");
        }
    }
    /**
     * Move student to batch from failed list by studentId
     * @param int $studentId
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     */
    public function moveBackFromFailedList($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        if (empty($studentId)) {
            throw new ProfessionalException("STUDENT_REQUIRED", "INVALID STUDENTID");
        }
        $sql_previosBatch = "SELECT previousBatch, failedInSemester FROM failed_students WHERE studentID = $studentId and isFailNow = 1";
        $failedDetails = $this->executeQueryForObject($sql_previosBatch);
        if (!empty($failedDetails)) {
            $sql_failedUpdate = "UPDATE failed_students SET isFailNow = 0 WHERE studentID = $studentId";
            $sql_batchUpdate = "UPDATE studentaccount SET batchID = $failedDetails->previousBatch , exitType = '', student_lock = 0 WHERE studentID = $studentId";
            try {
                $this->executeQuery($sql_failedUpdate);
                $this->executeQuery($sql_batchUpdate);
                $taskQueue = new AMSTaskQueue();
                $failedBatchId = BatchService::getInstance()->getFailedBatchId();
                $params = [
                    "hookName" => "on_change_student_batch_completed",
                    "hookParams" => [
                        "studentId" => $studentId,
                        "newBatchId" => $failedDetails->previousBatch,
                        "oldBatchId" => $failedBatchId,
                        "createdBy" => ($_SESSION['adminID'] ?? $_SESSION['staffID'] ?? 0)
                    ]
                ];
                $taskQueue->enqueue("EXECUTE HOOK", $params);
            } catch (\Exception $e) {
                throw new ProfessionalException("UPDATE_ERROR", "UPDATE FAILED");
            }
        } else {
            throw new ProfessionalException("STUDENT_NOT_IN_FAILED_LIST", "STUDENT_NOT_IN_FAILED_LIST");
        }
    }
    /**
     * Move student to batch from failed list by studentId with latest roll number
     * @param int $studentId
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     * @author Ajay
     */
    public function moveBackFromFailedListWithRollNoAssigned($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        if (empty($studentId)) {
            throw new ProfessionalException("STUDENT_REQUIRED", "INVALID STUDENTID");
        }
        $sql_previosBatch = "SELECT previousBatch, failedInSemester FROM failed_students WHERE studentID = $studentId and isFailNow = 1";
        $failedDetails = $this->executeQueryForObject($sql_previosBatch);
        $currentSemOfBatch = BatchService::getInstance()->getCurrentSemesterByBatchId($failedDetails->previousBatch);
        $sql_semReg = "SELECT id from semRegistration sr where batchId =$failedDetails->previousBatch and semId = $failedDetails->failedInSemester";
        $semRegId = $this->executeQueryForObject($sql_semReg)->id;
        if($semRegId == null)
        {
            $currentSemOfBatch--;
            $sql_semReg = "SELECT id from semRegistration sr where batchId =$failedDetails->previousBatch and semId = $currentSemOfBatch";
            $semRegId = $this->executeQueryForObject($sql_semReg)->id;
        }
        $staffId = $_SESSION['staffID'];
        if($semRegId)
        {
            $sql_sem_reg = "INSERT INTO semRegistrationStudentDetails (semRegistrationId,
                                                                         studentId,
                                                                          `name`,
                                                                            `value`,
                                                                             `createdBy`,
                                                                              `createdDate`,
                                                                               updatedBy,
                                                                                updatedDate
                                                                                ) VALUES($semRegId,
                                                                                    $studentId,
                                                                                    'confirmedByHod',
                                                                                     1,
                                                                                      $staffId, NOW(),$staffId, NOW())";
            $this->executeQuery($sql_sem_reg);
        }
        if (!empty($failedDetails)) {
            $sql_failedUpdate = "UPDATE failed_students SET isFailNow = 0 WHERE studentID = $studentId";
            $sql_batchUpdate = "UPDATE studentaccount SET batchID = $failedDetails->previousBatch , exitType = '', student_lock = 0 WHERE studentID = $studentId";
            try {
                $this->executeQuery($sql_failedUpdate);
                $this->executeQuery($sql_batchUpdate);
                $sql_getCurrentSemOfBatch = "SELECT semID,rollNoPrefix FROM batches WHERE batchID=$failedDetails->previousBatch";
                $currentSem = $this->executeQueryForObject($sql_getCurrentSemOfBatch);
                if($currentSem->semID)
                {
                    $sql_fetch_from_buffer = "SELECT `studentIds`,`currentStudentIdCount` FROM semTermRegistrationBuffer WHERE `promotedSem` = $currentSem->semID AND `batchId` = $failedDetails->previousBatch  ORDER BY `id` DESC" ;
                    $bufferData = (Object) $this->executeQueryForList($sql_fetch_from_buffer)[0];
                    if($bufferData)
                    {
                        $rollNoGenerator = (int)$bufferData->currentStudentIdCount;
                        $rollNoGenerator++;
                        $roll = sprintf("%02d", $rollNoGenerator);
                        $roll = $currentSem->rollNoPrefix.$roll;
                        $sql_rollNoUpdate = "UPDATE studentaccount set rollNo = '".$roll."' WHERE studentID = $studentId";
                        $this->executeQuery($sql_rollNoUpdate);
                        $sql_semTermRegisterTableEntry ="UPDATE semTermRegistrationBuffer SET `currentStudentIdCount` ='$rollNoGenerator'  WHERE batchId  =$failedDetails->previousBatch AND promotedSem = $currentSem->semID";
                        $this->executeQuery($sql_semTermRegisterTableEntry);
                    }
                }
                $taskQueue = new AMSTaskQueue();
                $failedBatchId = BatchService::getInstance()->getFailedBatchId();
                $params = [
                    "hookName" => "on_change_student_batch_completed",
                    "hookParams" => [
                        "studentId" => $studentId,
                        "newBatchId" => $failedDetails->previousBatch,
                        "oldBatchId" => $failedBatchId,
                        "createdBy" => ($_SESSION['adminID'] ?? $_SESSION['staffID'] ?? 0)
                    ]
                ];
                $taskQueue->enqueue("EXECUTE HOOK", $params);
            } catch (\Exception $e) {
                throw new ProfessionalException("UPDATE_ERROR", "UPDATE FAILED");
            }
        } else {
            throw new ProfessionalException("STUDENT_NOT_IN_FAILED_LIST", "STUDENT_NOT_IN_FAILED_LIST");
        }
    }
    /**
     * Move student to batch from failed list by admission number
     * @param int $admissionNo
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     */
    public function moveBackFromFailedListByAdmissionNo($admissionNo)
    {
        $admissionNo = $this->realEscapeString($admissionNo);
        if (empty($admissionNo)) {
            throw new ProfessionalException("STUDENT_REQUIRED", "INVALID ADMISSION NUMBER");
        }
        $sql_studentAcc = "SELECT studentID FROM studentaccount WHERE admissionNo = '$admissionNo'";
        try {
            $studentId = $this->executeQueryForObject($sql_studentAcc)->studentID;
        } catch (\Exception $e) {
            throw new ProfessionalException('ADMISSION_NO_ERROR', 'No student corresponding to the admission number');
        }
        $sql_previousBatch = "SELECT previousBatch, failedInSemester FROM failed_students WHERE studentID = $studentId and isFailNow = 1";
        $failedDetails = $this->executeQueryForObject($sql_previousBatch);
        if (!empty($failedDetails)) {
            $sql_failedUpdate = "UPDATE failed_students SET isFailNow = 0 WHERE studentID = $studentId";
            $sql_batchUpdate = "UPDATE studentaccount SET batchID = $failedDetails->previousBatch , exitType = '', student_lock = 0 WHERE studentID = $studentId";
            try {
                $this->executeQuery($sql_failedUpdate);
                return $this->executeQuery($sql_batchUpdate);
            } catch (\Exception $e) {
                throw new ProfessionalException("UPDATE_ERROR", "UPDATE FAILED");
            }
        } else {
            throw new ProfessionalException("STUDENT_NOT_IN_FAILED_LIST", "STUDENT_NOT_IN_FAILED_LIST");
        }
    }
    /**
     * get student details by studentEmail
     * @param string $emailId
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getStudentDetailsByEmailId($emailId)
    {
        $emailId = $this->realEscapeString($emailId);
        $sql = "SELECT studentID, studentName FROM studentaccount WHERE studentEmail = '$emailId'";
        try {
            $studentDetails = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * Update student password
     * @param int $studentId
     * @param string $password
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     */
    public function updateStudentPassword($studentId, $password)
    {
        $studentId = $this->realEscapeString($studentId);
        $password = $this->realEscapeString($password);
        $sql = "UPDATE studentaccount SET studentPassword = '" . md5($password) . "' WHERE studentID = $studentId";
        try {
            return $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * get student details by admission num
     * @param string $admissionNo
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getStudentDetailsByAdmissionNo($admissionNo)
    {
        $admissionNo = $this->realEscapeString($admissionNo);
        $sql = "SELECT studentID, studentAccount, studentName, isBlockedFromLibrary, libraryBlockReason, sa.batchID, batchName, semID, sa.deptID, dep.deptName, dep.departmentDesc from studentaccount sa inner join batches bat on sa.batchID = bat.batchID  inner join department dep on dep.deptID = sa.deptID WHERE admissionNo = '$admissionNo'";
        try {
            $studentDetails = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * Update student tcIssued
     * @param array $studentIds
     * @param int $value
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     */
    public function updateStudentsTcIssuedByStudentIds($studentIds, $value)
    {
        $studentIds = $this->realEscapeArray($studentIds);
        $value = $this->realEscapeString($value);
        $sql = "UPDATE studentaccount SET tcIssued= $value WHERE studentID in (" . implode(",", $studentIds) . ")";
        try {
            return $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Get all students assigned for a subject
     * @param int $batchId
     * @param int $semId
     * @param int $subjectId
     */
    public function getAllStudentsByBatchIdSemIdSubjectId($batchId, $semId, $subjectId, $sortBy = 'rollNo', $staffId = NULL)
    {
        $batchId = $this->realEscapeString($batchId);
        $semId = $this->realEscapeString($semId);
        $subjectId = $this->realEscapeString($subjectId);
        $sortBy = $this->realEscapeString($sortBy);
        $staffId = $this->realEscapeString($staffId);
        $isCurrentSem = SemesterService::getInstance()->isCurrentSemester($batchId, $semId);
        $subbatches = BatchService::getInstance()->getSubbatchBySubject($subjectId, $semId, $batchId, $staffId);
        if (empty($subbatches)) {
            if ($isCurrentSem) {
                $sql = "select  studentID AS id, studentName AS name, admissionNo AS admissionNumber, rollNo, regNo,null as subbatchID from  studentaccount where batchID=\"" . $batchId . "\" order by $sortBy";
            } else {
                $sql = "select sa.studentID AS id, studentName AS name, admissionNo AS admissionNumber, rollNo, regNo,null as subbatchID from studentaccount sa inner join batches ba on sa.batchID =  ba.batchID where ba.batchID = $batchId  union select sa.studentID AS id, studentName AS name, admissionNo AS admissionNumber, rollNo, regNo,null as subbatchID from failed_students fs left join studentaccount sa on fs.studentID= sa.studentID where previousBatch = $batchId and failedInSemester > $semId order by $sortBy";
            }
        } else {
            $subbatchIdList = array_map(function ($obj) {
                return $obj->subbatchID;
            }, $subbatches);
                if ($isCurrentSem) {
                    $sql = "select distinct sa.studentID AS id, studentName AS name, admissionNo AS admissionNumber, rollNo, regNo,ss.subbatchID from sbs_relation sr inner join subbatch_sbs ssbs on sr.sbsID = ssbs.sbsID inner join subbatch_student ss on ss.subbatchID = ssbs.subbatchID inner join studentaccount sa on sa.studentID = ss.studentID AND sa.batchID=sr.batchID where sr.batchID = $batchId and sr.semID = $semId and subjectID = $subjectId AND ss.subbatchID IN (".implode(', ', $subbatchIdList).") order by $sortBy";
                } else {
                    $sql = "select distinct sa.studentID AS id, studentName AS name, admissionNo AS admissionNumber, rollNo, regNo,ss.subbatchID from sbs_relation sr inner join subbatch_sbs ssbs on sr.sbsID = ssbs.sbsID inner join subbatch_student ss on ss.subbatchID = ssbs.subbatchID inner join studentaccount sa on sa.studentID = ss.studentID where sr.batchID = $batchId and sr.semID = $semId and subjectID = $subjectId and sa.studentID in (select studentID from studentaccount where batchID = $batchId union select studentID from failed_students where previousBatch = $batchId and failedInSemester > $semId) AND ss.subbatchID IN (".implode(', ', $subbatchIdList).") order by $sortBy";
                }
        }
        try {
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /* Update student batchId
     * @param int $studentId
     * @param int $batchId
     * @throws ProfessionalException
     * @return \com\linways\base\dto\MySqlResult
     */
    public function updateStudentBatch($studentId, $batchId)
    {
        $studentId = $this->realEscapeArray($studentId);
        $batchId = $this->realEscapeString($batchId);
        $sql = "update studentaccount set batchID = " . $batchId . " where studentID = " . $studentId . "";
        try {
            return $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * update campus type of batch
     * @param int $batchId
     * @param int $campusTypeId
     * @return object|array|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function updateCampusTypesOfBatch($batchId, $campusTypeId)
    {
        $batchId = $this->realEscapeString($batchId);
        $campusTypeId = $this->realEscapeString($campusTypeId);
        $query = "UPDATE studentaccount SET admissionType='" . $campusTypeId . "' WHERE batchID='" . $batchId . "'";
        try {
            return $this->executeQueryForList($query);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Get students assigned to a pseudo subject
     * @param int $psId
     * @return object|array|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getStudentsAssignedToApseudoSub($psId, $batchId = NULL)
    {
        $psId = $this->realEscapeString($psId);
        $batchId = $this->realEscapeString($batchId);
        $sqlBatch = "";
        if ($batchId)
            $sqlBatch = " and sa.batchID = " . $batchId;
        $sql = "SELECT sa.studentID, studentName, ba.batchID
                FROM pseudosubjects_students pss
                INNER JOIN studentaccount sa ON pss.studentID = sa.studentID
                INNER JOIN batches ba ON ba.batchID = sa.batchID
                INNER JOIN department de ON de.deptID = ba.deptID
                WHERE pss.pseudosubjectID = " . $psId . $sqlBatch . " order by ba.batchID;";
        try {
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Method for getting student details
     * @param int $studentId
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getStudentData($batchId, $semId)
    {
        $sql = '';
        $batchId = $this->realEscapeString($batchId);
        $semId = $this->realEscapeString($semId);
        $studentDetails = [];
        try {
            $sql = "SELECT sa.studentName,sa.regNo,sa.admissionNo FROM studentaccount sa INNER JOIN failed_students fs ON fs.studentID = sa.studentID WHERE fs.previousBatch = $batchId AND fs.failedInSemester = $semId AND fs.isFailNow = 1";
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * Search failed and tc issued students
     * @param SearchFailedStudentRequest $searchFailedStudentRequest
     * @return SearchFailedStudentResponse
     * @throws ProfessionalException
     */
    public function searchFailedStudents($searchFailedStudentRequest)
    {
        $searchFailedStudentRequest = $this->realEscapeObject($searchFailedStudentRequest);
        $studentDetails = new SearchFailedStudentResponse();
        $sql = "SELECT sa.studentID as id, sa.studentName as name, sa.regNo, sa.rollNo,sa.studentGender, sa.admissionNo, dept.deptName, bth.batchName, dept.deptID, bth.batchID, bth.patternID as courseTypeId, bct.type_code as typeCode, bct.type_name as typeName, bth.batchStartYear as startYear, bth.batchEndYear as endYear, dept.departmentDesc, sa.studentAddress, pdc.patterncourseName, student_lock, failedDate, studentEmail, exitType,sa.studentJoindate , sem.semName, CAST(fs.failedDate AS DATE) as stdFailedDate , fs.failedID,stc.issueDate,fs.remarks
        FROM studentaccount sa
        INNER JOIN failed_students fs ON fs.studentID=sa.studentID
        INNER JOIN batches bth ON (bth.batchID=fs.previousBatch)
        INNER JOIN department dept ON dept.deptID=bth.deptID
        INNER JOIN semesters sem ON sem.semID = bth.semID
        LEFT JOIN studentTransferCertificate stc ON stc.studentId = sa.studentID
        LEFT JOIN batch_course_type bct ON bct.id=bth.patternID
        LEFT JOIN pattern_deptcourses pdc ON bth.deptID = pdc.deptID AND bth.patterncourseID = pdc.patterncourseID
        WHERE isFailNow = 1 ";
        $sql_count = "SELECT count(sa.studentID) as totalRecord
            FROM studentaccount sa
            INNER JOIN failed_students fs ON fs.studentID=sa.studentID
            INNER JOIN batches bth ON (bth.batchID=fs.previousBatch)
            INNER JOIN department dept ON dept.deptID=bth.deptID
            INNER JOIN semesters sem ON sem.semID = bth.semID
            LEFT JOIN studentTransferCertificate stc ON stc.studentId = sa.studentID
            LEFT JOIN batch_course_type bct ON bct.id=bth.patternID
            LEFT JOIN pattern_deptcourses pdc ON bth.deptID = pdc.deptID AND bth.patterncourseID = pdc.patterncourseID
            WHERE isFailNow = 1 ";
        if ($searchFailedStudentRequest->name) {
            $sql_cond .= "AND sa.studentName like '%" . $searchFailedStudentRequest->name . "%' ";
        }
        if ($searchFailedStudentRequest->batchId) {
            $sql_cond .= "AND bth.batchID = '" . $searchFailedStudentRequest->batchId . "' ";
        }
        if ($searchFailedStudentRequest->deptId) {
            $sql_cond .= "AND dept.deptID = '" . $searchFailedStudentRequest->deptId . "' ";
        }
        if ($searchFailedStudentRequest->account) {
            $sql_cond .= "AND sa.studentAccount like '%" . $searchFailedStudentRequest->account . "%' ";
        }
        if ($searchFailedStudentRequest->email) {
            $sql_cond .= "AND sa.studentEmail like '%" . $searchFailedStudentRequest->email . "%' ";
        }
        if ($searchFailedStudentRequest->rollNo) {
            $sql_cond .= "AND sa.rollNo like '%" . $searchFailedStudentRequest->rollNo . "%' ";
        }
        if ($searchFailedStudentRequest->admissionNo) {
            $sql_cond .= "AND sa.admissionNo like '%" . $searchFailedStudentRequest->admissionNo . "%' ";
        }
        if ($searchFailedStudentRequest->isFailed) {
            $sql_cond .= "AND fs.isFailNow = '$searchFailedStudentRequest->isFailed";
        }
        if ($searchFailedStudentRequest->sortBy) {
            $sql_cond .= "order by $searchFailedStudentRequest->sortBy $searchFailedStudentRequest->sortOrder ";
        }
        if($searchFailedStudentRequest->previousBatchId){
            $sql_cond .= "AND fs.previousBatch = '$searchFailedStudentRequest->previousBatchId";
        }
        if($searchFailedStudentRequest->regNo){
            $sql_cond .= "AND sa.regNo = '$searchFailedStudentRequest->regNo";
        }
        if($searchFailedStudentRequest->tcIssued){
            $sql_cond .= "AND sa.tcIssued = '$searchFailedStudentRequest->tcIssued";
        }
        if($searchFailedStudentRequest->toDate && $searchFailedStudentRequest->fromDate){
            $sql_cond .= "AND stc.issueDate BETWEEN '$searchFailedStudentRequest->fromDate' AND  '$searchFailedStudentRequest->toDate";
        }
        $sql_count .= $sql_cond;
        $sql_cond .= " GROUP BY sa.studentID ORDER BY FIELD(bth.batchName,'failed') ASC ";
        $studentDetails->totalRecords = $this->executeQueryForObject($sql_count)->totalRecord;
        if ($searchFailedStudentRequest->export) {
            $searchFailedStudentRequest->endIndex = $studentDetails->totalRecords;
        }
        $sql .= $sql_cond;
        if($searchFailedStudentRequest->startIndex != ''){
            $sql .= "LIMIT $searchFailedStudentRequest->startIndex,$searchFailedStudentRequest->endIndex";
        }
        try {
            $studentDetails->students = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * Method for getting current studying or All students for a batch
     * @param unknown $batchId
     * @param unknown $allStudents
     * @return objectList[]
     * @throws ProfessionalException
     * @author Vishnu M
     */
    public function getStudentDetails($batchId, $allStudents = false)
    {
        $sql = '';
        $batchId = $this->realEscapeString($batchId);
        $studentDetails = [];
        $sql = "SELECT sa.studentID AS studentId, 
                        sa.myImage,
                        sa.studentSignImage,
                        sa.admissionNo,
                        sl.secondLangaugeName AS secondLanguageName,
                        sa.rollNo,
                        sa.studentName,
                        sa.studentGender,
                        rs.reservationName,
                        sa.studentBirthday AS dateOfBirth,
                        sa.studentJoindate AS studentJoinDate,
                        sa.regNo,
                        sca.casteName,
                        re.religionName,
                        aq.quotaCode,
                        sa.aadhaar_no,
                        sa.studentFather,
                        se.annualIncome,
                        se.parentOccupation,
                        sa.parentPhone,
                        sa.studentMother,
                        se.motherOccupation,
                        se.motherIncome,
                        se.commuhouse,
                        se.currentAddress1,
                        se.currentAddress2,
                        se.currentState,
                        se.currentCity,
                        se.currentCountry,
                        se.currentZipCode, sa.previousSchool, sa.yearOfPassing, bt.batchName, sr.reservName as seatReservName, ct.is_pg, se.motherPhone FROM studentaccount sa INNER JOIN batches bt ON bt.batchID=sa.batchID LEFT JOIN batch_course_type ct ON ct.id=bt.patternID LEFT JOIN secondLangauge sl ON sa.secondlangaugeID = sl.secondlangaugeID LEFT JOIN reservation_students rs ON rs.reservationID = sa.reservationID LEFT JOIN student_caste sca on sa.casteID = sca.casteID LEFT JOIN religion re ON sa.religion = re.religionID LEFT JOIN admission_quotas aq ON sa.quotaID = aq.quotaID LEFT JOIN student_reservation sr ON sr.reservID=sa.reservID LEFT JOIN studentaccount_extras se ON se.studentID=sa.studentID WHERE sa.batchID = $batchId";
        $sqlCond = " AND sa.studentID NOT IN (SELECT studentId FROM studentTransferCertificate) AND sa.studentID NOT IN (SELECT studentID FROM failed_students where isFailNow = 1)";
        $sqlTail = " ORDER BY sa.rollNo, sa.regNo ASC";
        $sql .= $allStudents ? "" : $sqlCond;
        $sql .= $sqlTail;
        try {
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    public function getStudentsByBatch($batchID)
    {
        $sql = "";
        $studentArray = [];
        $batchID = $this->realEscapeString($batchID);
        try {
            $sql = "SELECT sa.studentID, 
            sa.studentName, 
            sa.rollNo, 
            sa.regNo, 
            sa.admissionNo ,
            sa.myImage ,
            sa.studentSignImage ,
            b.batchName ,
            b.batchID
                from  studentaccount sa
                    inner join batches b 
                    on b.batchID = sa.batchID  
            where sa.batchID IN ($batchID) order by rollNo";
            $studentArray = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentArray;
    }
    /**
     * Method for verifying all students
     * @param batchId
     * @throws ProfessionalException
     *
     * @author Kishan Suresh
     */
    public function verifyAllStudentsByBatchId($batchId)
    {
        $sql = '';
        $batchId = $this->realEscapeString($batchId);
        try {
            $sql = "update studentaccount set studentVerified = 1 where batchID = '$batchId'";
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Method for unverifying all students
     * @param batchId
     * @throws ProfessionalException
     *
     * @author Kishan Suresh
     */
    public function unVerifyAllStudentsByBatchId($batchId)
    {
        $sql = '';
        $batchId = $this->realEscapeString($batchId);
        try {
            $sql = "update studentaccount set studentVerified = 0 where batchID = '$batchId'";
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * block and unblock students by batch
     * @param  $block
     * @param  $batchID
     * @return string
     * @throws ProfessionalException
     * @author Aswin
     */
    public function blockStudentByBatch($block, $batchID)
    {
        $batchID = $this->realEscapeString($batchID);
        $block = $this->realEscapeString($block);
        $query = "update studentaccount set student_lock=$block where batchID=$batchID";
        try {
            $response = $this->executeQuery($query);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return "success";
    }
    /**
     * Method for getting full students (current students and failed students)
     * @input $batchId
     * @author Ranjith Balachandran
     */
    public function getFullStudentList($batchId)
    {
        $sql = '';
        $fullStudentsList = [];
        $sql = "SELECT sa.studentID as studentId,sa.studentName as studentName,sa.regNo as regNo,sa.admissionNo as admissionNo, sa.phdTopicName, sa.phdCurrentStatus, sa.guideId FROM studentaccount sa WHERE sa.batchID = $batchId UNION SELECT sa.studentID as studentId, sa.studentName as studentName,sa.regNo as regNo,sa.admissionNo as admissionNo, sa.phdTopicName, sa.phdCurrentStatus, sa.guideId FROM failed_students fs INNER JOIN studentaccount sa ON sa.studentID = fs.studentID WHERE fs.previousBatch = $batchId order by regNo";
        try {
            $fullStudentsList = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $fullStudentsList;
    }
    /**
     * @param supplyExamId, studentId
     * Mthod for updating phd student details
     * @author Ranjith
     */
    public function updatePhdStudentDetails($guideId, $topicName, $currentStatus, $studentId)
    {
        $sql = "";
        $guideId = $this->realEscapeString($guideId);
        $topicName = $this->realEscapeString($topicName);
        $currentStatus = $this->realEscapeString($currentStatus);
        $studentId = $this->realEscapeString($studentId);
        try {
            $sql = "UPDATE studentaccount SET phdTopicName = '$topicName', phdCurrentStatus = '$currentStatus' , guideId = $guideId WHERE studentID = $studentId";
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Method for checking whether this student has applied for open course
     * @param int $studentId
     * @param int $openCourseId
     * @return unknown
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getStudentOpenCourseDetails($studentId, $openCourseId)
    {
        $sql = '';
        $studentId = $this->realEscapeString($studentId);
        $openCourseId = $this->realEscapeString($openCourseId);
        $studentOpenCourseDetails = null;
        try {
            $sql = "SELECT osa.studentaccounts_id AS studentId FROM opencourse_student_appln osa WHERE osa.studentaccounts_id = $studentId AND osa.opencourse_appln_initiate_id = $openCourseId";
            $studentOpenCourseDetails = $this->executeQueryForObject($sql)->studentId;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentOpenCourseDetails;
    }
    /**
     * get count of subbatch students by subbatchid
     * @param int $subbatchId
     * @return int
     * @throws ProfessionalException
     */
    public function getStudentsCountBySubbatchId($subbatchId)
    {
        $sql = "SELECT count(studentID) as studentCount from subbatch_student WHERE subbatchID=$subbatchId";
        try {
            return $this->executeQueryForObject($sql)->studentCount;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function updateStudentDetails($columnsAndValues, $studentId)
    {
        //give cloumns  as key and value
        $columnsAndValues = $this->realEscapeArray($columnsAndValues);
        $studentId = $this->realEscapeString($studentId);
        $updateColumns = "";
        if (empty($columnsAndValues))
            throw new ProfessionalException(ProfessionalException::ARRAY_EMPTY, "Please provide atleast one update column");
        foreach ($columnsAndValues as $column => $data) {
            $updateColumns .= $column .= "=" . "'" . $data . "'" . ",";
        }
        $updateColumns = rtrim($updateColumns, ",");
        $query = "UPDATE studentaccount SET " . $updateColumns . " WHERE studentID=$studentId";
        try {
            $this->executeQuery($query);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Method for getting coaching types
     * @return object|array|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getCoachingTypes()
    {
        $response = null;
        $sql = "SELECT id, typeName, createdBy, createdDate, updatedBy, updatedDate FROM coachingTypes ORDER BY id DESC";
        try {
            $response = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        if (count($response)) {
            return $response;
        } else {
            return 0;
        }
    }
    /**
     * Method for getting coaching types
     * @return object|array|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getScholarshipTypes()
    {
        $response = null;
        $sql = "SELECT id, typeName, createdBy, createdDate, updatedBy, updatedDate FROM scholarshipTypes ORDER BY id DESC";
        try {
            $response = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        if (count($response)) {
            return $response;
        } else {
            return 0;
        }
    }
    /**
     *
     * Method for inserting student data from excel
     * @param StudentDataExcelImport $excelData
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function insertStudentDataFromExcel($excelData, $headingArr)
    {
        $excelData = $this->realEscapeObject($excelData);
        $headingArr = $this->realEscapeArray($headingArr);
        $error_arr = array();
        $updateConditions = '';
        $insertFields = null;
        $insertValues = null;
        //$response = null;
        /* getting foreign key ids starts **/
        $departmentDetails = StudentService::getInstance()->getDepartmentByName($excelData->deptName);
        $batchDetails = StudentService::getInstance()->getBatchByName($excelData->batchName);
        $nationalityDetails = StudentService::getInstance()->getNationalityByName($excelData->nationality);
        $secondLanguageDetails = StudentService::getInstance()->getsecondLangaugeByName($excelData->secondLangaugeName);
        $religionDetails = StudentService::getInstance()->getReligionByName($excelData->religionName);
        $studentReservationDetails = StudentService::getInstance()->getStudentReservationByName($excelData->reservationName);
        $studentCasteDetails = StudentService::getInstance()->getStudentCasteByName($excelData->casteName);
        $studentSeatReservationDetails = StudentService::getInstance()->getStudentSeatReservationByName($excelData->reservName);
        $studentFeeCategoryDetails = StudentService::getInstance()->getStudentFeeCategoryByName($excelData->categoryName);
        $studentSubCasteDetails = StudentService::getInstance()->getStudentSubCasteByName($excelData->subcaste_name);
        $studentQuotaDetails = StudentService::getInstance()->getStudentQuotaByName($excelData->quotaName);
        $studentPovertyLineDetails = StudentService::getInstance()->getStudentPovertyLineByName($excelData->poverty_line);
        $studentDistrictDetails = StudentService::getInstance()->getStudentDistrictByName($excelData->districtName);
        $studentStateDetails = StudentService::getInstance()->getStudentStateByName($excelData->state_name);
        $studentTalukDetails = StudentService::getInstance()->getStudentTalukByName($excelData->talukName);
        /** Phd Details starts **/
        $coachingTypeDetails = StudentService::getInstance()->getCoachingTypeByName($excelData->coachingTypeName);
        $scholarshipTypeDetails = StudentService::getInstance()->getScholarshipTypeByName($excelData->typeName);
        $guideDetails = StudentService::getInstance()->getStaffDetailsByName($excelData->guideName);
        $coGuideDetails = StudentService::getInstance()->getStaffDetailsByName($excelData->coGuideName);
        /** Phd Details ends **/
        /* getting foreign key ids ends **/
        if (!in_array('admissionNo', $headingArr)) {
            array_push($error_arr, "AdmissionNo is mandatory while uploading student data");
            return $error_arr;
        }
        if (!in_array('batchName', $headingArr) || (!$batchDetails)) {
            array_push($error_arr, "Batch is mandatory while uploading student data");
            return $error_arr;
        }
        try {
            $sql = "SELECT studentID AS studentId FROM studentaccount WHERE admissionNo = '$excelData->admissionNo'";
            $studentPresent = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        if (in_array('studentName', $headingArr)) {
            if ($excelData->studentName) {
                $insertFields .= ',studentName';
                $insertValues .= ",'" . $excelData->studentName . "'";
                $updateConditions .= "studentName = '$excelData->studentName',";
            }
        }
        if (in_array('studentEmail', $headingArr)) {
            if ($excelData->studentEmail) {
                $insertFields .= ',studentEmail';
                $insertValues .= ",'" . $excelData->studentEmail . "'";
                $updateConditions .= "studentEmail = '$excelData->studentEmail',";
            }
        }
        if (in_array('studentGender', $headingArr)) {
            if ($excelData->studentGender) {
                $insertFields .= ',studentGender';
                $insertValues .= ",'" . $excelData->studentGender . "'";
                $updateConditions .= "studentGender = LOWER('$excelData->studentGender'),";
            }
        }
        if (in_array('studentBirthday', $headingArr)) {
            if ($excelData->studentBirthday) {
                $insertFields .= ',studentBirthday';
                $insertValues .= ",'" . $excelData->studentBirthday . "'";
                $updateConditions .= "studentBirthday = '$excelData->studentBirthday',";
            }
        }
        if (in_array('studentAddress', $headingArr)) {
            if ($excelData->studentAddress) {
                $insertFields .= ',studentAddress';
                $insertValues .= ",'" . $excelData->studentAddress . "'";
                $updateConditions .= "studentAddress = '$excelData->studentAddress',";
            }
        }
        if (in_array('studentPhone', $headingArr)) {
            if ($excelData->studentPhone) {
                $insertFields .= ',studentPhone';
                $insertValues .= ",'" . $excelData->studentPhone . "'";
                $updateConditions .= "studentPhone = '$excelData->studentPhone',";
            }
        }
        if (in_array('bloodGroup', $headingArr)) {
            if ($excelData->bloodGroup) {
                $insertFields .= ',bloodGroup';
                $insertValues .= ",'" . $excelData->bloodGroup . "'";
                $updateConditions .= "bloodGroup = '$excelData->bloodGroup',";
            }
        }
        if (in_array('admissionType', $headingArr)) {
            if ($excelData->admissionType) {
                $insertFields .= ',admissionType';
                $insertValues .= ",'" . $excelData->admissionType . "'";
                $updateConditions .= "admissionType = '$excelData->admissionType',";
            }
        }
        if (in_array('admissionNo', $headingArr)) {
            if ($excelData->admissionNo) {
                $insertFields .= ',admissionNo';
                $insertValues .= ",'" . $excelData->admissionNo . "'";
                $updateConditions .= "admissionNo = '$excelData->admissionNo',";
            }
        }
        if (in_array('rollNo', $headingArr)) {
            if ($excelData->rollNo) {
                $insertFields .= ',rollNo';
                $insertValues .= ",'" . $excelData->rollNo . "'";
                $updateConditions .= "rollNo = '$excelData->rollNo',";
            }
        }
        if (in_array('studentSurname', $headingArr)) {
            if ($excelData->studentSurname) {
                $insertFields .= ',studentSurname';
                $insertValues .= ",'" . $excelData->studentSurname . "'";
                $updateConditions .= "studentSurname = '$excelData->studentSurname',";
            }
        }
        if (in_array('studentFather', $headingArr)) {
            if ($excelData->studentFather) {
                $insertFields .= ',studentFather';
                $insertValues .= ",'" . $excelData->studentFather . "'";
                $updateConditions .= "studentFather = '$excelData->studentFather',";
            }
        }
        if (in_array('studentMother', $headingArr)) {
            if ($excelData->studentMother) {
                $insertFields .= ',studentMother';
                $insertValues .= ",'" . $excelData->studentMother . "'";
                $updateConditions .= "studentMother = '$excelData->studentMother',";
            }
        }
        if (in_array('studentJoindate', $headingArr)) {
            if ($excelData->studentJoindate) {
                $insertFields .= ',studentJoindate';
                $insertValues .= ",'" . $excelData->studentJoindate . "'";
                $updateConditions .= "studentJoindate = '$excelData->studentJoindate',";
            }
        }
        if (in_array('sslc', $headingArr)) {
            if ($excelData->sslc) {
                $insertFields .= ',sslc';
                $insertValues .= ",'" . $excelData->sslc . "'";
                $updateConditions .= "sslc = '$excelData->sslc',";
            }
        }
        if (in_array('plustwo', $headingArr)) {
            if ($excelData->plustwo) {
                $insertFields .= ',plustwo';
                $insertValues .= ",'" . $excelData->plustwo . "'";
                $updateConditions .= "plustwo = '$excelData->plustwo',";
            }
        }
        if (in_array('parentPhone', $headingArr)) {
            if ($excelData->parentPhone) {
                $insertFields .= ',parentPhone';
                $insertValues .= ",'" . $excelData->parentPhone . "'";
                $updateConditions .= "parentPhone = '$excelData->parentPhone',";
            }
        }
        if (in_array('regNo', $headingArr)) {
            if ($excelData->regNo) {
                $insertFields .= ',regNo';
                $insertValues .= ",'" . $excelData->regNo . "'";
                $updateConditions .= "regNo = '$excelData->regNo',";
            }
        }
        if (in_array('feewaiverScheme', $headingArr)) {
            if ($excelData->feewaiverScheme) {
                $insertFields .= ',feewaiverScheme';
                $insertValues .= ",'" . $excelData->feewaiverScheme . "'";
                $updateConditions .= "feewaiverScheme = '$excelData->feewaiverScheme',";
            }
        }
        if (in_array('studentLastName', $headingArr)) {
            if ($excelData->studentLastName) {
                $insertFields .= ',studentLastName';
                $insertValues .= ",'" . $excelData->studentLastName . "'";
                $updateConditions .= "studentLastName = '$excelData->studentLastName',";
            }
        }
        if (in_array('previousSchool', $headingArr)) {
            if ($excelData->previousSchool) {
                $insertFields .= ',previousSchool';
                $insertValues .= ",'" . $excelData->previousSchool . "'";
                $updateConditions .= "previousSchool = '$excelData->previousSchool',";
            }
        }
        if (in_array('parentOccupation', $headingArr)) {
            if ($excelData->parentOccupation) {
                $insertFields .= ',parentOccupation';
                $insertValues .= ",'" . $excelData->parentOccupation . "'";
                $updateConditions .= "parentOccupation = '$excelData->parentOccupation',";
            }
        }
        if (in_array('annualIncome', $headingArr)) {
            if ($excelData->annualIncome) {
                $insertFields .= ',annualIncome';
                $insertValues .= ",'" . $excelData->annualIncome . "'";
                $updateConditions .= "annualIncome = '$excelData->annualIncome',";
            }
        }
        if (in_array('aadhaar_no', $headingArr)) {
            if ($excelData->aadhaar_no) {
                $insertFields .= ',aadhaar_no';
                $insertValues .= ",'" . $excelData->aadhaar_no . "'";
                $updateConditions .= "aadhaar_no = '$excelData->aadhaar_no',";
            }
        }
        if (in_array('phdTopicName', $headingArr)) {
            if ($excelData->phdTopicName) {
                $insertFields .= ',phdTopicName';
                $insertValues .= ",'" . $excelData->phdTopicName . "'";
                $updateConditions .= "phdTopicName = '$excelData->phdTopicName',";
            }
        }
        if (in_array('phdCurrentStatus', $headingArr)) {
            if ($excelData->phdCurrentStatus) {
                $insertFields .= ',phdCurrentStatus';
                $insertValues .= ",'" . $excelData->phdCurrentStatus . "'";
                $updateConditions .= "phdCurrentStatus = '$excelData->phdCurrentStatus',";
            }
        }
        if (in_array('dateOfPhdRegistration', $headingArr)) {
            if ($excelData->dateOfPhdRegistration) {
                $insertFields .= ',dateOfPhdRegistration';
                $insertValues .= ",'" . $excelData->dateOfPhdRegistration . "'";
                $updateConditions .= "dateOfPhdRegistration = '$excelData->dateOfPhdRegistration',";
            }
        }
        if (in_array('phdAwardedDate', $headingArr)) {
            if ($excelData->phdAwardedDate) {
                $insertFields .= ',phdAwardedDate';
                $insertValues .= ",'" . $excelData->phdAwardedDate . "'";
                $updateConditions .= "phdAwardedDate = '$excelData->phdAwardedDate',";
            }
        }
        if (in_array('entranceQualifiedForPhD', $headingArr)) {
            if ($excelData->entranceQualifiedForPhD) {
                $insertFields .= ',entranceQualifiedForPhD';
                $insertValues .= ",'" . $excelData->entranceQualifiedForPhD . "'";
                $updateConditions .= "entranceQualifiedForPhD = '$excelData->entranceQualifiedForPhD',";
            }
        }
        if (in_array('SRFupgradationDate', $headingArr)) {
            if ($excelData->SRFupgradationDate) {
                $insertFields .= ',SRFupgradationDate';
                $insertValues .= ",'" . $excelData->SRFupgradationDate . "'";
                $updateConditions .= "SRFupgradationDate = '$excelData->SRFupgradationDate',";
            }
        }
        if (in_array('phdRegistrationType', $headingArr)) {
            if ($excelData->phdRegistrationType) {
                $insertFields .= ',phdRegistrationType';
                $insertValues .= ",'" . $excelData->phdRegistrationType . "'";
                $updateConditions .= "phdRegistrationType = '$excelData->phdRegistrationType',";
            }
        }
        if (in_array('phdRegistrationOrderNo', $headingArr)) {
            if ($excelData->phdRegistrationOrderNo) {
                $insertFields .= ',phdRegistrationOrderNo';
                $insertValues .= ",'" . $excelData->phdRegistrationOrderNo . "'";
                $updateConditions .= "phdRegistrationOrderNo = '$excelData->phdRegistrationOrderNo',";
            }
        }
        if (in_array('phdRegistrationOrderDate', $headingArr)) {
            if ($excelData->phdRegistrationOrderDate) {
                $insertFields .= ',phdRegistrationOrderDate';
                $insertValues .= ",'" . $excelData->phdRegistrationOrderDate . "'";
                $updateConditions .= "phdRegistrationOrderDate = '$excelData->phdRegistrationOrderDate',";
            }
        }
        if (in_array('batchName', $headingArr)) {
            if ($excelData->batchName) {
                if (!$batchDetails) {
                    array_push($error_arr, "Batch Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',batchID';
                    $insertValues .= ",'" . $batchDetails->batchID . "'";
                    $updateConditions .= "batchID = '$batchDetails->batchID',";
                }
            }
        }
        if (in_array('deptName', $headingArr)) {
            if ($excelData->deptName) {
                if (!$departmentDetails) {
                    array_push($error_arr, "Department Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',deptID';
                    $insertValues .= ",'" . $departmentDetails->deptID . "'";
                    $updateConditions .= "deptID = '$departmentDetails->deptID',";
                }
            }
        } else {
            $insertFields .= ',deptID';
            $insertValues .= ",'" . $batchDetails->deptID . "'";
            $updateConditions .= "deptID = '$batchDetails->deptID',";
        }
        if (in_array('nationality', $headingArr)) {
            if ($excelData->nationality) {
                if (!$nationalityDetails) {
                    array_push($error_arr, "Nationality Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',nationality_id';
                    $insertValues .= ",'" . $nationalityDetails->id . "'";
                    $updateConditions .= "nationality_id = '$nationalityDetails->id',";
                }
            }
        }
        if (in_array('secondLangaugeName', $headingArr)) {
            if ($excelData->secondLangaugeName) {
                if (!$secondLanguageDetails) {
                    array_push($error_arr, "Second Language Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',secondlangaugeID';
                    $insertValues .= ",'" . $secondLanguageDetails->secondlangaugeID . "'";
                    $updateConditions .= "secondlangaugeID = '$secondLanguageDetails->secondlangaugeID',";
                }
            }
        }
        if (in_array('religionName', $headingArr)) {
            if ($excelData->religionName) {
                if (!$religionDetails) {
                    array_push($error_arr, "Religion Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',religion';
                    $insertValues .= ",'" . $religionDetails->religionID . "'";
                    $updateConditions .= "religion = '$religionDetails->religionID',";
                }
            }
        }
        if (in_array('reservationName', $headingArr)) {
            if ($excelData->reservationName) {
                if (!$studentReservationDetails) {
                    array_push($error_arr, "Student Reservation Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',reservationID';
                    $insertValues .= ",'" . $studentReservationDetails->reservationID . "'";
                    $updateConditions .= "reservationID = '$studentReservationDetails->reservationID',";
                }
            }
        }
        if (in_array('casteName', $headingArr)) {
            if ($excelData->casteName) {
                if (!$studentCasteDetails) {
                    array_push($error_arr, "Caste Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',casteID';
                    $insertValues .= ",'" . $studentCasteDetails->casteID . "'";
                    $updateConditions .= "casteID = '$studentCasteDetails->casteID',";
                }
            }
        }
        if (in_array('reservName', $headingArr)) {
            if ($excelData->reservName) {
                if (!$studentSeatReservationDetails) {
                    array_push($error_arr, "Seat Reservation Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',reservID';
                    $insertValues .= ",'" . $studentSeatReservationDetails->reservID . "'";
                    $updateConditions .= "reservID = '$studentSeatReservationDetails->reservID',";
                }
            }
        }
        if (in_array('categoryName', $headingArr)) {
            if ($excelData->categoryName) {
                if (!$studentFeeCategoryDetails) {
                    array_push($error_arr, "Fee Category Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',application_fee_category_id';
                    $insertValues .= ",'" . $studentFeeCategoryDetails->id . "'";
                    $updateConditions .= "application_fee_category_id = '$studentFeeCategoryDetails->id',";
                }
            }
        }
        if (in_array('subcaste_name', $headingArr)) {
            if ($excelData->subcaste_name) {
                if (!$studentSubCasteDetails) {
                    array_push($error_arr, "Sub Caste Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',student_subcaste_id';
                    $insertValues .= ",'" . $studentSubCasteDetails->id . "'";
                    $updateConditions .= "student_subcaste_id = '$studentSubCasteDetails->id',";
                }
            }
        }
        if (in_array('quotaName', $headingArr)) {
            if ($excelData->quotaName) {
                if (!$studentQuotaDetails) {
                    array_push($error_arr, "Quota Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',quotaID';
                    $insertValues .= ",'" . $studentQuotaDetails->quotaID . "'";
                    $updateConditions .= "quotaID = '$studentQuotaDetails->quotaID',";
                }
            }
        }
        if (in_array('poverty_line', $headingArr)) {
            if ($excelData->poverty_line) {
                if (!$studentPovertyLineDetails) {
                    array_push($error_arr, "PovertyLine Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',poverty_line';
                    $insertValues .= ",'" . $studentPovertyLineDetails->id . "'";
                    $updateConditions .= "poverty_line = '$studentPovertyLineDetails->id',";
                }
            }
        }
        if (in_array('districtName', $headingArr)) {
            if ($excelData->districtName) {
                if (!$studentDistrictDetails) {
                    array_push($error_arr, "District Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',district_id';
                    $insertValues .= ",'" . $studentDistrictDetails->id . "'";
                    $updateConditions .= "district_id = '$studentDistrictDetails->id',";
                }
            }
        }
        if (in_array('state_name', $headingArr)) {
            if ($excelData->state_name) {
                if (!$studentStateDetails) {
                    array_push($error_arr, "State Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',state_id';
                    $insertValues .= ",'" . $studentStateDetails->id . "'";
                    $updateConditions .= "state_id = '$studentStateDetails->id',";
                }
            }
        }
        if (in_array('talukName', $headingArr)) {
            if ($excelData->talukName) {
                if (!$studentTalukDetails) {
                    array_push($error_arr, "Taluk Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',taluk_id';
                    $insertValues .= ",'" . $studentTalukDetails->id . "'";
                    $updateConditions .= "taluk_id = '$studentTalukDetails->id',";
                }
            }
        }
        if (in_array('guideName', $headingArr)) {
            if ($excelData->guideName) {
                if (!$guideDetails) {
                    array_push($error_arr, "Guide Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',guideId';
                    $insertValues .= ",'" . $guideDetails->staffID . "'";
                    $updateConditions .= "guideId = '$guideDetails->staffID',";
                }
            }
        }
        if (in_array('coGuideName', $headingArr)) {
            if ($excelData->coGuideName) {
                if (!$coGuideDetails) {
                    array_push($error_arr, "Co-guide Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',coGuideId';
                    $insertValues .= ",'" . $coGuideDetails->staffID . "'";
                    $updateConditions .= "coGuideId = '$coGuideDetails->staffID',";
                }
            }
        }
        if (in_array('coachingTypeName', $headingArr)) {
            if ($excelData->coachingTypeName) {
                if (!$coachingTypeDetails) {
                    array_push($error_arr, "Coaching Type Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',coachingTypes_id';
                    $insertValues .= ",'" . $coachingTypeDetails->id . "'";
                    $updateConditions .= "coachingTypes_id = '$coachingTypeDetails->id',";
                }
            }
        }
        if (in_array('typeName', $headingArr)) {
            if ($excelData->typeName) {
                if (!$scholarshipTypeDetails) {
                    array_push($error_arr, "Scholarship Type Details is invalid or not found for Admission No $excelData->admissionNo");
                } else {
                    $insertFields .= ',scholarshipTypes_id';
                    $insertValues .= ",'" . $scholarshipTypeDetails->id . "'";
                    $updateConditions .= "scholarshipTypes_id = '$scholarshipTypeDetails->id',";
                }
            }
        }
        if ($studentPresent) {
            $updateConditions = rtrim($updateConditions, ",");
            if ($excelData->admissionNo) {
                try {
                    $sql = "UPDATE studentaccount SET " . $updateConditions . " WHERE studentAccount = '$excelData->admissionNo'";
                    if (empty($error_arr)) {
                        $this->executeQuery($sql);
                    }
                } catch (\Exception $e) {
                    throw new ProfessionalException($e->getCode(), $e->getMessage(), $error_arr);
                }
            } else {
                array_push($error_arr, "AdmissionNo is mandatory while uploading student data");
            }
        } else {
            if ($excelData->admissionNo) {
                try {
                    $sql = "INSERT INTO studentaccount (studentAccount,studentPassword $insertFields) VALUES ('" . $excelData->admissionNo . "', md5('" . $excelData->admissionNo . "') $insertValues)";
                    if (empty($error_arr)) {
                        $this->executeQuery($sql);
                    }
                } catch (\Exception $e) {
                    throw new ProfessionalException($e->getCode(), $e->getMessage(), $error_arr);
                }
            } else {
                array_push($error_arr, "AdmissionNo is mandatory while uploading student data");
            }
        }
        return $error_arr;
    }
    /**
     * Method for getting departmentId by name
     * @param unknown $deptName
     * @return unknown
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getDepartmentByName($deptName)
    {
        $sql = '';
        $deptName = $this->realEscapeString($deptName);
        $departmentId = null;
        try {
            $sql = "SELECT deptID FROM department WHERE deptName = '$deptName'";
            $departmentId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $departmentId;
    }
    /**
     * Method for getting batchId by name
     * @param unknown $batchName
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getBatchByName($batchName)
    {
        $sql = '';
        $batchName = $this->realEscapeString($batchName);
        $batchId = null;
        try {
            $sql = "SELECT batchID,deptID,semID FROM batches WHERE batchName = '$batchName'";
            $batchId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $batchId;
    }
    /**
     * Method for getting nationalityId by name
     * @param unknown $nationalityName
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getNationalityByName($nationalityName)
    {
        $sql = '';
        $nationalityName = $this->realEscapeString($nationalityName);
        $nationalityId = null;
        try {
            $sql = "SELECT id FROM nationality WHERE nationalityName = '$nationalityName'";
            $nationalityId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $nationalityId;
    }
    /**
     * Method for getting secondLanguageId by name
     * @param unknown $secondLangaugeName
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getsecondLangaugeByName($secondLangaugeName)
    {
        $sql = '';
        $secondLangaugeName = $this->realEscapeString($secondLangaugeName);
        $secondLangaugeId = null;
        try {
            $sql = "SELECT secondlangaugeID FROM secondLangauge WHERE secondLangaugeName = '$secondLangaugeName'";
            $secondLangaugeId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $secondLangaugeId;
    }
    /**
     * Method for getting religionId by name
     * @param unknown $religionName
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getReligionByName($religionName)
    {
        $sql = '';
        $religionName = $this->realEscapeString($religionName);
        $religionId = null;
        try {
            $sql = "SELECT religionID FROM religion WHERE religionName = '$religionName'";
            $religionId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $religionId;
    }
    /**
     * Method for getting student reservation Id by name
     * @param unknown $reservationName
     * @return unknown
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getStudentReservationByName($reservationName)
    {
        $sql = '';
        $reservationName = $this->realEscapeString($reservationName);
        $studentReservationId = null;
        try {
            $sql = "SELECT reservationID FROM reservation_students WHERE reservationName = '$reservationName'";
            $studentReservationId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentReservationId;
    }
    /**
     * Method for getting student casteId by name
     * @param unknown $casteName
     * @return unknown
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getStudentCasteByName($casteName)
    {
        $sql = '';
        $casteName = $this->realEscapeString($casteName);
        $casteId = null;
        try {
            $sql = "SELECT casteID FROM student_caste WHERE casteName = '$casteName'";
            $casteId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $casteId;
    }
    /**
     * Method for getting student seat reservation Id by name
     * @param unknown $reservName
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getStudentSeatReservationByName($reservName)
    {
        $sql = '';
        $reservName = $this->realEscapeString($reservName);
        $seatReservationId = null;
        try {
            $sql = "SELECT reservID FROM student_reservation WHERE reservName = '$reservName'";
            $seatReservationId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $seatReservationId;
    }
    /**
     * Method for getting student fee category Id by name
     * @param unknown $categoryName
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getStudentFeeCategoryByName($categoryName)
    {
        $sql = '';
        $categoryName = $this->realEscapeString($categoryName);
        $feeCategoryId = null;
        try {
            $sql = "SELECT id FROM application_fee_category WHERE categoryName = '$categoryName'";
            $feeCategoryId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $feeCategoryId;
    }
    /**
     * Method for getting student sub caste id by name
     * @param unknown $subCasteName
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getStudentSubCasteByName($subCasteName)
    {
        $sql = '';
        $subCasteName = $this->realEscapeString($subCasteName);
        $subCasteId = null;
        try {
            $sql = "SELECT id FROM student_subcaste WHERE subcaste_name = '$subCasteName'";
            $subCasteId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $subCasteId;
    }
    /**
     * Method for getting student admission quota Id by name
     * @param unknown $quotaName
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getStudentQuotaByName($quotaName)
    {
        $sql = '';
        $quotaName = $this->realEscapeString($quotaName);
        $quotaId = null;
        try {
            $sql = "SELECT quotaID FROM admission_quotas WHERE quotaName = '$quotaName'";
            $quotaId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $quotaId;
    }
    /**
     * Method for getting student poverty line Id by name
     * @param unknown $povertyLine
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getStudentPovertyLineByName($povertyLine)
    {
        $sql = '';
        $povertyLine = $this->realEscapeString($povertyLine);
        $povertyLineId = null;
        try {
            $sql = "SELECT id FROM poverty_line WHERE poverty_line = '$povertyLine'";
            $povertyLineId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $povertyLineId;
    }
    /**
     * Method for getting student district Id by name
     * @param unknown $districtName
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getStudentDistrictByName($districtName)
    {
        $sql = '';
        $districtName = $this->realEscapeString($districtName);
        $districtId = null;
        try {
            $sql = "SELECT id FROM districts WHERE districtName = '$districtName'";
            $districtId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $districtId;
    }
    /**
     * Method for getting student state Id by name
     * @param unknown $stateName
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getStudentStateByName($stateName)
    {
        $sql = '';
        $stateName = $this->realEscapeString($stateName);
        $stateId = null;
        try {
            $sql = "SELECT id FROM admission_indian_states WHERE state_name = '$stateName'";
            $stateId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $stateId;
    }
    /***
     * Method for getting student taluk Id by name
     * @param unknown $talukName
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getStudentTalukByName($talukName)
    {
        $sql = '';
        $talukName = $this->realEscapeString($talukName);
        $talukId = null;
        try {
            $sql = "SELECT id FROM taluks WHERE talukName = '$talukName'";
            $talukId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $talukId;
    }
    /***
     * Method for getting phd student coaching type Id by name
     * @param unknown $coachingTypeName
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getCoachingTypeByName($coachingTypeName)
    {
        $sql = '';
        $coachingTypeName = $this->realEscapeString($coachingTypeName);
        $coachingTypeId = null;
        try {
            $sql = "SELECT id FROM coachingTypes WHERE typeName = '$coachingTypeName'";
            $coachingTypeId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $coachingTypeId;
    }
    /***
     * Method for getting phd student scholarship type Id by name
     * @param unknown $scholarshipTypeName
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getScholarshipTypeByName($scholarshipTypeName)
    {
        $sql = '';
        $scholarshipTypeName = $this->realEscapeString($scholarshipTypeName);
        $scholarshipTypeId = null;
        try {
            $sql = "SELECT id FROM scholarshipTypes WHERE typeName = '$scholarshipTypeName'";
            $scholarshipTypeId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $scholarshipTypeId;
    }
    /***
     * Method for getting guide staffId by name
     * @param unknown $staffName
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getStaffDetailsByName($staffName)
    {
        $sql = '';
        $staffName = $this->realEscapeString($staffName);
        $staffId = null;
        try {
            $sql = "SELECT staffID FROM staffaccounts WHERE staffName = '$staffName'";
            $staffId = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $staffId;
    }
    /**
     * Method for updating payment status in dynamic form online payment
     * @param unknown $studentId
     * @param unknown $applnId
     * @param unknown $mainId
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function approveStudentPaymentStatus($studentId, $applnId, $mainId)
    {
        $sql = '';
        $studentId = $this->realEscapeString($studentId);
        $applnId = $this->realEscapeString($applnId);
        $mainId = $this->realEscapeString($mainId);
        try {
            $sql = "UPDATE applnform_online_payment SET status = 'success' , transactionDate = '" . date("Y-m-d H:i:s") . "' WHERE studentID = $studentId AND id = $mainId AND dynamicform_initiate_id = $applnId";
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        try {
            $sql = "UPDATE dynamicform_studentchallan SET paymentStatus = 1 WHERE dynamicform_initiate_id = $applnId AND studentaccount_id = $studentId";
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Method for updating approve status for a student
     * @param unknown $studentId
     * @param unknown $applnId
     * @param unknown $approveStatus
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function updateStudentApproveStatus($studentId, $applnId, $approveStatus)
    {
        $sql = '';
        $studentId = $this->realEscapeString($studentId);
        $applnId = $this->realEscapeString($applnId);
        // value of aproveStatus for "NOT APPROVED STATUS" is 1
        if ($approveStatus == 1) {
            $cond = 'approveStatus = 0';
        } else {
            $cond = 'approveStatus = 1';
        }
        try {
            $sql = "UPDATE dynamicform_studentchallan SET $cond WHERE studentaccount_id = $studentId AND dynamicform_initiate_id = $applnId";
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Method for getting student mc No
     * @param unknown $studentId
     * @param unknown $mcPrefixId
     * @return unknown
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getStudentMcNo($studentId, $mcPrefixId)
    {
        $sql = '';
        $studentId = $this->realEscapeString($studentId);
        $mcPrefixId = $this->realEscapeString($mcPrefixId);
        $studentMcNo = null;
        try {
            $sql = "SELECT migrationCertificateNo AS mcNo FROM studentMigrationCertificateNo WHERE studentaccount_id = $studentId AND migration_prefix_id = $mcPrefixId AND is_deleted = 0";
            $studentMcNo = $this->executeQueryForObject($sql)->mcNo;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentMcNo;
    }
    /**
     * Method for getting max Mc No
     * @param unknown $mcPrefixId
     * @return unknown
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getMaxMcNo($mcPrefixId)
    {
        $sql = '';
        $mcPrefixId = $this->realEscapeString($mcPrefixId);
        $getMaxMcNo = null;
        try {
            $sql = "SELECT max(migrationCertificateNo) AS maxMcNo FROM studentMigrationCertificateNo WHERE migration_prefix_id = $mcPrefixId";
            $getMaxMcNo = $this->executeQueryForObject($sql)->maxMcNo;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $getMaxMcNo;
    }
    /**
     * Method for adding student mc No
     * @param unknown $studentId
     * @param unknown $mcNo
     * @param unknown $mcPrefixId
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function addStudentMcNo($studentId, $mcNo, $mcPrefixId)
    {
        $sql = '';
        $issueDate = date('Y-m-d');
        $studentId = $this->realEscapeString($studentId);
        $mcPrefixId = $this->realEscapeString($mcPrefixId);
        $mcNo = $this->realEscapeString($mcNo);
        $createdBy = $_SESSION['adminID'];
        $updatedBy = $_SESSION['adminID'];
        $alreadyAvailableNoId = null;
        $checkMcNoPresent = CertificateService::getInstance()->getMigrationCertNo($studentId);
        if (!$checkMcNoPresent) {
            $sqlCheck = "SELECT id FROM studentMigrationCertificate WHERE migrationCertificateNo = $mcNo AND prefixId = $mcPrefixId AND isDeleted = 1";
            $alreadyAvailableNoId = $this->executeQueryForObject($sqlCheck)->id;
            if ($alreadyAvailableNoId) {
                try {
                    $sql = "UPDATE studentMigrationCertificate SET issueDate = '$issueDate', studentId = $studentId, isDeleted = 0,  updatedBy = $updatedBy , updatedDate =  UTC_TIMESTAMP() WHERE id = $alreadyAvailableNoId";
                    $this->executeQuery($sql);
                } catch (\Exception $e) {
                    throw new ProfessionalException($e->getCode(), $e->getMessage());
                }
            } else {
                try {
                    $sql = "INSERT INTO studentMigrationCertificate (studentId,migrationCertificateNo,prefixId,createdBy,createdDate,updatedBy,updatedDate,issueDate) VALUES ($studentId,'$mcNo',$mcPrefixId,$createdBy,utc_timestamp(),$updatedBy,utc_timestamp(),'$issueDate')";
                    $this->executeQuery($sql);
                } catch (\Exception $e) {
                    throw new ProfessionalException($e->getCode(), $e->getMessage());
                }
            }
        }
    }
    /**
     * Method for getting student cancel Certificate No
     * @param unknown $studentId
     * @param unknown $cancelPrefixId
     * @return unknown
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getStudentCancelCertificateNo($studentId, $cancelPrefixId)
    {
        $sql = '';
        $studentId = $this->realEscapeString($studentId);
        $cancelPrefixId = $this->realEscapeString($cancelPrefixId);
        $studentCancelNo = null;
        try {
            $sql = "SELECT cancellationCertificateNo AS cancelNo FROM studentCancellationCertificateNo WHERE studentaccount_id = $studentId AND cancellation_prefix_id = $cancelPrefixId AND is_deleted = 0";
            $studentCancelNo = $this->executeQueryForObject($sql)->cancelNo;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentCancelNo;
    }
    /**
     * Method for getting min Cancel No with isDelete = 1;
     * @param unknown $mcPrefixId
     * @return unknown
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getMinCancelNo($cancelPrefixId)
    {
        $sql = '';
        $cancelPrefixId = $this->realEscapeString($cancelPrefixId);
        $getMinCancelNo = null;
        try {
            $sql = "SELECT min(cancellationCertificateNo) AS minCancelNo FROM studentCancellationCertificateNo WHERE cancellation_prefix_id = $cancelPrefixId AND is_deleted = 1";
            $getMinCancelNo = $this->executeQueryForObject($sql)->minCancelNo;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $getMinCancelNo;
    }
    /**
     * Method for getting max Cancel No
     * @param unknown $mcPrefixId
     * @return unknown
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function getMaxCancelNo($cancelPrefixId)
    {
        $sql = '';
        $cancelPrefixId = $this->realEscapeString($cancelPrefixId);
        $getMaxCancelNo = null;
        try {
            $sql = "SELECT max(cancellationCertificateNo) AS maxCancelNo FROM studentCancellationCertificateNo WHERE cancellation_prefix_id = $cancelPrefixId";
            $getMaxCancelNo = $this->executeQueryForObject($sql)->maxCancelNo;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $getMaxCancelNo;
    }
    /** Method for getting all registered exam details for a student
     * @author Ranjith Balachandran
     **/
    public function getStudentRegisteredExamDetails($studentId)
    {
        $sql = '';
        $studentId = $this->realEscapeString($studentId);
        $studentExamDetails = [];
        try {
            $sql = "SELECT t1.examMonth, t1.examYear,t1.examregID FROM exam_registration t1 INNER JOIN exam_reg_studentchallan t2 ON t1.examregID = t2.examregID WHERE t2.studentID = $studentId AND t2.paid = 1 AND t1.shortCourse = 0";
            $studentExamDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentExamDetails;
    }
    /** Method for getting semID of an exam for a exam registration
     * @author Ranjith Balachandran
     **/
    public function getExamSemId($examRegId)
    {
        $sql = '';
        $examRegId = $this->realEscapeString($examRegId);
        $semId = null;
        try {
            $sql = "SELECT t1.semID AS semId FROM exam_registration_batches t1 WHERE t1.examregID = $examRegId";
            $semId = $this->executeQueryForObject($sql)->semId;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $semId;
    }
    /*
        Method for updating cancel no with not used cancel nos
        @author Ranjith Balachandran
    */
    public function updateCancelNo($studentId, $cancelNo, $cancelPrefixId)
    {
        $sql = '';
        $studentId = $this->realEscapeString($studentId);
        $cancelNo = $this->realEscapeString($cancelNo);
        $cancelPrefixId = $this->realEscapeString($cancelPrefixId);
        try {
            $sql = "UPDATE studentCancellationCertificateNo SET cancellationCertificateNo = $cancelNo , is_deleted = 0 , studentaccount_id = $studentId WHERE cancellation_prefix_id = $cancelPrefixId AND cancellationCertificateNo = $cancelNo";
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Method for adding student cancel No
     * @param unknown $studentId
     * @param unknown $cancelNo
     * @param unknown $cancelPrefixId
     * @throws ProfessionalException
     * @author Ranjith Balachandran
     */
    public function addStudentCancelNo($studentId, $cancelNo, $cancelPrefixId)
    {
        $sql = '';
        $issueDate = date('Y-m-d');
        $studentId = $this->realEscapeString($studentId);
        $cancelPrefixId = $this->realEscapeString($cancelPrefixId);
        $cancelNo = $this->realEscapeString($cancelNo);
        $createdBy = $_SESSION['adminID'];
        $updatedBy = $_SESSION['adminID'];
        $alreadyAvailableNoId = null;
        $checkCancelNoPresent = CertificateService::getInstance()->getCancelCertNo($studentId);
        if (!$checkCancelNoPresent) {
            $sqlCheck = "SELECT id FROM studentCancellationCertificate WHERE cancellationCertificateNo = $cancelNo AND prefixId = $cancelPrefixId AND isDeleted = 1";
            $alreadyAvailableNoId = $this->executeQueryForObject($sqlCheck)->id;
            if ($alreadyAvailableNoId) {
                try {
                    $sql = "UPDATE studentCancellationCertificate SET issueDate = '$issueDate',  studentId = $studentId, isDeleted = 0,  updatedBy = $updatedBy , updatedDate =  UTC_TIMESTAMP() WHERE id = $alreadyAvailableNoId";
                    $this->executeQuery($sql);
                } catch (\Exception $e) {
                    throw new ProfessionalException($e->getCode(), $e->getMessage());
                }
            } else {
                try {
                    $sql = "INSERT INTO studentCancellationCertificate (studentId,cancellationCertificateNo,prefixId,createdBy,createdDate,updatedBy,updatedDate,issueDate) VALUES ($studentId,'$cancelNo',$cancelPrefixId,$createdBy,utc_timestamp(),$updatedBy,utc_timestamp(),'$issueDate')";
                    $this->executeQuery($sql);
                } catch (\Exception $e) {
                    throw new ProfessionalException($e->getCode(), $e->getMessage());
                }
            }
        }
    }
    /* Undocumented function
    *
    * @param integer $batchID
    * @param integer $semID
    * @param integer $subbatchID
    * @param string $sortByColumn
    * @return void
    */
    public function getStudentDetailsByBatchSemIdAndSubbatchId($batchID, $semID, $subbatchID = 0, $sortByColumn = 'rollNo')
    {
        $sql = "";
        $isCurrentSem = SemesterService::getInstance()->isCurrentSemester($batchID, $semID);
        if ($isCurrentSem) {
            if ($subbatchID) {
                $sql = "select  sa.studentID, sa.studentAccount, sa.studentName, sa.studentEmail, sa.studentPhone, sa.student_lock, dep.deptName, sa.batchID, sa.rollNo, sa.admissionNo, sa.parentPhone, sa.regNo, sa.studentGender, sa.studentAddress, sa.parentAddress1, sa.parentAddress2, sa.parentState, sa.parentCity, sa.parentCountry, sa.parentZipCode, sa.studentID as id, ba.batchName from  studentaccount sa inner join subbatch_student ss on sa.studentID = ss.studentID inner join batches ba on  ba.batchID = sa.batchID inner join department dep on dep.deptID = sa.deptID  inner join semesters sem on sem.semID = ba.semID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID  where sa.batchID=$batchID and ss.subbatchID = $subbatchID and joinedSem.orderNo <= sem.orderNo ORDER BY sa.$sortByColumn;";
            } else {
                $sql = "select  sa.studentID, sa.studentAccount, sa.studentName, sa.studentEmail, sa.studentPhone, sa.student_lock, dep.deptName, sa.batchID, sa.rollNo, sa.admissionNo, sa.parentPhone, sa.regNo, sa.studentGender, sa.studentAddress, sa.parentAddress1, sa.parentAddress2, sa.parentState, sa.parentCity, sa.parentCountry, sa.parentZipCode, sa.studentID as id, ba.batchName from  studentaccount sa inner join department dep on dep.deptID = sa.deptID inner join batches ba on  ba.batchID = sa.batchID  inner join semesters sem on sem.semID = ba.semID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID where sa.batchID=$batchID and joinedSem.orderNo <= sem.orderNo ORDER BY sa.$sortByColumn";
            }
        } else {
            $semDetails = NULL;
            $semDetails = SemesterService::getInstance()->getSemDetailsBySemId($semID);
            if ($subbatchID) {
                $sql = "select  sa.studentID, sa.studentAccount, sa.studentName, sa.studentEmail, sa.studentPhone, sa.student_lock, dep.deptName, sa.batchID, sa.rollNo, sa.admissionNo, sa.parentPhone, sa.regNo, sa.studentGender, sa.studentAddress, sa.parentAddress1, sa.parentAddress2, sa.parentState, sa.parentCity, sa.parentCountry, sa.parentZipCode, sa.studentID as id, bt.batchName from studentaccount sa inner join department dep on dep.deptID = sa.deptID  inner join batches bt on sa.batchID = bt.batchID inner join subbatch_student ss on sa.studentID = ss.studentID where  subbatchID = $subbatchID and  sa.studentID in(select studentID from studentaccount sa inner join batches ba on sa.batchID = ba.batchID inner join semesters sem on sem.semID = ba.semID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID  where ba.batchID = $batchID and joinedSem.orderNo <= $semDetails->orderNo union select sa.studentID from failed_students fs inner join studentaccount sa on sa.studentID = fs.studentID inner join semesters fsem on fsem.semID = fs.failedInSemester inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID where previousBatch = $batchID and fsem.orderNo > $semDetails->orderNo and joinedSem.orderNo <= $semDetails->orderNo) ORDER BY $sortByColumn";
            } else {
                $sql = "select  sa.studentID, sa.studentAccount, sa.studentName, sa.studentEmail, sa.studentPhone, sa.student_lock, dep.deptName, sa.batchID, sa.rollNo, sa.admissionNo, sa.parentPhone, sa.regNo, sa.studentGender, sa.studentAddress, sa.parentAddress1, sa.parentAddress2, sa.parentState, sa.parentCity, sa.parentCountry, sa.parentZipCode, sa.studentID as id, ba.batchName from studentaccount sa inner join department dep on dep.deptID = sa.deptID inner join batches ba on sa.batchID =  ba.batchID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID where ba.batchID = $batchID and joinedSem.orderNo <= $semDetails->orderNo union select  sa.studentID, sa.studentAccount, sa.studentName, sa.studentEmail, sa.studentPhone, sa.student_lock, dep.deptName, sa.batchID, sa.rollNo, sa.admissionNo, sa.parentPhone, sa.regNo, sa.studentGender, sa.studentAddress, sa.parentAddress1, sa.parentAddress2, sa.parentState, sa.parentCity, sa.parentCountry, sa.parentZipCode, sa.studentID as id, ba.batchName from failed_students fs left join studentaccount sa on fs.studentID= sa.studentID inner join department dep on dep.deptID = sa.deptID inner join batches ba on sa.batchID =  ba.batchID inner join semesters fsem on fsem.semID = fs.failedInSemester inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID where previousBatch =$batchID and fsem.orderNo > $semDetails->orderNo and joinedSem.orderNo <= $semDetails->orderNo order by $sortByColumn";
            }
        }
        try {
            $studentList = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentList;
    }
    /**
     * add student extras
     * @param StudentExtras $studentExtra
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     */
        public function addStudentExtras($studentExtra)
        {
            global $settings;
            $studentExtra = $this->realEscapeObject($studentExtra);
            $extraFields = '';
            $extraValues = '';
            if ($settings) {
                $extraFields = ", studentVisa, residentPermitNo, permanentDistrict, permanentLandNumber, currentDistrict, currentLandNumber, fatherPhone, fatherMobileCountryCode, motherMobileCountryCode, guardianMobileCountryCode, guardianEmail, tenthMonthOfCompletion, tenthCountryOfInstitution, plusOneMonthOfCompletion, plusOneCountryOfInstitution, twelthMonthOfCompletion, twelthCountryOfInstitution, twelthSecondLanguageOpted, secondLanguageToChoose";
                $extraValues = ", '$studentExtra->studentVisa', '$studentExtra->residentPermitNo', '$studentExtra->permanentDistrict', '$studentExtra->permanentLandNumber', '$studentExtra->currentDistrict', '$studentExtra->currentLandNumber', '$studentExtra->fatherPhone', '$studentExtra->fatherMobileCountryCode', '$studentExtra->motherMobileCountryCode', '$studentExtra->guardianMobileCountryCode', '$studentExtra->guardianEmail', '$studentExtra->tenthMonthOfCompletion', '$studentExtra->tenthCountryOfInstitution', '$studentExtra->plusOneMonthOfCompletion', '$studentExtra->plusOneCountryOfInstitution', '$studentExtra->twelthMonthOfCompletion', '$studentExtra->twelthCountryOfInstitution', '$studentExtra->twelthSecondLanguageOpted', '$studentExtra->secondLanguageToChoose'";
            }
            // Add additional fields
            $extraFields .= ", program_code, tenth_std_max_marks, tenth_std_total_mark, place_of_12th_std_studied, 
            twelth_std_max_marks, twelth_std_total_marks_obtained, certificates_verified_online, 
            course_of_diploma_studied, place_of_diploma_studied, diploma_registration_no, 
            diploma_maximum_marks, diploma_total_marks_obtained, diploma_overall_percentage, 
            second_third_languages_pu_12th, pu_12th_board_stream, graduation_course, 
            first_sem_marks_cgpa, second_sem_marks_cgpa, third_sem_marks_cgpa, 
            fourth_sem_marks_cgpa, fifth_sem_marks_cgpa, sixth_sem_marks_cgpa, 
            seventh_sem_marks_cgpa, eighth_sem_marks_cgpa, ninth_sem_marks_cgpa, 
            tenth_sem_marks_cgpa, total_marks_cgpa_in_graduation, 
            total_marks_cgpa_in_graduation_obtained, online_verification, status, 
            ug_course_name, ug_maximum_marks_cgpa, ug_total_marks_cgpa_obtained, 
            pg_course, pg_maximum_marks_cgpa, pg_total_marks_cgpa_obtained, pg_percentage, 
            course_of_10th_studied, place_of_10th_studied, state_of_10th_studied,
            course_of_12th_studied, place_of_12th_studied, state_of_12th_studied,
            diploma_qualifying_exam_board, diploma_college_name, state_of_diploma_studied,
            diploma_month_year_of_passing, ug_qualifying_exam_board, ug_college_name,
            course_of_ug_studied, place_of_ug_studied, state_of_ug_studied,
            ug_registration_no, ug_month_year_of_passing, pg_qualifying_exam_board,
            pg_college_name, course_of_pg_studied, place_of_pg_studied,
            state_of_pg_studied, pg_registration_no, pg_month_year_of_passing,
            maximum_marks_in_pcm, twelth_month_and_year, chemistry_computer_electronics_marks,
            total_marks_obtained_in_pcm, pcm_percentage, ug_university, documents_verification";
            
            // Add additional values
            $extraValues .= ", '$studentExtra->programCode', '$studentExtra->tenthStdMaxMarks', '$studentExtra->tenthStdTotalMark', '$studentExtra->placeOf12thStdStudied', 
            '$studentExtra->twelthStdMaxMarks', '$studentExtra->twelthStdTotalMarksObtained', '$studentExtra->certificatesVerifiedOnline', 
            '$studentExtra->courseOfDiplomaStudied', '$studentExtra->placeOfDiplomaStudied', '$studentExtra->diplomaRegistrationNo', 
            '$studentExtra->diplomaMaximumMarks', '$studentExtra->diplomaTotalMarksObtained', '$studentExtra->diplomaOverallPercentage', 
            '$studentExtra->secondThirdLanguagesPu12th', '$studentExtra->pu12thBoardStream', '$studentExtra->graduationCourse', 
            '$studentExtra->firstSemMarksCgpa', '$studentExtra->secondSemMarksCgpa', '$studentExtra->thirdSemMarksCgpa', 
            '$studentExtra->fourthSemMarksCgpa', '$studentExtra->fifthSemMarksCgpa', '$studentExtra->sixthSemMarksCgpa', 
            '$studentExtra->seventhSemMarksCgpa', '$studentExtra->eighthSemMarksCgpa', '$studentExtra->ninthSemMarksCgpa', 
            '$studentExtra->tenthSemMarksCgpa', '$studentExtra->totalMarksCgpaInGraduation', 
            '$studentExtra->totalMarksCgpaInGraduationObtained', '$studentExtra->onlineVerification', '$studentExtra->status', 
            '$studentExtra->ugCourseName', '$studentExtra->ugMaximumMarksCgpa', '$studentExtra->ugTotalMarksCgpaObtained', 
            '$studentExtra->pgCourse', '$studentExtra->pgMaximumMarksCgpa', '$studentExtra->pgTotalMarksCgpaObtained', '$studentExtra->pgPercentage',
            '$studentExtra->courseOf10thStudied', '$studentExtra->placeOf10thStudied', '$studentExtra->stateOf10thStudied',
            '$studentExtra->courseOf12thStudied', '$studentExtra->placeOf12thStudied', '$studentExtra->stateOf12thStudied',
            '$studentExtra->diplomaQualifyingExamBoard', '$studentExtra->diplomaCollegeName', '$studentExtra->stateOfDiplomaStudied',
            '$studentExtra->diplomaMonthYearOfPassing', '$studentExtra->ugQualifyingExamBoard', '$studentExtra->ugCollegeName',
            '$studentExtra->courseOfUgStudied', '$studentExtra->placeOfUgStudied', '$studentExtra->stateOfUgStudied',
            '$studentExtra->ugRegistrationNo', '$studentExtra->ugMonthYearOfPassing', '$studentExtra->pgQualifyingExamBoard',
            '$studentExtra->pgCollegeName', '$studentExtra->courseOfPgStudied', '$studentExtra->placeOfPgStudied',
            '$studentExtra->stateOfPgStudied', '$studentExtra->pgRegistrationNo', '$studentExtra->pgMonthYearOfPassing',
            '$studentExtra->maximumMarksInPcm', '$studentExtra->twelthMonthAndYear', '$studentExtra->chemistryComputerElectronicsMarks',
            '$studentExtra->totalMarksObtainedInPcm', '$studentExtra->pcmPercentage', '$studentExtra->ugUniversity', '$studentExtra->documentsVerification'";
            $sql = "INSERT INTO studentaccount_extras (
                        studentID, currentAddress1, currentAddress2, permanentAddress1,permanentAddress2, placeofBirth, stateOfBirth, countryOfBirth,passportNo,passportIssuingCountry, passportValidUpto,
                        permanentState, permanentCity,permanentCountry,permanentZipCode,currentState,currentCity,currentCountry,currentZipCode,fatherEducation,annualIncome,parentOccupation,fatherEmail,
                        motherEducation,motherIncome,motherOccupation,motherEmail,residentCategory,motherTongue,extraAcitivites,belongsTo,isHandicapped,handicappedDesc,permahouse,commuhouse,motherPhone,
                        tenthBoard, tenthSchool, tenthRegno, tenthYear, twelthBoard, twelthSchool, twelthRegno, twelthYear, twelthMathsMarksObtained, twelthMathsMaxMark, twelthPhyMarkObtained, twelthPhyMaxMark, twelthCheMarkObtained, twelthCheMaxMark,
                        plusOneInstitution, plusOneRegNo, plusOneYear, plusOneBoard, plusOneMathsMarksObtained, plusOneMathsMaxMark, plusOnePhyMarkObtained, plusOnePhyMaxMark, plusOneCheMaxMark, plusOneCheMarkObtained,
                        entranceapplnno, entranceRollno, entranceMark, entrancePaperI,entrancePaperII,
                        guardianName, guardian_address_line1, guardian_address_line2, guardian_address_line3, guardian_address_city, guardian_address_state, guardian_address_zip_code, guardian_address_country, guardianLandline, guardianMob,guardianRelationship,
                        hobbies, medicalHistory, medicationNeeded, allergiesIfany,parentlandPh
                        $extraFields
                    )
                    VALUES (
                        '$studentExtra->studentID','$studentExtra->currentAddress1', '$studentExtra->currentAddress2', '$studentExtra->permanentAddress1','$studentExtra->permanentAddress2','$studentExtra->placeofBirth','$studentExtra->stateOfBirth', '$studentExtra->countryOfBirth','$studentExtra->passportNo','$studentExtra->passportIssuingCountry', '" . date('Y-m-d', strtotime($studentExtra->passportValidUpto)) . "','$studentExtra->permanentState','$studentExtra->permanentCity',
                         '$studentExtra->permanentCountry','$studentExtra->permanentZipCode','$studentExtra->currentState','$studentExtra->currentCity','$studentExtra->currentCountry','$studentExtra->currentZipCode','$studentExtra->fatherEducation','$studentExtra->annualIncome','$studentExtra->parentOccupation','$studentExtra->fatherEmail',
                         '$studentExtra->motherEducation', '$studentExtra->motherIncome','$studentExtra->motherOccupation','$studentExtra->motherEmail','$studentExtra->residentCategory','$studentExtra->motherTongue','$studentExtra->extraAcitivites','$studentExtra->belongsTo','$studentExtra->isHandicapped','$studentExtra->handicappedDesc', '$studentExtra->permahouse', '$studentExtra->commuhouse','$studentExtra->motherPhone',
                         '$studentExtra->tenthBoard', '$studentExtra->tenthSchool', '$studentExtra->tenthRegno', '$studentExtra->tenthYear', '$studentExtra->twelthBoard', '$studentExtra->twelthSchool', '$studentExtra->twelthRegno', '$studentExtra->twelthYear', '$studentExtra->twelthMathsMarksObtained', '$studentExtra->twelthMathsMaxMark', '$studentExtra->twelthPhyMarkObtained', '$studentExtra->twelthPhyMaxMark', '$studentExtra->twelthCheMarkObtained',
                         '$studentExtra->twelthCheMaxMark', '$studentExtra->plusOneInstitution', '$studentExtra->plusOneRegNo', '$studentExtra->plusOneYear', '$studentExtra->plusOneBoard', '$studentExtra->plusOneMathsMarksObtained', '$studentExtra->plusOneMathsMaxMark', '$studentExtra->plusOnePhyMarkObtained', '$studentExtra->plusOnePhyMaxMark', '$studentExtra->plusOneCheMaxMark', '$studentExtra->plusOneCheMarkObtained',
                         '$studentExtra->entranceapplnno', '$studentExtra->entranceRollno', '$studentExtra->entranceMark', '$studentExtra->entrancePaperI', '$studentExtra->entrancePaperII',
                         '$studentExtra->guardianName', '$studentExtra->guardian_address_line1', '$studentExtra->guardian_address_line2', '$studentExtra->guardian_address_line3', '$studentExtra->guardian_address_city', '$studentExtra->guardian_address_state', '$studentExtra->guardian_address_zip_code', '$studentExtra->guardian_address_country', '$studentExtra->guardianLandline', '$studentExtra->guardianMob','$studentExtra->guardianRelationship',
                         '$studentExtra->hobbies', '$studentExtra->medicalHistory', '$studentExtra->medicationNeeded', '$studentExtra->allergiesIfany','$studentExtra->parentlandPh'
                          $extraValues
                    )";
        try {
            return $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalExcsteeption($e->getCode(), $e->getMessage());
        }
    }
    /**
     * update student extras
     * @param StudentExtras $studentExtra
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     */
    public function updateStudentExtras($studentExtra,$settings)
    {
        $studentExtra = $this->realEscapeObject($studentExtra);
        $sql ="UPDATE studentaccount_extras SET
        currentAddress1 = '$studentExtra->currentAddress1',
        currentAddress2 = '$studentExtra->currentAddress2',
        permanentAddress1 = '$studentExtra->permanentAddress1',
        permanentAddress2 = '$studentExtra->permanentAddress2',
        placeofBirth = '$studentExtra->placeofBirth',
        stateOfBirth = '$studentExtra->stateOfBirth',
        countryOfBirth = '$studentExtra->countryOfBirth',
        passportNo = '$studentExtra->passportNo',
        passportIssuingCountry = '$studentExtra->passportIssuingCountry',
        passportValidUpto = '" . date('Y-m-d', strtotime($studentExtra->passportValidUpto)) . "',
        fatherEducation = '$studentExtra->fatherEducation',
        annualIncome = '$studentExtra->annualIncome',
        parentOccupation = '$studentExtra->parentOccupation',
        fatherEmail = '$studentExtra->fatherEmail',
        motherEducation = '$studentExtra->motherEducation',
        motherIncome = '$studentExtra->motherIncome',
        motherOccupation = '$studentExtra->motherOccupation',
        motherEmail = '$studentExtra->motherEmail',
        motherTongue = '$studentExtra->motherTongue',
        extraAcitivites = '$studentExtra->extraAcitivites',
        belongsTo = '$studentExtra->belongsTo',
        isHandicapped = '$studentExtra->isHandicapped',
        handicappedDesc = '$studentExtra->handicappedDesc',
        permahouse = '$studentExtra->permahouse',
        commuhouse = '$studentExtra->commuhouse',
        motherPhone = '$studentExtra->motherPhone',
        tenthBoard = '$studentExtra->tenthBoard',
        tenthSchool = '$studentExtra->tenthSchool',
        tenthRegno = '$studentExtra->tenthRegno',
        tenthYear = '$studentExtra->tenthYear',
        twelthBoard = '$studentExtra->twelthBoard',
        twelthSchool = '$studentExtra->twelthSchool',
        twelthRegno = '$studentExtra->twelthRegno',
        twelthYear = '$studentExtra->twelthYear',
        twelthMathsMarksObtained = '$studentExtra->twelthMathsMarksObtained',
        twelthMathsMaxMark = '$studentExtra->twelthMathsMaxMark',
        twelthPhyMarkObtained = '$studentExtra->twelthPhyMarkObtained',
        twelthPhyMaxMark = '$studentExtra->twelthPhyMaxMark',
        twelthCheMarkObtained = '$studentExtra->twelthCheMarkObtained',
        twelthCheMaxMark = '$studentExtra->twelthCheMaxMark',
        plusOneInstitution = '$studentExtra->plusOneInstitution',
        plusOneRegNo = '$studentExtra->plusOneRegNo',
        plusOneYear = '$studentExtra->plusOneYear',
        plusOneBoard = '$studentExtra->plusOneBoard',
        plusOneMathsMarksObtained = '$studentExtra->plusOneMathsMarksObtained',
        plusOneMathsMaxMark = '$studentExtra->plusOneMathsMaxMark',
        plusOnePhyMarkObtained = '$studentExtra->plusOnePhyMarkObtained',
        plusOnePhyMaxMark = '$studentExtra->plusOnePhyMaxMark',
        plusOneCheMaxMark = '$studentExtra->plusOneCheMaxMark',
        plusOneCheMarkObtained = '$studentExtra->plusOneCheMarkObtained',
        entranceapplnno = '$studentExtra->entranceapplnno',
        entranceRollno = '$studentExtra->entranceRollno',
        entranceMark = '$studentExtra->entranceMark',
        entrancePaperI = '$studentExtra->entrancePaperI',
        entrancePaperII = '$studentExtra->entrancePaperII',
        guardianName = '$studentExtra->guardianName',
        guardian_address_line1 = '$studentExtra->guardian_address_line1',
        guardian_address_line2 = '$studentExtra->guardian_address_line2',
        guardian_address_line3 = '$studentExtra->guardian_address_line3',
        guardian_address_city = '$studentExtra->guardian_address_city',
        guardian_address_state = '$studentExtra->guardian_address_state',
        guardian_address_zip_code = '$studentExtra->guardian_address_zip_code',
        guardian_address_country = '$studentExtra->guardian_address_country',
        guardianLandline = '$studentExtra->guardianLandline',
        guardianMob = '$studentExtra->guardianMob',
        guardianRelationship = '$studentExtra->guardianRelationship',
        hobbies = '$studentExtra->hobbies',
        medicalHistory = '$studentExtra->medicalHistory',
        medicationNeeded = '$studentExtra->medicationNeeded',
        allergiesIfany = '$studentExtra->allergiesIfany',
        residentCategory = '$studentExtra->residentCategory',
        parentlandPh = '$studentExtra->parentlandPh'
        ";
        if ($settings) {
        $sql .= ", studentVisa = '$studentExtra->studentVisa',
          residentPermitNo = '$studentExtra->residentPermitNo',
          permanentDistrict = '$studentExtra->permanentDistrict',
          permanentLandNumber = '$studentExtra->permanentLandNumber',
          currentDistrict = '$studentExtra->currentDistrict',
          currentLandNumber = '$studentExtra->currentLandNumber',
          fatherPhone = '$studentExtra->fatherPhone',
          fatherMobileCountryCode = '$studentExtra->fatherMobileCountryCode',
          motherMobileCountryCode = '$studentExtra->motherMobileCountryCode',
          guardianMobileCountryCode = '$studentExtra->guardianMobileCountryCode',
          guardianEmail = '$studentExtra->guardianEmail',
          tenthMonthOfCompletion = '$studentExtra->tenthMonthOfCompletion',
          tenthCountryOfInstitution = '$studentExtra->tenthCountryOfInstitution',
          plusOneMonthOfCompletion = '$studentExtra->plusOneMonthOfCompletion',
          plusOneCountryOfInstitution = '$studentExtra->plusOneCountryOfInstitution',
          twelthMonthOfCompletion = '$studentExtra->twelthMonthOfCompletion',
          twelthCountryOfInstitution = '$studentExtra->twelthCountryOfInstitution',
          twelthSecondLanguageOpted = '$studentExtra->twelthSecondLanguageOpted',
          secondLanguageToChoose = '$studentExtra->secondLanguageToChoose'
        ";
        }
$sql .= " WHERE studentID = '$studentExtra->studentID'";
        try {
            return $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * get student extras by student Id
     * @param int $studentId
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getStudentExtrasByStudentId($studentId)
    {
        global $settings;
        $studentId = $this->realEscapeString($studentId);
        $studentAdditionalDetails = ", program_code, tenth_std_max_marks, tenth_std_total_mark, place_of_12th_std_studied, 
        twelth_std_max_marks, twelth_std_total_marks_obtained, certificates_verified_online, 
        course_of_diploma_studied, place_of_diploma_studied, diploma_registration_no, 
        diploma_maximum_marks, diploma_total_marks_obtained, diploma_overall_percentage, 
        second_third_languages_pu_12th, pu_12th_board_stream, graduation_course, 
        first_sem_marks_cgpa, second_sem_marks_cgpa, third_sem_marks_cgpa, 
        fourth_sem_marks_cgpa, fifth_sem_marks_cgpa, sixth_sem_marks_cgpa, 
        seventh_sem_marks_cgpa, eighth_sem_marks_cgpa, ninth_sem_marks_cgpa, 
        tenth_sem_marks_cgpa, total_marks_cgpa_in_graduation, 
        total_marks_cgpa_in_graduation_obtained, online_verification, status, 
        ug_course_name, ug_maximum_marks_cgpa, ug_total_marks_cgpa_obtained, 
        pg_course, pg_maximum_marks_cgpa, pg_total_marks_cgpa_obtained, pg_percentage,
        course_of_10th_studied, place_of_10th_studied, state_of_10th_studied,
        course_of_12th_studied, place_of_12th_studied, state_of_12th_studied,
        diploma_qualifying_exam_board, diploma_college_name, state_of_diploma_studied,
        diploma_month_year_of_passing, ug_qualifying_exam_board, ug_college_name,
        course_of_ug_studied, place_of_ug_studied, state_of_ug_studied,
        ug_registration_no, ug_month_year_of_passing, pg_qualifying_exam_board,
        pg_college_name, course_of_pg_studied, place_of_pg_studied,
        state_of_pg_studied, pg_registration_no, pg_month_year_of_passing,
        maximum_marks_in_pcm, twelth_month_and_year, chemistry_computer_electronics_marks,
        total_marks_obtained_in_pcm, pcm_percentage,
        ug_university, documents_verification
        ";
        $sql = "SELECT currentAddress1, currentAddress2, permanentAddress1, permanentAddress2, placeofBirth, stateOfBirth, countryOfBirth, passportNo, passportIssuingCountry, passportValidUpto, studentVisa, residentPermitNo, permanentState, permanentCity, permanentCountry, permanentZipCode, currentState, currentCity, currentCountry, currentZipCode, fatherEducation, annualIncome, parentOccupation, fatherEmail, motherEducation, motherIncome, motherOccupation, motherEmail, residentCategory, motherTongue, extraAcitivites, belongsTo, isHandicapped, handicappedDesc, permahouse, commuhouse,se.motherPhone, se.tenthBoard, se.tenthSchool, se.tenthRegno, se.tenthYear, se.twelthBoard, se.twelthSchool, se.twelthRegno, se.twelthYear, se.twelthMathsMarksObtained,se.twelthMathsMaxMark,se.twelthPhyMarkObtained,se.twelthPhyMaxMark,se.twelthCheMarkObtained,se.twelthCheMaxMark, se.plusOneInstitution,se.plusOneRegNo,se.plusOneYear,se.plusOneBoard,se.plusOneMathsMarksObtained,se.plusOneMathsMaxMark,se.plusOnePhyMarkObtained,se.plusOnePhyMaxMark,se.plusOneCheMaxMark,se.plusOneCheMarkObtained, se.entranceapplnno,se.entranceRollno,se.entranceMark,se.entrancePaperI,se.entrancePaperII, se.guardianName,se.guardian_address_line1,se.guardian_address_line2,se.guardian_address_line3,se.guardian_address_city,se.guardian_address_state,se.guardian_address_zip_code,se.guardian_address_country,se.guardianLandline,se.guardianMob,se.guardianLandline,se.guardianRelationship, se.hobbies,se.medicalHistory,se.medicationNeeded,se.allergiesIfany,se.residentCategory,se.parentlandPh,se.extra_details ";
        if ($settings) {
            $sql .= ", se.permanentDistrict, se.permanentLandNumber, se.currentDistrict, se.currentLandNumber, se.fatherPhone, se.fatherMobileCountryCode, se.motherMobileCountryCode, se.guardianMobileCountryCode, se.guardianEmail, se.tenthMonthOfCompletion, se.tenthCountryOfInstitution, se.plusOneMonthOfCompletion, se.plusOneCountryOfInstitution, se.twelthMonthOfCompletion, se.twelthCountryOfInstitution, se.twelthSecondLanguageOpted, secondLanguageToChoose";
        }
        $sql .= " $studentAdditionalDetails  FROM studentaccount_extras se WHERE studentID = $studentId";
        try {
            return $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * add student educational details
     * @param array $educationDetails
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     */
    public function addStudentEducationDetails($educationDetails)
    {
        $educationDetails = $this->realEscapeArray($educationDetails);
        $sql = "INSERT INTO student_previous_education_details (studentId, qualification, university, institution, state, percentage, year,no_of_attempts,stream_name,month_of_pass,register_no,no_of_certificates_submitted) VALUES ";
        $value = [];
        foreach ($educationDetails as $eduDetails) {
            $value[] = "('$eduDetails->studentId', '$eduDetails->qualification', '$eduDetails->university', '$eduDetails->institution', '$eduDetails->state', '$eduDetails->percentage', '$eduDetails->year','$eduDetails->noOfAttempts','$eduDetails->streamName','$eduDetails->monthOfPass','$eduDetails->registerNo','$eduDetails->noOfCertificatesSubmitted')";
        }
        $sql .= implode(', ', $value);
        try {
            return $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * remove student education details
     * @param int $studentId
     * @throws ProfessionalException
     */
    public function removeStudentEducationDetailsByStudentId($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        try {
            $sql = "DELETE FROM student_previous_education_details where studentId=$studentId";
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * get student education details
     * @param int $studentId
     * @throws ProfessionalException
     */
    public function getStudentEducationDetailsByStudentId($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        try {
            $sql = "SELECT * FROM student_previous_education_details where studentId=$studentId";
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * get student education details with url encoded
     * @param int $studentId
     * @throws ProfessionalException
     * @author Ajay C
     */
    public function getStudentEducationDetailsByStudentIdURLEncodedFormat($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        try {
            $sql = "SELECT * FROM student_previous_education_details where studentId=$studentId";
            $result =urlencode(serialize($this->executeQueryForList($sql)));
            return $result;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * add student sports details
     * @param array $sportsDetails
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     */
    public function addStudentSportsDetails($sportsDetails)
    {
        $sportsDetails = $this->realEscapeArray($sportsDetails);
        $sql = "INSERT INTO student_sports_details (studentId, details, level, position) VALUES ";
        $value = [];
        foreach ($sportsDetails as $details) {
            $value[] = "('$details->studentId', '$details->details', '$details->level', '$details->position')";
        }
        $sql .= implode(', ', $value);
        try {
            return $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * remove student education details
     * @param int $studentId
     * @throws ProfessionalException
     */
    public function removeStudentSportsDetailsByStudentId($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        try {
            $sql = "DELETE FROM student_sports_details where studentId=$studentId";
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * get student sports details
     * @param int $studentId
     * @throws ProfessionalException
     */
    public function getStudentSportsDetailsByStudentId($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        try {
            $sql = "SELECT * FROM student_sports_details where studentId=$studentId";
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getAllStudentsOfABatchByBatchIdSemIdAndSubbatchId($batchID, $semID, $subbatchID = 0, $sortByColumn = "regNo")
    {
        $batchID = $this->realEscapeString($batchID);
        $semID = $this->realEscapeString($semID);
        $subbatchID = $this->realEscapeString($subbatchID);
        $sortByColumn = $this->realEscapeString($sortByColumn);
        $isCurrentSem = SemesterService::getInstance()->isCurrentSemester($batchID, $semID);
        if ($subbatchID) {
            if ($isCurrentSem) {
                $sql = "SELECT sa.studentID, sa.studentName,sa.rollNo,sa.studentAccount, sa.regNo, sa.studentGender from  studentaccount sa inner join subbatch_student ss on sa.studentID = ss.studentID inner join batches ba on  ba.batchID = sa.batchID  inner join semesters sem on sem.semID = ba.semID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID  where sa.batchID=$batchID and ss.subbatchID = $subbatchID and joinedSem.orderNo <= sem.orderNo ORDER BY sa.$sortByColumn;";
            } else {
                $semDetails = SemesterService::getInstance()->getSemDetailsBySemId($semID);
                $sql = "SELECT sa.studentID, sa.studentName, rollNo, sa.regNo, sa.studentAccount, sa.studentGender from studentaccount sa  inner join subbatch_student ss on sa.studentID = ss.studentID where  subbatchID = $subbatchID and  sa.studentID in (SELECT studentID from studentaccount sa inner join batches ba on sa.batchID = ba.batchID inner join semesters sem on sem.semID = ba.semID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID  where ba.batchID = $batchID and joinedSem.orderNo <= $semDetails->orderNo union select sa.studentID from failed_students fs inner join studentaccount sa on sa.studentID = fs.studentID inner join semesters fsem on fsem.semID = fs.failedInSemester inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID where previousBatch = $batchID and fsem.orderNo > $semDetails->orderNo and joinedSem.orderNo <= $semDetails->orderNo) ORDER BY $sortByColumn";
            }
        } else {
            if ($isCurrentSem) {
                $sql = "SELECT sa.studentID, sa.studentName,sa.rollNo, sa.studentAccount, sa.regNo, sa.studentGender from  studentaccount sa inner join batches ba on  ba.batchID = sa.batchID  inner join semesters sem on sem.semID = ba.semID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID where sa.batchID=$batchID and joinedSem.orderNo <= sem.orderNo ORDER BY sa.$sortByColumn";
            } else {
                $semDetails = SemesterService::getInstance()->getSemDetailsBySemId($semID);
                $sql = "SELECT sa.studentID, sa.studentName, sa.rollNo, sa.studentAccount, sa.regNo, sa.studentGender from studentaccount sa inner join batches ba on sa.batchID =  ba.batchID inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID where ba.batchID = $batchID and joinedSem.orderNo <= $semDetails->orderNo union select sa.studentID, sa.studentName, sa.rollNo, sa.studentAccount, sa.regNo, sa.studentGender from failed_students fs left join studentaccount sa on fs.studentID= sa.studentID inner join semesters fsem on fsem.semID = fs.failedInSemester inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID where previousBatch =$batchID and fsem.orderNo > $semDetails->orderNo and joinedSem.orderNo <= $semDetails->orderNo order by $sortByColumn";
            }
        }
        try {
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $th) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     *  details of students where taken elective subject
     * @param int $studentId
     * @throws ProfessionalException
     */
    public function getStudentsBySubjectId($batchID, $semID, $subjectID)
    {
        $batchID = $this->realEscapeString($batchID);
        $semID = $this->realEscapeString($semID);
        $subjectID = $this->realEscapeString($subjectID);
        $subbatchDetails = BatchService::getInstance()->getSubbatchBySubject($subjectID, $semID, $batchID);
        if (empty($subbatchDetails)) {
            try {
                $sql = "select sac.regNo,sac.studentAccount,sac.studentName,sac.studentEmail,sac.rollNo,sac.studentID from studentaccount sac  inner join batches ba on ba.batchID=sac.batchID inner join semesters sem ON sem.semID=ba.semID where ba.batchID = $batchID and sem.semID=$semID group  by sac.studentID";
                $studentDetails = $this->executeQueryForList($sql);
            } catch (\Exception $e) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        } else {
            try {
                $sql = "select sac.regNo,sac.studentAccount,sac.studentName,sac.studentEmail,sac.rollNo,sac.studentID from sbs_relation sr inner join subjects sub on sub.subjectID = sr.subjectID
                INNER JOIN subbatch_sbs sb on sb.sbsID=sr.sbsID
                INNER JOIN subbatches su on su.subbatchID =sb.subbatchID
                INNER join subbatch_student ss on ss.subbatchID=su.subbatchID
                INNER JOIN studentaccount sac on sac.studentID=ss.studentID  where sr.batchID = $batchID and sr.semID=$semID and sub.subjectID=$subjectID";
                $studentDetails = $this->executeQueryForList($sql);
            } catch (\Exception $e) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        }
        return $studentDetails;
    }
    /**
     * Move student to failed list by batch
     * @param string $batchId
     * @param string $exitType
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     * @author Vishnu M
     */
    public function moveStudentToFailedListByBatch($batchId, $exitType = SettingsConstants::EXIT_TYPE_FAILED)
    {
        $batchId = $this->realEscapeString($batchId);
        $exitType = $this->realEscapeString($exitType);
        $adminId = $_SESSION['adminID'];
        try {
            if (empty($batchId)) {
                throw new ProfessionalException("BATCH_REQUIRED", "INVALID BATCH");
            } else {
                $failedBatchId = BatchService::getInstance()->getFailedBatchId();
                $batch = BatchService::getInstance()->getBatchDetailsById($batchId);
            }
            if ($exitType != SettingsConstants::EXIT_TYPE_FAILED && $exitType != SettingsConstants::EXIT_TYPE_DISCONTINUED) {
                throw new ProfessionalException("INVALID_EXIT_TYPE", "INVALID EXIT_TYPE");
            }
            if ($batchId == $failedBatchId) {
                throw new ProfessionalException("STUDENTS_ALREADY_IN_FAILED_LIST", "STUDENT ALREADY EXISTS IN FAILED LIST");
            }
            $semester = SemesterService::getInstance()->getPreviousSemsters($batch->currentSemId);
            $sql = "INSERT INTO failed_students ( studentID, previousBatch, failedInSemester, hisSemestersInThisbatch,  failedDate,updated_by,userType ) SELECT studentID, batchID, '$batch->currentSemId', '$semester', UTC_TIMESTAMP(),'$adminId','ADMIN' FROM studentaccount WHERE batchID = '$batchId";
            $this->executeQuery($sql);
            $updateSql = "UPDATE studentaccount SET batchID = '$failedBatchId' , exitType = '$exitType', student_lock = 1  WHERE batchID = '$batchId";
            $this->executeQuery($updateSql);
        } catch (\Exception $e) {
            throw new ProfessionalException("UPDATE_ERROR", "UPDATION FAILED");
        }
    }
    /**
     * Get student's second language
     * @param Integer $studentId
     * @return Object $secondLangauge
     * @throws ProfessionalException
     * @author Vishnu M
     */
    public function getStudentSecondLanguageByStudentId($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        $secondLanguage = null;
        try {
            $sql = "SELECT sl.secondlangaugeID AS id, sl.secondLangaugeName AS name, sl.secondLangaugedesc AS description, sl.secondLangaugeCode AS code FROM secondLangauge sl INNER JOIN studentaccount sa ON ( sa.secondlangaugeID = sl.secondlangaugeID ) WHERE sa.studentID = '$studentId";
            $secondLanguage = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $secondLanguage;
    }
    /**
     * Get student's optionalsubjects (OPEN_ELECTIVES)
     * @param Integer $studentId
     * @return Array $optionalSubjects
     * @throws ProfessionalException
     * @author Vishnu M
     */
    public function getStudentOptionalSubjectsByStudentId($studentId, $elective = null)
    {
        $studentId = $this->realEscapeString($studentId);
        $electives[ExamSubjectTypeConstants::OPEN_ELECTIVE] = "'" . ExamSubjectTypeConstants::OPEN_ELECTIVE . "'";
        if ($elective) {
            $electives[$elective] = "'" . $elective . "'";
        }
        $electives = implode(',', $electives);
        $optionalSubjects = null;
        try {
            // $sql = "SELECT s.subjectID, esc.semID, s.subjectName, s.subjectDesc FROM subjects s INNER JOIN exam_reg_studentsubject ers ON (s.subjectID = ers.subjectID) INNER JOIN studentaccount sa ON (sa.studentID = ers.studentID) INNER JOIN exam_subjectcredit esc ON (ers.subjectID = esc.subjectID AND s.subjectID = esc.subjectID AND esc.batchID = sa.batchID) WHERE esc.subjectType = '$openElective' AND sa.studentID = '$studentId' ";
            $sql = "SELECT s.subjectID, esc.semID, s.subjectName, s.subjectDesc ,s.syllabusName FROM subjects s INNER JOIN exam_reg_studentsubject ers ON (s.subjectID = ers.subjectID) INNER JOIN studentaccount sa ON (sa.studentID = ers.studentID) INNER JOIN exam_subjectcredit esc ON (ers.subjectID = esc.subjectID AND s.subjectID = esc.subjectID AND esc.batchID = sa.batchID) INNER JOIN batches b ON (b.batchID = sa.batchID AND esc.semID = IF(b.semID <= b.final_semester, b.semID, b.final_semester)) WHERE esc.subjectType IN ($electives) AND sa.studentID = '$studentId";
            $optionalSubjects = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $optionalSubjects;
    }
    public function batchChangeAssinc($request)
    {
        $request = $this->realEscapeObject($request);
        if ($request->oldBatchId != $request->newBatchId) {
            $hookParams = [];
            $hooks = LinwaysHooks::getInstance();
            $hookParams['studentId'] = $request->studentId;
            $hookParams['newBatchId'] = $request->newBatchId;
            $hookParams['oldBatchId'] = $request->oldBatchId;
            $hookParams['createdBy'] = $request->createdBy;
            $hooks->apply_filters('on_change_student_batch_completed', $hookParams);
        }
    }
    /**
     * Get student's course type by studentId
     * @param Integer $studentId
     * @return Object $details
     * @author Vishnu M
     */
    public function getCourseTypeByStudentId($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        $details = null;
        $sql = "SELECT sa.studentID, b.batchID, ct.courseTypeID, ct.course_Type as courseType FROM studentaccount sa INNER JOIN batches b ON (b.batchID = sa.batchID ) INNER JOIN course_type ct ON (ct.courseTypeID = b.courseTypeID) WHERE studentID = '$studentId";
        try {
            $details = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $details;
    }
    public function getStudentFailedBatches($studentId, $includeBatchShuffle = FALSE)
    {
        $sql = null;
        $studentId = $this->realEscapeString($studentId);
        $failedBatchName = BatchConstants::BATCH_FAILED_NAME;
        $condition = null;
        if ($includeBatchShuffle == FALSE) {
            $batchShuffle = FailedReason::BATCH_SHUFFLE;
            $condition = " AND (fs.reason != '$batchShuffle' OR fs.reason IS NULL) ";
        }
        $sql = "SELECT fs.failedID, fs.studentID, fs.previousBatch, fs.failedInSemester, fs.failedDate, b.batchName, b.deptID, b.semID, s.semName FROM failed_students fs INNER JOIN batches b ON fs.previousBatch = b.batchID INNER JOIN semesters s ON s.semID = fs.failedInSemester WHERE b.batchName != '$failedBatchName' AND studentID = '$studentId$condition ORDER BY s.orderNo ASC";
        try {
            $studentFailedBatches = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentFailedBatches;
    }
    public function getStudentDetailOnTheBasesOfGenderAndBatchId($batchID, $gender)
    {
        $batchID = $this->realEscapeString($batchID);
        $gender = $this->realEscapeString($gender);
        $sql = "SELECT t1.regNo,t1.studentAccount,t1.parentPhone,t1.studentEmail, sl.secondLangaugeName, t1.studentName
        from studentaccount t1
        left join secondLangauge sl on sl.secondlangaugeID = t1.secondlangaugeID
        where t1.batchID='$batchID'";
        if ($gender) {
            $sql .= "and t1.studentGender='$gender';";
        }
        try {
            $studentDeatils = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDeatils;
    }
    /**
     * @param $searchClass
     * @return Object
     * @throws ProfessionalException
     */
    public function getStudentDetailWithSecondLanguageID($searchClass)
    {
        $searchClass = $this->realEscapeObject($searchClass);
        $sql = "";
        $sql = "
        select sa.regNo,sa.studentName,bat.batchName,cp.patternDesc,cp.patternName,bat.course_type_id
        from studentaccount sa
        inner join batches bat on bat.batchID = sa.batchID";
        if ($searchClass->courseTypeID) {
            $sql .= " and bat.courseTypeID = " . $searchClass->courseTypeID;
        }
        if ($searchClass->deptID) {
            $sql .= " and bat.deptID = " . $searchClass->deptID;
        }
        if ($searchClass->patternID) {
            $sql .= " and bat.patternID = " . $searchClass->patternID;
        }
        if ($searchClass->patterncourseID) {
            $sql .= " and bat.patterncourseID = " . $searchClass->patterncourseID;
        }
        if ($searchClass->patterncourseID) {
            $sql .= " and bat.semID = " . $searchClass->semID;
        }
        $sql .= " left join course_pattern cp on cp.patternID = bat.patternID
        where sa.secondlangaugeID = '$searchClass->secondLanguageID' and (sa.studentGender='male' or sa.studentGender='female')";
        if ($searchClass->batchID) {
            $sql .= " and sa.batchID = '$searchClass->batchID'";
        }
        try {
            $studentDeatils = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDeatils;
    }
    /**
     * Get student's exact batchID (commonly for failed student)
     *
     * @param [type] $semID
     * @param [type] $studentID
     * @param [type] $batchID
     * @return void
     */
    public function getStudentsBatchIDBySemIDandStudentID($semID, $studentID, $batchID = null)
    {
        if (!$batchID) {
            $batchIDs = $this->getFailedStudentBatchs($studentID);
            $sql = "select orderNo from semesters where semID = '$semID';";
            $orderNo = $this->executeQueryForObject($sql);
            $batchID = $batchIDs[$orderNo->orderNo];
        }
        $sql = "select examregID from exam_registration_batches erb where erb.batchID = '$batchID' and erb.semID = '$semID'";
        try {
            $examregID = $this->executeQueryForObject($sql);
            if ($examregID) {
                $sql = "select * from exam_reg_studentchallan where examregID='$examregID->examregID' and studentID ='$studentID'";
                $va = $this->executeQueryForObject($sql);
                if ($va) {
                    return $batchID;
                }
            }
            return false;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDeatils;
    }
    /**
     * get student's batchID corresponding to sem from failed_student table
     *
     * @param [type] $studentID
     * @return [object] semOrderNo:batchID
     */
    public function getFailedStudentBatchs($studentID)
    {
        $sql = "SELECT failedInSemester,previousBatch FROM failed_students WHERE studentID ='$studentID' ORDER BY failedInSemester ASC;";
        try {
            $rows = $this->executeQueryForList($sql);
            $i = 1;
            $a = 0;
            if ($rows) {
                foreach ($rows as $row) {
                    $a = $row->failedInSemester - $a;
                    for ($j = 1; $j < $a; $j++) {
                        $batchIDs[$i] = $row->previousBatch;
                        $i++;
                    }
                    $a -= 1;
                }
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $batchIDs;
    }
    /**
     * Update Students on Batch Transfer
     * @param object $transferBatchRequest
     * @return \com\linways\base\dto\MySqlResult
     * @throws ProfessionalException
     * @author Anoop
     */
    public function updateStudentsForBatchTransfer($transferBatchRequest)
    {
        $transferBatchRequest = $this->realEscapeObject($transferBatchRequest);
        $studentIdList = $transferBatchRequest->studentIdList;
        $updateexitType = "";
        $adminId = $_SESSION['adminID'];
        $faileBatchId = BatchService::getInstance()->getFailedBatchId();
        $failed = 0;
        // $student->secondLanguageId = !empty($student->secondLanguageId) ? $student->secondLanguageId : 'NULL';
        $studentId = current($studentIdList);
        $changeAttendanceBatchId = true;
        foreach ($studentIdList as $studentId) {
            $sql = "SELECT sa.batchID, ba.semID, sa.joiningSemId,sem.type,sem.orderNo ,sa.student_lock FROM studentaccount sa INNER JOIN batches ba ON sa.batchID = ba.batchID LEFT JOIN semesters sem on sem.semID = ba.semID WHERE sa.studentID =$studentId";
            $batchDetails = $this->executeQueryForObject($sql);
            $previousBatchId = $batchDetails->batchID;
            $semID = $batchDetails->semID;
            $currentJoiningSemId = $batchDetails->joiningSemId;
            //move students to failed batch ----for future development now exicute only else block
            if ($transferBatchRequest->batchID == $faileBatchId) {
                if ($previousBatchId != $faileBatchId) {
                    $updateexitType = ", exitType = '$transferBatchRequest->exitType";
                    $sql = "call move_failedstudents(\"$studentId\",$semID,0)";
                    //echo $sql;
                    $this->executeQuery($sql);
                    $failed = 1;
                    $student_lock = 1;
                    $studentPreviousSemesters = $this->getPreviousSemestersOfThisBatch($studentId,$batchDetails);
                    $sqlForUpdatingFailedStudents = "UPDATE  failed_students SET reason ='" . FailedReason::FAILED . "',hisSemestersInThisbatch = '$studentPreviousSemesters',updated_by = '".$adminId."',userType = 'ADMIN'  WHERE studentID=$studentId AND previousBatch = '$previousBatchId'";
                    $this->executeQuery($sqlForUpdatingFailedStudents);
                }
            } else {
                if ($transferBatchRequest->preservePreviousData == "true") {
                    $changeAttendanceBatchId = false;
                    $sqlForBatchTransfer = "call move_failedstudents(\"$studentId\",$semID,0)";
                    $this->executeQuery($sqlForBatchTransfer);
                    $studentPreviousSemesters = $this->getPreviousSemestersOfThisBatch($studentId,$batchDetails);
                    $sqlForUpdatingReason = "UPDATE  failed_students SET reason ='" . FailedReason::BATCH_SHUFFLE . "',hisSemestersInThisbatch = '$studentPreviousSemesters',updated_by = '".$adminId."',userType = 'ADMIN' WHERE studentID=$studentId AND previousBatch = '$previousBatchId'";
                    $this->executeQuery($sqlForUpdatingReason);
                }
                $updateexitType = ", exitType = '' ";
                $sql_update = "UPDATE failed_students SET isFailNow = 0 WHERE studentID = \"$studentId\"";
                $this->executeQuery($sql_update);
            }
            if ($previousBatchId != $transferBatchRequest->newBatchId && $failed == 0 && $changeAttendanceBatchId) {
                $sql = "UPDATE attendance SET batchID=\"" . $transferBatchRequest->newBatchId . "\" WHERE studentID=\"" . $studentId . "\" AND batchID=\"" . $previousBatchId . "\"";
                $this->executeQuery($sql);
                $sql = "INSERT INTO admin_who_migarte_batch (adminID, studentID) VALUES(\"" . $transferBatchRequest->updatedBy . "\", \"" . $studentId . "\")";
                $this->executeQuery($sql);
            }
            // $feeReservations = !empty($student->feeReservationId)?"fee_reservations_id=\"$student->feeReservationId\",":"";
            $sql = "UPDATE studentaccount SET
                        deptID='$transferBatchRequest->deptID',
                        batchID='$transferBatchRequest->newBatchId'
                    WHERE studentID='$studentId'";
            try {
                $this->executeQuery($sql);
            } catch (\Exception $e) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        }
        return true;
    }
    /**
     * @param $departmentId
     * @return array|Object
     * @throws ProfessionalException
     */
    public function getPassedStudentsCountInMinimumStipulatedTimeInDepartmentAndYear($departmentId, $year)
    {
        $totalStudents = 0;
        $sql = "SELECT COUNT(DISTINCT  sa.studentID) as totalStudents FROM studentaccount sa
                INNER JOIN  batches b on sa.batchID = b.batchID
                INNER JOIN exam_student_passout_year espy on sa.studentID = espy.student_id AND b.batchEndYear = espy.passout_year
                WHERE b.deptID = $departmentId AND b.batchStartYear = $year";
        try {
            $totalStudents = $this->executeQueryForObject($sql)->totalStudents;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $totalStudents;
    }
    /**
     * @param $registerNumber
     * @return Object|null
     * @throws ProfessionalException
     */
    public function getCourseTypeByRegisterNumber($registerNumber)
    {
        $registerNumber = $this->realEscapeString($registerNumber);
        $details = null;
        $sql = "SELECT sa.studentID, b.batchID, ct.courseTypeID, ct.course_Type as courseType FROM studentaccount sa
                INNER JOIN batches b ON (b.batchID = sa.batchID )
                INNER JOIN course_type ct ON (ct.courseTypeID = b.courseTypeID) WHERE regNo = '$registerNumber";
        try {
            $details = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $details;
    }
    public function getStudentBasicDetailsById($studentID)
    {
        $sql = "SELECT
            st.studentAccount,st.studentName,st.studentEmail,st.studentGender,st.studentBirthday,st.studentAddress,st.studentPhone,st.deptID,st.batchID,st.community,st.category,st.bloodGroup,st.admissionType,st.lateral,st.NRI,st.rollNo,st.studentSurname,st.studentFather,st.studentMother,st.studentJoindate,st.myImage,st.sslc,st.plustwo,st.hosteller,st.parentPhone,st.regNo,st.feewaiverScheme,st.admissionNo,st.exitType,st.rfId,st.quotaID AS quotaId,st.ugPercentage,st.casteID,st.fee_reservations_id,st.nationality_id AS nationalityId,st.previousSchool,st.highestExamPassed,st.prev_institute_dateofpassing AS previousDateOfPassing,st.prev_institute_regiNo AS previousRegisterNumber,st.admitSemester AS admittedSemester,st.admissionTCNo,st.busroute,st.state_id AS stateId,st.district_id AS districtId,st.taluk_id AS talukId,st.annualIncome,st.aadhaar_no AS aadharNo,st.poverty_line AS povertyLineId,st.campus_type_id AS campusTypeId,st.joiningSemId,st.casteID,st.reservID,st.otherreservID,st.reservationID,st.phdTopicName,st.phdCurrentStatus,st.guideId,st.secondlangaugeID,st.studentSignImage,studentVerified,st.parentAddress1,st.parentAddress2,st.parentCity,st.parentZipCode,st.parentCountry,st.parentState,st.applicationNo,st.studentLastLogin,st.cap_id,
            nat.nationalityName,
            sl.secondLangaugeName,
            re.religionName AS religion,
            dept.deptName,dept.departmentDesc,
            bat.batchName,
            sem.semName,
            se.parentPincode,se.motherTongue,se.extraAcitivites,se.father_income,se.fatherEmail,se.parentOccupation,se.parentMob,se.motherOccupation,se.motherEmail,se.annualIncome,se.permanentAddress1,se.permanentAddress2,se.motherIncome,se.permacity,se.parentCountry,se.permanentZipCode,se.commuhouse,se.currentState,se.currentCity,se.currentCountry,se.currentZipCode,se.permanentCity,se.permanentState,se.permanentCountry,se.permanentZipCode,se.currentAddress1,se.currentAddress2,se.commuhouse,se.permahouse
            FROM
            studentaccount st
                LEFT JOIN
            studentaccount_extras se ON se.studentID = st.studentID
                LEFT JOIN
            nationality nat ON nat.id = st.nationality_id
                LEFT JOIN
            secondLangauge sl ON sl.secondlangaugeID = st.secondlangaugeID
                LEFT JOIN
            religion re ON re.religionID = st.religion
                LEFT JOIN
            department dept ON dept.deptID = st.deptID
                LEFT JOIN
            batches bat ON bat.batchID = st.batchID
                LEFT JOIN
            semesters sem ON bat.semID = sem.semID
                WHERE
            st.studentID = $studentID;
        ";
        try {
            $studentDetails = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     *get students details by batchIDs
     * @param string $batchIDs
     * @param null $courseTypeID
     * @param null $batchStartYear
     * @return studentDetails
     * @throws ProfessionalException
     */
    public function getStudentsByBatches($batchIDs = null, $courseTypeID = null, $batchStartYear = null)
    {
        $condition = "";
        if ($batchIDs != "ALL") {
            $condition .= " st.batchID in (" . $batchIDs . ") and";
        }
        if ($courseTypeID) {
            $condition .= " b.courseTypeID = $courseTypeID and";
        }
        if ($batchStartYear) {
            $condition .= " b.batchStartYear = $batchStartYear and";
        }
        $condition = rtrim($condition, 'and');
        $batchIDs = $this->realEscapeString($batchIDs);
        try {
            $sql = "SELECT st.studentID, st.studentName, st.rollNo, st.regNo,st.admissionNo,st.studentAccount, sl.secondLangaugeName
            from  studentaccount st
            inner join batches b on st.batchID = b.batchID
            left join secondLangauge sl on sl.secondlangaugeID = st.secondlangaugeID
            where $condition order by b.batchID,length(st.regNo),st.regNo";
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     *get students details in  suply/regular exam registration
     * @param string $batchIDs
     * @return studentDetails
     */
    public function getExamRegisteredStudents($request)
    {
        $request = $this->realEscapeObject($request);
        $examRegType = $request->examRegType;
        $examRegId = $request->examRegId;
        $departmentsSelected = $request->departmentsSelected;
        $batchSelected = is_array($request->batchSelected) ? implode(",", $request->batchSelected) : $request->batchSelected;
        $isMarklistSerialNo = $request->isMarklistSerialNo;
        $secondLanguage = $request->secondLanguage;
        $coursePatternId = $request->coursePatternId;
        $deptIdSql = "";
        $batchIdSql = "";
        $columns = "";
        $joinTable = "";
        $sqlConditions = '';
        if ($secondLanguage) {
            $columns .= ",b.semID AS batchSem,
            sl.secondLangaugeName,
            sl.secondlangaugeID AS secondlangaugeId";
            $joinTable .= "LEFT JOIN
            secondLangauge sl ON sl.secondlangaugeID = sa.secondlangaugeID";
        }
        if ($departmentsSelected) {
            $sqlConditions .= " AND b.deptID IN ($departmentsSelected)";
        }
        if ($batchSelected) {
            $sqlConditions .= " AND e.batchID IN ($batchSelected)";
        }
        if ($examRegType == ExamType::REGULAR) {
            $examRegStudentTable = "exam_reg_studentchallan";
            $examRegStudentTableRegColumnName = "examregID";
            $examRegTable = "exam_registration";
            $examRegTableRegColumnName = "examregID";
            $examTableColumnName = "examregID";
            $markListSerialTableExamRegColumnName = "examregID";
            if($request->excludeStudentsWithCourseMode){
                $sqlConditions .= "  AND (ers.courseMode != '$request->excludeStudentsWithCourseMode' || ers.courseMode is null)";
            }
            // $blockStudentTableExamRegColumnName = "examreg_id";
        } else if ($examRegType == ExamType::SUPPLY) {
            $examRegStudentTable = "exam_supplementary_student_details";
            $examRegStudentTableRegColumnName = "exam_supplementary_id";
            $examRegTable = "exam_supplementary";
            $examRegTableRegColumnName = "id";
            $examTableColumnName = "supply_examreg_id";
            $markListSerialTableExamRegColumnName = "supplyExamRegId";
            // $blockStudentTableExamRegColumnName = "supplyreg_id";
        }
        if ($isMarklistSerialNo) {
            $columns .= ",mss.serialNo,
            mss.createdDate AS issueDate";
            $joinTable .= " LEFT JOIN
            marklist_serialNo_student mss ON mss.studentId = sa.studentID
                AND mss.$markListSerialTableExamRegColumnName = ers.$examRegStudentTableRegColumnName";
        }
        if ($request->includeBatchDetails) {
            $columns .= ",b.batchDesc,
            d.deptID,
            d.deptName,
            d.departmentDesc,
            sem.semName AS sem";
            $joinTable .= " INNER JOIN
            department d ON d.deptID = b.deptID
                INNER JOIN
            semesters sem ON sem.semID = e.semID";
        }
        if ($request->studentIds) {
            $studentIdString = implode(',', $request->studentIds) ? implode(',', $request->studentIds) : $request->studentIds;
            $sqlConditions .= " AND sa.studentID IN($studentIdString)";
        }
        if ($request->coursePatternId) {
            $coursePatternIdString = is_array($request->coursePatternId) ? implode(',', $request->coursePatternId) : $request->coursePatternId;
            $sqlConditions .= " AND b.patternID IN($coursePatternIdString)";
        }
        if ($request->semId) {
            $semIdString = is_array($request->semId) ? implode(',', $request->semId) : $request->semId;
            $sqlConditions .= " AND e.semID IN($semIdString)";
        }
        if ($request->gender) {
            $sqlConditions .= " AND sa.studentGender LIKE '$request->gender'";
        }
        if ($request->batchId) {
            $batchIdString = is_array($request->batchId) ? implode(',', $request->batchId) : $request->batchId;
            $sqlConditions .= " AND b.batchID IN($batchIdString)";
        }
        try {
            $sql = "SELECT DISTINCT
            sa.studentID,
            sa.studentName,
            sa.batchID,
            sa.myImage,
            sa.regNo,
            sa.rollNo,
            e.semID,
            b.batchName,
            b.batchOptionName,
            pdc.patterncourseCode
            $columns
        FROM
            $examRegStudentTable ers
                INNER JOIN
            studentaccount sa ON ers.studentID = sa.studentID
                INNER JOIN
            batches b ON sa.batchID = b.batchID
            LEFT JOIN pattern_deptcourses pdc ON pdc.patterncourseID = b.patterncourseID
                INNER JOIN
            exam e ON e.$examTableColumnName = ers.$examRegStudentTableRegColumnName
                AND b.batchID = e.batchID
                $joinTable
        WHERE
            ers.paid = 1
            $sqlConditions
            AND ers.$examRegStudentTableRegColumnName = $examRegId
        ORDER BY sa.batchID, sa.regNo";
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /*
     * @author Vishnu M
     */
    public function getStudentSpecialization($studentId, $batchId, $semId)
    {
        $studentId = $this->realEscapeString($studentId);
        $batchId = $this->realEscapeString($batchId);
        $semId = $this->realEscapeString($semId);
        $specialization = null;
        $sql = "SELECT sm.specialisationName FROM specialisation_master sm INNER JOIN specialisation_student_relation ssr ON (sm.id = ssr.specialisationId) WHERE ssr.studentID = '$studentId' AND ssr.batchID = '$batchId' AND ssr.semID = '$semId";
        try {
            $specialization = $this->executeQueryForObject($sql)->specialisationName;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $specialization;
    }
    /**
     * Get student details (failed) by batchId & semId
     * @param Integer $previousBatchId
     * @param Integer $semId
     * @return objectList[]
     * @throws ProfessionalException
     * @author Vishnu M
     */
    public function getFailedStudentDetails($previousBatchId, $semId)
    {
        $sql = '';
        $previousBatchId = $this->realEscapeString($previousBatchId);
        $semId = $this->realEscapeString($semId);
        $batchShuffle = FailedReason::BATCH_SHUFFLE;
        $studentDetails = [];
        try {
            $sql = "SELECT sa.studentID, sa.studentName, sa.regNo, sa.rollNo, sa.admissionNo, sa.myImage,
            sa.studentSignImage FROM studentaccount sa INNER JOIN failed_students fs ON fs.studentID = sa.studentID WHERE fs.previousBatch = $previousBatchId AND fs.failedInSemester > '$semId' AND FIND_IN_SET('$semId', fs.hisSemestersInThisbatch) AND (fs.reason != '$batchShuffle' OR fs.reason IS NULL)";
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     *get students details by batchIDs
     * @param object $request
     * @return studentDetails
     * @throws ProfessionalException
     */
    public function getStudentsInRangeByBatches($request)
    {
        $request = $this->realEscapeObject($request);
        $batchSelected = $request->batchSelected;
        $registerNumberFrom = $request->registerNumberFrom;
        $registerNumberTo = $request->registerNumberTo;
        $secondLanguage = $request->secondLanguage;
        $whereCondition = "";
        $joinTable = "";
        $columns = "";
        $unionCond = "";
        if ($batchSelected) {
            $whereCondition .= " AND b.batchID IN ($batchSelected)";
        }
        if ($batchSelected) {
            $columns .= ",
                sl.secondlangaugeID,
                sl.secondLangaugeName";
            $joinTable .= "    LEFT JOIN
            secondLangauge sl ON sl.secondlangaugeID = sa.secondlangaugeID";
        }
        if ($request->considerSecondLanguage2) {
            $columns .= ",
                sl2.secondlangaugeID as secLang2ID,
                sl2.secondLangaugeName as secLang2Name";
            $joinTable .= "    LEFT JOIN
            secondLangauge sl2 ON sl2.secondlangaugeID = sa.secondLanguage2ID";
        }
        if ($registerNumberFrom && $registerNumberTo) {
            $whereCondition .= " AND sa.regNo BETWEEN '$registerNumberFrom' AND '$registerNumberTo'";
        } elseif ($registerNumberFrom) {
            $whereCondition .= " AND sa.regNo IN ('$registerNumberFrom')";
        } elseif ($registerNumberTo) {
            $whereCondition .= " AND sa.regNo IN ('$registerNumberTo')";
        }
        if ($request->considerFailedStudents && $request->semId) {
            $unionCond = " UNION
                SELECT
                    sa.studentID,
                    sa.studentName,
                    sa.rollNo,
                    sa.regNo,
                    b.semID$columns
                FROM
                    failed_students fs
                    INNER JOIN
                        studentaccount sa ON fs.studentID = sa.studentID
                        INNER JOIN
                    batches b ON fs.previousBatch = b.batchID AND FIND_IN_SET($request->semId, fs.hisSemestersInThisbatch)
                    $joinTable
                WHERE
                    b.batchName <> 'failed'
                    $whereCondition ";
            $whereCondition .= " AND studentID NOT IN (SELECT fs.studentID from failed_students fs WHERE fs.studentID = sa.studentID AND FIND_IN_SET($request->semId, fs.hisSemestersInThisbatch))";
        }
        try {
            $sql = "SELECT
                sa.studentID,
                sa.studentName,
                sa.rollNo,
                sa.regNo,
                b.semID$columns
            FROM
                studentaccount sa
                    INNER JOIN
                batches b ON sa.batchID = b.batchID
                $joinTable
            WHERE
                b.batchName <> 'failed'
                $whereCondition  $unionCond
            ORDER BY regNo";
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    public function getGenders()
    {
        $query = "SELECT gid AS id,gname AS name FROM gender";
        try {
            $response = $this->executeQueryForList($query);
            return $response;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Add specializations
     * @param String $specializationName
     * @return Boolean
     * @throws ProfessionalException
     * @author anoop
     */
    public function addStudentSpecialization($specializationName)
    {
        $sql = '';
        $specializationName = $this->realEscapeString($specializationName);
        try {
            $sql = "INSERT INTO specialisation_master (specialisationName) VALUES('$specializationName')";
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return true;
    }
    /**
     * Get student details with specializations
     * @param String $specializationName
     * @return Boolean
     * @throws ProfessionalException
     * @author anoop
     */
    public function getStudentsSpecializationDetail($request)
    {
        $sql = '';
        $request = $this->realEscapeObject($request);
        $studentId = $request->studentId;
        $semId = $request->semId;
        $batchId = $request->batchId;
        try {
            $sql = "SELECT
            sm.id,
            sm.specialisationName
        FROM
            specialisation_student_relation ssr
                LEFT JOIN
            specialisation_master sm ON ssr.specialisationId = sm.id
        WHERE
            ssr.studentId = '$studentId'
                AND
            ssr.semId = '$semId'
                AND
            ssr.batchId = '$batchId'";
            $specialization = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $specialization;
    }
    /**
     * assign specializations to student
     * @param String $specializationName
     * @return Boolean
     * @throws ProfessionalException
     * @author anoop
     */
    public function assignSpecializationToStudent($request)
    {
        $sql = '';
        $request = $this->realEscapeObject($request);
        $studentId = $request->studentId;
        $semId = $request->semId;
        $batchId = $request->batchId;
        $specializationId = $request->specializationId;
        try {
            $sql = "INSERT INTO specialisation_student_relation (specialisationId, studentId, semId, batchId) VALUES('$specializationId','$studentId','$semId','$batchId')";
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return true;
    }
    /**
     * Update specializations to student
     * @param String $specializationName
     * @return Boolean
     * @throws ProfessionalException
     * @author anoop
     */
    public function updateSpecializationToStudent($request)
    {
        $sql = '';
        $request = $this->realEscapeObject($request);
        $studentId = $request->studentId;
        $semId = $request->semId;
        $batchId = $request->batchId;
        $specializationId = (int)$request->specializationId;
        try {
            if($specializationId){
                $sql = "UPDATE specialisation_student_relation
                    SET specialisationId = '$specializationId'
                    WHERE studentId = '$studentId'
                    AND semId = '$semId'
                    AND batchId = '$batchId'";
            }
            else{
                $sql ="DELETE FROM specialisation_student_relation
                    WHERE studentId = '$studentId'
                    AND semId = '$semId'
                    AND batchId = '$batchId'";
            }
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $specialization;
    }
    /**
     * Get specializations
     * @param String $specializationName
     * @return Boolean
     * @throws ProfessionalException
     * @author anoop
     */
    public function getSpecializationDetail()
    {
        try {
            $sql = "SELECT
            sm.id,
            sm.specialisationName AS name
        FROM
            specialisation_master sm";
            $specializations = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $specializations;
    }
    /**
     * Get student details by subBatchId
     * @param Integer $subbatchId
     * @return objectList[]
     * @throws ProfessionalException
     * @author anoop
     */
    public function getStudentDetailsBySubBatch($subBatchId)
    {
        $sql = '';
        $subBatchId = $this->realEscapeString($subBatchId);
        $studentDetails = NULL;
        try {
            $sql = "SELECT
            sa.studentID,
            sa.studentName,
            sa.regNo,
            sa.rollNo,
            sa.admissionNo
        FROM
            studentaccount sa
                INNER JOIN
            subbatch_student ss ON ss.studentID = sa.studentID
        WHERE
            ss.subbatchID IN ($subBatchId)";
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * Get student details by SubjectId and internal marks
     * @param Integer $subbatchId
     * @return objectList[]
     * @throws ProfessionalException
     * @author anoop
     */
    public function getStudentDetailsByRequestWithInternalMark($request)
    {
        $sql = '';
        $request = $this->realEscapeObject($request);
        $subjectId = $request->subjectId;
        $batchId = $request->batchId;
        $semesterId = $request->semesterId;
        $subBatchId = $request->subBatchId;
        $examTypeId = $request->examTypeId;
        $examId = $request->examId;
        $studentDetails = NULL;
        $innerJoinTables = "";
        $whereConditions = "";
        $joinConditionsForStudentMarks = "AND sm.subjectID = e.subjectID
                                            AND sm.semID = e.semID
                                            AND sm.batchID = e.batchID
                                            AND sm.examID = e.examID";
        if ($semesterId) {
            $whereConditions .= " AND sr.semID = $semesterId";
        }
        if ($examId) {
            // $whereConditions .= " AND sm.examID IN ($examId)" ;
        }
        if ($batchId) {
            $whereConditions .= " AND sr.batchID = $batchId";
        }
        if ($subjectId) {
            $whereConditions .= " AND sr.subjectID = $subjectId";
        }
        if ($subBatchId != NULL) {
            $whereConditions .= " AND ss.subbatchID IN ($subBatchId)";
            $whereConditions .= " AND e.subbatchID = ss.subbatchID ";
            $joinConditionsForStudentMarks ="AND sm.subjectID = e2.subjectID
                                            AND sm.semID = e2.semID
                                            AND sm.batchID = e2.batchID
                                            AND sm.examID = e2.examID";
        }
        if ($examTypeId) {
            $whereConditions .= " AND e.examTypeID IN ($examTypeId)";
        }
        try {
            $sql = "SELECT DISTINCT
            sa.studentID,
            sa.studentName,
            sa.regNo,
            sa.rollNo,
            sa.admissionNo,
            ss.subbatchID,
            CASE
                WHEN sm.marksObtained >= 0 THEN sm.marksObtained
                WHEN sm.marksObtained = -1 THEN 'AB'
                WHEN CAST( sm.marksObtained AS DECIMAL(4,3)) = -0.001 THEN 'MAL'
                WHEN sm.marksObtained IS NULL THEN ''
            END AS marks,
            e.examID,
            e.examName,
            e.examTotalMarks,
            e.subjectID
        FROM
        studentaccount sa
            INNER JOIN
        sbs_relation sr ON sr.batchID = sa.batchID
            INNER JOIN
        exam e ON e.subjectID = sr.subjectID
            AND e.semID = sr.semID
            AND e.batchID = sr.batchID
            LEFT JOIN
        subbatch_sbs ssbs ON ssbs.sbsID = sr.sbsID
            LEFT JOIN
        subbatch_student ss ON ss.studentID = sa.studentID
            AND ss.subbatchID = ssbs.subbatchID
            LEFT JOIN
        exam e2 ON e2.subjectID = sr.subjectID
            AND e2.semID = sr.semID
            AND e2.batchID = sr.batchID
            AND e2.subbatchID = ssbs.subbatchID
            AND e2.examTypeID = e.examTypeID
            LEFT JOIN
        student_marks sm ON sm.studentID = sa.studentID
            $joinConditionsForStudentMarks
        WHERE
            1 = 1
            $whereConditions
        GROUP BY sa.studentID
        ORDER BY sa.regNo ASC";
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    public function getDomiciles()
    {
        $query = "SELECT id,name FROM admission_domicile";
        try {
            $domiciles = $this->executeQueryForList($query);
            return $domiciles;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * get transportation Id of student by student Id
     * @param  $studentId
     * @return
     * @throws ProfessionalException
     * @throws ProfessionalException
     * @author anoop
     */
    public function studentTransportaionId($studentId)
    {
        $sql = '';
        $studentId = $this->realEscapeString($studentId);
        try {
            $sql = "SELECT brbpID FROM transportation_students WHERE studentID = $studentId";
            $transportaionId = $this->executeQueryForObject($sql)->brbpID;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $transportaionId;
    }
    /**
     * @param $studentId
     * @return mixed
     * @throws ProfessionalException
     */
    public function getStudentNameById($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        $sql = "SELECT studentName FROM studentaccount WHERE studentID  =$studentId";
        try {
            return $this->executeQueryForObject($sql)->studentName;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param $batchID
     * @param $deptID
     * @return mixed
     * @throws ProfessionalException
     */
    public function getStudentListByBatchIdAndDeptId($batchID, $deptID)
    {
        $batchID = $this->realEscapeString($batchID);
        $deptID = $this->realEscapeString($deptID);
        $condition = "";
        $condition .= $batchID ? "AND st.batchID = $batchID " : "";
        $condition .= $deptID ? "AND bat.deptID = $deptID " : "";
        $sql = "select st.studentID,st.studentName from
                studentaccount st
                inner join batches bat on st.batchID = bat.batchID
                inner join department dept on dept.deptID = bat.deptID where 1=1 $condition ;";
        try {
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param $studentId
     * @param bool $considerPassoutSem
     * @return bool
     * @throws ProfessionalException
     * @author Vishnu M
     */
    public function isStudentInFinalSemester($studentId, $considerPassoutSem = FALSE)
    {
        $studentId = $this->realEscapeString($studentId);
        $considerPassoutSem = $this->realEscapeString($considerPassoutSem);
        $sql = null;
        $condition = null;
        if ($considerPassoutSem == TRUE) {
            $condition .= " AND s.orderNo >= b.final_semester ";
        } else {
            $condition .= " AND s.orderNo = b.final_semester ";
        }
        try {
            $sql = "SELECT s.semID FROM studentaccount sa INNER JOIN batches b ON b.batchID = sa.batchID INNER JOIN semesters sem ON b.semID = sem.semID INNER JOIN semesters s ON s.type = sem.type WHERE s.semID = b.semID AND sa.studentID = '$studentId" . $condition . " ";
            $result = $this->executeQueryForObject($sql);
            if (!empty ($result)) {
                return true;
            }
            return false;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param GetStudentForAdmissionRegisterRequest $request
     * @return array|Object
     * @throws ProfessionalException
     */
    public function getStudentDetailsByBatchAndCampusType(GetStudentForAdmissionRegisterRequest $request, $includeDiscontinued = "false")
    {
        GLOBAL $KARNATAKA;
        $hasUucmsid = $KARNATAKA?",sa.uucmsid":"";
        $request = $this->realEscapeObject($request);
        $studentDetails = [];
        $whereConditions = "";
        if (!empty($request->campusTypeId) && !$request->isBatchWiseCampusType) {
            $whereConditions .= " AND sac.id = $request->campusTypeId ";
        } elseif (!empty($request->campusTypeId)) {
            $whereConditions .= " AND bc.id = $request->campusTypeId ";
        }
        if (!empty($request->batchIds)) {
            $whereConditions .= " AND sa.batchID IN (" . implode(",", $request->batchIds) . ")";
        }
        $sql = "SELECT sa.studentID AS studentId, sa.myImage, sa.studentSignImage, sa.admissionNo, sl.secondLangaugeName
        AS secondLanguageName, sa.rollNo, sa.studentName, sa.studentGender, rs.reservationName,
        sa.studentBirthday AS dateOfBirth, sa.studentJoindate AS studentJoinDate, sa.regNo, sca.casteName,
        re.religionName, aq.quotaCode,sa.aadhaar_no, sa.studentFather, se.annualIncome, se.parentOccupation,
        sa.parentPhone, sa.studentMother, se.motherOccupation, se.motherIncome, se.commuhouse, se.currentAddress1,
        se.currentAddress2, se.currentState, se.currentCity, se.currentCountry, se.currentZipCode, sa.previousSchool,
        sa.yearOfPassing, bt.batchName,bt.batchStartYear, bt.batchEndYear,cp.patternDesc as courseDesc, sr.reservName as seatReservName, ct.is_pg, se.motherPhone,sac.name as studentCampusType,
        sa.father_salutation, sa.mother_salutation, sa.studentPhone, sa.parentAddress1, sa.parentAddress2,sa.parentCity,
        sa.parentZipCode,aq.quotaName, sa.prev_institute_regiNo, sa.prev_institute_dateofpassing, stc.tcNo, stc.issueDate,
        s.semName as joinSem,pd.patterncourseCode as courseCode, sa.studentAddress, sae.studentResPhone,dpt.deptName,
        stc.leavingDate,stc.leaving_deptID,stc.lastSemId,stc.reasonForLeave,stc.remarks,sccc.ccNo,
        sccc.createdDate as courseConductCertificateDate,ldept.deptName as leavingDept,sa.category,nat.nationalityName,sa.state,se.motherTongue,sc.subsiderycoursename,se.placeofBirth,stat.state_name as stateName,pd.patterncourseName,sa.admissionTCNo$hasUucmsid
                FROM studentaccount sa INNER JOIN batches bt ON bt.batchID=sa.batchID
                INNER JOIN batch_course_type ct ON ct.id=bt.patternID
                INNER JOIN batches b ON b.batchID =sa.batchID
                LEFT JOIN secondLangauge sl ON sa.secondlangaugeID = sl.secondlangaugeID
                LEFT JOIN reservation_students rs ON rs.reservationID = sa.reservationID
                LEFT JOIN student_caste sca on sa.casteID = sca.casteID
                LEFT JOIN religion re ON sa.religion = re.religionID
                LEFT JOIN admission_quotas aq ON sa.quotaID = aq.quotaID
                LEFT JOIN student_reservation sr ON sr.reservID=sa.reservID
                LEFT JOIN studentaccount_extras se ON se.studentID=sa.studentID
                LEFT JOIN campus_type sac on sa.campus_type_id = sac.id
                LEFT JOIN campus_type bc ON bc.id = b.campus_typeID
                LEFT JOIN studentTransferCertificate stc ON stc.studentId=sa.studentID
                LEFT JOIN studentCourseConductCertificate sccc on sccc.studentId = sa.studentID
                LEFT JOIN department ldept on stc.leaving_deptID = ldept.deptID
                LEFT JOIN semesters s ON s.semID=sa.joiningSemId
                LEFT JOIN pattern_deptcourses pd ON pd.patterncourseID=b.patterncourseID
                LEFT JOIN subsiderycourse sc ON sc.pattern_deptcourses_id = pd.patterncourseID
                LEFT JOIN department dpt ON dpt.deptID=bt.deptID
                LEFT JOIN state stat ON stat.id = sa.state_id
                LEFT JOIN nationality nat ON nat.id = sa.nationality_id
                LEFT JOIN course_pattern cp ON cp.patternID = pd.patternID
                LEFT JOIN studentaccount_extras sae ON sae.studentID=sa.studentID
                WHERE 1=1 $whereConditions  ";
        if ($includeDiscontinued == "true") {
            $failedWhereConditions = "";
            if (!empty($request->campusTypeId) && !$request->isBatchWiseCampusType) {
                $failedWhereConditions .= " AND sac.id = $request->campusTypeId ";
            } elseif (!empty($request->campusTypeId)) {
                $failedWhereConditions .= " AND bc.id = $request->campusTypeId ";
            }
            if (!empty($request->batchIds)) {
                $failedWhereConditions .= " AND fs.previousBatch IN (" . implode(",", $request->batchIds) . ")";
            }
            $sql .= " UNION
                SELECT sa.studentID AS studentId, sa.myImage, sa.studentSignImage, sa.admissionNo, sl.secondLangaugeName
                AS secondLanguageName, sa.rollNo, sa.studentName, sa.studentGender, rs.reservationName,
                sa.studentBirthday AS dateOfBirth, sa.studentJoindate AS studentJoinDate, sa.regNo, sca.casteName,
                re.religionName, aq.quotaCode,sa.aadhaar_no, sa.studentFather, se.annualIncome, se.parentOccupation,
                sa.parentPhone, sa.studentMother, se.motherOccupation, se.motherIncome, se.commuhouse, se.currentAddress1,
                se.currentAddress2, se.currentState, se.currentCity, se.currentCountry, se.currentZipCode, sa.previousSchool,
                sa.yearOfPassing, b.batchName, sr.reservName as seatReservName, ct.is_pg, se.motherPhone,sac.name as studentCampusType,
                sa.father_salutation, sa.mother_salutation, sa.studentPhone, sa.parentAddress1, sa.parentAddress2,sa.parentCity,
                sa.parentZipCode,aq.quotaName, sa.prev_institute_regiNo, sa.prev_institute_dateofpassing, stc.tcNo, stc.issueDate,
                s.semName as joinSem,pd.patterncourseCode as courseCode, sa.studentAddress, sae.studentResPhone,dpt.deptName ,
                stc.leavingDate,stc.leaving_deptID,stc.lastSemId,stc.reasonForLeave,stc.remarks,sccc.ccNo,
                sccc.createdDate as courseConductCertificateDate,ldept.deptName as leavingDept,sa.category,nat.nationalityName,sa.state,se.motherTongue,sc.subsiderycoursename,se.placeofBirth,stat.state_name as stateName,pd.patterncourseName,sa.admissionTCNo$hasUucmsid
                    FROM studentaccount sa INNER JOIN failed_students fs ON fs.studentID=sa.studentID
                    INNER JOIN batches b ON b.batchID =fs.previousBatch
                    INNER JOIN batch_course_type ct ON ct.id=b.patternID
                    LEFT JOIN secondLangauge sl ON sa.secondlangaugeID = sl.secondlangaugeID
                    LEFT JOIN reservation_students rs ON rs.reservationID = sa.reservationID
                    LEFT JOIN student_caste sca on sa.casteID = sca.casteID
                    LEFT JOIN religion re ON sa.religion = re.religionID
                    LEFT JOIN admission_quotas aq ON sa.quotaID = aq.quotaID
                    LEFT JOIN student_reservation sr ON sr.reservID=sa.reservID
                    LEFT JOIN studentaccount_extras se ON se.studentID=sa.studentID
                    LEFT JOIN campus_type sac on sa.campus_type_id = sac.id
                    LEFT JOIN campus_type bc ON bc.id = b.campus_typeID
                    LEFT JOIN studentTransferCertificate stc ON stc.studentId=sa.studentID
                    LEFT JOIN studentCourseConductCertificate sccc on sccc.studentId = sa.studentID
                    LEFT JOIN department ldept on stc.leaving_deptID = ldept.deptID
                    LEFT JOIN semesters s ON s.semID=sa.joiningSemId
                    LEFT JOIN pattern_deptcourses pd ON pd.patterncourseID=b.patterncourseID
                    LEFT JOIN subsiderycourse sc ON sc.pattern_deptcourses_id = pd.patterncourseID
                    LEFT JOIN department dpt ON dpt.deptID=b.deptID
                    LEFT JOIN state stat ON stat.id = sa.state_id
                    LEFT JOIN nationality nat ON nat.id = sa.nationality_id
                    LEFT JOIN studentaccount_extras sae ON sae.studentID=sa.studentID
                    WHERE 1=1 $failedWhereConditions ";
        }
        $sql .= " ORDER BY $request->sortBy";
        try {
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * Return student batch id by student id
     *
     * @param $studentId
     * @return mixed
     * @throws ProfessionalException
     * @author jithinvijayan
     */
    public function getStudentBatchIdByStudentId($studentId)
    {
        $sql = "SELECT b.batchID  as batchId
                FROM studentaccount sa
                INNER JOIN batches b ON b.batchID = sa.batchID
                WHERE studentID  = $studentId";
        try {
            return $this->executeQueryForObject($sql)->batchId;
        } catch (Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getStudentList($batchID, $semID, $subBatchID, $sortByColumn)
    {
        $batchID = $this->realEscapeString($batchID);
        $semID = $this->realEscapeString($semID);
        $subBatchID = $this->realEscapeString($subBatchID);
        $sortByColumn = $this->realEscapeString($sortByColumn);
        $sort = $sortByColumn ? "ORDER BY " . $sortByColumn : "";
        $isCurrentSem = SemesterService::getInstance()->isCurrentSemester($batchID, $semID);
        if ($isCurrentSem) {
            if ($subBatchID) {
                $sql = "select  sa.studentID, sa.studentAccount, sa.studentName,UPPER(sa.studentGender) as gender , sa.rollNo, sa.regNo, ba.semID,sem.semName
                from  studentaccount sa
                inner join subbatch_student ss on sa.studentID = ss.studentID
                inner join batches ba on  ba.batchID = sa.batchID
                inner join semesters sem on ba.semID = sem.semID
                inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID
                where sa.batchID=$batchID and ss.subbatchID = $subBatchID and joinedSem.orderNo <= sem.orderNo $sort;";
            } else {
                $sql = "select sa.studentID, sa.studentAccount, sa.studentName,UPPER(sa.studentGender) as gender , sa.rollNo, sa.regNo, ba.semID ,sem.semName
                from  studentaccount sa
                inner join batches ba on  ba.batchID = sa.batchID
                inner join semesters sem on sem.semID = ba.semID
                inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID where sa.batchID=$batchID and joinedSem.orderNo <= sem.orderNo $sort;";
            }
        } else {
            $semDetails = SemesterService::getInstance()->getSemDetailsBySemId($semID);
            if ($subBatchID) {
                $sql = "
                select  sa.studentID, sa.studentAccount, sa.studentName,UPPER(sa.studentGender) as gender , sa.rollNo, sa.regNo ,sem.semID, sem.semName
                from studentaccount sa
                inner join subbatch_student ss on sa.studentID = ss.studentID
                inner join subbatch_sbs subs on subs.subbatchID = ss.subbatchID
                inner join sbs_relation sbs on sbs.sbsID = subs.sbsID
                inner join semesters sem on sem.semID = sbs.semID
                where  ss.subbatchID = $subBatchID and  sa.studentID
                in(
                    select studentID
                    from studentaccount sa
                    inner join batches ba on sa.batchID = ba.batchID
                    inner join semesters sem on sem.semID = ba.semID
                    inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID
                    where ba.batchID = $batchID and joinedSem.orderNo <= $semDetails->orderNo
                    union
                    select sa.studentID
                    from failed_students fs
                    inner join studentaccount sa on sa.studentID = fs.studentID
                    inner join semesters fsem on fsem.semID = fs.failedInSemester
                    inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID
                    where previousBatch = $batchID and fsem.orderNo > $semDetails->orderNo and joinedSem.orderNo <= $semDetails->orderNo
                    )
                $sort";
            } else {
                $sql = "
                select sa.studentID, sa.studentAccount, sa.studentName, sa.rollNo,UPPER(sa.studentGender) as gender , sa.regNo ,joinedSem.semID,joinedSem.semName
                from studentaccount sa
                inner join batches ba on sa.batchID =  ba.batchID
                inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID
                where ba.batchID = $batchID and joinedSem.orderNo <= $semDetails->orderNo
                union
                select sa.studentID, sa.studentAccount, sa.studentName,UPPER(sa.studentGender) as gender , sa.rollNo, sa.regNo ,joinedSem.semID,joinedSem.semName
                from failed_students fs
                left join studentaccount sa on fs.studentID= sa.studentID
                inner join department dep on dep.deptID = sa.deptID
                inner join semesters fsem on fsem.semID = fs.failedInSemester
                inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID
                where previousBatch =$batchID and fsem.orderNo > $semDetails->orderNo and joinedSem.orderNo <= $semDetails->orderNo $sort";
            }
        }
        try {
            $studentDetails = $this->executeQueryForList($sql);
            return $studentDetails;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /** Formways services**/
    /**
     * get all student for api with total count
     * @param GetStudentsRequest $request
     * @return object|array|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     * @author gadheyan
     */
    public function getAllStudentsForFormways(GetStudentsRequest $request)
    {
        $responseList = [];
        $request = $this->realEscapeObject($request);
        $sql = "SELECT sa.studentID AS value,
        sa.studentName AS label
        FROM
        studentaccount sa
        WHERE 1=1 ";
        if ($request) {
            if ($request->id) {
                $filter .= "AND sa.studentID = '$request->id'";
            }
            if ($request->deptId) {
                $filter .= "AND sa.deptID = '$request->deptId'";
            }
            if ($request->batchId) {
                $filter .= "AND sa.batchID = '$request->batchId'";
            }
            if ($request->studentLock) {
                $filter .= "AND sa.student_lock = '$request->studentLock'";
            }
            if ($request->username) {
                $filter .= "AND sa.studentAccount = '$request->username'";
            }
            if ($request->name) {
                $filter .= "AND sa.studentName like '%$request->name%'";
            }
            if ($request->email) {
                $filter .= "AND sa.studentEmail = '$request->email'";
            }
            if ($request->gender) {
                $filter .= "AND sa.studentGender = '$request->gender'";
            }
            if ($request->phoneNo) {
                $filter .= "AND sa.studentPhone = '$request->phoneNo'";
            }
            if ($request->category) {
                $filter .= "AND sa.category = '$request->category'";
            }
            if ($request->bloodGroup) {
                $filter .= "AND sa.bloodGroup = '$request->bloodGroup'";
            }
            if ($request->admissionNo) {
                $filter .= "AND sa.admissionNo = '$request->admissionNo'";
            }
            if ($request->admissionQuota) {
                $filter .= "AND aq.quotaName = '$request->admissionQuota'";
            }
            if ($request->religion) {
                $filter .= "AND r.religionName = '$request->religion'";
            }
            if ($request->caste) {
                $filter .= "AND c.casteName = '$request->caste'";
            }
        }
        if ($request->sortBy) {
            $orderBy = " ORDER BY $request->sortBy $request->sortOrder";
        }
        $pagination = " LIMIT " .
            ((int)$request->_page - 1) * (int)$request->_pageSize . "," .
            (int)$request->_pageSize;
        try {
            $sql = $sql . $filter . $orderBy . $pagination;
            $studentRecords = $this->executeQueryForList($sql);
            return $studentRecords;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Get list of student gender
     *
     * @throws ProfessionalException
     */
    public function getStudentGenderList()
    {
        $sql = "SELECT DISTINCT studentGender AS name FROM studentaccount";
        try {
            return $this->executeQueryForList($sql);
        } catch (Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getStudentDetailsForPrintForm($studentId)
    {
        $studentDetails = NULL;
        $studentId = $this->realEscapeString($studentId);
        $sql = "SELECT sa.studentID as id,
            sa.studentName as name,
            sa.studentAccount,
            sa.regNo,
            sa.rollNo,
            sa.admissionNo,
            sa.studentEmail,
            sa.studentPhone,
            sa.parentPhone,
            dept.deptName,
            bth.batchName,
            dept.deptID,
            bth.batchID,
            bth.patternID as courseTypeId,
            bct.type_name as typeName,
            bth.batchStartYear as startYear,
            bth.batchEndYear as endYear,
            dept.departmentDesc,
            sa.tcIssued,
            sa.studentAddress,
            sa.studentEmail,
            sa.studentPhone,
            sem.semID,
            sem.semName,
            sem.year,
            sem.orderNo,
            sem.type,
            sa.studentJoindate,
            sa.exitType,
            sa.studentSignImage,
            sa.quotaID as quotaId,
            sa.student_lock,
            na.nationalityName,
            sa.previousSchool as previousSchool,
            sa.highestExamPassed as highestExamPassed,
            sa.prev_institute_dateofpassing as previousPassDate,
            sa.prev_institute_regiNo as prevRegNo,
            sa.admissionTCNo as admissionTCNo,
            sa.busroute as busroute,
            sa.state_id as stateId,
            sa.district_id as districtId,
            sa.taluk_id as talukId,
            sa.annualIncome as annualIncome,
            sa.aadhaar_no as aadharNo,
            sa.poverty_line as povertyLineId,
            sa.campus_type_id as campusTypeId,
            sa.secondlangaugeID as secondLanguageId,
            sa.joiningSemId as joiningSemId,
            sa.reservID as reservID,
            sa.reservationID as studentReservationID,
            sa.phdTopicName as phpTopicName,
            sa.phdCurrentStatus as currentStatus,
            sa.guideId as guideId,
            sl.secondLangaugeName,
            pdc.patterncourseName,
            pdc.patterncourseCode,
            pdc.patterncourseID,
            pdc.patternAbbreviation AS patternAbbreviation,
            sa.religion AS religion,
            sa.community,
            sa.category,
            sa.studentBirthday,
            sa.studentFather,
            sa.sslc,
            sa.plustwo,
            sa.parentOccupation,
            sa.studentGender,
            sa.myImage,
            sa.studentSignImage,
            sc.subsiderycoursename AS subsideryCourseName,
            se.entranceRank,
            sa.plustwo,
            sa.studentFather,
            sa.studentMother,
            se.parentOccupation as fatherOccupation,
            se.motherOccupation,
            aq.quotaName,
            se.commuhouse,
            se.commupin,
            se.currentAddress1,
            se.currentAddress2,
            se.permahouse,
            se.permapin,
            se.permanentAddress1,
            se.permanentAddress2,
            se.currentCity,
            se.permanentCity,
            se.permanentZipCode,
            se.currentZipCode,
            bct.type_code AS coursePatternName,
            bct.is_pg AS isPG,sr.reservName as reservationName,
            sa.cap_id,
            sa.bloodGroup,
            re.religionName,
            se.fatherEmail,
            se.motherEmail,
            se.parentMob,
            se.motherPhone,
            se.guardian_address_line1,
            se.guardian_address_line2,
            se.guardian_address_line3,
            se.guardian_address_city,
            se.guardian_address_state,
            se.guardian_address_zip_code,
            se.guardian_address_country,
            sa.applicationNo,
            se.motherIncome,
            se.fatherCurrency,
            se.motherCurrency,
            ad.name as domicileName,
            sa.studentSignImage as SignImage
            FROM studentaccount sa INNER JOIN department dept ON sa.deptID=dept.deptID INNER JOIN batches bth ON sa.batchID=bth.batchID LEFT JOIN batch_course_type bct ON bth.patternID = bct.id left join semesters sem on sem.semID = bth.semID left join secondLangauge sl on sl.secondlangaugeID = sa.secondlangaugeID left join pattern_deptcourses pdc ON bth.patterncourseID = pdc.patterncourseID LEFT JOIN subsiderycourse sc ON pdc.patterncourseID = sc.pattern_deptcourses_id LEFT JOIN studentaccount_extras se ON se.studentID = sa.studentID LEFT JOIN admission_quotas aq ON aq.quotaID = sa.quotaID LEFT JOIN student_reservation sr ON sr.reservID = sa.reservID LEFT JOIN religion re ON re.religionID=sa.religion LEFT JOIN nationality na ON na.id = sa.nationality_id LEFT JOIN
            admission_domicile ad ON ad.id = sa.domicile_id WHERE sa.studentID = $studentId";
        try {
            $studentDetails = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    public function getStudentEducationDetailsByStudentIdAndQualification($studentId, $qualification)
    {
        $studentId = $this->realEscapeString($studentId);
        $qualification = $this->realEscapeString($qualification);
        try {
            $sql = "SELECT * FROM student_previous_education_details where studentId=$studentId and qualification=\"$qualification\"";
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param $name
     * @return Object
     * @throws AMSException
     *
     */
    public function searchStudenttByString($details)
    {
        $details = $this->realEscapeString($details);
        $sql = "SELECT * FROM studentaccount WHERE 1=1 ";
        if ($details->studentName) {
            $sql .= "AND studentName LIKE '%$details->studentName%'";
        }
        if ($details->studentMob) {
            $sql .= "AND studentPhone LIKE '%$details->studentMob%'";
        }
        if ($details->parentMob) {
            $sql .= "AND parentPhone LIKE '%$details->parentMob%'";
        }
        try {
            $subjects = $this->executeQueryForList($sql);
            return $subjects;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getPreviousBatch($studentId)
    {
        $sql = "";
        $studentId = $this->realEscapeObject($studentId);
        $studentIdString = is_array($studentId) ? implode(',', $studentId) : $studentId;
        $sql = "SELECT studentID AS studentId, previousBatch  FROM failed_students WHERE studentID IN ($studentIdString) AND isFailNow = 0";
        try {
            $studentBatches = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentBatches;
    }
    /**
     * @param $name
     * @return Object
     * @throws AMSException
     *
     */
    public function getStudentsMarksCardSerialNoInBatch($batchId, $type, $supplyId = null)
    {
        $batchId = $this->realEscapeArray($batchId);
        $batchId = is_array($batchId) ? implode(",", $batchId) : $batchId;
        $type = $this->realEscapeString($type);
        $supplyId = $this->realEscapeString($supplyId);
        $condition = "";
        if ($type == MarkList::REGULAR) {
            $columnTobeNull = "supplyExamRegId";
            $semColumn = "erb.semID AS semId,";
            $leftJoin = "LEFT JOIN exam_registration_batches erb ON
            erb.batchID = sa.batchID
            AND erb.examregID = mss.examRegId";
        } else if ($type == MarkList::SUPPLEMENTARY) {
            $columnTobeNull = "examRegId";
            $semColumn = "sib.current_semID AS semId,";
            $leftJoin = "LEFT JOIN supply_improve_batches sib ON
            sib.batchID = sa.batchID
            AND sib.exam_supplementary_id = mss.supplyExamRegId";
            $condition = " AND msn.`type` NOT IN ('" . MarkList::CONSOLIDATED . "') AND mss.supplyExamRegId = $supplyId";
        }
        $sql = "SELECT
            sa.studentID AS studentId,
            $semColumn
            sa.regNo,
            sa.studentName AS name,
            sa.myImage,
            sa.studentSignImage,
            mss.marklist_serialNo_id AS serialNoTypeId,
            mss.serialNo,
            msn.`type`
        FROM
            studentaccount sa
        LEFT JOIN marklist_serialNo_student mss ON
            mss.studentId = sa.studentID
        LEFT JOIN marklist_serialNo msn ON
            msn.id = mss.marklist_serialNo_id
            $leftJoin
        WHERE
            sa.batchID IN ($batchId)
            AND mss.$columnTobeNull IS NULL
            $condition";
        try {
            $students = $this->executeQueryForList($sql);
            return $students;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getStudentsInBatch($batchId)
    {
        $batchId = $this->realEscapeArray($batchId);
        $batchId = is_array($batchId) ? implode(",", $batchId) : $batchId;
        $sql = "SELECT
            sa.studentID AS studentId,
            sa.regNo,
            sa.studentName AS name,
            sa.myImage,
            sa.studentSignImage,
            sa.batchID AS batchId
        FROM
            studentaccount sa
        WHERE
            sa.batchID IN ($batchId)
            ORDER BY sa.regNo";
        try {
            $students = $this->executeQueryForList($sql);
            return $students;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getSupplyRegisteredStudentsInBatch($batchId, $supplyId)
    {
        $batchId = $this->realEscapeArray($batchId);
        $batchId = is_array($batchId) ? implode(",", $batchId) : $batchId;
        $sql = "SELECT
            sa.studentID AS studentId,
            sa.regNo,
            sa.studentName AS name,
            sa.myImage,
            sa.studentSignImage,
            sa.batchID AS batchId
        FROM
            exam_supplementary_student_details essd
        INNER JOIN studentaccount sa ON
            sa.studentID = essd.studentID
        WHERE
            sa.batchID IN ($batchId)
            AND essd.exam_supplementary_id = '$supplyId'
            ORDER BY sa.regNo";
        try {
            $students = $this->executeQueryForList($sql);
            return $students;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     *get students details by batchIDs
     * @param object $request
     * @return studentDetails
     * @throws ProfessionalException
     * @author sibin
     */
    public function getStudentsForEnrolmentByBatch($request)
    {
        $request = $this->realEscapeObject($request);
        $batchSelected = $request->batchSelected;
        $whereCondition = "";
        $joinTable = "";
        $columns = "";
        if ($batchSelected) {
            $whereCondition .= " AND b.batchID IN ($batchSelected)";
        }
        try {
            $sql = "SELECT
                sa.studentID,
                sa.studentName,
                sa.rollNo,
                sa.regNo,
                b.semID,
                DATE_FORMAT(studentBirthday, '%d-%m-%y') as studentBirthday,
                sa.studentEmail,
                sa.studentPhone,
                SUBSTRING_INDEX(myImage,'.',-1) as extention,
                pd.patternCourseName,
                pd.patterncourseCode
            FROM
                studentaccount sa
                    INNER JOIN
                batches b ON sa.batchID = b.batchID
                    INNER JOIN
                pattern_deptcourses pd ON b.patterncourseID = pd.patterncourseID
                $joinTable
            WHERE
                b.batchName <> 'failed'
                $whereCondition
            ORDER BY sa.regNo";
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    //get studentId by studentRegId
    public function getStudentIdByStudentRegId($studentRegId)
    {
        $regNo = $this->realEscapeArray($studentRegId);
        $sql = "SELECT studentID from studentaccount
                where
                regNo='$regNo'
                ";
        try {
            $studentId = $this->executeQueryForObject($sql);
            return $studentId;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    //end get studentId by studentRegId
    //get geting all exam block reason
    public function getblockReasons()
    {
        $sql = "SELECT
                    id,
                    reason,
                    reason_type,
                    adminId
                FROM
                exam_reg_block_reason
                ";
        try {
            $blockReason = $this->executeQueryForList($sql);
            return $blockReason;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    //end geting  all exam  block reason
    //get geting exam blocked reason For subject
    public function getblockedReasonByStudentSubject($studentId, $examregId, $examTypeValue, $subjectId)
    {
        if ($examTypeValue === 0) { //Regular Exam
            $examreg_id = $examregId;
            $supplyreg_id = 'NULL';
        } else if ($examTypeValue === 1) {
            $supplyreg_id = $examregId;
            $examreg_id = 'NULL';
        }
        $response = null;
        $condition = $examTypeValue ? " AND erbs.supplyreg_id = '$examregId" : " AND erbs.examreg_id = '$examregId";
        $sql = "SELECT    erbs.id,
                    erbs.reason_id as reasonId
                    FROM
                    exam_reg_blocked_student erbs
                    WHERE erbs.student_id = '$studentId'
                     AND erbs.subject_id = '$subjectId'
                     $condition";
        try {
            $blockedReason = $this->executeQueryForObject($sql);
            return $blockedReason;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    //end geting exam blocked reason For subject
    /**
     *getSubjectsByExamRegAndStudentId($studentDetails)
     * @param object $studentDetails
     * @return studentDetails
     * @throws ProfessionalException
     * @author sibin
     */
    public function getSubjectsDetailsByStudentDetails($studentDetails)
    {
        $examregId = $studentDetails->examregId;
        $studentId = $studentDetails->studentId;
        $batchId = $studentDetails->batchId;
        $semId = $studentDetails->semId;
        $addCondition = NULL;
        if($studentDetails->considerPracticalSubjects == 0)
        {
            $addCondition = "AND s.isTheory = 1";
        }
        $sql = "SELECT
                e.examID,e.batchID,e.semID,s.subjectID,s.subjectName,s.syllabusName,s.subjectDesc,ers.examregID,gsm.marks as graceMark , gsm.remarks ,s.isTheory,gsm.fianlize as finalize,gsm.approve from subjects s
                inner join exam_reg_studentsubject ers
                on ers.subjectID = s.subjectID
                inner join exam e
                on e.subjectID=s.subjectID
                and
                e.examregID=ers.examregID
                left join gracemarks_student_marks gsm
                on gsm.studentID=ers.studentID
                and
                gsm.subjectID=e.subjectID
                and
                gsm.examID=e.examID
                LEFT JOIN
                   exam_subjectcredit esc ON esc.subjectID = s.subjectID AND esc.batchID=e.batchID AND esc.semID=e.semID
                where ers.studentID='$studentId'
                and ers.examregID='$examregId'
                and e.batchID='$batchId'
                and e.semID='$semId$addCondition
                ORDER BY  esc.subjectOrder ASC,s.subjectID ASC";
        try {
            $subjects = $this->executeQueryForList($sql);;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        $subjectDetails['batchId'] = $batchId;
        $subjectDetails['sem'] = $semId;
        $subjectDetails['studentId'] = $studentId;
        $subjectDetails['examregId'] = $examregId;
        $subjectDetails['subjects'] = $subjects;
        return $subjectDetails;
    }
//end getSubjectsByExamRegAndStudentId($studentDetails)
    /**
     * student details by reg no For Failed Students
     * @param string $regNo
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getStudentDetailsByRegNoForFailedStudents($regNo)
    {
        $regNo = $this->realEscapeString($regNo);
        $sql = "SELECT sa.studentID as id, sa.studentName as name , sa.deptID, bt.courseTypeID,sa.batchID FROM studentaccount sa INNER JOIN batches bt on (sa.batchID = bt.batchID ) WHERE sa.regNo = '$regNo'";
        try {
            $studentDetails = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * Update Failed Student details
     * @param string $request
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function updateStudentFailedList($request)
    {
        $request = $this->realEscapeObject($request);
        $updatedBy = $_SESSION['adminID'];
        $updatedDate = date("Y-m-d h:i:s");
        $status = 0;
        $sql = "SELECT previousBatch, failedID from failed_students WHERE failedID = '$request->failedId'";
        $studentDetails = $this->executeQueryForObject($sql);
        if ($studentDetails){
            $failedId = $studentDetails->failedID;
            $sqlQuerry = "SELECT previousBatch, failedID from failed_students WHERE studentID = '$request->studentId' AND previousBatch = '$request->batchId' AND failedID != '$request->failedId'";
            $duplicateEntry = $this->executeQueryForObject($sqlQuerry);
            if ($duplicateEntry){
                $status = 1;
            }
            else{
                $sql1 = "UPDATE failed_students set previousBatch = '$request->batchId', failedInSemester = '$request->semId', hisSemestersInThisbatch = '$request->hisSem', isFailNow = '$request->isFail', failedDate = '$request->failDate', updated_by = '$updatedBy', updated_date = '$updatedDate',userType = 'EXAMCONTROLLER_ADMIN' WHERE failedID = '$request->failedId'";
            }
        }
        else{
            $sql3 = "SELECT previousBatch, failedID from failed_students WHERE studentID = '$request->studentId' AND previousBatch = '$request->batchId'";
            $failedDetails = $this->executeQueryForObject($sql3);
            if ($failedDetails){
                $status = 1;
                $failedId = $request->failedId;
            }
            else{
                $sql1 = "INSERT INTO failed_students (studentID, previousBatch, failedInSemester, hisSemestersInThisbatch, isFailNow, failedDate , updated_by, updated_date,userType) VALUES('$request->studentId', '$request->batchId', '$request->semId', '$request->hisSem', '$request->isFail', '$request->failDate', '$updatedBy', '$updatedDate','EXAMCONTROLLER_ADMIN')";
            }
        }
        try {
            if ( $status == 0){
                $response = $this->executeQuery($sql1);
            }
            if ( empty($failedId)){
                $sql4 = "SELECT previousBatch, failedID from failed_students WHERE studentID = '$request->studentId' AND previousBatch = '$request->batchId'";
                $result = $this->executeQueryForObject($sql4);
                $failedId = $result->failedID;
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        $response->failedId = $failedId;
        $response->status = $status;
        return $response;
    }
    /**
     * Failed Student details by studentId
     * @param string $restudentIDgNo
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getFailedStudentDetailsList($studentId)
    {
        $regNo = $this->realEscapeString($studentId);
        $sql = "SELECT failedID, studentID, previousBatch, failedInSemester, isFailNow, IF(failedDate = 0  , now(),failedDate) as failedDate from failed_students WHERE studentID = \"$studentId\"";
        try {
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * Delete Failed Student details
     * @param string $failedId
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function deleteStudentFailedList($failedId)
    {
        $failedId = $this->realEscapeObject($failedId);
        $sql = "DELETE from failed_students WHERE failedID = \"$failedId\"";
        try {
            $response = $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $response;
    }
    public function getAllStudentMailIdByRequest($request)
    {
        $sqlArray = [];
        $conditions = $request->studentIds?" AND st.studentID IN (".implode(',',$request->studentIds).") ":"";
        $conditions .= $request->studentBatchIDs?" AND st.batchID IN (".implode(',',$request->studentBatchIDs).") ":"";
        $conditions .= $request->studentDeptIds?" AND dept.deptID IN (".implode(',',$request->studentDeptIds).") ":"";
        $conditions .= $request->yearID?" AND bat.batchStartYear IN (".implode(',',$request->yearID).") ":"";
        if(!$request->includeCourseCompletedStudents)
            $conditions .= " AND sem.semName <> '" . Semester::COURSE_COMPLETED_SEM . "'";
        if($request->sentTostudents && ($request->studentIds || $request->allStudent))
        {
            $sqlArray [] = "SELECT st.studentID, st.studentName, st.studentEmail AS Email , st.studentPhone AS Phone, ext.fatherEmail, ext.motherEmail, ext.parentEmail, 'student' AS type  FROM studentaccount st
                INNER JOIN batches bat ON bat.batchID = st.batchID
                INNER JOIN semesters sem ON bat.semID = sem.semID
                INNER JOIN department dept ON dept.deptID = bat.deptID
                LEFT JOIN studentaccount_extras ext ON ext.studentID = st.studentID
            WHERE 1=1 $conditions";
        }
        if($request->sentToStudentParents && ($request->studentIds || $request->allStudent))
        {
            $sqlArray [] = "SELECT st.studentID, st.studentName, ext.parentEmail AS Email , st.parentPhone AS Phone, ext.fatherEmail, ext.motherEmail, ext.parentEmail, 'Parent' AS type FROM studentaccount st
                INNER JOIN batches bat ON bat.batchID = st.batchID
                INNER JOIN semesters sem ON bat.semID = sem.semID
                INNER JOIN department dept ON dept.deptID = bat.deptID
                LEFT JOIN studentaccount_extras ext ON ext.studentID = st.studentID
                WHERE 1=1 $conditions";
        }
        if($sqlArray)
        {
            $sql = implode(' UNION ',$sqlArray);
            try {
                if((!empty($request->studentDeptIds) || $request->allDept ) && (!empty($request->studentBatchIDs) || $request->allBatch ))
                {
                    $studentDetails = $this->executeQueryForList($sql);
                }
                return $studentDetails;
            } catch (\Exception $e) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        }
    }
    /**
     * Returns sub batch id of student
     *
     * @param $studentId
     * @param $subjectId
     * @param $batchId
     * @param $staffId
     * @return Object|integer
     * @throws ProfessionalException
     */
    public function getStudentSubBatchIdBySubjectAndBatchID($studentId, $subjectId, $batchId, $staffId)
    {
        $studentId = (int)$this->realEscapeString($studentId);
        $subjectId = (int)$this->realEscapeString($subjectId);
        $batchId = (int)$this->realEscapeString($batchId);
        $staffId = (int)$this->realEscapeString($staffId);
        if (empty($studentId)) {
            throw new ProfessionalException(ProfessionalException::INVALID_STUDENT_ID, "Invalid student details given");
        }
        if (empty($subjectId)) {
            throw new ProfessionalException(ProfessionalException::INVALID_SUBJECT_ID, "Invalid subject details given");
        }
        if (empty($batchId)) {
            throw new ProfessionalException(ProfessionalException::INVALID_BATCH_ID, "Invalid batch details given");
        }
        if (empty($staffId)) {
            throw new ProfessionalException(ProfessionalException::INVALID_STAFF_ID, "Invalid staff details given");
        }
        $sql = "SELECT sb.subbatchID as id
                FROM subbatches sb
                INNER JOIN subbatch_sbs sbs ON sbs.subbatchID = sb.subbatchID
                INNER JOIN sbs_relation sr ON sbs.sbsID = sr.sbsID
                INNER JOIN subbatch_student ss ON sbs.subbatchID = ss.subbatchID
                INNER JOIN batches b ON b.batchID = sr.batchID AND sr.semID = b.semID
                WHERE sr.staffID = $staffId AND sr.batchID = $batchId
                AND sr.subjectID = $subjectId AND ss.studentID=$studentId";
        try {
            $subBatchIds = $this->executeQueryForList($sql);
            if (count($subBatchIds) === 1) {
                return $subBatchIds[0]->id;
            } elseif (empty($subBatchIds)) {
                return 0;
            }
            throw new ProfessionalException(ProfessionalException::MULTIPLE_SUB_BATCH_FOUND, "Multiple sub-batch details found");
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getStudentsByBatchIdSemIdSubjectIdStaffId($batchId,$semesterId,$subjectId,$staffId)
    {
        $batchId = $this->realEscapeString($batchId);
        $semesterId = $this->realEscapeString($semesterId);
        $subjectId = $this->realEscapeString($subjectId);
        $staffId = $this->realEscapeString($staffId);
        try{
            $subbatches = BatchService::getInstance()->getSubbatchBystaffIdAndSubjectId($batchId,$subjectId,$semesterId,$staffId);
            if(empty($subbatches))
            {
                $sql = "select  studentID, studentName, admissionNo, rollNo, regNo from  studentaccount where batchID=\"" . $batchId . "\"";
                $studentList = $this->executeQueryForList($sql);
            }
            else
            {
                $studentList = [];
                foreach($subbatches as $subbatch)
                {
                    $students = StudentService::getInstance()->getStudentDetailsByBatchSemIdAndSubbatchId($batchId,$semesterId,$subbatch->subbatchID,'rollNo');
                    if(!empty($students))
                    {
                        $studentList = array_merge($studentList,$students);
                    }
                }
            }
            return $studentList;
        }catch(\Exception $e) {
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * Update Fee status
     * @param $challanNo
     * @throws ProfessionalException
     */
    public function updateChallanStatusByChallanNo($challanNo)
    {
        $challanNo = $this->realEscapeString($challanNo);
        $date = date('Y-m-d');
        $sql = "SELECT * FROM exam_reg_studentchallan WHERE challanNo = $challanNo ";
        try{
            $challanDetails = $this->executeQueryForObject($sql);
            if (!empty ($challanDetails)){
                $sql = "UPDATE exam_reg_studentchallan SET paid = 1 , dateofPay = '$date' WHERE challanNo = $challanNo";
                try {
                    return $this->executeQuery($sql);
                } catch (\Exception $e) {
                    throw new ProfessionalException($e->getCode(), $e->getMessage());
                }
            }
            else{
                return $challanNo;
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
     /**
     * Update Fee status
     * @param $challanNo
     * @throws ProfessionalException
     */
    public function updateChallanStatusByChallanNoForSupply($challanNo)
    {
        $challanNo = $this->realEscapeString($challanNo);
        $date = date('Y-m-d');
        $sql = "SELECT * FROM exam_supplementary_student_details WHERE challanNo = $challanNo ";
        try{
            $challanDetails = $this->executeQueryForObject($sql);
            if (!empty ($challanDetails)){
                $sql = "UPDATE exam_supplementary_student_details SET paid = 1 , approved = 1, fee_paidDate = '$date' WHERE challanNo = $challanNo";
                try {
                    return $this->executeQuery($sql);
                } catch (\Exception $e) {
                    throw new ProfessionalException($e->getCode(), $e->getMessage());
                }
            }
            else{
                return $challanNo;
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     *getSupplyStudentDetails
     * @return studentDetails
     * @throws ProfessionalException
     * @author sibin
     */
    public function getSupplyStudentDetails($batchId,$regularExamId,$examRegId,$getAttendedStudentsOnly = false,$supplyExamId = null){
        $batchId = $this->realEscapeString($batchId);
        $regularExamId = $this->realEscapeString($regularExamId);
        $examRegId = $this->realEscapeString($examRegId);
        $joinExamReg = "";
        if ($getAttendedStudentsOnly && $supplyExamId) {
            $joinExamReg .= "INNER JOIN exam_attendance ea
                                ON ea.examID ='$supplyExamId' AND ea.studentID = sa.studentID AND ea.isAbsent = '0'";
        }
        $sql ="SELECT distinct ess.studentID,
                        sa.studentName,
                        sa.batchID,
                        sa.regNo,
                        ess.exam_supplementary_id
                        from  exam_supplementary_student_subjects ess
                                    inner join studentaccount sa
                                        on sa.studentID=ess.studentID
                                    inner join exam_supplementary_student_details esd
                                        on esd.studentID=ess.studentID
                                    $joinExamReg
                                    where sa.batchID='$batchId'
                                    and ess.examID='$regularExamId'
                                    and ess.exam_supplementary_id='$examRegId'
                                    and esd.exam_supplementary_id=ess.exam_supplementary_id
                                    and esd.paid=1 ORDER BY sa.regNo ASC";
        try{
            $studentList=$this->executeQueryForList($sql);;
        }
        catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentList;
    }
    public function getStudentCountBySbsId($request){
        $request = $this->realEscapeObject($request);
        if(!$request->pseudoSubjectId)
        {
            $sql = "SELECT COUNT(DISTINCT studentID) AS studentCount
            FROM (
                SELECT std.studentID AS studentID FROM sbs_relation sbs
                INNER JOIN studentaccount std ON std.batchID = sbs.batchID
                LEFT JOIN subbatch_sbs ssbs ON ssbs.sbsID = sbs.sbsID
                WHERE ssbs.sbsID IS NULL AND sbs.sbsID IN ($request->sbsId) group by std.studentID
            UNION
                SELECT sss.studentID AS studentID
                FROM sbs_relation sbs
                INNER JOIN subbatch_sbs ss ON ss.sbsID = sbs.sbsID
                INNER JOIN subbatch_student sss ON sss.subbatchID = ss.subbatchID
                INNER JOIN studentaccount std ON std.studentID = sss.studentID AND std.batchID = sbs.batchID
                WHERE ss.sbsID IN ($request->sbsId) group by sss.studentID
            ) AS student;";
        }
        else
        {
            $sql = "SELECT count(DISTINCT pstd.studentID) as studentCount FROM
            pseudosubjects_sbs psbs
            INNER JOIN sbs_relation sbs ON psbs.sbsID = sbs.sbsID
            INNER JOIN pseudosubjects_students pstd on psbs.pseudosubjectID = pstd.pseudosubjectID
            INNER JOIN studentaccount std on std.studentID = pstd.studentID AND std.batchID = sbs.batchID
            LEFT JOIN batches bat ON bat.batchID = std.batchID
            LEFT JOIN department dept on dept.deptID = bat.deptID
            WHERE psbs.pseudosubjectID = ".$request->pseudoSubjectId." AND sbs.subjectID = ".$request->subjectId." AND sbs.staffID = ".$request->staffId."
            ORDER BY bat.batchName,std.rollNo;";
        }
        try{
            $studentCount=$sql?$this->executeQueryForObject($sql)->studentCount:null;
        }
        catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentCount;
    }
    public function getStudentsInBatchBySubjectId($batchId, $semId, $subjectId)
    {
        $batchId = $this->realEscapeString($batchId);
        $semId = $this->realEscapeString($semId);
        $subjectId = $this->realEscapeString($subjectId);
        $sql = "SELECT
            sac.studentID studentId,
            subs.subbatchID AS subBatchId
        FROM
            studentaccount sac
        INNER JOIN sbs_relation sbsr ON
            sbsr.batchID = sac.batchID
        LEFT JOIN subbatch_sbs ssbs ON
            ssbs.sbsID = sbsr.sbsID
        LEFT JOIN subbatch_student subs ON
            subs.subbatchID = ssbs.subbatchID
            AND subs.studentID = sac.studentID
        WHERE
            sac.batchID = $batchId
            AND sbsr.subjectID = $subjectId
            AND sbsr.semID = $semId";
        try {
            $students = $this->executeQueryForList($sql);
            $subbatchStudents = array_filter($students,function($student){
                return $student->subBatchId;
            });
            if(!empty($subbatchStudents)) $students = $subbatchStudents;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $students;
    }
    public function getStudentOpenCourse($studentId, $batchId)
    {
        $studentId = $this->realEscapeString($studentId);
        $batchId = $this->realEscapeString($batchId);
        $sql = "SELECT
            ps.subjectName AS pseudoSubjectName,
            ps.courseTypeID AS courseTypeId,
            sbsr.subjectID AS subjectId,
            sbsr.semID AS semId,
            s.subjectDesc AS subjectName,
            s.subjectName AS subjectCode,
            s.syllabusName
        FROM
            pseudosubjects ps
        INNER JOIN pseudosubjects_students pss ON
            pss.pseudosubjectID = ps.pseudosubjectID
        INNER JOIN pseudosubjects_sbs pssbs ON
            pssbs.pseudosubjectID = ps.pseudosubjectID
            AND pssbs.pseudosubjectID = pss.pseudosubjectID
        INNER JOIN sbs_relation sbsr ON
            sbsr.sbsID = pssbs.sbsID
        INNER JOIN subjects s ON
            s.subjectID = sbsr.subjectID
        WHERE
            ps.isOpencourse = 1
            AND pss.studentID = $studentId
            AND sbsr.batchID = $batchId";
        try {
            $students = $this->executeQueryForList($sql);
            $subbatchStudents = array_filter($students,function($student){
                return $student->subBatchId;
            });
            if(!empty($subbatchStudents)) $students = $subbatchStudents;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $students;
    }
    public function searchStudentList(SearchStudentRequest $searchStudentRequest)
    {
        $studentDetails = new SearchStudentResponse();
        $searchStudentRequest->subbatchIds =array_filter($searchStudentRequest->subbatchIds, function ($i) use ($value) { return $i !== '0'; });
        if($searchStudentRequest->isPseudoSubject)
        {
            $sqltemp="from  studentaccount sa
                                 inner join subbatch_student ss on sa.studentID = ss.studentID
                                 inner join subbatch_sbs ssb ON ssb.subbatchID=ss.subbatchID
                                 inner join sbs_relation sr ON sr.sbsID=ssb.sbsID
                                 inner join batches ba on  ba.batchID = sa.batchID
                                 inner join department dep on dep.deptID = sa.deptID
                                 inner join semesters sem on sem.semID = ba.semID
                                 inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID
                                 left join studentaccount_extras se ON se.studentID=sa.studentID
                                 left join admission_domicile ad on ad.id = sa.domicile_id
                                 where ss.subbatchID  IN (".implode(', ', $searchStudentRequest->subbatchIds).")
                                 and sr.staffID=$searchStudentRequest->staffId
                                 and joinedSem.orderNo <= sem.orderNo
                                 ORDER BY sa.batchID, sa.$searchStudentRequest->sortBy";
            $sql = "SELECT  sa.studentID,
                         sa.studentAccount,
                         sa.studentName,
                         sa.studentEmail,
                         sa.studentPhone,
                         sa.student_lock,
                         dep.deptName,
                         sa.batchID,
                         sa.rollNo,
                         sa.admissionNo,
                         sa.parentPhone,
                         sa.regNo,
                         sa.studentGender,
                         sa.myImage,
                         sa.studentBirthday,
                         sa.studentSurname,
                         sa.studentFather,
                         sa.studentMother,
                         sa.studentJoindate,
                         sa.studentAddress,
                         sa.religion,
                         sa.casteID,
                         sa.category,
                         sa.bloodGroup,
                         sa.admissionType,
                         sa.rfid,
                         sa.cap_id,
                         sa.nationality_id,
                         sa.secondlangaugeID,
                         IF(sa.lateral='1',
                        'true',
                        'false') as `lateral`,
                         IF(sa.NRI='1',
                        'true',
                        'false') as NRI,
                         IF(sa.feewaiverScheme='1',
                        'true',
                        'false') as feewaiverScheme,
                         se.motherTongue,
                         se.extraAcitivites,
                         se.parentOccupation,
                         se.annualIncome,
                         se.motherOccupation,
                         se.motherIncome,
                         se.commuhouse,
                         se.currentAddress1,
                         se.currentAddress2,
                         se.currentState,
                         se.currentCity,
                         se.currentCountry,
                         se.currentZipCode,
                         se.permahouse,
                         se.permanentAddress1,
                         se.permanentAddress2,
                         se.permanentState,
                         se.permanentCity,
                         se.permanentCountry,
                         se.permanentZipCode,
                         ba.batchName,
                         sem.semName,
                         ba.batchID,
                         sem.semID,
                         sr.subjectID,
                         sa.sslc,
                         sa.plustwo,
                         se.fatherEmail,
                         se.motherEmail,
                         sa.uucmsid,
                         sa.candidateIsFrom,
                         sa.candidateCountryCode,
                         sa.phdExpiry,
                         sa.village,
                         sa.abcId,
                         sa.domicile_id ".$sqltemp;
            $sql_count="SELECT count(sa.studentID) as totalRecord ".$sqltemp;
        }
        else
        {
            $isCurrentSem = SemesterService::getInstance()->isCurrentSemester($searchStudentRequest->batchId, $searchStudentRequest->semId);
            if($isCurrentSem)
            {
                if (!empty($searchStudentRequest->subbatchIds))
                {
                    $sqltemp="from  studentaccount sa
                                inner join subbatch_student ss on sa.studentID = ss.studentID
                                inner join batches ba on  ba.batchID = sa.batchID
                                inner join department dep on dep.deptID = sa.deptID
                                inner join semesters sem on sem.semID = ba.semID
                                inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID
                                inner join subbatches sb ON sb.subbatchID=ss.subbatchID
                                left join studentaccount_extras se ON se.studentID=sa.studentID
                                left join admission_domicile ad on ad.id = sa.domicile_id
                                where sa.batchID=$searchStudentRequest->batchId
                                    and ss.subbatchID  IN (".implode(', ', $searchStudentRequest->subbatchIds).")
                                    and joinedSem.orderNo <= sem.orderNo
                                ORDER BY sa.$searchStudentRequest->sortBy";
                    $sql = "SELECT  sa.studentID,
                                     sa.studentAccount,
                                     sa.studentName,
                                     sa.studentEmail,
                                     sa.studentPhone,
                                     sa.student_lock,
                                     dep.deptName,
                                     sa.batchID,
                                     sa.rollNo,
                                     sa.admissionNo,
                                     sa.parentPhone,
                                     sa.regNo,
                                     sa.studentGender,
                                     sa.myImage,
                                     sa.studentBirthday,
                                     sa.studentSurname,
                                     sa.studentFather,
                                     sa.studentMother,
                                     sa.studentJoindate,
                                     sa.studentAddress,
                                     sa.religion,
                                     sa.casteID,
                                     sa.category,
                                     sa.bloodGroup,
                                     sa.admissionType,
                                     sa.rfid,
                                     sa.cap_id,
                                     sa.nationality_id,
                                     sa.secondlangaugeID,
                                     IF(sa.lateral='1',
                                    'true',
                                    'false') as `lateral`,
                                     IF(sa.NRI='1',
                                    'true',
                                    'false') as NRI,
                                     IF(sa.feewaiverScheme='1',
                                    'true',
                                    'false') as feewaiverScheme,
                                     se.motherTongue,
                                     se.extraAcitivites,
                                     se.parentOccupation,
                                     se.annualIncome,
                                     se.motherOccupation,
                                     se.motherIncome,
                                     se.commuhouse,
                                     se.currentAddress1,
                                     se.currentAddress2,
                                     se.currentState,
                                     se.currentCity,
                                     se.currentCountry,
                                     se.currentZipCode,
                                     se.permahouse,
                                     se.permanentAddress1,
                                     se.permanentAddress2,
                                     se.permanentState,
                                     se.permanentCity,
                                     se.permanentCountry,
                                     se.permanentZipCode,
                                     sb.subbatchName,
                                     sa.sslc,
                                     sa.plustwo,
                                     se.fatherEmail,
                                     se.motherEmail,
                                      sa.uucmsid,
                                      sa.abcId,
                                      sa.domicile_id ".$sqltemp;
                    $sql_count="SELECT count(sa.studentID) as totalRecord ".$sqltemp;
                }
                else
                {
                    $sqltemp = "from  studentaccount sa
                                    inner join department dep on dep.deptID = sa.deptID
                                    inner join batches ba on  ba.batchID = sa.batchID
                                    inner join semesters sem on sem.semID = ba.semID
                                    inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID
                                    left join studentaccount_extras se ON se.studentID=sa.studentID ".(!empty($searchStudentRequest->actualSubbatchList)?"
                                    LEFT JOIN subbatch_student ss on sa.studentID = ss.studentID AND ss.subbatchID IN (".implode(", ", $searchStudentRequest->actualSubbatchList).")
                                    LEFT JOIN subbatches sb ON sb.subbatchID=ss.subbatchID ":"")."
                                    left join admission_domicile ad on ad.id = sa.domicile_id
                                    where sa.batchID=$searchStudentRequest->batchId and joinedSem.orderNo <= sem.orderNo
                                    ORDER BY sa.$searchStudentRequest->sortBy";
                    $sql = "SELECT  sa.studentID,
                                 sa.studentAccount,
                                 sa.studentName,
                                 sa.studentEmail,
                                 sa.studentPhone,
                                 sa.student_lock,
                                 dep.deptName,
                                 sa.batchID,
                                 sa.rollNo,
                                 sa.admissionNo,
                                 sa.parentPhone,
                                 sa.regNo,
                                 sa.studentGender,
                                 sa.myImage,
                                 sa.studentSignImage,
                                 sa.studentBirthday,
                                 sa.studentSurname,
                                 sa.studentFather,
                                 sa.studentMother,
                                 sa.studentJoindate,
                                 sa.studentAddress,
                                 sa.religion,
                                 sa.casteID,
                                 sa.category,
                                 sa.bloodGroup,
                                 sa.admissionType,
                                 sa.rfid,
                                 sa.cap_id,
                                 sa.nationality_id,
                                 sa.secondlangaugeID,
                                 IF(sa.lateral='1',
                                'true',
                                'false') as `lateral`,
                                 IF(sa.NRI='1',
                                'true',
                                'false') as NRI,
                                 IF(sa.feewaiverScheme='1',
                                'true',
                                'false') as feewaiverScheme,
                                 se.motherTongue,
                                 se.extraAcitivites,
                                 se.parentOccupation,
                                 se.annualIncome,
                                 se.motherOccupation,
                                 se.motherIncome,
                                 se.commuhouse,
                                 se.currentAddress1,
                                 se.currentAddress2,
                                 se.currentState,
                                 se.currentCity,
                                 se.currentCountry,
                                 se.currentZipCode,
                                 se.permahouse,
                                 se.permanentAddress1,
                                 se.permanentAddress2,
                                 se.permanentState,
                                 se.permanentCity,
                                 se.permanentCountry,
                                 se.permanentZipCode,
                                 sa.sslc,
                                 sa.plustwo,
                                 se.fatherEmail,
                                 se.motherEmail,
                                 sa.uucmsid,
                                 sa.abcId,
                                 sa.domicile_id ".(!empty($searchStudentRequest->actualSubbatchList)?",sb.subbatchName ":"").$sqltemp;
                    $sql_count="SELECT count(sa.studentID) as totalRecord ".$sqltemp;
                }
            }
            else
            {
                $semDetails = SemesterService::getInstance()->getSemDetailsBySemId($searchStudentRequest->semId);
                if (!empty($searchStudentRequest->subbatchIds))
                {
                    $sql = "SELECT  sa.studentID,
                                     sa.studentAccount,
                                     sa.studentName,
                                     sa.studentEmail,
                                     sa.studentPhone,
                                     sa.student_lock,
                                     dep.deptName,
                                     sa.batchID,
                                     sa.rollNo,
                                     sa.admissionNo,
                                     sa.parentPhone,
                                     sa.regNo,
                                     sa.studentGender,
                                     sa.myImage,
                                     sa.studentBirthday,
                                     sa.studentSurname,
                                     sa.studentFather,
                                     sa.studentMother,
                                     sa.studentJoindate,
                                     sa.studentAddress,
                                     sa.religion,
                                     sa.casteID,
                                     sa.category,
                                     sa.bloodGroup,
                                     sa.admissionType,
                                     sa.rfid,
                                     sa.cap_id,
                                     sa.nationality_id,
                                     sa.secondlangaugeID,
                                     IF(sa.lateral='1',
                                    'true',
                                    'false') as `lateral`,
                                     IF(sa.NRI='1',
                                    'true',
                                    'false') as NRI,
                                     IF(sa.feewaiverScheme='1',
                                    'true',
                                    'false') as feewaiverScheme,
                                     se.motherTongue,
                                     se.extraAcitivites,
                                     se.parentOccupation,
                                     se.annualIncome,
                                     se.motherOccupation,
                                     se.motherIncome,
                                     se.commuhouse,
                                     se.currentAddress1,
                                     se.currentAddress2,
                                     se.currentState,
                                     se.currentCity,
                                     se.currentCountry,
                                     se.currentZipCode,
                                     se.permahouse,
                                     se.permanentAddress1,
                                     se.permanentAddress2,
                                     se.permanentState,
                                     se.permanentCity,
                                     se.permanentCountry,
                                     se.permanentZipCode,
                                     sb.subbatchName,
                                     sa.sslc,
                                     sa.plustwo,
                                     se.fatherEmail,
                                     se.motherEmail,
                                     sa.uucmsid,
                                     sa.domicile_id
                                     from studentaccount sa
                                     inner join department dep on dep.deptID = sa.deptID
                                     inner join subbatch_student ss on sa.studentID = ss.studentID
                                     inner join subbatches sb ON sb.subbatchID=ss.subbatchID
                                     left join studentaccount_extras se ON se.studentID=sa.studentID
                                     left join admission_domicile ad on ad.id = sa.domicile_id
                                     where  ss.subbatchID IN (".implode(', ', $searchStudentRequest->subbatchIds).")
                                     and  sa.studentID in(
                                            select studentID from
                                                        studentaccount sa
                                                        inner join batches ba on sa.batchID = ba.batchID
                                                        inner join semesters sem on sem.semID = ba.semID
                                                        inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID
                                                        where ba.batchID = $searchStudentRequest->batchId and joinedSem.orderNo <= $semDetails->orderNo
                                                    union
                                            select sa.studentID from
                                                        failed_students fs
                                                        inner join studentaccount sa on sa.studentID = fs.studentID
                                                        inner join semesters fsem on fsem.semID = fs.failedInSemester
                                                        inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID
                                                        where previousBatch = $searchStudentRequest->batchId
                                                            and fsem.orderNo > $semDetails->orderNo
                                                            and joinedSem.orderNo <= $semDetails->orderNo
                                                        )
                                                        ORDER BY $searchStudentRequest->sortBy";
                    $sql_count="SELECT count(*) as totalRecord FROM (".$sql.") as stdnt";
                }
                else
                {
                    $sql = "SELECT  sa.studentID,
                             sa.studentAccount,
                             sa.studentName,
                             sa.studentEmail,
                             sa.studentPhone,
                             sa.student_lock,
                             dep.deptName,
                             sa.batchID,
                             sa.rollNo,
                             sa.admissionNo,
                             sa.parentPhone,
                             sa.regNo,
                             sa.studentGender,
                             sa.myImage,
                             sa.studentBirthday,
                             sa.studentSurname,
                             sa.studentFather,
                             sa.studentMother,
                             sa.studentJoindate,
                             sa.studentAddress,
                             sa.religion,
                             sa.casteID,
                             sa.category,
                             sa.bloodGroup,
                             sa.admissionType,
                             sa.rfid,
                             sa.cap_id,
                             sa.nationality_id,
                             sa.secondlangaugeID,
                             IF(sa.lateral='1',
                            'true',
                            'false') as `lateral`,
                             IF(sa.NRI='1',
                            'true',
                            'false') as NRI,
                             IF(sa.feewaiverScheme='1',
                            'true',
                            'false') as feewaiverScheme,
                             se.motherTongue,
                             se.extraAcitivites,
                             se.parentOccupation,
                             se.annualIncome,
                             se.motherOccupation,
                             se.motherIncome,
                             se.commuhouse,
                             se.currentAddress1,
                             se.currentAddress2,
                             se.currentState,
                             se.currentCity,
                             se.currentCountry,
                             se.currentZipCode,
                             se.permahouse,
                             se.permanentAddress1,
                             se.permanentAddress2,
                             se.permanentState,
                             se.permanentCity,
                             se.permanentCountry,
                             se.permanentZipCode,
                             sa.sslc,
                             sa.plustwo,
                             se.fatherEmail,
                             se.motherEmail,
                             sa.uucmsid,
                             sa.domicile_id
                             from studentaccount sa
                             inner join department dep on dep.deptID = sa.deptID
                             inner join batches ba on sa.batchID =  ba.batchID
                             inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID
                             left join studentaccount_extras se ON se.studentID=sa.studentID
                             left join admission_domicile ad on ad.id = sa.domicile_id
                             where ba.batchID = $searchStudentRequest->batchId and joinedSem.orderNo <= $semDetails->orderNo
                                union
                            select sa.studentID,
                                    sa.studentAccount,
                                     sa.studentName,
                                     sa.studentEmail,
                                     sa.studentPhone,
                                     sa.student_lock,
                                     dep.deptName,
                                     sa.batchID,
                                     sa.rollNo,
                                      sa.admissionNo,
                                     sa.parentPhone,
                                     sa.regNo,
                                     sa.studentGender,
                                    sa.myImage,
                                     sa.studentBirthday,
                                     sa.studentSurname,
                                     sa.studentFather,
                                     sa.studentMother,
                                     sa.studentJoindate,
                                     sa.studentAddress,
                                     sa.religion,
                                     sa.casteID,
                                     sa.category,
                                     sa.bloodGroup,
                                     sa.admissionType,
                                     sa.rfid,
                                     sa.cap_id,
                                     sa.nationality_id,
                                     sa.secondlangaugeID,
                                     IF(sa.lateral='1',
                                    'true',
                                    'false') as `lateral`,
                                     IF(sa.NRI='1',
                                    'true',
                                    'false') as NRI,
                                     IF(sa.feewaiverScheme='1',
                                    'true',
                                    'false') as feewaiverScheme,
                                     se.motherTongue,
                                     se.extraAcitivites,
                                     se.parentOccupation,
                                     se.annualIncome,
                                     se.motherOccupation,
                                     se.motherIncome,
                                     se.commuhouse,
                                     se.currentAddress1,
                                     se.currentAddress2,
                                     se.currentState,
                                     se.currentCity,
                                     se.currentCountry,
                                     se.currentZipCode,
                                     se.permahouse,
                                     se.permanentAddress1,
                                     se.permanentAddress2,
                                     se.permanentState,
                                     se.permanentCity,
                                     se.permanentCountry,
                                     se.permanentZipCode,
                                     sa.sslc,
                                     sa.plustwo,
                                     se.fatherEmail,
                                     se.motherEmail ,
                                     sa.uucmsid,
                                    sa.domicile_id
                                     from failed_students fs
                                     left join studentaccount sa on fs.studentID= sa.studentID
                                     inner join department dep on dep.deptID = sa.deptID
                                     inner join semesters fsem on fsem.semID = fs.failedInSemester
                                     inner join semesters joinedSem on sa.joiningSemId = joinedSem.semID
                                     left join studentaccount_extras se ON se.studentID=sa.studentID
                                     left join admission_domicile ad on ad.id = sa.domicile_id
                                     where previousBatch =$searchStudentRequest->batchId
                                     and fsem.orderNo > $semDetails->orderNo
                                     and joinedSem.orderNo <= $semDetails->orderNo
                                     order by $searchStudentRequest->sortBy";
                    $sql_count="SELECT count(*) as totalRecord FROM (".$sql.") as stdnt";
                }
            }
        }
        try {
            $studentCount = $this->executeQueryForObject($sql_count)->totalRecord;
            $studentDetails->totalRecords = $studentCount;
            if ($searchStudentRequest->export) {
                $searchStudentRequest->endIndex = $studentDetails->totalRecords;
            }
            $sql .= " LIMIT $searchStudentRequest->startIndex,$searchStudentRequest->endIndex";
            $studentDetails->students = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    public function updateStudentProfile($fieldList, $studentId)
    {
        $fieldList = $this->realEscapeArray($fieldList);
        $studentId = $this->realEscapeString($studentId);
        $sql = "UPDATE studentaccount SET ";
        $value = [];
        foreach ($fieldList as $field) {
            if ($field->fieldType != 'address') {
                $value[] = "$field->columnName=" . ($field->value ? "'$field->value'" : 'null');
            }
        }
        $sql .= implode(', ', $value) . " WHERE studentID=" . $studentId;
        try {
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException ($e->getCode(), $e->getMessage());
        }
    }
    public function updateStudentExtrasProfile($fieldList, $studentId)
    {
        $fieldList = $this->realEscapeArray($fieldList);
        $studentId = $this->realEscapeString($studentId);
        $sql_check ="SELECT studentID from studentaccount_extras WHERE studentID=$studentId";
        $row = $this->executeQueryForObject($sql_check);
        if(empty($row))
        {
            $sql_insert="INSERT INTO studentaccount_extras(studentID) VALUES ($studentId)";
            $this->executeQueryForObject($sql_insert);
        }
        $sql = "UPDATE studentaccount_extras SET ";
        $value = [];
        foreach ($fieldList as $field) {
            if ($field->fieldType != 'address') {
                $value[] = "$field->columnName=" . ($field->value ? "'$field->value'" : 'null');
            }
        }
        $sql .= implode(', ', $value) . " WHERE studentID=" . $studentId;
        try {
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException ($e->getCode(), $e->getMessage());
        }
    }
     /**
     * get students with blocked status
     * @param batchId
     * @throws ProfessionalException
     */
    public function getExamBlockedStudentsByBatch($examRegId,$batchId)
    {
        $examRegId = $this->realEscapeString($examRegId);
        $batchId = $this->realEscapeString($batchId);
        $sql = "SELECT
                    sa.studentID AS studentId,
                    sa.regNo,
                    sa.studentName AS name,
                    sa.batchID AS batchId,
                    ebs.block_student as blockedStudentId,
                    ebs.block_student_remark as blockedStudentRemark,
                    ebs.block_hall_ticket as blockedHallTicket,
                    ebs.block_hall_ticket_remark as blockedHallTicketRemark,
                    esw.withheld as blockResult,
                    esw.reasonId
                FROM
                    studentaccount sa
                LEFT JOIN exam_blocked_students ebs
                    on ebs.studentId=sa.studentID
                    and ebs.batchId=sa.batchID
                    and ebs.examRegId='$examRegId'
                LEFT JOIN exam_students_withheld esw
                    on esw.studentID=sa.studentID
                    and esw.examRegId='$examRegId'
                WHERE
                    sa.batchID IN ($batchId)
                    ORDER BY sa.regNo;";
        try {
            $students = $this->executeQueryForList($sql);
            return $students;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
      /**
     * readmissionDetails by studentId
     * @param string $restudentIDgNo
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getReAdmissionDetails($studentId)
    {
        $regNo = $this->realEscapeString($studentId);
        $sql = "SELECT id, exam_registration_id as examRegID, batches_id as batchID, semesters_id as semID, studentaccount_id as studentID, newRegNo from tokenRegistrationReAdmission WHERE studentaccount_id = \"$studentId\"";
        try {
            $response = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $response;
    }
      /**
     * Update Failed Student details
     * @param string $request
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function updateReAdmissionDetails($request)
    {
        $request = $this->realEscapeObject($request);
        $status = 0;
        $sql = "SELECT studentaccount_id from tokenRegistrationReAdmission WHERE id = '$request->id'";
        $studentDetails = $this->executeQueryForObject($sql);
        if ($studentDetails){
            $id = $request->id;
            $sqlQuerry = "SELECT studentaccount_id from tokenRegistrationReAdmission WHERE studentaccount_id = '$request->studentId' AND batches_id = '$request->batchId' AND exam_registration_id = '$request->examRegId' AND semesters_id = '$request->semId' AND id != '$request->id'";
            $duplicateEntry = $this->executeQueryForObject($sqlQuerry);
            if ($duplicateEntry){
                $status = 1;
            }
            else{
            $condition ='';
                $sql1 = "UPDATE tokenRegistrationReAdmission set batches_id = '$request->batchId', semesters_id = '$request->semId', exam_registration_id = '$request->examRegId', newRegNo='$request->newRegNo' WHERE id = '$request->id'";
            }
        }
        else{
            $sql3 = "SELECT studentaccount_id from tokenRegistrationReAdmission WHERE studentaccount_id = '$request->studentId' AND batches_id = '$request->batchId' AND exam_registration_id = '$request->examRegId' AND semesters_id = '$request->semId'";
            $failedDetails = $this->executeQueryForObject($sql3);
            if ($failedDetails){
                $status = 1;
                $id = $request->id;
            }
            else{
                $sql1 = "INSERT INTO tokenRegistrationReAdmission (batches_id, exam_registration_id, semesters_id, studentaccount_id, newRegNo) VALUES( '$request->batchId', '$request->examRegId', '$request->semId', '$request->studentId','$request->newRegNo')";
            }
        }
        try {
            if ( $status == 0){
                $response = $this->executeQuery($sql1);
            }
            if ( empty($id)){
                $sql4 = "SELECT studentaccount_id from tokenRegistrationReAdmission WHERE studentaccount_id = '$request->studentId' AND batches_id = '$request->batchId' AND exam_registration_id = '$request->examRegId' AND semesters_id = '$request->semID'";
                $result = $this->executeQueryForObject($sql4);
                $id = $result->id;
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        $response->id = $id;
        $response->status = $status;
        return $response;
    }
 /**
     * Delete Failed Student details
     * @param string $failedId
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function deleteReAdmissionDetails($id)
    {
        $id = $this->realEscapeObject($id);
        $sql = "DELETE from tokenRegistrationReAdmission WHERE id = \"$id\"";
        try {
            $response = $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $response;
    }
    public function getStudentBatchBySemId($studentId,$semId)
    {
        $semId = $this->realEscapeString($semId);
        $studentId = $this->realEscapeString($studentId);
        $sql = "SELECT group_concat(semID) as semIds FROM semesters WHERE orderNo = (SELECT orderNo FROM semesters WHERE semID = $semId);";
        $semIds = explode(',',$this->executeQueryForObject($sql)->semIds);
        foreach ($semIds as $key => $semID) {
            $findBatch = "select previousBatch from failed_students where studentID = $studentId and find_in_set('$semID',hisSemestersInThisbatch);";
            $batchId = $this->executeQueryForObject($findBatch)->previousBatch;
            break;
        }
        return $batchId?$batchId:false;
    }
    public function getPreviousSemestersOfThisBatch($studentId,$batchDetails)
    {
        $batchDetails = $this->realEscapeObject($batchDetails);
        $studentId = $this->realEscapeString($studentId);
        $sql = "SELECT GROUP_CONCAT(semID) AS hisSemestersInThisbatch FROM semesters WHERE ( SELECT IF(MAX(failedInSemester),MAX(failedInSemester), 1) FROM failed_students WHERE studentID = $studentId AND previousBatch <> $batchDetails->batchID) <= orderNo  AND $batchDetails->orderNo > orderNo AND type = '$batchDetails->type';";
        $hisSemestersInThisbatch = $this->executeQueryForObject($sql)->hisSemestersInThisbatch;
        if(!$hisSemestersInThisbatch){
            $hisSemestersInThisbatch = SemesterService::getInstance()->getPreviousSemsters($batchDetails->semID);
        }else{
            $sql = "select group_concat(hisSemestersInThisbatch) from failed_students where studentID = ".$studentId;
            $hisPreSemestersInThisbatch = explode(',',$this->executeQueryForObject($sql)->hisSemestersInThisbatch);
            $hisSemestersInThisbatch = explode(',',$hisSemestersInThisbatch);
            $hisSemestersInThisbatch = implode(',',array_unique(array_merge($hisPreSemestersInThisbatch[0]?$hisPreSemestersInThisbatch:[],$hisSemestersInThisbatch)));
        }
        return $hisSemestersInThisbatch;
    }
    /**
     * @param $studentId
     * @throws ProfessionalException
     */
    public function getStudentRegNoById($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        $sql = "SELECT studentID,studentName,regNo FROM studentaccount WHERE studentID  = '$studentId'";
        try {
            return $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getHostelStudents($request){
        $request = $this->realEscapeObject($request);
        $sql = "select st.studentID,st.studentName,st.regNo,st.studentGender,st.rollNo, sh.buildingID, sh.levelID, sh.roomID, sh.joiningDate, sh.endDate, sh.remarks, sh.hostel_student_request_id, sh.admit_time from studentaccount st
        inner join student_hosteler sh on sh.studentID = st.studentID
        where st.batchID = '$request->batchId';";
        try {
            $hostelers = $this->executeQueryForList($sql);
            return empty($hostelers) ? [] : $hostelers;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getFailedStudentDetailsByStudentId($studentId){
        try {
            $studentId = $this->realEscapeString($studentId);
            $sql = "SELECT st.studentID,st.studentName,st.batchID,st.regNo,st.rollNo,st.admissionNo,fst.previousBatch,fst.reason,fst.failedDate,fst.failedInSemester,fst.reason,st.studentJoinDate,st.studentBirthday FROM studentaccount st
            INNER JOIN failed_students fst on fst.studentID = st.studentID
            WHERE fst.isFailNow = 1 AND st.studentID = $studentId
            ORDER BY fst.failedID DESC LIMIT 1;";
            return $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
     /**
     * Get students assigned to  pseudo subjects
     * @param object $request
     * @return object|array|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getStudentsAssignedToPseudoSubject($request)
    {
        $request = $this->realEscapeObject($request);
        $sql = "SELECT sa.studentID,sa.regNo, sa.studentName,p.pseudosubjectID,p.subjectName, b.batchID,b.batchName ,sem.semName as semester,d.deptName,s.subjectID as mappedSubjectId,s.subjectName as mappedSubjectName
                FROM pseudosubjects_students pss
                INNER JOIN pseudosubjects p ON p.pseudosubjectID = pss.pseudosubjectID
                INNER JOIN studentaccount sa ON pss.studentID = sa.studentID
                INNER JOIN batches b ON b.batchID = sa.batchID
                INNER JOIN semesters sem ON sem.semID = b.semID
                INNER JOIN department d ON d.deptID = b.deptID
                LEFT JOIN subject_pseudo_subjects sps ON sps.pseudo_subject_id = p.pseudosubjectID
                LEFT JOIN subjects s ON s.subjectID = sps.subject_id
                WHERE 1=1";
        if($request->deptId){
            $sql .= " AND d.deptID = $request->deptId ";
        }
        if (count($request->psIds)>0){
            $sql .= " AND pss.pseudosubjectID IN (".implode(",",$request->psIds).")" ;
        }
        if($request->sortByStudentOrder){
            $sql .= " ORDER BY pss.pseudosubjectID,sa.$request->sortBy";
        }
        else{
            $sql .= " ORDER BY pss.pseudosubjectID,b.batchID,sa.$request->sortBy";
        }
        $totalRecords = count( $this->executeQueryForList($sql));
        if($request->startIndex>=0) {
            $sql .= " LIMIT $request->startIndex$request->endIndex";
        }
        try {
            $response = new SearchStudentResponse();
            $response->report = $this->executeQueryForList($sql);
            $response->totalRecords = $totalRecords;
            return $response;
        }
        catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Get student Previous Batch By SemId
     * @throws ProfessionalException
     */
    public function getStudentPreviousBatchBySemId($studentId,$semId)
    {
        $semId = $this->realEscapeString($semId);
        $studentId = $this->realEscapeString($studentId);
        try {
            $findBatch = "select previousBatch from failed_students where studentID = $studentId and find_in_set('$semId',hisSemestersInThisbatch);";
            $batchId = $this->executeQueryForObject($findBatch)->previousBatch;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $batchId?$batchId:false;
    }
    /** Update Student Fields
     * @param object $request
     * @return NULL
     * @throws ProfessionalException
     */
    public function resetStudentFields($request) {
        $request = $this->realEscapeObject($request);
        $field1 = "";
        $field2 = "";
        foreach($request->fields as $field) {
            $sql = $sql1 = $sql2 ="";
            $field1 = $this->getStudentField($field['fromField']);
            $field2 = $this->getStudentField($field['toField']);
            try {
                if($field['toField'] == "PASSWORD") {
                    if($field['prefix'] && $field['suffix']) {
                        $field1 = "concat('".$field['prefix']."',concat($field1,'".$field['suffix']."'))";
                        $sql = "UPDATE studentaccount SET $field2 = md5($field1) WHERE batchID IN (".implode(",",$request->batchIds).")";
                    }
                    else if($field['prefix']  && empty($field['suffix'])){
                        $sql = "UPDATE studentaccount SET $field2 = md5(concat('".$field['prefix']."',$field1)) WHERE batchID IN (".implode(",",$request->batchIds).")";
                    }
                    else if($field['suffix']  && empty($field['prefix'])) {
                        $sql = "UPDATE studentaccount SET $field2 = md5(concat($field1,'".$field['suffix']."')) WHERE batchID IN (".implode(",",$request->batchIds).")";
                    }
                    else{
                        $sql = "UPDATE studentaccount SET $field2 = md5($field1) WHERE batchID IN (".implode(",",$request->batchIds).")";
                    }
                    $this->executeQueryForList($sql);
                }
                else {
                    $sql = "UPDATE studentaccount SET $field2 = $field1 WHERE batchID IN (".implode(",",$request->batchIds).")";
                    $this->executeQueryForList($sql);
                    if($field['prefix']){
                        $sql1 = "UPDATE studentaccount SET $field2 = concat('".$field['prefix']."',$field2) WHERE batchID IN (".implode(",",$request->batchIds).")";
                        $this->executeQueryForList($sql1);
                    }
                    if($field['suffix']) {
                        $sql2 = "UPDATE studentaccount SET $field2 = concat($field2,'".$field['suffix']."') WHERE batchID IN (".implode(",",$request->batchIds).")";
                        $this->executeQueryForList($sql2);
                    }
                }
            }
            catch (\Exception $e) {
                throw new ProfessionalException($e->getCode(), $field1." cannot be copied to ".$field2);
            }
        }
        try {
            $fields_json = json_encode($request->fields);
            $studentBatchIds = json_encode(["batchIds" => $request->batchIds]);
            $sql_log = "INSERT INTO student_fields_reset_log(updated_fields,students_details ,created_by ,created_date) VALUES ('" .$fields_json."','".$studentBatchIds."',".$_SESSION ['adminID'].",utc_timestamp())";
            $this->executeQueryForObject($sql_log);
        }
        catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    private function getStudentField($field) {
        if($field == 'USERNAME') {
            return 'studentAccount';
        }
        elseif($field == 'PASSWORD') {
            return 'studentPassword';
        }
        elseif($field == 'ADMISSION_NUMBER') {
            return 'admissionNo';
        }
        elseif($field == 'ROLL_NUMBER') {
            return 'rollNo';
        }
        elseif($field == 'REGISTER_NUMBER') {
            return 'regNo';
        }
        else
            return '';
    }
    /**
     * Get dynamic form details for print
     * @throws ProfessionalException
     */
    public function getDynamicFromStudentDetailsForPrint($request){
        $request = $this->realEscapeObject($request);
        $sql="SELECT di.id, di.formName, di.fromDate, di.toDate, di.paymentMethod, di.feeType, di.feeAmount, di.fineAmount, di.fineStartDate, di.fineEndDate, di.filePath , di.applnFormPrintOut,dis.id as studentDataId,dis.studentaccount_id,dis.paymentMethod,disc.paymentStatus,disc.approveStatus
            FROM dynamicform_initiate di
            INNER JOIN dynamicform_studentdata dis ON dis.dynamicform_initiate_id = di.id
            INNER JOIN studentaccount st ON st.studentID = dis.studentaccount_id
            INNER JOIN dynamicForm_appln_batches dib ON dib.dynamicform_initiate_id = di.id AND find_in_set(st.batchID,dib.batchIDs)
            LEFT JOIN dynamicform_studentchallan disc ON disc.dynamicform_initiate_id = di.id AND disc.studentaccount_id = dis.studentaccount_id
            AND ((disc.paymentStatus = 1 AND dis.paymentMethod = 'payu') or (dis.paymentMethod <> 'payu'))
            WHERE di.id = ".$request->formId." AND dis.studentaccount_id = ".$request->studentId."
            GROUP BY dis.studentaccount_id;";
        try {
            return $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
     /*
     * get student specialization by batchId
     */
    public function getStudentSpecializationByBatchId($studentId, $batchId)
    {
        $studentId = $this->realEscapeString($studentId);
        $batchId = $this->realEscapeString($batchId);
        $specialization = null;
        $sql = "SELECT sm.specialisationName FROM specialisation_master sm INNER JOIN specialisation_student_relation ssr ON (sm.id = ssr.specialisationId) WHERE ssr.studentID = '$studentId' AND ssr.batchID = '$batchId'";
        try {
            $specialization = $this->executeQueryForObject($sql)->specialisationName;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $specialization;
    }
    /**
     * get  student note for a particular hour
     * @param GetStudentsRequest $request
     * @throws ProfessionalException
     */
    public function getStudentHourNote($request)
    {
        $request = $this->realEscapeObject($request);
        $sql = "SELECT note FROM student_hour_wise_notes WHERE studentID = '$request->studentID' AND date = '$request->date' AND hour= '$request->hour' AND sbsID= '$request->sbsID'";
        try {
            $result = $this->executeQueryForObject($sql)->note;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $result;
    }
    /**
     * save student note for a particular hour
     * @param GetStudentsRequest $
     * @throws ProfessionalException
     */
    public function saveStudentHourNote($request)
    {
        $request = $this->realEscapeObject($request);
        $sql = "INSERT INTO `student_hour_wise_notes` (`studentID`, `date`, `hour`, `sbsID`, `note`, `created_by`, `created_date`, `updated_by`, `updated_date`) VALUES ('$request->studentID', '$request->date', '$request->hour', '$request->sbsID', '$request->note', '$request->studentID',utc_timestamp() , '$request->studentID', utc_timestamp())";
        try {
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return true;
    }
    /**
     * update student note for a particular hour
     * @param GetStudentsRequest $
     * @throws ProfessionalException
     */
    public function updateStudentHourNote($request)
    {
        $request = $this->realEscapeObject($request);
        $sql = "UPDATE student_hour_wise_notes SET note = '$request->note' ,updated_by = '$request->studentID' ,updated_date = utc_timestamp()   WHERE studentID = '$request->studentID' AND date = '$request->date' AND hour= '$request->hour' AND sbsID= '$request->sbsID'";
        try {
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return true;
    }
    public function getStudentDetailsForEditProfileFromStudentPortal($studentId){
        $sql = "SELECT t1.studentID,t1.studentAccount, t1.studentName, t1.studentEmail, t1.studentGender, t1.studentBirthday, t1.studentAddress, t1.studentPhone,
     t1.deptID, t1.batchID, r.religionName,t1.religion ,sc.casteName , t1.category, t1.bloodGroup, t1.admissionType,t1.quotaId,
      t1.NRI, t2.deptName, t3.batchName, t1.rollNo, t1.studentSurname, t1.studentFather, t1.studentMother, t1.studentJoindate, t1.myImage,
      t1.sslc, t1.plustwo, t1.hosteller, t1.parentPhone, t1.regNo, t1.feewaiverScheme,t1.admissionNo,t1.ugPercentage, ctype.is_pg,t1.casteID,
       t1.previousSchool, t1.highestExamPassed, t1.prev_institute_dateofpassing , t1.prev_institute_regiNo ,
        t1.admitSemester , t1.admissionTCNo, t1.busroute, t1.state_id, t1.district_id , t1.taluk_id,
         t1.annualIncome, t1.aadhaar_no , t1.poverty_line , t1.campus_type_id, t1.studentSignImage, t1.nationality_id,
          t1.quotaID, t1.busroute, t1.dateOfPhdRegistration,t1.guideId,t1.coGuideId,t1.phdRegistrationType,t1.phdCurrentStatus,t1.phdAwardedDate,t1.phdTopicName,
          t1.coachingTypes_id ,t1.entranceQualifiedForPhD,t1.SRFupgradationDate,t1.scholarshipTypes_id,t1.cap_id,
          t1.reservationID,t1.reservID,se.placeofBirth, se.countryOfBirth, se.stateOfBirth, se.motherTongue, se.fatherEducation, se.fatherEmail,
          se.annualIncome as fatherAnnualIncome, se.parentOccupation,
           se.motherEducation, se.motherIncome, se.motherOccupation, se.motherEmail, se.motherPhone, se.residentCategory, se.passportNo,
            se.passportIssuingCountry, se.passportValidUpto, se.extraAcitivites, se.belongsTo, se.isHandicapped,se.handicappedDesc,
            se.permahouse, se.permanentAddress1, se.permanentAddress2, se.permanentState, se.permanentCity, se.permanentCountry,
            se.permanentZipCode, se.commuhouse, se.currentAddress1, se.currentAddress2, se.currentState, se.currentCity, se.currentCountry,
            se.currentZipCode,se.guardian_address_line1, se.guardian_address_line2, se.guardian_address_line3, se.guardian_address_city,
            se.guardian_address_state, se.guardian_address_zip_code, se.guardian_address_country,
            se.guardianName, se.guardianMob, se.guardianLandline, se.guardianRelationship,se.parentlandPh,se.plusOneBoard ,se.plusOneMathsMarksObtained,se.plusOneMathsMaxMark,
            se.plusOnePhyMarkObtained ,se.plusOneCheMarkObtained,se.plusOnePhyMaxMark ,se.plusOneCheMaxMark,se.plusOneInstitution ,se.plusOneRegNo ,se.plusOneYear,se.twelthBoard,
            se.twelthSchool,se.twelthRegno,se.twelthYear,se.twelthMathsMaxMark,se.twelthPhyMarkObtained ,se.twelthCheMarkObtained ,se.twelthPhyMaxMark
            ,se.twelthCheMaxMark ,se.twelthMathsMarksObtained ,se.entranceapplnno,
            se.entranceRollno,se.entrancePaperI,se.entrancePaperII,se.entranceMark,se.tenthBoard,se.tenthSchool,se.tenthRegno,se.tenthYear,
se.medicationNeeded,se.allergiesIfany,se.hobbies,se.medicalHistory,t1.abcId
                FROM studentaccount t1
                    LEFT JOIN religion r
                    ON t1.religion=r.religionID
                    LEFT JOIN student_caste sc
                    ON t1.casteID=sc.casteID
                    INNER JOIN department t2
                    INNER JOIN batches t3
                    LEFT JOIN studentaccount_extras se on t1.studentID = se.studentID
                    LEFT JOIN batch_course_type ctype ON ctype.id = t3.patternID
                WHERE t1.studentID='$studentId' AND t2.deptID=t1.deptID AND t3.batchID = t1.batchID";
       try {
            $data = $this->executeQueryForObject($sql);
            $data->entrancePaperII = round($data->entrancePaperII,2);
            $data->entranceMark = round($data->entranceMark,2);
            $data->entranceMark = round($data->entranceMark,2);
            return $data;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getStudentIsPgOrNot($studentId){
        $sql = "SELECT ctype.is_pg FROM studentaccount t1
                    INNER JOIN batches t3
                    LEFT JOIN batch_course_type ctype ON ctype.id = t3.patternID
                WHERE t1.studentID='$studentId' AND t3.batchID = t1.batchID";
       try {
            $data = $this->executeQueryForObject($sql);
            return $data;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getAllStudentsOfABatchByBatchIdOrExamRegistrationId($batchId,$examRegistrationId)
    {
        if(is_null($batchId))
        {
            $sql = "SELECT
                        sa.studentName,
                        sa.studentID,
                        sa.rollNo,
                        sa.studentAccount,
                        sa.regNo,
                        sa.studentGender
                    FROM
                        group_members gm
                    LEFT JOIN
                        studentaccount sa ON sa.studentId = gm.members ->> '$.studentId'
                    LEFT JOIN
                        `groups` g ON g.id = gm.groups_id
                    LEFT JOIN
                        ec_exam_registration_batch eerb ON eerb.groups_id = g.id
                    LEFT JOIN
                        ec_exam_registration eer ON eer.id = eerb.ec_exam_registration_id
                    WHERE
                        eer.id = '$examRegistrationId'";
        }
        else
        {
            $sql = "SELECT
                        sa.studentName,
                        sa.studentID,
                        sa.rollNo,
                        sa.studentAccount,
                        sa.regNo,
                        sa.studentGender
                    FROM
                        group_members gm
                    LEFT JOIN
                        studentaccount sa ON sa.studentId = gm.members ->> '$.studentId'
                    LEFT JOIN
                        `groups` g ON g.id = gm.groups_id
                    WHERE
                        gm.groups_id = '$batchId";
        }
        try
        {
            $studentDetails = $this->executeQueryForList($sql);
        }
        catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
 //get students in batch for address book print by batch id
    public function getStudentsByBatchId($batchID)
    {
        $batchID = $this->realEscapeObject($batchID);
        $sql ="SELECT t1.studentID,t1.studentAddress, t1.parentPhone, t1.bloodGroup,t1.myimage,t1.studentBirthday,t1.studentAccount, t1.studentName, t1.studentEmail, t1.studentPhone, t1.student_lock, t2.deptName,t3.batchID, t3.batchName ,t1.rollNo, t1.studentVerified,
        t1.admissionNo,t1.regNo , t4.permanentAddress1, t4.permanentAddress2,t4.permanentState, t4.permanentCity, t4.permanentZipCode FROM studentaccount t1
        inner join department t2 on t2.deptID=t1.deptID
        inner join  batches t3  on t3.batchID=t1.batchID
        left join studentaccount_extras t4  on t4.studentID = t1.studentID  where t1.batchID=\"$batchID\" ORDER BY t1.rollNo";
        try {
            $studentList = $this->executeQueryForList($sql);
            return $studentList;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Get student photo details by student id
     * @param Integer $studentID
     * @throws ProfessionalException
     * @return Object studentDetails
     */
    public function getStudentPhotoByStudentId($studentID)
    {
        $sql = "SELECT
                    studentID, studentName, studentGender AS gender, myImage
                FROM
                    studentaccount
                WHERE
                    studentID = '$studentID";
        try {
            $result = $this->executeQueryForObject($sql);
            if($result){
                return $result;
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return true;
    }
    /**
     * Method to get TC issued student details
     * @param Object request
     * @return Array List
     * @throws ProfessionalException
     */
    public function getTcIssuedStudentDetails($request){
        $request = $this->realEscapeObject($request);
        $cond = '';
        if($request->deptId){
            $cond .= " AND bat.deptID = '$request->deptId";
        }
        if($request->batchId){
            $cond .= " AND sa.batchID = '$request->batchId";
        }
        if($request->semId){
            $cond .= " AND bat.semID = '$request->semId";
        }
        if($request->name){
            $cond .= " AND sa.studentName like '%$request->name%' ";
        }
        $sql= "SELECT
                    stc.id,
                    stc.issueDate,
                    sa.studentID,
                    sa.studentName,
                    dept.deptName,
                    bat.batchName,
                    sem.semName
                FROM
                    studentTransferCertificate stc
                        LEFT JOIN
                    studentaccount sa ON sa.studentID = stc.studentId
                        INNER JOIN
                    batches bat ON bat.batchID = sa.batchID
                        INNER JOIN
                    department dept ON dept.deptID = bat.deptID
                        INNER JOIN
                    semesters sem ON sem.semID = bat.semID
                WHERE
                    sa.tcIssued = 1 $cond ";
        try {
            $studentList = $this->executeQueryForList($sql);
            return $studentList;
        }
        catch(\Exception $e) {
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * Update failed date of failed_students
     * @param Int faileddate,Id
     * @return Boolean
     * @throws ProfessionalException
     */
    public function updateStudentFailedDate($failedDate,$studentID){
        $sql = " UPDATE `failed_students` SET `failedDate`='$failedDate'
                WHERE `studentID`='$studentID";
        try {
            if($this->executeQuery($sql,true)){
                return true;
            }
        }
        catch(\Exception $e) {
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
        return false;
    }
    /**
     * Update TC issue date of student
     * @param Int issueDate,Id
     * @return Boolean
     * @throws ProfessionalException
     */
    public function updateStudentTcIssueDate($issueDate,$studentId){
        $sql = " UPDATE `studentTransferCertificate` SET `issueDate`='$issueDate'
                WHERE `studentId`='$studentId'";
        try {
            if($this->executeQuery($sql,true)){
                return true;
            }
        }
        catch(\Exception $e) {
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
        return false;
    }
     /**
     * get students with blocked status for supply
     * @param batchId
     * @throws ProfessionalException
     */
    public function getExamBlockedStudentsByBatchSupply($examRegId,$batchId)
    {
        $examRegId = $this->realEscapeString($examRegId);
        $batchId = $this->realEscapeString($batchId);
        $sql = "SELECT
                    sa.studentID AS studentId,
                    sa.regNo,
                    sa.studentName AS name,
                    sa.batchID AS batchId,
                    ebs.block_student as blockedStudentId,
                    ebs.block_student_remark as blockedStudentRemark,
                    ebs.block_hall_ticket as blockedHallTicket,
                    ebs.block_hall_ticket_remark as blockedHallTicketRemark,
                    esw.withheld as blockResult,
                    esw.reasonId
                FROM
                    studentaccount sa
                LEFT JOIN exam_blocked_students ebs
                    on ebs.studentId=sa.studentID
                    and ebs.batchId=sa.batchID
                    and ebs.supplyRegId='$examRegId'
                LEFT JOIN supplyexam_students_withheld esw
                    on esw.studentID=sa.studentID
                    and esw.exam_supplementary_id='$examRegId'
                WHERE
                    sa.batchID IN ($batchId)
                    ORDER BY sa.regNo;";
        try {
            $students = $this->executeQueryForList($sql);
            return $students;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
        /**
     * get blocked students from exam reg
     * @param batchId,examRegId,StudentId
     * @throws ProfessionalException
     */
    public function getStudentHallTicketBlockedStatus($examregID, $batchID, $studentID, $isSupply){
        $studentId = $this->realEscapeString($studentID);
        $batchId = $this->realEscapeString($batchID);
        $examregId = $this->realEscapeString($examregID);
        $isSupply = $this->realEscapeString($isSupply);
        $result="";
        $examTypeField = "examRegId";
        if($isSupply){
            $examTypeField = "supplyRegId";
        }
        $isExistSql ="select examRegId,batchId,studentId, block_hall_ticket_remark from exam_blocked_students
                        where $examTypeField='$examregId'
                        and batchId='$batchId'
                        and studentId='$studentId'
                        and block_hall_ticket = 1";
        try {
            $result = $this->executeQueryForObject($isExistSql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $result;
    }
    /**
     * get exam registered student details by examRegId, deptId, and  subjectId
     */
    public function getExamRegisteredStudentDetailsByDeptartment($isSupply,$examRegId,$subjectId,$deptId,$batchId)
    {
        $isSupply = $this->realEscapeString($isSupply);
        $examRegId = $this->realEscapeString($examRegId);
        $subjectId = $this->realEscapeString($subjectId);
        $batchId = $this->realEscapeString($batchId);
        $studentDetails = [];
        if (!$isSupply) {
            $sql = "SELECT DISTINCT sa.studentID as studentId,sa.regNo,sa.studentName,sa.batchID,e.examID, e.semId FROM studentaccount sa
                        INNER JOIN exam_reg_studentsubject erss ON (sa.studentID = erss.studentID)
                        INNER JOIN exam e ON (e.examregID = erss.examregID AND e.subjectID = erss.subjectID AND sa.batchID = e.batchID)
                        INNER JOIN batches bt ON (sa.batchID = bt.batchID)
                        INNER JOIN exam_reg_studentchallan ersc ON ersc.studentID = sa.studentID AND ersc.examregID ='$examRegId'
                        WHERE erss.examregID = '$examRegId' AND e.subjectID='$subjectId' AND ersc.paid=1  and bt.deptID = '$deptId' and bt.batchID = '$batchId' order by sa.regNo";
        } else  {
            $sql = "SELECT DISTINCT sa.studentID as studentId,sa.regNo,sa.studentName,sa.batchID,es.examID, es.semId
            FROM studentaccount sa
                        INNER JOIN exam_supplementary_student_subjects esss ON (sa.studentID = esss.studentID)
                        INNER JOIN exam e ON (e.examID = esss.examID AND sa.batchID = e.batchID)
                        INNER JOIN exam es ON (e.subjectID = es.subjectID AND es.supply_examreg_id = esss.exam_supplementary_id AND es.batchID = e.batchID)
                        INNER JOIN batches bt ON (sa.batchID = bt.batchID)
                        INNER JOIN exam_supplementary_student_details essd ON essd.studentID = sa.studentID AND essd.exam_supplementary_id ='$examRegId'
                        WHERE esss.exam_supplementary_id = '$examRegId' AND es.subjectID='$subjectId' AND essd.paid=1 and bt.deptID = '$deptId' and bt.batchID = '$batchId' order by sa.regNo";
        }
        try {
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * student details by roll No
     * @param string $roll No
     * @throws ProfessionalException
     */
    public function getStudentDetailsByRollNo($rollNo)
    {
        $rollNo = $this->realEscapeString($rollNo);
        $sql = "SELECT sa.studentID as id, sa.studentName as name, dept.deptName, bth.batchName, sa.regNo, sa.rollNo, dept.deptName, bth.batchName, dept.deptID, bth.batchID, bth.patternID as courseTypeId, bth.batchStartYear as startYear, bth.batchEndYear as endYear, dept.departmentDesc, sa.tcIssued, sa.studentAddress, bth.courseTypeID FROM studentaccount sa INNER JOIN department dept ON sa.deptID=dept.deptID INNER JOIN batches bth ON sa.batchID=bth.batchID AND dept.deptID=bth.deptID WHERE rollNo = \"$rollNo\"";
        try {
            $studentDetails = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * Update Student Image ResourceId
     * @return Boolean
     * @throws ProfessionalException
     */
    public function updateStudentProfileImageResource($studentId,$resourceId){
        if(!$studentId){
            throw new ProfessionalException("INVALID_ENTITY","Invalid Data");
        }
        try {
            $userTypes = [];
            $userId ="";
            $userTypes []= $_SESSION['adminID'] || $GLOBALS['userType'] == 'ADMIN' ?'ADMIN':false;
            $userTypes []= $_SESSION['staffID'] || $GLOBALS['userType'] == 'STAFF' ?'STAFF':false;
            $userTypes []= $_SESSION['studentID'] || $GLOBALS['userType'] == 'STUDENT'?'STUDENT':false;
            $userType = false;
            foreach($userTypes as $user)
            {
                if($user != false)
                {
                    $userType = $user;
                    break;
                }
            }
            if($userType)
            {
                switch($userType){
                    case 'ADMIN':
                            $sql = " UPDATE `studentaccount` SET `my_image_resource_id`='$resourceId'
                            WHERE `studentId`='$studentId'";
                            $this->executeQuery($sql);
                            $userId = $_SESSION['adminID'];
                            $this->logger->info(Events::STUDENT_IMAGE_UPDATE, [
                                "userId" => $userId,
                                "userType" => UserType::ADMIN,
                                "status" => StatusConstants::SUCCESS
                            ]);
                            break;
                    case 'STAFF':
                            $sql = " UPDATE `studentaccount` SET `my_image_resource_id`='$resourceId'
                            WHERE `studentId`='$studentId'";
                            $this->executeQuery($sql);
                            $userId = $_SESSION['staffID'];
                            $this->logger->info(Events::STUDENT_IMAGE_UPDATE, [
                                "userId" => $userId,
                                "userType" => UserType::STAFF,
                                "status" => StatusConstants::SUCCESS]);
                            break;
                    case 'STUDENT':
                            $sql = " UPDATE `studentaccount` SET `my_image_resource_id`='$resourceId'
                            WHERE `studentId`='$studentId'";
                            $this->executeQuery($sql);
                            $userId = $_SESSION['studentID'];
                            $this->logger->info(Events::STUDENT_IMAGE_UPDATE, [
                                "userId" => $userId,
                                "userType" => UserType::STUDENT,
                                "status" => StatusConstants::SUCCESS]);
                            break;
                    default:
                            $sql = " UPDATE `studentaccount` SET `my_image_resource_id`='$resourceId'
                            WHERE `studentId`='$studentId'";
                            $this->executeQuery($sql);
                            $userId = 'UNAUTHORIZED';
                            $this->logger->info(Events::STUDENT_IMAGE_UPDATE, [
                                "userId" => $userId,
                                "userType" => UserType::UNAUTHORIZED,
                                "status" => StatusConstants::SUCCESS]);
                            break;
                    }
            }
        }
        catch(\Exception $e) {
            $this->logger->error(Events::STUDENT_IMAGE_UPDATE, [
                "userId" => $userId,
                "userType" => UserType::STUDENT,
                "status" => StatusConstants::FAILED,
                "error" => $e->getCode(),
                "message" => $e->getMessage()
                ]);
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * Update Student Signature Image ResourceId
     * @return
     * @throws ProfessionalException
     */
    public function updateStudentSignatureImageResource($studentId,$resourceId){
        if(!$studentId){
            throw new ProfessionalException("INVALID_ENTITY","Invalid Data");
        }
        try {
            $userTypes = [];
            $userId ="";
            $userTypes []= $_SESSION['adminID'] || $GLOBALS['userType'] == 'ADMIN' ?'ADMIN':false;
            $userTypes []= $_SESSION['staffID'] || $GLOBALS['userType'] == 'STAFF' ?'STAFF':false;
            $userTypes []= $_SESSION['studentID'] || $GLOBALS['userType'] == 'STUDENT'?'STUDENT':false;
            $userType = false;
            foreach($userTypes as $user)
            {
                if($user != false)
                {
                    $userType = $user;
                    break;
                }
            }
            if($userType)
            {
                switch($userType){
                    case 'ADMIN':
                            $sql = " UPDATE `studentaccount` SET `my_sign_img_resource_id`='$resourceId' WHERE `studentId`='$studentId'";
                            $this->executeQuery($sql);
                            $userId = $_SESSION['adminID'];
                            $this->logger->info(Events::STUDENT_IMAGE_UPDATE, [
                                "userId" => $userId,
                                "userType" => UserType::ADMIN,
                                "status" => StatusConstants::SUCCESS
                            ]);
                            break;
                    case 'STAFF':
                            $sql = " UPDATE `studentaccount` SET `my_sign_img_resource_id`='$resourceId' WHERE `studentId`='$studentId'";
                            $this->executeQuery($sql);
                            $userId = $_SESSION['staffID'];
                            $this->logger->info(Events::STUDENT_IMAGE_UPDATE, [
                                "userId" => $userId,
                                "userType" => UserType::STAFF,
                                "status" => StatusConstants::SUCCESS]);
                            break;
                    case 'STUDENT':
                            $sql = " UPDATE `studentaccount` SET `my_sign_img_resource_id`='$resourceId' WHERE `studentId`='$studentId'";
                            $this->executeQuery($sql);
                            $userId = $_SESSION['studentID'];
                            $this->logger->info(Events::STUDENT_IMAGE_UPDATE, [
                                "userId" => $userId,
                                "userType" => UserType::STUDENT,
                                "status" => StatusConstants::SUCCESS]);
                            break;
                        break;
                    default:
                            $sql = " UPDATE `studentaccount` SET `my_sign_img_resource_id`='$resourceId' WHERE `studentId`='$studentId'";
                            $this->executeQuery($sql);
                            $userId = 'UNAUTHORIZED';
                            $this->logger->info(Events::STUDENT_IMAGE_UPDATE, [
                                "userId" => $userId,
                                "userType" => UserType::UNAUTHORIZED,
                                "status" => StatusConstants::SUCCESS]);
                            break;
                    }
            }
        }
        catch(\Exception $e) {
            $this->logger->error(Events::STUDENT_IMAGE_UPDATE, [
                "userId" => $userId,
                "userType" => UserType::STUDENT,
                "status" => StatusConstants::FAILED,
                "error" => $e->getCode(),
                "message" => $e->getMessage()
                ]);
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * Update Parent Signature Image ResourceId
     * @return
     * @throws ProfessionalException
     */
    public function updateParentSignatureImageResource($studentId,$resourceId){
        $studentId = $this->realEscapeString($studentId);
        $sql = " UPDATE `studentaccount` SET `parent_sign_img_resource_id`='$resourceId' WHERE `studentId`='$studentId'";
        try {
         return $this->executeQuery($sql);
        }
        catch (\Exception $e) {
        throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * get student profile pic by studentId
     * set throughWorker to true to fetch image in queue
     * @param string $studentId
     * @param boolean $throughWorker default false
     * @return Object
     * @throws ProfessionalException
     */
    public function getStudentProfilePic($studentId, $throughWorker=false){
        $sql = " SELECT lr.storage_object as storageObj,lr.path,backend_type,lr.id as resourceId
                FROM studentaccount sa inner join lin_resource lr on lr.id = sa.my_image_resource_id
                WHERE sa.studentID = $studentId";
        try {
            $imageDetails = $this->executeQueryForObject($sql);
            if($imageDetails->storageObj && $imageDetails->backend_type == 'S3'){
                $fileObj = json_decode(preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $imageDetails->storageObj));
                if($throughWorker){
                    $imageDetails->docpath=S3Utils::getPresignedUrLForQueue($fileObj->bucket, $fileObj->key);
                } else {
                    $imageDetails->docpath=S3Utils::getPreSignedURL($fileObj->bucket, $fileObj->key);
                }
            }
            else if($imageDetails->backend_type == 'LOCAL_STORAGE'){
                $imageDetails->docpath = "../" . $imageDetails->path;
            }
            else{
                return false;
            }
            return $imageDetails;
        }
        catch(\Exception $e) {
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * get student signature pic by studentId
     * set throughWorker to true to fetch image in queue
     * @param string $studentId
     * @param boolean $throughWorker default false
     * @return Object
     * @throws ProfessionalException
     */
    public function getStudentSignPic($studentId, $throughWorker=false){
        $sql = " SELECT lr.storage_object as storageObj ,lr.path,backend_type,lr.id as resourceId
                FROM studentaccount sa inner join lin_resource lr on lr.id = sa.my_sign_img_resource_id
                WHERE sa.studentID = $studentId";
        try {
            $imageDetails = $this->executeQueryForObject($sql);
            if($imageDetails->storageObj && $imageDetails->backend_type == 'S3'){
                $fileObj = json_decode(preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $imageDetails->storageObj));
                if($throughWorker){
                    $imageDetails->docpath=S3Utils::getPresignedUrLForQueue($fileObj->bucket, $fileObj->key);
                } else {
                    $imageDetails->docpath=S3Utils::getPreSignedURL($fileObj->bucket, $fileObj->key);
                }
            }
            else if($imageDetails->backend_type == 'LOCAL_STORAGE'){
                $imageDetails->docpath = "../" . $imageDetails->path;
            }
            else{
                return false;
            }
            return $imageDetails;
        }
        catch(\Exception $e) {
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
    }
    public function searchStudentForListDown($request)
    {
        $request = $this->realEscapeObject($request);
        $sql = "SELECT studentID, studentName, regNo, parentPhone, studentPhone FROM studentaccount WHERE 1=1 ";
        if ($request->regNo) {
            $sql .= "AND regNo LIKE '%$request->regNo%'";
        }
        if ($request->studentName) {
            $sql .= "AND studentName LIKE '%$request->studentName%'";
        }
        if ($request->studentMob) {
            $sql .= "AND studentPhone LIKE '%$request->studentMob%'";
        }
        if ($request->parentMob) {
            $sql .= "AND parentPhone LIKE '%$request->parentMob%'";
        }
        if($request->limitBy !== "")
        {
            $limitQuery .= " LIMIT $request->limitBy";
        }
        try {
            $students = $this->executeQueryForList($sql.$limitQuery);
            return $students;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getParentSignPic($studentId){
        $sql = " SELECT lr.storage_object as storageObj ,lr.path,backend_type,lr.id as resourceId
                FROM studentaccount sa inner join lin_resource lr on lr.id = sa.parent_sign_img_resource_id
                WHERE sa.studentID = $studentId";
        try {
            $imageDetails = $this->executeQueryForObject($sql);
            if($imageDetails->storageObj && $imageDetails->backend_type == 'S3'){
                $fileObj = json_decode(preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $imageDetails->storageObj));
                $imageDetails->docpath=S3Utils::getPreSignedURL($fileObj->bucket, $fileObj->key);
            }
            else if($imageDetails->backend_type == 'LOCAL_STORAGE'){
                $imageDetails->docpath = "../" . $imageDetails->path;
            }
            else{
                return false;
            }
            return $imageDetails;
        }
        catch(\Exception $e) {
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
    }
      /**
     * Get student details (failed) by batchId & semId
     * @param Integer $previousBatchId
     * @param Integer $semId
     * @return objectList[]
     * @throws ProfessionalException
     */
    public function getFailedStudentDetailsByBatchIdAndSemId($previousBatchId, $semId)
    {
        $sql = '';
        $previousBatchId = $this->realEscapeString($previousBatchId);
        $semId = $this->realEscapeString($semId);
        $batchShuffle = FailedReason::BATCH_SHUFFLE;
        $studentDetails = [];
        try {
            $sql = "SELECT sa.studentID, sa.studentName, sa.regNo, sa.rollNo, sa.admissionNo, sa.myImage,
            sa.studentSignImage FROM studentaccount sa INNER JOIN failed_students fs ON fs.studentID = sa.studentID WHERE fs.previousBatch = $previousBatchId AND fs.failedInSemester > '$semId' AND FIND_IN_SET('$semId', fs.hisSemestersInThisbatch)";
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
     /**
     * get exam registered student details by regId and  subjectId
     */
    public function getExamRegisteredStudentDetailsByExamRegIdAndSubjectId($request)
    {
        $request = $this->realEscapeObject($request);
        $studentDetails = [];
        $joinHall="";
        $examIdField = "";
        if($request->hallId){
            $examIdField = $request->isSupply ? "es.examID": "e.examID";
            $joinHall = "INNER JOIN exam_hall_arranged_students ehas ON ehas.examID = $examIdField AND ehas.studentID = sa.studentID AND ehas.hallID IN ($request->hallId)";
        }
        if (!$request->isSupply) {
            $sql = "SELECT DISTINCT sa.studentID as studentId,sa.regNo,sa.studentName,sa.batchID,e.examID, e.semId,efn.false_number, e.examTotalMarks FROM studentaccount sa
                        INNER JOIN exam_reg_studentsubject erss ON (sa.studentID = erss.studentID)
                        INNER JOIN exam e ON (e.examregID = erss.examregID AND e.subjectID = erss.subjectID AND sa.batchID = e.batchID)
                        INNER JOIN exam_reg_studentchallan ersc ON ersc.studentID = sa.studentID AND ersc.examregID = erss.examregID
                        $joinHall
                        LEFT JOIN examcontroller_false_number efn ON efn.studentID = sa.studentID AND efn.examregID = erss.examregID AND efn.examID = e.examID
                        WHERE erss.examregID IN ($request->examRegId) AND e.subjectID = '$request->subjectId' and e.semID = '$request->semId' AND ersc.paid=1  order by efn.false_number";
        } else  {
            $sql = "SELECT DISTINCT sa.studentID as studentId,sa.regNo,sa.studentName,sa.batchID,es.examID, es.semId,efn.false_number, es.examTotalMarks
            FROM studentaccount sa
                        INNER JOIN exam_supplementary_student_subjects esss ON (sa.studentID = esss.studentID)
                        INNER JOIN exam e ON (e.examID = esss.examID AND sa.batchID = e.batchID)
                        INNER JOIN exam es ON (e.subjectID = es.subjectID AND es.supply_examreg_id = esss.exam_supplementary_id AND es.batchID = e.batchID)
                        INNER JOIN exam_supplementary_student_details essd ON essd.studentID = sa.studentID AND essd.exam_supplementary_id = esss.exam_supplementary_id
                        $joinHall
                        LEFT JOIN examcontroller_false_number efn ON efn.studentID = sa.studentID AND efn.exam_supplementary_id = esss.exam_supplementary_id AND efn.examID = es.examID
                        WHERE esss.exam_supplementary_id IN ($request->examRegId) AND es.subjectID='$request->subjectId' AND essd.paid=1 order by efn.false_number";
        }
        try {
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * Create company for student placement
     * @param Object $request
     * @throws ProfessionalException
     */
    public function createCompanyForPlacement($request){
        $request = $this->realEscapeObject($request);
        $sql="INSERT INTO `student_placement_company` (`name`, `code`, `is_enabled`, `created_by`, `created_at`)
                VALUES ('$request->companyName', '$request->companyCode', '$request->isEnabled', '$request->staffID', UTC_TIMESTAMP()) ";
        try {
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Fetch placement company for student placement
     * @throws ProfessionalException
     */
    public function getAllPlacementCompanies(){
        $sql= " SELECT id , name, code, is_enabled as isEnabled, properties
                from  student_placement_company";
        try {
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Fetch placement company for student placement
     * @throws ProfessionalException
     */
    public function getAllPlacementCompaniesByRequest($request){
        $request = $this->realEscapeObject($request);
        $cond = "";
        if($request->showEnabledOnly){
            $cond .= " AND is_enabled = 1 ";
        }
        $sql= " SELECT id , name, code, is_enabled as isEnabled, properties
                from  student_placement_company
                WHERE 1=1 $cond";
        try {
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Update placement company for student placement
     * @throws ProfessionalException
     */
    public function updatePlacementCompanyDetails($request){
        $request = $this->realEscapeObject($request);
        $sql= " UPDATE student_placement_company
                SET name = '$request->companyName' ,code='$request->companyCode', is_enabled='$request->isEnabled'
                where id = '$request->id'";
        try {
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Delete placement company
     * @throws ProfessionalException
     */
    public function deletePlacementCompanyById($id){
        $sql= " DELETE from student_placement_company where id='$id'";
        try {
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Fetch students from placement
     * @param Object
     * @throws ProfessionalException
     */
    public function fetchStudentsPlacementDetails($request){
        $request = $this->realEscapeObject($request);
        $sql= " SELECT sp.id as placementId, sp.student_id as studentId, sp.psId, sp.placement_company_id as companyId,
                sp.placement_status_id as placementStatusId,
                sp.is_placed_id as isPlacedId, sp.remark_id as remarkId, sa.studentName, sa.studentID as studentId
                from student_placement sp
                inner join studentaccount sa on sa.studentID = sp.student_id
                where sp.psId = '$request->psId' AND sp.placement_company_id = '$request->companyId";
        try {
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Fetch students for placement
     * @param Object
     * @throws ProfessionalException
     */
    public function fetchStudentsForPlacementDetails($request){
        $request = $this->realEscapeObject($request);
        $sql= " SELECT psst.pseudosubjectID as psId,sa.studentName,
                0 as placementStatusId,0 as isPlacedId, 0 as remarkId,sa.studentID as studentId,
                0 as placementId
                from pseudosubjects_students psst
                inner join studentaccount sa on psst.studentID = sa.studentID
                where pseudosubjectID = $request->psId ";
        try {
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Save Student Placement details
     * @param Object
     * @throws ProfessionalException
     */
    public function saveStudentPlacementDetails($request){
        $request = $this->realEscapeObject($request);
        try {
            foreach($request->studentList as $student){
                $student = (object)$student;
                if((int)$student->placementId != 0){
                    $sql = "UPDATE student_placement
                            SET placement_company_id = '$request->companyId',
                            placement_status_id = '$student->placementStatusId'  ,
                            is_placed_id = '$student->isPlacedId',
                            remark_id = '$student->remarkId',
                            updated_by = '$request->staffId',
                            updated_at = UTC_TIMESTAMP()
                            WHERE id = '$student->placementId'
                            ";
                    $this->executeQuery($sql);
                }
                else{
                    $sql = "INSERT INTO student_placement (`student_id`, `psId`, `placement_company_id`, `placement_status_id`, `is_placed_id`, `remark_id`, `created_by`, `created_at`)
                            VALUES ('$student->studentId', '$student->psId', '$request->companyId', '$student->placementStatusId', '$student->isPlacedId', '$student->remarkId', '$request->staffId', 'UTC_TIMESTAMP()')";
                    $this->executeQuery($sql);
                }
            }
            return;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Update Placement Properties
     * @param JSON
     * @throws ProfessionalException
     */
    public function updatePlacementProperties($properties){
        $sql= " UPDATE settings
                SET value = '$properties'
                WHERE name = 'STUDENT_PLACEMENT_PROPERTIES' and type = 'PLACEMENT_SETTINGS'";
        try {
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function checkPlacementProperty($request){
        if($request->propertyKey == 'is_placed'){
            $sql=" SELECT id from student_placement where is_placed_id = $request->propertyId ";
            $result = $this->executeQueryForList($sql);
            if($result){
                throw new ProfessionalException("ERROR_DELETING","Cannot Delete Property In Use!");
            }
        }
        elseif($request->propertyKey == "placement_status"){
            $sql=" SELECT id from student_placement where placement_status_id = $request->propertyId ";
            $result = $this->executeQueryForList($sql);
            if($result){
                throw new ProfessionalException("ERROR_DELETING","Cannot Delete Property In Use!");
            }
        }
        elseif($request->propertyKey == "remark"){
            $sql=" SELECT id from student_placement where remark_id = $request->propertyId ";
            $result = $this->executeQueryForList($sql);
            if($result){
                throw new ProfessionalException("ERROR_DELETING","Cannot Delete Property In Use!");
            }
        }
        return true;
        try {
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * student details by reg no request
     * @param string $regNo
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getStudentDetailsByRequest($request)
    {
        $request = $this->realEscapeObject($request);
        $sql = "SELECT sa.studentID as id, sa.studentName as name, dept.deptName, bth.batchName, sa.regNo, sa.rollNo, dept.deptName, bth.batchName, dept.deptID, bth.batchID, bth.patternID as courseTypeId, bth.batchStartYear as startYear, bth.batchEndYear as endYear, dept.departmentDesc, sa.tcIssued, sa.studentAddress, bth.courseTypeID FROM studentaccount sa LEFT JOIN department dept ON sa.deptID=dept.deptID INNER JOIN batches bth ON sa.batchID=bth.batchID  WHERE regNo = \"$request->regNo\"";
        try {
            $studentDetails = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * get student add-on course details
     * @param $studentId
     * @return $studentDetails
     * @throws ProfessionalException
     */
    public function getStudentAddonCourse($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        $sql = "SELECT ac.semID, ac.courseID, ac.courseName, acs.mark, acs.grade from addon_course_studentmarks acs INNER JOIN addon_courses ac ON (acs.courseID = ac.courseID) WHERE acs.studentID = $studentId ORDER BY ac.semID ASC";
        try {
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
      /**
     * get student regular exam registration
     * @param $studentId
     * @return $regularExams
     * @throws ProfessionalException
     */
    public function getRegularExamRegistrationsOfStudent ($studentId){
        $studentId = $this->realEscapeString($studentId);
        if(empty($studentId)){
            throw new ProfessionalException(ProfessionalException::INVALID_REQUEST, "Student id is null");
        }
        $sql = null;
        try {
            $sql = "SELECT
                        DISTINCT er.examregID AS examRegId,
                        erb.semID AS semId,
                        erb.batchID AS batchId
                    FROM
                        exam_registration er
                    INNER JOIN exam_registration_batches erb ON
                        erb.examregID = er.examregID
                    INNER JOIN exam_reg_studentchallan ersc ON
                        ersc.examregID = er.examregID
                    INNER JOIN studentaccount sa ON
                        sa.studentID = ersc.studentID
                    LEFT JOIN failed_students fs
                        ON fs.studentID = sa.studentID
                        AND FIND_IN_SET(erb.semID, fs.hisSemestersInThisbatch)
                    WHERE
                        ersc.studentID = $studentId
                    AND erb.batchID = IF (fs.previousBatch, fs.previousBatch, sa.batchID);";
            $regularExams =  $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException ($e->getCode(), $e->getMessage());
        }
        return $regularExams;
    }
    /**
     * student reservation
     * @return Array
     * @throws ProfessionalException
     */
    public function getStudentReservationForDatImport()
    {
        $sql = "SELECT reservationID as id,reservationName as name FROM reservation_students";
        try {
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * student seat reservation
     * @return Array
     * @throws ProfessionalException
     */
    public function getStudentSeatReservationForDatImport()
    {
        $sql = "SELECT reservID as id, reservName as name, other_reserv FROM student_reservation";
        try {
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
     /**
     * get student regular exam registration
     * @param $studentId
     * @return $regularExams
     * @throws ProfessionalException
     */
    public function getStudentByRequestForPseudoSubjectImport ($request){
        $request = $this->realEscapeObject($request);
        // if(empty($studentId)){
        //     throw new ProfessionalException(ProfessionalException::INVALID_REQUEST, "Student id is null");
        // }
            $where = [];
            $request->regNo?$where[] = " std.regNo = '".$request->regNo."' ":null;
            $request->rollNo?$where[] = " std.rollNo = '".$request->rollNo."' ":null;
            $request->admissionNo?$where[] = " std.admissionNo = '".$request->admissionNo."' ":null;
            $request->id?$where[] = " std.studentID = '".$request->id."' ":null;
            $request->userName?$where[] = " std.studentAccount = '".$request->userName."' ": null;
        try {
            $sql = "SELECT std.batchID AS batchId,b.batchName,std.studentID AS id,0 AS isAssigned,std.studentName AS name,std.regNo AS registerNumber,std.rollNo AS rollNumber from studentaccount std
            INNER JOIN batches b ON b.batchID = std.batchID ".($where?" WHERE ".implode(' AND ',$where):"");
            $studentList = $this->executeQueryForList($sql);
            if($studentList && count($studentList) == 1){
                return $studentList[0];
            }else{
                return null;
            }
        } catch (\Exception $e) {
            throw new ProfessionalException ($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param $name
     *
     */
    public function getStudentsForExportShow()
    {
        $sql = "SELECT std.batchID AS batchId,b.batchName,std.studentID AS id,0 AS isAssigned,std.studentName AS name,std.regNo AS registerNumber,std.rollNo AS rollNumber,std.admissionNo from studentaccount std
        INNER JOIN batches b ON b.batchID = std.batchID
        WHERE std.regNo and std.rollNo limit 10";
        try {
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     *
     */
    public function generateAsyncStudentPhotoDownload($request){
        $files = array();
        try{
            // $studentPhotoName = CommonService::getInstance()->getSettings(SettingsConstants::STUDENT_PHOTO, SettingsConstants::STUDENT_PHOTO_DOWNLOAD_NAME);
            $changePhotoName = CommonService::getInstance()->getSettings(SettingsConstants::ADMIN_SETTINGS,SettingsConstants::SHOW_ADMINSIDE_STUDENT_PHOTO_LABEL_AS_REGISTER_NUMBER);
            if($request->filterBy)
            {
                $studentPhotoName = $request->filterBy;
            }
            // $studentPhotoName = $studentPhotoName?"{{".$studentPhotoName."}}":"{{admissionNo}}";
            $studentIdList = $request->studentIdList;
            $studentList = $request->studentList;
            $batchId = $request->batchId;
            $type = $request->type;
            // $batchDetails = BatchService::getInstance()->getBatchDetails($batchId);
            if(!empty($studentIdList)){
                foreach ($studentIdList as $studentId) {
                    $student = CommonUtil::objArraySearch($studentList, 'studentId', $studentId);
                    if($type == "PROFILE"){
                        $imageDetails = $this->getStudentProfilePic($studentId);
                    }
                    else{
                        $imageDetails = $this->getStudentSignPic($studentId);
                    }
                    $storageObj = json_decode($imageDetails->storageObj);
                    $credentials = new stdClass();
                    $credentials->accessKey = getenv('AWS_ACCESS_KEY');
                    $credentials->secretKey = getenv('AWS_CLIENT_SECRET_KEY');
                    $student->myImage = str_replace("../","",$student->myImage);
                    if($imageDetails->backend_type == 'S3'){
                        $student->myImage = $imageDetails->docpath;
                        $img = new stdClass();
                        $img->url =$student->myImage;
                        $img->bucket = $storageObj->bucket;
                        $img->key = $storageObj->key;
                        $img->source = $img->key;
                        $img->name = StringUtil::replace_tags($studentPhotoName, array(
                            "admissionNo"=> $student->admissionNo,
                            "studentName"=>$student->studentName,
                            "regNo"=>$student->regNo,
                            "rollNo"=>$student->rollNo
                        )).".".pathinfo($img->source, PATHINFO_EXTENSION);
                        $files[] = $img;
                    }
                    else if (file_exists(DOCUMENT_ROOT . $student->myImage)) {
                        $img = new stdClass();
                        $img->source =DOCUMENT_ROOT . $student->myImage;
                        $img->name = StringUtil::replace_tags($studentPhotoName, array(
                            "admissionNo"=> $student->admissionNo,
                            "studentName"=>$student->studentName,
                            "regNo"=>$student->regNo,
                            "rollNo"=>$student->rollNo
                        )).".".pathinfo($img->source, PATHINFO_EXTENSION);
                        $files[] = $img;
                    }
                }
            }
            else{
                foreach ($studentList as $student) {
                    if($type == "PROFILE"){
                        $imageDetails = $this->getStudentProfilePic($student->studentId);
                    }
                    else{
                        $imageDetails = $this->getStudentSignPic($student->studentId);
                    }
                    $storageObj = json_decode($imageDetails->storageObj);
                    $credentials = new stdClass();
                    $credentials->accessKey = getenv('AWS_ACCESS_KEY');
                    $credentials->secretKey = getenv('AWS_CLIENT_SECRET_KEY');
                    $student->myImage = str_replace("../","",$student->myImage);
                    if($imageDetails->backend_type == 'S3'){
                        $student->myImage = $imageDetails->docpath;
                        $img = new stdClass();
                        $img->url =$student->myImage;
                        $img->bucket = $storageObj->bucket;
                        $img->key = $storageObj->key;
                        $img->source = $img->key;
                        $img->name = StringUtil::replace_tags($studentPhotoName, array(
                            "admissionNo"=> $student->admissionNo,
                            "studentName"=>$student->studentName,
                            "regNo"=>$student->regNo,
                            "rollNo"=>$student->rollNo
                        )).".".pathinfo($img->source, PATHINFO_EXTENSION);
                        $files[] = $img;
                    }
                    else if (file_exists(DOCUMENT_ROOT. $student->myImage)) {
                        $img = new stdClass();
                        $img->source =DOCUMENT_ROOT. $student->myImage;
                        $img->name = StringUtil::replace_tags($studentPhotoName, array(
                            "admissionNo"=> $student->admissionNo,
                            "studentName"=>$student->studentName,
                            "regNo"=>$student->regNo,
                            "rollNo"=>$student->rollNo
                        )).".".pathinfo($img->source, PATHINFO_EXTENSION);
                        $files[] = $img;
                    }
                }
            }
            $zipPath = DOCUMENT_ROOT."studentsphoto/".$request->collegeCode;
            $zipname = $request->zipname;
            $credentials = new \stdClass();
            $credentials->accessKey=SecurityUtils::decryptAndVerify($request->accessKey, "S3-UPLOAD-LINWAYS");
            $credentials->secretKey=SecurityUtils::decryptAndVerify($request->secretKey, "S3-UPLOAD-LINWAYS");
            // $isZipCreated=CommonUtil::createZipFolder($files, $zipPath, $zipname, false, $credentials);
            $isZipCreated=CommonUtil::createZipUsingZipStream($files, $zipPath, $zipname, false, $credentials);
            if($isZipCreated)
            {
                // $zipname .= ".zip";
                $uploadResourceRequest = new UploadResourceRequest();
                $uploadResourceRequest->fileName = $zipname;
                $uploadResourceRequest->filePath = $zipPath."/".$zipname;
                $uploadResourceRequest->context = ResourceContext::STUDENT_PHOTOS_DOWNLOAD;
                $uploadResourceRequest->backendType = BackendTypes::S3;
                $uploadResourceRequest->s3FolderPath = $request->collegeCode. "/studentsphoto" . "/";
                $uploadResourceRequest->bucket = SecurityUtils::decryptAndVerify($request->bucket, "S3-UPLOAD-LINWAYS");
                $uploadResourceRequest->accessKey = SecurityUtils::decryptAndVerify($request->accessKey, "S3-UPLOAD-LINWAYS");
                $uploadResourceRequest->secretKey = SecurityUtils::decryptAndVerify($request->secretKey, "S3-UPLOAD-LINWAYS");
                $uploadResourceRequest->createdBy = $request->createdBy;
                $uploadResourceRequest->updatedBy = $request->updatedBy;
                $resourceId = ResourceService::getInstance()->uploadResource($uploadResourceRequest);
                // $asyncReport = $request->asyncReport;
                $getAsyncReportRequest = new GetAsyncReportRequest();
                $getAsyncReportRequest->asyncReportId = $request->asyncReportId;
                $asyncReport = AsyncReportService::getInstance()->getAsyncReport($getAsyncReportRequest)[0];
                $asyncReport->linResourceId = $resourceId;
                AsyncReportService::getInstance()->saveAsyncReport($asyncReport);
                if(file_exists($zipPath."/".$zipname)){
                    unlink($zipPath."/".$zipname);
                }
            }
        }
         catch (\Exception $e) {
            throw new ProfessionalException($e->getCode,$e->getMessage());
        }
    }
    public function generateAsyncStudentPhotoDownloadCourseType($request){
        $files = array();
        try{
            // $studentPhotoName = CommonService::getInstance()->getSettings(SettingsConstants::STUDENT_PHOTO, SettingsConstants::STUDENT_PHOTO_DOWNLOAD_NAME);
            $changePhotoName = CommonService::getInstance()->getSettings(SettingsConstants::ADMIN_SETTINGS,SettingsConstants::SHOW_ADMINSIDE_STUDENT_PHOTO_LABEL_AS_REGISTER_NUMBER);
            if($request->filterBy)
            {
                $studentPhotoName = $request->filterBy;
            }
            $studentPhotoName = $studentPhotoName?"{{".$studentPhotoName."}}":"{{admissionNo}}";
            $studentIdList = $request->studentIdList;
            $studentList = $request->studentList;
            $batchId = $request->batchId;
            $type = $request->type;
            // $batchDetails = BatchService::getInstance()->getBatchDetails($batchId);
            if(!empty($studentIdList)){
                foreach ($studentIdList as $studentId) {
                    $student = CommonUtil::objArraySearch($studentList, 'studentId', $studentId);
                    if($type == "PROFILE"){
                        $imageDetails = $this->getStudentProfilePic($studentId);
                    }
                    else{
                        $imageDetails = $this->getStudentSignPic($studentId);
                    }
                    $storageObj = json_decode($imageDetails->storageObj);
                    $credentials = new stdClass();
                    $credentials->accessKey = getenv('AWS_ACCESS_KEY');
                    $credentials->secretKey = getenv('AWS_CLIENT_SECRET_KEY');
                    $student->myImage = str_replace("../","",$student->myImage);
                    if($imageDetails->backend_type == 'S3'){
                        $student->myImage = $imageDetails->docpath;
                        $img = new stdClass();
                        $img->url =$student->myImage;
                        $img->bucket = $storageObj->bucket;
                        $img->key = $storageObj->key;
                        $img->source = $img->key;
                        $img->name = StringUtil::replace_tags($studentPhotoName, array(
                            "admissionNo"=> $student->admissionNo,
                            "studentName"=>$student->studentName,
                            "regNo"=>$student->regNo,
                            "rollNo"=>$student->rollNo
                        )).".".pathinfo($img->source, PATHINFO_EXTENSION);
                        $files[] = $img;
                    }
                    else if (file_exists(DOCUMENT_ROOT . $student->myImage)) {
                        $img = new stdClass();
                        $img->source =DOCUMENT_ROOT . $student->myImage;
                        $img->name = StringUtil::replace_tags($studentPhotoName, array(
                            "admissionNo"=> $student->admissionNo,
                            "studentName"=>$student->studentName,
                            "regNo"=>$student->regNo,
                            "rollNo"=>$student->rollNo
                        )).".".pathinfo($img->source, PATHINFO_EXTENSION);
                        $files[] = $img;
                    }
                }
            }
            else{
                foreach ($studentList as $student) {
                    if($type == "PROFILE"){
                        $imageDetails = $this->getStudentProfilePic($student->studentId);
                    }
                    else{
                        $imageDetails = $this->getStudentSignPic($student->studentId);
                    }
                    $storageObj = json_decode($imageDetails->storageObj);
                    $credentials = new stdClass();
                    $credentials->accessKey = getenv('AWS_ACCESS_KEY');
                    $credentials->secretKey = getenv('AWS_CLIENT_SECRET_KEY');
                    $student->myImage = str_replace("../","",$student->myImage);
                    if($imageDetails->backend_type == 'S3'){
                        $student->myImage = $imageDetails->docpath;
                        $img = new stdClass();
                        $img->url =$student->myImage;
                        $img->bucket = $storageObj->bucket;
                        $img->key = $storageObj->key;
                        $img->source = $img->key;
                        $img->name = StringUtil::replace_tags($studentPhotoName, array(
                            "admissionNo"=> $student->admissionNo,
                            "studentName"=>$student->studentName,
                            "regNo"=>$student->regNo,
                            "rollNo"=>$student->rollNo
                        )).".".pathinfo($img->source, PATHINFO_EXTENSION);
                        $files[] = $img;
                    }
                    else if (file_exists(DOCUMENT_ROOT. $student->myImage)) {
                        $img = new stdClass();
                        $img->source =DOCUMENT_ROOT. $student->myImage;
                        $img->name = StringUtil::replace_tags($studentPhotoName, array(
                            "admissionNo"=> $student->admissionNo,
                            "studentName"=>$student->studentName,
                            "regNo"=>$student->regNo,
                            "rollNo"=>$student->rollNo
                        )).".".pathinfo($img->source, PATHINFO_EXTENSION);
                        $files[] = $img;
                    }
                }
            }
            $zipPath = DOCUMENT_ROOT."studentsphoto/".$request->collegeCode;
            $zipname = $request->zipname;
            $credentials = new \stdClass();
            $credentials->accessKey=SecurityUtils::decryptAndVerify($request->accessKey, "S3-UPLOAD-LINWAYS");
            $credentials->secretKey=SecurityUtils::decryptAndVerify($request->secretKey, "S3-UPLOAD-LINWAYS");
            // $isZipCreated=CommonUtil::createZipFolder($files, $zipPath, $zipname, false, $credentials);
            $isZipCreated=CommonUtil::createZipUsingZipStream($files, $zipPath, $zipname, false, $credentials);
            if($isZipCreated)
            {
                // $zipname .= ".zip";
                $uploadResourceRequest = new UploadResourceRequest();
                $uploadResourceRequest->fileName = $zipname;
                $uploadResourceRequest->filePath = $zipPath."/".$zipname;
                $uploadResourceRequest->context = ResourceContext::STUDENT_PHOTOS_DOWNLOAD;
                $uploadResourceRequest->backendType = BackendTypes::S3;
                $uploadResourceRequest->s3FolderPath = $request->collegeCode. "/studentsphoto" . "/";
                $uploadResourceRequest->bucket = SecurityUtils::decryptAndVerify($request->bucket, "S3-UPLOAD-LINWAYS");
                $uploadResourceRequest->accessKey = SecurityUtils::decryptAndVerify($request->accessKey, "S3-UPLOAD-LINWAYS");
                $uploadResourceRequest->secretKey = SecurityUtils::decryptAndVerify($request->secretKey, "S3-UPLOAD-LINWAYS");
                $uploadResourceRequest->createdBy = $request->createdBy;
                $uploadResourceRequest->updatedBy = $request->updatedBy;
                $resourceId = ResourceService::getInstance()->uploadResource($uploadResourceRequest);
                // $asyncReport = $request->asyncReport;
                $getAsyncReportRequest = new GetAsyncReportRequest();
                $getAsyncReportRequest->asyncReportId = $request->asyncReportId;
                $asyncReport = AsyncReportService::getInstance()->getAsyncReport($getAsyncReportRequest)[0];
                $asyncReport->linResourceId = $resourceId;
                AsyncReportService::getInstance()->saveAsyncReport($asyncReport);
                if(file_exists($zipPath."/".$zipname)){
                    unlink($zipPath."/".$zipname);
                }
            }
        }
         catch (\Exception $e) {
            throw new ProfessionalException($e->getCode,$e->getMessage());
        }
    }
    /**
     * get students by mooc exam registration
     * @throws ProfessionalException
     */
    public function getMoocExamRegistrationStudents($request)
    {
        $request = $this->realEscapeObject($request);
        $sql = null;
        $condition = "";
        $students=[];
        if($request->examRegId){
            $condition .=" AND ersc.examregID IN ($request->examRegId)";
        }
        if ($request->batchId) {
            $condition .= " AND sa.batchID IN ($request->batchId)";
        }
        if ($request->courseMode) {
            $condition .= " AND ersc.courseMode = '$request->courseMode";
        }
        if ($request->studentId) {
            $condition .= " AND ersc.studentID IN ($request->studentId)";
        }
        try {
            $sql = "SELECT ersc.studentID,sa.regNo,sa.studentName,ersc.approved,ersc.courseMode,ersc.payment_remarks FROM exam_reg_studentchallan ersc
                    INNER JOIN studentaccount sa ON sa.studentID = ersc.studentID
                    WHERE  1 =1
                    $condition";
            $students =  $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $students;
    }
    /**
     * get supply exam registered details of students
     * @throws ProfessionalException
     */
    public function getSupplyExamsRegistrationOfStudent ($studentId){
        $studentId = $this->realEscapeString($studentId);
        if(empty($studentId)){
            throw new ProfessionalException(ProfessionalException::INVALID_REQUEST, "Student id is null");
        }
        $sql = null;
        try {
            $sql = "SELECT
                es.id,
                es.supplyDesc AS name,
                es.semID AS semId
            FROM
                exam_supplementary es
            INNER JOIN exam_supplementary_student_details essd ON
                essd.exam_supplementary_id = es.id
            WHERE
                essd.isSupply = 1 AND essd.studentID = $studentId";
            $supplyExams =  $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException ($e->getCode(), $e->getMessage());
        }
        return $supplyExams;
    }
    /**
     * with held student ExamResult by  examregistration
     * @author Sibin
     */
    public function blockStudentExamResultByExamRegistration($request)
    {
        $request = $this->realEscapeObject($request);
        $student = $request->student;
        if(!empty($student->reasonId)){
            $student->reasonId = implode(",",$student->reasonId);
        }else{
            $student->reasonId ="";
        }
        if ($student->reasonId) {
            $reasonColumn = ",reasonId";
            $reasonColumnValue = ",'$student->reasonId'";
        }
        if ($request->isSupply) {
            if ($student->blockResult) {
                $sql     = "INSERT INTO supplyexam_students_withheld(exam_supplementary_id, studentID,withheld$reasonColumn,adminId) VALUES($request->examRegId,$student->studentId,1 $reasonColumnValue,'$request->adminId') ON DUPLICATE KEY UPDATE withheld = values(withheld) ,reasonId = values(reasonId),adminId = values(adminId)";
            } else {
                $sql     = "UPDATE supplyexam_students_withheld set withheld = 0 ,reasonId = null WHERE exam_supplementary_id = '$request->examRegId' AND studentID = '$student->studentId'";
            }
        } else {
            if ($student->blockResult) {
                $sql     = "INSERT INTO exam_students_withheld(examregID,studentID,withheld $reasonColumn,adminId) VALUES($request->examRegId,$student->studentId,1 $reasonColumnValue,'$request->adminId') ON DUPLICATE KEY UPDATE withheld = values(withheld) ,reasonId = values(reasonId),adminId = values(adminId)";
            } else {
                $sql     = "UPDATE exam_students_withheld set withheld = 0 ,reasonId = null WHERE examregID = '$request->examRegId' AND studentID = '$student->studentId'";
            }
        }
        try {
            $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return true;
    }
    /**
     * Search Student with Basic Details
     * @param SearchStudentRequest $searchStudentRequest
     * @return \com\linways\core\ams\professional\response\SearchStudentResponse
     */
    public function searchStudentBasicDetails($searchStudentRequest, $exact = false){
        $studentDetails = new SearchStudentResponse();
        $sql_cond = "";
        $joins = "";
        if (!$searchStudentRequest == NULL) {
            $failedBatchId = BatchService::getInstance()->getFailedBatchId();
            $method = $searchStudentRequest->method ? $searchStudentRequest->method : 'AND';
            $sql_count = "SELECT count(sa.studentID) AS totalRecord ";
            $sql = "SELECT sa.studentID,sa.studentName,sa.studentAccount,sa.regNo,sa.admissionNo,sa.rollNo,sa.studentEmail,dept.deptID,dept.deptName, bth.batchID,bth.batchName,bth.semID, sec.secondLangaugeName,sem.semName";
            $searchStudentRequest->subbatchIds =array_filter($searchStudentRequest->subbatchIds, function ($i) { return $i !== '0'; });
            $joins .= (!empty($searchStudentRequest->subbatchId) || !empty($searchStudentRequest->subbatchIds)) ? " INNER JOIN subbatch_student ss on sa.studentID = ss.studentID ":"";
            $sql .= "
                FROM studentaccount sa
                    INNER JOIN batches bth ON sa.batchID=bth.batchID
                    INNER JOIN department dept ON bth.deptID=dept.deptID
                    INNER JOIN course_type ct on bth.courseTypeID = ct.courseTypeID
                    INNER JOIN semesters sem on sem.semID = bth.semID
                    $joins
                    LEFT JOIN secondLangauge sec ON sec.secondlangaugeID = sa.secondlangaugeID ";
            $sql_count .= "
            FROM studentaccount sa
                INNER JOIN batches bth ON sa.batchID=bth.batchID
                INNER JOIN department dept ON dept.deptID=bth.deptID
                INNER JOIN course_type ct on bth.courseTypeID = ct.courseTypeID
                INNER JOIN semesters sem on sem.semID = bth.semID
                $joins
                LEFT JOIN secondLangauge sec ON sec.secondlangaugeID = sa.secondlangaugeID ";
                $sql .= " WHERE sa.batchID is not null AND sa.batchID <> $failedBatchId ";
                $sql_count .= " WHERE sa.batchID is not null AND sa.batchID <> $failedBatchId ";
            if ($searchStudentRequest->id) {
                $sql_cond .= "$method sa.studentID = '" . $searchStudentRequest->id . "' ";
            }
            if ($searchStudentRequest->name) {
                $sql_cond .= "$method sa.studentName like '%" . $searchStudentRequest->name . "%' ";
            }
            if ($searchStudentRequest->batchId) {
                $sql_cond .= "$method sa.batchID = '" . $searchStudentRequest->batchId . "' ";
            }
            if (!empty($searchStudentRequest->batchIds)) {
                $sql_cond .= "$method sa.batchID IN ('" . implode("','",$searchStudentRequest->batchIds) . "') ";
            }
            if ($searchStudentRequest->deptId) {
                $sql_cond .= "$method sa.deptID = '" . $searchStudentRequest->deptId . "' ";
            }
            if (!empty($searchStudentRequest->deptIds)) {
                $sql_cond .= "$method sa.deptID IN ('" . implode("','",$searchStudentRequest->deptIds) . "') ";
            }
            if ($searchStudentRequest->account) {
                $sql_cond .= "$method sa.studentAccount like '%" . $searchStudentRequest->account . "%' ";
            }
            if ($searchStudentRequest->email) {
                $sql_cond .= "$method sa.studentEmail like '%" . $searchStudentRequest->email . "%' ";
            }
            if ($searchStudentRequest->rollNo) {
                if (!$exact) {
                    $sql_cond .= "$method sa.rollNo like '%" . $searchStudentRequest->rollNo . "%' ";
                } else {
                    $sql_cond .= "$method sa.rollNo = '" . $searchStudentRequest->rollNo . "' ";
                }
            }
            if ($searchStudentRequest->admissionNo) {
                if (!$exact) {
                    $sql_cond .= "$method sa.admissionNo like '%" . $searchStudentRequest->admissionNo . "%' ";
                } else {
                    $sql_cond .= "$method sa.admissionNo = '" . $searchStudentRequest->admissionNo . "' ";
                }
            }
            if ($searchStudentRequest->regNo) {
                if (!$exact) {
                    $sql_cond .= "$method sa.regNo like '%" . $searchStudentRequest->regNo . "%' ";
                } else {
                    $sql_cond .= "$method sa.regNo = '" . $searchStudentRequest->regNo . "' ";
                }
            }
            if ($searchStudentRequest->studentIds) {
                $sql_cond .= " $method sa.studentID IN (" . $searchStudentRequest->studentIds . ")";
            }
            if ($searchStudentRequest->coursePattern) {
                $sql_cond .= " $method ct.courseTypeID IN (".$searchStudentRequest->coursePattern.")";
            }
            if ($searchStudentRequest->year) {
                $sql_cond .= " $method bth.batchStartYear IN (".$searchStudentRequest->year.")";
            }
            if ($searchStudentRequest->coursePatternId) {
                $sql_cond .= " $method bth.patternID IN (".$searchStudentRequest->coursePatternId.")";
            }
            if ($searchStudentRequest->excludeDiscontinuedStudents){
                $sql_cond .= " $method sa.exitType <> '".SettingsConstants::EXIT_TYPE_DISCONTINUED."'";
            }
            if($searchStudentRequest->subbatchId){
                $sql_cond .= " $method  ss.subbatchID  IN (".$searchStudentRequest->subbatchId.")";
            }
            if(!empty($searchStudentRequest->subbatchIds)){
                $sql_cond .= " $method  ss.subbatchID  IN (".implode(', ', $searchStudentRequest->subbatchIds).")";
            }
            if ($searchStudentRequest->sortBy) {
                $sql_order = " order by $searchStudentRequest->sortBy $searchStudentRequest->sortOrder ";
            }
            $sql_count .= $sql_cond;
            $sql .= $sql_cond;
            if (!$searchStudentRequest->excludeFaildStudent) {
                $sql_count2 = "SELECT count(sa.studentID) AS totalRecord ";
                $sql2 = "SELECT sa.studentID,sa.studentName,sa.studentAccount,sa.regNo,sa.admissionNo,sa.rollNo,sa.studentEmail,dept.deptID,dept.deptName, bth.batchID,bth.batchName,bth.semID, sec.secondLangaugeName,sem.semName";
                $sql2 .= " FROM studentaccount sa
                    INNER JOIN failed_students fs ON fs.studentID=sa.studentID
                    INNER JOIN batches bth ON fs.previousBatch=bth.batchID
                    INNER JOIN department dept ON bth.deptID=dept.deptID
                    INNER JOIN semesters sem ON sem.semID = fs.failedInSemester
                    INNER JOIN course_type ct on bth.courseTypeID = ct.courseTypeID
                    $joins
                    LEFT JOIN secondLangauge sec ON sec.secondlangaugeID = sa.secondlangaugeID ";
                $sql_count2 .= " FROM studentaccount sa
                    INNER JOIN failed_students fs ON fs.studentID=sa.studentID
                    INNER JOIN batches bth ON fs.previousBatch=bth.batchID
                    INNER JOIN department dept ON bth.deptID=dept.deptID
                    INNER JOIN semesters sem ON sem.semID = fs.failedInSemester
                    INNER JOIN course_type ct on bth.courseTypeID = ct.courseTypeID
                    $joins
                    LEFT JOIN secondLangauge sec ON sec.secondlangaugeID = sa.secondlangaugeID ";
                $sql2 .= "
                    WHERE sa.batchID is not null AND fs.isFailNow='1'" . $sql_cond . "GROUP BY sa.studentID";
                $sql_count2 .= "
                    WHERE sa.batchID is not null AND fs.isFailNow='1'" . $sql_cond . "GROUP BY sa.studentID";
                $sql .= "GROUP BY sa.studentID UNION " . $sql2;
                $sql_count .= "GROUP BY sa.studentID UNION " . $sql_count2;
            }
            $sql .= $sql_order;
            try{
                $studentCount = $this->executeQueryForObject($sql_count)->totalRecord;
                $studentDetails->totalRecords = $studentCount;
                if ($searchStudentRequest->export) {
                    $searchStudentRequest->endIndex = $studentDetails->totalRecords;
                }
                $sql .= " LIMIT $searchStudentRequest->startIndex,$searchStudentRequest->endIndex";
                $studentDetails->students = $this->executeQueryForList($sql);
            } catch (\Exception $e) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        }
        return $studentDetails;
    }
     /**
     * @author Ajay
     * @param $studentId
     * @return $Object->student_advance_details
     *
     *
     */
    private function isExistAnEntryForAdvancedProfile($studentId){
        $sql = "SELECT `student_advance_details` FROM advance_student_profile WHERE `student_id` = $studentId";
        $res = $this->executeQueryForObject($sql);
        $res=json_decode($res->student_advance_details);
        return $res;
    }
    /**
     * @author Ajay
     * @param $studentId
     * @param $Object
     *
     *
     */
    public function submitFormAdvancedProfile($studentId,$Object){
        try{
            $Object = $this->realEscapeObject($Object);
            $exist=$this->isExistAnEntryForAdvancedProfile($studentId);
            if(!$exist){
                $Object = json_encode($Object);
                $Object = addSlashes($Object);
                $sql = "INSERT INTO advance_student_profile(`student_id`,`student_advance_details`) VALUES ($studentId,'$Object')";
                $this->executeQuery($sql);
            }
            else{
                $sql = "SELECT `student_advance_details` FROM advance_student_profile WHERE `student_id` = $studentId";
                $updateBuffer = $this->executeQueryForObject($sql);
                $updateBuffer = json_decode($updateBuffer->student_advance_details);
                $updateBuffer = json_encode((object)array_merge((array) $updateBuffer ,(array) $Object));
                $updateBuffer = addSlashes($updateBuffer);
                $sql = "UPDATE advance_student_profile SET `student_advance_details` = '$updateBuffer' WHERE `student_id` = $studentId";
                $this->executeQuery($sql);
            }
            }
        catch(\Exception $e){
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @author Ajay
     * @param $studentId
     * @return Object
     * @throws ProfessionalException
     */
    public function getDataForAdvancedProfile($studentId){
        try{
            $result = new stdClass();
            $result->advanceDetails = new stdClass();
            $result->studentDetails = new stdClass();
            $sql = "SELECT `student_advance_details` FROM advance_student_profile WHERE `student_id` = $studentId";
            $advanceDetails = $this->executeQueryForObject($sql)->student_advance_details;
            // $result->advanceDetails = $advanceDetails?json_decode($advanceDetails):new \stdClass;
            $result->advanceDetails = $advanceDetails?json_decode(ResultHandler::convertObjectToUTF8Format($advanceDetails)):new \stdClass;
            $result->studentDetails = $this->getStudentDataforAdvanceProfile($studentId);
            return $result;
        }
        catch(\Exception $e){
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @author Ajay
     * @param $studentId
     * @return Object
     * @throws ProfessionalException
     */
    public function getStudentDataforAdvanceProfile($studentId){
        try{
                $sql = "SELECT s.studentName as personName,
                                s.rollNo as personRoll ,
                                s.studentGender as personGender ,
                                s.bloodGroup as personBlood ,
                                s.studentEmail as personEmail ,
                                s.studentPhone as personPhone ,
                                s.studentAddress as personAddress ,
                                s.studentFather as fatherName ,
                                se.parentOccupation as fatherOccupation,
                                s.parentAddress1 as parentOfficeAddress,
                                s.parentPhone as fatherPhone,
                                se.mobilePhone as fatherMobile,
                                se.fatherEmail as fatherEmail,
                                s.studentMother as motherName,
                                se.motherEducation as motherQualification,
                                se.motherOccupation,
                                se.motherPhone ,
                                se.motherEmail,
                                b.batchName
                                FROM studentaccount s
                                LEFT JOIN studentaccount_extras se ON se.studentID =s.studentID
                                INNER JOIN `batches` b ON  s.batchID=b.batchID
                WHERE s.studentID = $studentId";
                $result = $this->executeQueryForObject($sql);
                return $result;
        }
        catch(\Exception $e){
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @author Ajay
     * @return Array
     * @throws ProfessionalException
     * @param StudentId
     */
    public function getMentorMenteeForAdvancedProfile($studentId){
        try {
                $sql="SELECT
                IF(msstf.is_absent is NULL,
                1,
                msstf.is_absent) as isAbsent,
                st.staffAccount,
                st.staffName,
                st.staffCode,
                ms.id as mentorSessionId,
                ms.session_no,
                ms.session_name,
                ms.hour,
                ms.date,
                ms.psid,
                ms.staffId,
                pss.studentID,
                s.studentEmail as email,
                s.regNo,
                b.batchName,
                s.studentName,
                s.rollNo,
                msstf.feedback,
                ms.isFinalSubmitted as isSubmitted,
                s2.semID ,
                s2.semName,
                mssf.feedback as studentFeedback
                from
                    mentor_session ms
                inner join pseudosubjects_students pss on
                    ms.psid = pss.pseudosubjectID
                inner join pseudosubjects_sbs psbs on
                    ms.psid = psbs.pseudosubjectID
                inner join sbs_relation sbsr on
                    sbsr.sbsID = psbs.sbsID
                inner join studentaccount s on
                    s.studentId = pss.studentId
                inner join batches b on
                    b.batchID = sbsr.batchID
                    and s.batchID = b.batchID
                left join staffaccounts st on
                    ms.staffId = st.staffID
                left join mentor_session_staff_feedback msstf on
                    msstf.session_id = ms.id
                    and msstf.studentID = pss.studentID
                left join mentor_session_student_feedback mssf on s.studentID =mssf.studentID AND ms.id = mssf.session_id
                left JOIN semesters s2 on
                    sbsr.semID = s2.semID
                where
                    1 = 1
                    and s.studentID = $studentId";
                    $result = $this->executeQueryForList($sql, $this->mapper[StudentServiceMapper::GET_MENTOR_MENTEE_DETAILS_BY_STUDENT_ID_FOR_API]);
                    return $result;
        }
        catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * @author Ajay
     * @return Array
     * @throws ProfessionalException
     * @param request
     */
     public function getStudentMarkHtmlResponse($request)
     {
        $batchID = $request->batchID;
        $studentID = $request->studentID;
        $semID = $request->semID;
        $showClsAvg = CommonService::getInstance()->getSettings(SettingsConstants::INTERNAL_ASSESSMENT_SETTINGS,SettingsConstants::SHOW_STUDENT_MY_PERFORMANCE_CLASS_AVERAGE);
        $showPercentage = CommonService::getInstance()->getSettings(SettingsConstants::INTERNAL_MARK_SETTINGS,SettingSConstants::SHOW_STUDENT_MY_PERFORMANCE_PERCENTAGE);
        $batchID = $request->batchId;
        $studentID = $request->studentID;
        $response .= "<span id=''>";
        $semID = (int) sql_real_escape_string($_GET['semID']);
        if (!$semID || $semID == 'undefined') {
            $sql = "SELECT semID FROM batches WHERE batchID=" . $request->batchId;
            $result = sql_query($sql, $connect);
            $row = sql_fetch_row($result);
            $semID = $row[0];
        }
        else{
            $getBatchFromFailedStudents = CommonService::getInstance()->getSettings(SettingsConstants::STUDENT,SettingsConstants::GET_BATCH_FROM_FAILED_STUDENTS);
            if($getBatchFromFailedStudents){
                try {
                    $batchID = StudentService::getInstance()->getStudentBatchBySemId($studentID,$semID);
                    $batchID = $batchID?$batchID:$request->batchId;
                }
                catch (\Throwable $th) {
                    $batchID = $request->batchId;
                }
            }else{
                $batchID = $request->batchId;
            }
        }
            $ExamTypes = ExamService::getInstance()->getExamType(false,false);
            // $typeID = $ExamType->typeID;
            // $typeName = $ExamType->typeName;
            $getStudentSubjectRequest = new stdClass();
            $getStudentSubjectRequest->batchId = $batchID;
            $getStudentSubjectRequest->semId = $semID;
            $getStudentSubjectRequest->studentId = $studentID;
            $getStudentSubjectRequest->includeSubjectCategory = true;
            $studentSubjects = (array) ReportService::getInstance()->getBatchSubjectsDetails($getStudentSubjectRequest);
            $publishByStaff = CommonService::getInstance()->getSettings(SettingsConstents::INTERNAL_MARK_SETTINGS,SettingsConstants::PUBLISH_MARKS_BY_STAFF) === "1";
            $colspan = $showPercentage?5:4;
                if (count($ExamTypes)) {
                    foreach ($ExamTypes as $type) {
                        $typeID = $type->typeID;
                        $sql = "select t1.examID, t2.subjectName,t1.examTotalMarks, t2.subjectDesc from exam t1 inner join subjects t2 ON t1.subjectID=t2.subjectID left join subbatch_student ss ON ss.subbatchID=t1.subbatchID and ss.studentID=$studentID where t1.batchID=$batchID and t1.semID=$semID and t1.examTypeID=$typeID AND (ss.subbatchID is not null OR t1.subbatchID=0)";
                        $result = sql_query($sql, $connect);
                        if (sql_num_rows($result)) {
                            $flag = 1;
                            $response .=  "
                            <table class='table table-striped flexible-table student-data-table' cellpadding='0' cellspacing='0' border='0' align='left'>
                                <thead class='cf f-thead' id=''>
                                    <tr class='table-name f-tr'>
                                        <th id='head' colspan='$colspan'>
                                            <b>".$type->typeName."</b>
                                        </th>
                                    </tr>
                                    <tr class='main-head hidden-on-mobile f-tr'>
                                        <th >Subject Name</th>
                                        <th class='numeric' >Marks Obtained</th>";
                                        if($showPercentage){
                                            $response .=  "<th class='numeric' >Percentage</th>";
                                        }
                                    if($showClsAvg){
                                        $response .=  "<th class='numeric' >Class Average</th>";
                                    }
                            $response .=  "      <th class='numeric' >Max Marks</th></tr>
                                </thead>
                            <tbody class='normal-title f-tbody'>";
                            $total_marks = 0;
                            $exams_total = 0;
                            $no__of_exams = 0;
                            $total_percent = 0;
                            $weighted_average = 0;
                            $weighted_totalmark = 0;
                            // while ($row = sql_fetch_array($result)) {
                            foreach ($studentSubjects as $key => $subject) {
                                $examDetails = ExamService::getInstance()->getExamDetailsByBatchAndSubjectIdAndExamType($subject->id, $batchID, $semID, null, null, null, $type->typeID)[0];
                                $examRequest = new stdClass();
                                $examRequest->batchId = $subject->batchID;
                                $examRequest->studentId = $studentID;
                                $examRequest->semId = $subject->subjectSemId;
                                $examRequest->examTypeId = $type->typeID;
                                $examRequest->subjectId = $subject->id;
                                $markDetails = ExamService::getInstance()->getAllExamMarksByRequest($examRequest)[0];
                                $sql = "select AVG(marksObtained) from student_marks where semID=$semID and batchID='$batchID' and examTypeID = $typeID and examID= ".$examDetails->examID." and marksObtained!=-1";
                                $avg_result = sql_query($sql, $connect);
                                $avg_row = sql_fetch_row($avg_result);
                                if (!empty($examDetails)) {
                                    $published = $publishByStaff ? ExamService::getInstance()->isSessionalExamMarkSubmitted($examDetails->examID) : true;
                                    if($published){
                                        switch ($markDetails->marksObtained) {
                                            case 'A':
                                            case 'MAL':
                                                $total_marks = $total_marks + 0;
                                                $total_percent = $total_percent + 0;
                                                break;
                                            default:
                                                $total_marks = ( $markDetails->markID ? $markDetails->marksObtained : 0 ) + $total_marks;
                                                $total_percent = round((float) $markDetails->percentage,2) + $total_percent;
                                                $weighted_average = $weighted_average + (round((float) $markDetails->percentage,2) * $examDetails->examTotalMarks);
                                                break;
                                        }
                                        $weighted_totalmark = $weighted_totalmark + $examDetails->examTotalMarks;
                                        $no__of_exams++;
                                        $exams_total = $exams_total + $markDetails->examTotalMarks;
                                        $response .=  "
                                        <tr class='f-tr'><td data-title='Subject Name' >" . $subject->code . " ". $subject->name ."&nbsp;</td>
                                            <td data-title='Marks Obtained' class='numeric' > ". ( $markDetails->markID? $markDetails->marksObtained : "--" ) ."&nbsp;</td>";
                                            if($showPercentage){
                                                $response .=  "<td data-title='Percentage' class='numeric' >" . round((float) $markDetails->percentage,2) . "%&nbsp;</td>";
                                            }
                                        if($showClsAvg){
                                            $response .=  "<td data-title='Class Average' class='numeric' >" . round($avg_row[0], 2) . "&nbsp;</td>";
                                        }
                                        $response .=  "<td data-title='Max Marks' class='numeric' >".$examDetails->examTotalMarks." &nbsp;</td></tr>";
                                        $total_flag = 1;
                                    }
                                }
                            }
                            if (!$total_flag) {
                                //Display no data available
                                $response .=  '</tbody>
                                        <tfoot class="text-align-center">
                                            <tr class="f-tr">
                                                <td align="center" class="no-table-data" colspan="5">
                                                    No Data Available
                                                </td>
                                            </tr>
                                        </tfoot>';
                            }
                            if ($exams_total != 0) {
                                $percentage = $weighted_average / $weighted_totalmark;
                                $weighted_average = ($total_percent / $no__of_exams);
                                $weighted_average = round($weighted_average, 2);
                            } else {
                                $percentage = 0;
                            }
                            if ($total_flag == 1) {
                                $response .=  "<tr class='text-danger f-tr'><td  class='hide-col' >Total</td>";
                                $response .=  "<td data-title='Total' colspan='4'>$total_marks&nbsp;&nbsp;</td></tr>";
                                if($showPercentage){
                                    $response .=  "<tr class='text-danger f-tr'><td class='hide-col'>Percentage</td>";
                                    $response .=  "<td data-title='Percentage' colspan='4'>" . round($percentage, 2) . "%&nbsp;</td></tr>";
                                    $response .=  "<tr class='text-danger f-tr'><td class='hide-col'>Weighted Percentage</td>";
                                    $response .=  "<td data-title='Weighted Percentage' colspan='4'>" . $weighted_average . "%&nbsp;</td></tr>";
                                }
                            }
                            $total_flag = 0;
                            $response .=  "</table><br />";
                        }
                    }
                    if (!$flag) {
                        $response .=  '<div class="no-data m-t-25 w-90-percentage-xs">There are no records available</div>';
                    }
                } else {
                    $response .=  '<div class="no-data m-t-25 w-90-percentage-xs">There are no records available</div>';
                }
                $response .= "<br>";
                //echo $response;
                return $response;
                // if($showNormlMrk){
                //     include "normalised_marks.php";
                // }
     }
     /**
      * @author Ajay
      * @param request
      * @throws ProfessionalException
      * @return Array
      */
     public function getSemesterDetailsForAdvanceProfile($request){
        try{
            $sql = "SELECT semID FROM batches WHERE batchID=" .$request->batchId;
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $batch;
    }
    public function updatePublishStatus($batchId,$semId,$examTypeId,$status="true")    {
        $sql = "UPDATE exam SET publish = '$status' WHERE batchID ='$batchId' and semID ='$semId' and examTypeID ='$examTypeId'";
        $this->executeQuery($sql);
    }
    public function getPublishStatus($batchId,$semId,$examTypeId)
    {
        $sql = "SELECT publish FROM exam WHERE batchID ='$batchId' and semID ='$semId' and examTypeID ='$examTypeId'";
        $helper = new stdClass();
        $helper->publish = "false";
        $result = $this->executeQueryForObject($sql)??$helper;
        return $result;
    }
    public function togglePublishStatus($batchId,$semId,$examTypeId)
    {
        $status = $this->getPublishStatus($batchId,$semId,$examTypeId);
    }
    public function addStudentToV4($studentId = null,$oldBatchId = null){
        $studentId = $this->realEscapeObject($studentId);
        $oldBatchId = $this->realEscapeObject($oldBatchId);
        $userId =  $_SESSION['userId']?$_SESSION['userId']:$GLOBALS['userId'];
        if(!($studentId || $oldBatchId)){
            throw new ProfessionalException(ProfessionalException::INVALID_DATA, "Please enter a valid details");
        }
        try {
            $sql = "SELECT  b.groups_id from  studentaccount s
                    INNER JOIN batches b ON b.batchID = s.batchId
                    where studentID = '$studentId'";
            $alreadyExistingBatch = $this->executeQueryForObject($sql);
            $this->executeQuery("INSERT IGNORE INTO student_program_account (student_id, current_program_id, properties, created_by, created_date, updated_by, updated_date)
            SELECT st.studentID, p.id, json_object('status', 'ACTIVE', 'termId', b.semID, 'tcIssued', 0, 'rollNumber', st.rollNo, 'admitSemester', b.semID, 'yearOfPassing', st.yearOfPassing, 'academicStatus', 'ACTIVE', 'currentBatchId', g.id, 'registerNumber', st.regNo, 'admissionNumber', st.admissionNo), 1, utc_timestamp(), 1, utc_timestamp()
            FROM studentaccount st
            INNER JOIN `batches` b ON b.batchID = st.batchID
            INNER JOIN `groups` g ON b.groups_id = g.id
            INNER JOIN program p ON p.id = g.properties->>'$.programId'
            WHERE ".($studentId ? " st.studentID = '$studentId" :"").($oldBatchId ? " st.batchID = '$oldBatchId" :"")." AND st.studentID not in (select student_id from student_program_account) ;");
            $this->executeQuery("INSERT IGNORE INTO student_program_batch_log (program_student_id, program_id, batch_group_id, term_id, properties, created_by, created_date, updated_by, updated_date)
            SELECT sp.id, sp.current_program_id, sp.current_batch_id, sp.current_term_id, json_object('reason',null, 'isActive',true, 'academicStatus','ACTIVE'),'$userId', NOW(), '$userId', NOW()
            FROM student_program_account sp
            INNER JOIN studentaccount st ON st.studentID = sp.student_id
            WHERE ".($studentId ? " st.studentID = '$studentId" :"").($oldBatchId ? " st.batchID = '$oldBatchId" :"").";");
            $this->executeQuery("INSERT IGNORE INTO group_members (id, groups_id, members, properties, created_by, created_date, updated_by, updated_date)
            SELECT LEFT(REPLACE(UUID(),'-',''), 17), sp.current_batch_id,JSON_OBJECT('studentId',sp.id),json_object('academicStatus','ACTIVE'), 1, utc_timestamp(), 1, utc_timestamp()
            FROM student_program_account sp
            INNER JOIN studentaccount st ON st.studentID = sp.student_id
            WHERE ".($studentId ? " st.studentID = '$studentId" :"").($oldBatchId ? " st.batchID = '$oldBatchId" :"").";");
            //COMMENTED DUE TO THE ERROR IN CONDITION
            //BEACUSE OT CHECKING ANY THING AHANIST THE SUBJECT GROUP
            // $this->executeQuery("INSERT IGNORE INTO `group_members`
            //     (`id`, `groups_id`, `members`, `properties`, `created_by`, `updated_by`)
            // SELECT
            //     LEFT(REPLACE(UUID(),'-',''), 17),
            //     gr.child_groups_id,json_object('studentId',spa.id),
            //     json_object('isFailed',false,'academicStatus','ACTIVE'),1,1
            // FROM `cluster` c
            //     INNER JOIN `cluster_groups_relations` cg ON cg.cluster_id = c.id
            //     INNER JOIN `groups_relations` gr ON gr.child_groups_id = cg.groups_id
            //     INNER JOIN `groups` sg ON sg.id = gr.child_groups_id
            //     INNER JOIN `student_program_account` spa ON spa.current_batch_id = gr.parent_groups_id
            //     INNER JOIN `cm_academic_paper_subjects` aps ON aps.id = sg.paperSubjectId
            //     INNER JOIN `cm_academic_paper` ap ON ap.id = aps.cm_academic_paper_id
            //     INNER JOIN `cm_syllabus_academic_term_settings` terms ON terms.id = ap.cm_syllabus_academic_term_settings_id
            //         and spa.current_term_id = terms.academic_term_id
            //     INNER JOIN studentaccount st ON st.studentID = spa.student_id
            // WHERE c.type = 'SUBJECT' AND ".($studentId ? " st.studentID = '$studentId' " :"").($oldBatchId ? " st.batchID = '$oldBatchId' " :"").";");
            $roleId = RoleService::getInstance()->getRoleByCode(RoleService::ROLE_STUDENTS)->id;
            if((int)$roleId){
                $userRole = new AddUserToRoleRequest();
                $userRole->roleId = $roleId;
                $userRole->userId = $studentId;
                $userRole->userType = RoleService::USER_TYPE_STUDENT;
                $userRole->createdBy = $_SESSION['userId']?$_SESSION['userId']:$GLOBALS['userId'];
                $userRole->updatedBy = $_SESSION['userId']?$_SESSION['userId']:$GLOBALS['userId'];
                UserRoleService::getInstance()->assignUserRole($userRole);
            }
            $roleId = RoleService::getInstance()->getRoleByCode(RoleService::ROLE_PARENT)->id;
            if((int)$roleId){
                $userRole = new AddUserToRoleRequest();
                $userRole->roleId = $roleId;
                $userRole->userId = $studentId;
                $userRole->userType = RoleService::USER_TYPE_PARENT;
                $userRole->createdBy = $_SESSION['userId']?$_SESSION['userId']:$GLOBALS['userId'];
                $userRole->updatedBy = $_SESSION['userId']?$_SESSION['userId']:$GLOBALS['userId'];
                UserRoleService::getInstance()->assignUserRole($userRole);
            }
            if($alreadyExistingBatch !== $oldBatchId){
                $curl = curl_init();
                $domain = "";
                if ($_SERVER['HTTP_HOST'] != 'localhost') {
                    $domain = rtrim($_SERVER['HTTP_HOST']);
                }
                if (getenv("DEBUG") !== "true") {
                    $handlerUrl = "https://" . $domain . "/academics/api/v1/student/move-students";
                } else {
                    $handlerUrl = "http://localhost/academics/api/v1/student/move-students";
                }
                $header = $GLOBALS['_SERVER']['REDIRECT_HTTP_AUTHORIZATION'];
                $headers = array(
                    'Content-Type:application/json',
                    'Authorization:' . $header
                );
                // Query parameters
                $moveStudentRequestData = array(
                    'studentIdList' => array(
                        array('studentId' => $studentId)
                    ),
                    'batchId' => $oldBatchId
                );
                $jsonData = json_encode(array('moveStudentRequest' => $moveStudentRequestData));
                curl_setopt($curl, CURLOPT_URL, $handlerUrl);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $jsonData);
                curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json',
                    'Authorization: ' . $header
                ));
                $curl_response = curl_exec($curl);
                // Check for errors
                 if ($curl_response === false) {
                    return false;
                }
                else {
                    // Process the response, e.g., decode JSON and use it
                    $responseArray = json_decode($curl_response, true);
                    if ($responseArray) {
                        // Handle the JSON response data
                    } else {
                        echo 'Failed to decode JSON response';
                    }
                }
            }
            $this->addStudentAutomatcallyToSubjectCommunity($studentId);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function updateStudentToV4($studentId = null,$oldBatchId = null){
        $studentId = $this->realEscapeString($studentId);
        $oldBatchId = $this->realEscapeString($oldBatchId);
        if(!($studentId || $oldBatchId)){
            throw new ProfessionalException(ProfessionalException::INVALID_DATA, "Please enter a valid details");
        }
        try {
            $this->executeQuery("UPDATE `student_program_account` sp
            INNER JOIN `studentaccount` st ON st.studentID = sp.student_id
            INNER JOIN `groups` g ON g.id = sp.current_batch_id
            INNER JOIN `program` p ON p.id = g.properties->>'$.programId'
            SET sp.properties = JSON_SET(sp.properties,'$.yearOfPassing',st.yearOfPassing,'$.rollNumber',st.rollNo,'$.registerNumber',st.regNo,'$.admissionNumber', st.admissionNo),sp.updated_by = 1, sp.updated_date = utc_timestamp()
            WHERE ".($studentId ? " st.studentID = '$studentId" :"").($oldBatchId ? " st.batchID = '$oldBatchId" :"").";");
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Get student Previous Batch By SemId
     * @throws ProfessionalException
     */
    public function getStudentPreviousBatchDetailsBySemId($studentId, $semId)
    {
        $semId = $this->realEscapeString($semId);
        $studentId = $this->realEscapeString($studentId);
        $batch = null;
        try {
            $sql = " SELECT fs.previousBatch,fs.isFailNow,fs.failedInSemester,b.semID AS semId  FROM failed_students fs
                    INNER JOIN batches b ON b.batchID = fs.previousBatch
                    INNER JOIN studentaccount sa ON sa.studentID = fs.studentID AND sa.batchID !=fs.previousBatch
                    WHERE fs.studentID = $studentId AND find_in_set('$semId',hisSemestersInThisbatch)";
            $batch = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $batch;
    }
    /**
     * Get student current details
     * @throws ProfessionalException
     */
    public function getV4StudentDetails($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        if(empty($studentId)){
            throw new ProfessionalException(ProfessionalException::INVALID_DATA, "Please enter a valid details");
        }
        try {
            $sql = " SELECT s.studentName as `name`,p.name AS programName, g.name AS batchName, d.deptName AS departmentName from studentaccount s
            INNER JOIN student_program_account spa ON spa.student_id = s.studentID
            INNER JOIN program p ON p.id = spa.current_program_id
            INNER JOIN `groups` g ON g.id = spa.current_batch_id
            INNER JOIN department d ON d.deptID = g.properties->>'$.departmentId'
            WHERE s.studentID = $studentId;";
            return $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function createV4MoveStudentFailedRequest(FailedStudentRequest $request,$toState = StatusConstants::FAILED){
        $request = $this->realEscapeObject($request);
        $where = [];
        $request->studentId ? $where[] = " s.studentID = $request->studentId " : null;
        $request->batchId ? $where[] = " b.batchID = $request->batchId " : null;
        if(empty($request->studentId) && empty($request->batchId)){
            throw new ProfessionalException(ProfessionalException::INVALID_PARAMETER, "Invalid parameters");
        }
        if(empty($request->reason)){
            throw new ProfessionalException(ProfessionalException::INVALID_REASON, "Invalid reason, should need reason for every request");
        }
        switch ($request->reason) {
            case 'DISCONTINUED':
            case 'TC_ISSUED':
            case 'TC_ISSUED_WITH_FAILED':
                $toState = StatusConstants::DISCONTINUE;
                break;
            case 'FAILED':
                $toState = StatusConstants::FAILED;
                break;
        }
        try {
            $sql = "INSERT IGNORE INTO v3_v4_move_student_to_failed_request (student_program_id,group_id,term_id,to_state,status,reason,remarks,created_date,created_by)
            SELECT spa.id ,b.groups_id,s2.termId,'$toState','NOT_DONE','$request->reason','$request->remarks',UTC_TIMESTAMP(),created_by
            FROM studentaccount s
            INNER JOIN student_program_account spa ON spa.student_id = s.studentID
            INNER JOIN batches b ON b.groups_id = spa.current_batch_id
            INNER JOIN semesters s2 ON s2.termId = spa.current_term_id
            " . ($where ? " WHERE " . implode(' AND ', $where) : "") . ";";
            return $this->executeQuery($sql);
        } catch (\Throwable $th) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getV4MoveStudentFailedRequest(FailedStudentRequest $request){
        $request = $this->realEscapeObject($request);
        $where = [];
        $request->studentId ? $where[] = " spa.student_id = $request->studentId " : null;
        $request->studentId ? $where[] = " spa.id = $request->studentId " : null;
        $request->batchId ? $where[] = " b.batchID = $request->batchId " : null;
        $request->state ? $where[] = " v3.status = '$request->state" : null;$request->status ? $where[] = " v3.status = '$request->status" : null;
        try {
            $sql = "SELECT v3.* FROM v3_v4_move_student_to_failed_request v3
            INNER JOIN student_program_account spa ON spa.id = v3.student_program_id
            " . ($where ? " WHERE " . implode(' AND ', $where) : "") . ";";
            return $this->executeQueryForList($sql);
        } catch (\Throwable $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function deleteV4Request($ids = []){
        $ids = $this->realEscapeObject($ids);
        if(!empty($ids)){
            try {
                $sql = "DELETE FROM v3_v4_move_student_to_failed_request v3
                WHERE v3.id IN (".implode(',',$ids).") AND v3.status IN ('NOT_DONE','FAILURE');";
                return $this->executeQuery($sql);
            } catch (\Throwable $th) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        }
    }
    public function updateV4RequestAsFailer($ids = []){
        $ids = $this->realEscapeObject($ids);
        if(!empty($ids)){
            try {
                $sql = "UPDATE v3_v4_move_student_to_failed_request v3
                SET v3.status = ".StatusConstants::FAILURE."
                WHERE v3.id in (".implode(',',$ids).");";
                return $this->executeQuery($sql);
            } catch (\Throwable $th) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        }
    }
    /**
     * Get student subjectwise block status attendance
     * @throws ProfessionalException
     */
    public function getStudentSubjectAttendanceBlockStatus($request)
    {
        $request = $this->realEscapeObject($request);
        $status = false;
        if($request->isSupply){
            $condition = " AND  erbs.supplyreg_id IN ($request->examRegId)";
        }else{
            $condition = " AND  erbs.examreg_id IN ($request->examRegId)";
        }
        try {
            $sql = "SELECT erbs.reason_id from exam_reg_blocked_student erbs
                    INNER JOIN exam_reg_block_reason erbr ON erbr.id = erbs.reason_id
                    WHERE erbs.student_id IN ($request->studentId) AND erbs.subject_id IN ($request->subjectId) AND erbr.reason = 'Attendance Shortage' $condition";
            $blockReasons = $this->executeQueryForList($sql);
            if(empty($blockReasons)){
                $status = false;
            }else{
                $status = true;
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $status;
    }
    /**
     *
     * @param int $request
     * @return $studentDetails
     * @throws ProfessionalException
     */
    public function getAllStudentDetailsByRequest($request)
    {
        $studentDetails = NULL;
        $request = $this->realEscapeObject($request);
        $sql = "SELECT sa.studentID as id,
            sa.studentName as name,
            sa.studentAccount,
            sa.studentPassword,
            sa.regNo,
            sa.rollNo,
            sa.admissionNo,
            sa.applicationNo,
            sa.studentEmail,
            sa.studentPhone,
            sa.parentPhone,
            sa.tcIssued,
            dept.deptName,
            bth.batchName,
            dept.deptID,
            bth.batchID,
            bth.patternID as courseTypeId,
            bth.courseTypeID,
            bct.type_name as typeName,
            bth.batchStartYear as startYear,
            bth.batchEndYear as endYear,
            bth.final_semester as finalSem,
            dept.departmentDesc,
            sa.tcIssued,
            sa.studentAddress,
            sa.studentEmail,
            sa.studentPhone,
            sem.semID,
            sem.semName,
            sem.year,
            sem.orderNo,
            sem.type,
            sa.parentAddress1,
            sa.parentAddress2,
            sa.parentCity,
            sa.parentZipCode,
            sa.parentCountry,
            sa.parentState,
            sa.studentJoindate,
            sa.exitType,
            sa.studentSignImage,
            sa.quotaID as quotaId,
            sa.student_lock,
            sa.nationality_id as nationalityId,
            sa.previousSchool as previousSchool,
            sa.highestExamPassed as highestExamPassed,
            sa.prev_institute_dateofpassing as previousPassDate,
            sa.prev_institute_regiNo as prevRegNo,
            sa.admissionTCNo as admissionTCNo,
            sa.busroute as busroute,
            sa.state_id as stateId,
            sa.district_id as districtId,
            sa.taluk_id as talukId,
            sa.annualIncome as annualIncome,
            sa.aadhaar_no as aadharNo,
            sa.poverty_line as povertyLineId,
            sa.campus_type_id as campusTypeId,
            sa.secondlangaugeID as secondLanguageId,
            sa.joiningSemId as joiningSemId,
            sa.reservID as reservID,
            sa.reservationID as studentReservationID,
            sa.phdTopicName as phpTopicName,
            sa.phdCurrentStatus as currentStatus,
            sa.guideId as guideId,
            sl.secondLangaugeName,
            pdc.patterncourseName,
            pdc.patterncourseCode,
            pdc.patterncourseID,
            pdc.patternAbbreviation AS patternAbbreviation,
            sa.religion AS religion,
            sa.community,
            sa.category,
            sa.studentBirthday,
            sa.studentFather,
            sa.sslc,
            sa.plustwo,
            sa.parentOccupation,
            sa.studentGender,
            sa.myImage,
            sa.studentSignImage,
            sc.subsiderycoursename AS subsideryCourseName,
            se.entranceRank,
            sa.plustwo,
            sa.studentFather,
            sa.studentMother,
            se.parentOccupation as fatherOccupation,
            se.motherOccupation,
            aq.quotaName,
            se.commuhouse,
            se.commupin,
            se.currentAddress1,
            se.currentAddress2,
            se.permahouse,
            se.permapin,
            se.permanentAddress1,
            se.permanentAddress2,
            se.currentCity,
            se.permanentCity,
            se.permanentZipCode,
            se.currentZipCode,
            bct.type_code AS coursePatternName,
            bct.is_pg AS isPG,sr.reservName as reservationName,
            sa.cap_id,
            sa.bloodGroup,
            re.religionName,
            CONCAT_WS(' ',se.commuhouse,se.currentAddress1,se.currentAddress2,se.currentCity,se.currentCountry,se.currentState,se.currentZipCode) as additional_info_currentAddress,
            CONCAT_WS(' ',se.permaHouse,se.permanentAddress1,se.permanentAddress2,se.permanentCity,se.permanentCountry,se.permanentState,se.permanentZipCode) as additional_info_permanentAddress,
            state.state_name as stateName,
            cp.patternName,cp.patternDesc,
            sa.admission_entry_type,
            caste.casteID,
            caste.casteName,
            rs.reservationID,
            rs.reservationName AS studentReservation,
            nat.nationalityName,
            s.state_name AS state,
            pdc.extraSettings
            FROM studentaccount sa
            INNER JOIN department dept ON sa.deptID=dept.deptID
            INNER JOIN batches bth ON bth.batchID IN ($request->batchID)
            LEFT JOIN batch_course_type bct ON bth.patternID = bct.id
            LEFT JOIN semesters sem ON sem.semID = bth.semID
            LEFT JOIN secondLangauge sl ON sl.secondlangaugeID = sa.secondlangaugeID
            LEFT JOIN pattern_deptcourses pdc ON bth.patterncourseID = pdc.patterncourseID
            LEFT JOIN subsiderycourse sc ON pdc.patterncourseID = sc.pattern_deptcourses_id
            LEFT JOIN studentaccount_extras se ON se.studentID = sa.studentID
            LEFT JOIN admission_quotas aq ON aq.quotaID = sa.quotaID
            LEFT JOIN student_reservation sr ON sr.reservID = sa.reservID
            LEFT JOIN religion re ON re.religionID=sa.religion
            LEFT JOIN state ON state.id = sa.state_id
            LEFT JOIN course_pattern cp on cp.patternID = bth.patternID
            LEFT JOIN student_caste caste ON caste.casteID=sa.casteID
            LEFT JOIN reservation_students rs ON rs.reservationID=sa.reservationID
            LEFT JOIN nationality nat ON nat.id = sa.nationality_id
            LEFT JOIN state s ON sa.state_id=s.id
            WHERE sa.studentID IN($request->studentID)";
        try {
            $studentDetails = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     *
     * @param int $studentId
     * @return $certificates
     * @throws ProfessionalException
     */
    public function getStudentCertificates($studentId)
    {
        $studentId = $this->realEscapeObject($studentId);
        $sql = "SELECT
                    ascc.certificateName,
                    s.resourseId,
                    lr.storage_object as `object`,
                    lr.path
                from
                    studentaccount_certificates s
                inner join admission_student_certificates ascc on
                    s.certificateID = ascc.certificateID
                inner join lin_resource lr on s.resourseId=lr.id
                WHERE
                    studentID = '$studentId'";
        try {
            $certificates = $this->executeQueryForList($sql);
            foreach ($certificates as $certificate)
            {
                $fileObj = json_decode(preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $certificate->object));
                if($fileObj->bucket && $fileObj->key)
                {
                    $certificate->docpath=S3Utils::getPreSignedURL($fileObj->bucket, $fileObj->key);
                }
                else{
                    $certificate->docpath = false;
                }
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $certificates;
    }
     /**
     *
     * @param int $batchID
     * @return $students
     * @throws ProfessionalException
     */
    public function getStudentsByBatchForCustomReport($batchID,$selectedFields,$customfieldSelected)
    {
        //default inner join batches
        $selected = $selectedFields;
        $selects = [];
        $joins = [];
        $fieldsArray = AdvancedStudentReportService::getInstance()->formFieldsForCustomReport();
        $formatStudentBirthday = false;
        $buffer = [];
        foreach($fieldsArray as $fields)
        {
            $field = json_decode($fields->columnHeaderMapping);
            foreach ($field as $target)
            {
                if ($target->field === 'studentBirthday' && in_array($target->id,$selected)) {
                    $formatStudentBirthday = true;
                }
                if(in_array($target->id,$selected))
                {
                    if($target->combined && count($target->combined) > 0)
                    {
                        $combinedField = [];
                        foreach ($target->combined as $fieldToMerge) {
                            if($target->innerJoin || $target->leftJoin)
                            {
                                $pre = "";
                                if($target->innerJoin)
                                {
                                    $temp = explode(" ",$target->innerJoin);
                                    $pre = $temp[1];
                                    $sql_join_string = " INNER JOIN ".$target->innerJoin." on ".$target->joinOn." ";
                                    if($target->alreadyJoined)
                                    {
                                        $buffer[] = $sql_join_string;
                                    }
                                    else
                                    {
                                        $joins[] = $sql_join_string;
                                    }
                                }
                                if($target->leftJoin)
                                {
                                    $temp = explode(" ",$target->leftJoin);
                                    $pre = $temp[1];
                                    $sql_join_string = " LEFT JOIN ".$target->leftJoin." on ".$target->joinOn." ";
                                    if($target->alreadyJoined)
                                    {
                                        $buffer[] = $sql_join_string;
                                    }
                                    else
                                    {
                                        $joins[] = $sql_join_string;
                                    }
                                }
                                $combinedField[] = "$pre.".$fieldToMerge;
                            }
                            else
                            {
                                $combinedField[] = "sa.".$fieldToMerge;
                            }
                        }
                        $combinedString = implode(",",$combinedField);
                        $selects[] = "CONCAT_WS(' ',$combinedString) as ".$target->field;
                    }
                    else
                    {
                        if($target->innerJoin || $target->leftJoin)
                        {
                            $sql_select_string = $target->field?$target->field:"";
                            if($target->field)
                            {
                                $selects[] = $sql_select_string;
                            }
                        }
                        else{
                            if(str_contains($target->field,"."))
                            {
                                $sql_select_string = $target->field?$target->field:"";
                            }
                            else
                            {
                                $sql_select_string = $target->field?"sa.".$target->field:"";
                            }
                            if($target->field)
                            {
                                $selects[] = $sql_select_string;
                            }
                        }
                        if($target->innerJoin != "")
                        {
                            $sql_join_string = " INNER JOIN ".$target->innerJoin." on ".$target->joinOn." ";
                            if($target->alreadyJoined)
                            {
                                $buffer[] = $sql_join_string;
                            }
                            else
                            {
                                $joins[] = $sql_join_string;
                            }
                        }
                        if($target->leftJoin != "")
                        {
                            $sql_join_string = " LEFT JOIN ".$target->leftJoin." on ".$target->joinOn." ";
                            if($target->alreadyJoined)
                            {
                                $buffer[] = $sql_join_string;
                            }
                            else
                            {
                                $joins[] = $sql_join_string;
                            }                        }
                    }
                }
            }
        }
        $selectQuery = count($selects)>0?",".implode(",",$selects):"";
        foreach($buffer as $missed)
        {
            if(!in_array($missed,$joins))
            {
                $joins[] = $missed;
                // inserting missing joins
            }
        }
        $joinQuery = count($joins)>0?implode(" ",$joins):"";
        $sql = "";
        $studentArray = [];
        $batchID = $this->realEscapeString($batchID);
        if(count($customfieldSelected) > 0)
        {
            $cFieldsSelected = [];
            foreach($customfieldSelected as $field)
            {
                $cFieldsSelected[] = "customFields.fields->>'$.$field'";
            }
            $selectQuery .= ",".implode(",",$cFieldsSelected);
            $joinQuery .= " LEFT JOIN ams_custom_fields_student_value customFields ON sa.studentID = customFields.student_id";
        }
        try {
            $sql = "SELECT
                sa.rollNo,
                sa.studentName,
                b.batchName
                ".$selectQuery."
                    from  studentaccount sa
                    inner join batches b
                    on b.batchID = sa.batchID
                        $joinQuery
                where sa.batchID=\"$batchID\" order by rollNo";
                $studentArray = $this->executeQueryForList($sql);
                if ($formatStudentBirthday) {
                    foreach ($studentArray as $student) {
                        $currentDate = $student->studentBirthday;
                        $timestamp = strtotime($currentDate);
                        if ($timestamp !== false) {
                            $formattedDate = date('d-m-Y', $timestamp);
                            $student->studentBirthday = $formattedDate;
                        }
                    }
                }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentArray;
    }
    /**
     * @param $applicationId
     * @return string
     * @throws ProfessionalException
     */
    public function getStudentDetailsForSsp($request)
    {
        $sql = "SELECT
                    s.studentID,
                    s.studentName,
                    s.studentBirthday,
                    s.regNo,
                    s.rollNo,
                    s.studentFather,
                    s.studentMother,
                    s.studentGender,
                    sc.Course_Name,
                    s.studentJoindate,
                    s.`lateral`,
                    s.prev_institute_dateofpassing,
                    s.previousSchool,
                    ct.course_Type,
                    sd.Discipline_Code,
                    sd.Discipline_name,
                     sc.Course_Name,
                    sc.Course_Code,
                    s.studentPhone,
                    se.guardianName,
                     log.last_log,
                     log.log,
                    s.ssp_id,
                     s.student_aadhar_name,
                     CASE
                        WHEN b.semID > 1 THEN 'Y'
                        WHEN b.semID = 1 AND aasd.paid = 1 AND aasd.admitted = 1 THEN 'Y'
                        ELSE 'N'
                    END AS admission_completed
                FROM studentaccount s
                INNER JOIN adm_admission_admitted_student_details aasd on s.studentID = aasd.studentAccountId
                INNER JOIN batches b ON b.batchID = s.batchID
                INNER JOIN semesters sem ON b.semID = sem.semID
                INNER JOIN course_type ct ON ct.courseTypeID = b.courseTypeID
                INNER JOIN course_pattern cp ON cp.patternID = b.patternID
                INNER JOIN pattern_deptcourses pd ON pd.patterncourseID = b.patterncourseID AND pd.patternID = cp.patternID
                INNER JOIN ssp_course sc ON sc.Course_Code = cp.ssp_course_id
                INNER JOIN ssp_discipline sd ON sd.id = pd.ssp_discipline_id
                LEFT JOIN studentaccount_extras se ON se.studentID = s.studentID
                LEFT JOIN ssp_student_log log ON log.student_id = s.studentID and log.academic_year_code = '$request->academicYearCode'
                WHERE b.batchID = $request->batchId AND s.regNo != '' ";
        try {
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getStudentDetailsForSspAndSingleStudent($request)
    {
        $sql = "SELECT
                    s.studentID,
                    s.studentName,
                    s.studentBirthday,
                    s.regNo,
                    s.rollNo,
                    s.studentFather,
                    s.studentMother,
                    s.studentGender,
                    sc.Course_Name,
                    s.studentJoindate,
                    s.`lateral`,
                    s.prev_institute_dateofpassing,
                    s.previousSchool,
                    ct.course_Type,
                    sd.Discipline_Code,
                    sd.Discipline_name,
                     sc.Course_Name,
                    sc.Course_Code,
                    s.studentPhone,
                    se.guardianName,
                     log.last_log,
                     log.log,
                    s.ssp_id,
                     s.student_aadhar_name,
                     CASE
                        WHEN b.semID > 1 THEN 'Y'
                        WHEN b.semID = 1 AND aasd.paid = 1 AND aasd.admitted = 1 THEN 'Y'
                        ELSE 'N'
                    END AS admission_completed
                FROM studentaccount s
                INNER JOIN adm_admission_admitted_student_details aasd on s.studentID = aasd.studentAccountId
                INNER JOIN batches b ON b.batchID = s.batchID
                INNER JOIN semesters sem ON b.semID = sem.semID
                INNER JOIN course_type ct ON ct.courseTypeID = b.courseTypeID
                INNER JOIN course_pattern cp ON cp.patternID = b.patternID
                INNER JOIN pattern_deptcourses pd ON pd.patterncourseID = b.patterncourseID AND pd.patternID = cp.patternID
                INNER JOIN ssp_course sc ON sc.Course_Code = cp.ssp_course_id
                INNER JOIN ssp_discipline sd ON sd.id = pd.ssp_discipline_id
                LEFT JOIN studentaccount_extras se ON se.studentID = s.studentID
                LEFT JOIN ssp_student_log log ON log.student_id = s.studentID and log.academic_year_code = '$request->academicYearCode'
                WHERE s.studentID = $request->studentID;";
        try {
            return $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param $applicationId
     * @return string
     * @throws ProfessionalException
     */
    public function getStudentPreviousDetailsForSsp($request)
    {
        $this->realEscapeObject($request);
        if(!empty($request->semId)){
            $semesters = SemesterService::getInstance()->getSemDetailsBySemId($request->semId);
            if(!empty($semesters)){
                $sql = "SELECT
                    s.studentID,s.studentName,s.studentBirthday,s.regNo,s.rollNo,s.studentFather,s.studentMother,s.studentGender,sc.Course_Name,s.studentJoindate,s.`lateral`,s.prev_institute_dateofpassing,s.previousSchool,ct.course_Type,sd.Discipline_Code,sd.Discipline_name, sc.Course_Name,sc.Course_Code,s.studentPhone,se.guardianName, md.mark_details->>'$.totalMaxMark' AS totalMaxMark,md.mark_details->>'$.lastExamYear' AS lastExamYear, md.total_marks AS obtained_mark, md.status,md.percentage,vsem.`year` as exam_year
                FROM studentaccount s
                INNER JOIN ec_semster_consolidated_mark_details md ON md.student_id = s.studentID
                INNER JOIN batches b ON b.batchID = md.batch_id
                INNER JOIN course_type ct ON ct.courseTypeID = b.courseTypeID
                INNER JOIN course_pattern cp ON cp.patternID = b.patternID
                INNER JOIN pattern_deptcourses pd ON pd.patterncourseID = b.patterncourseID AND pd.patternID = cp.patternID
                INNER JOIN ssp_course sc ON sc.Course_Code = cp.ssp_course_id
                INNER JOIN ssp_discipline sd ON sd.id = pd.ssp_discipline_id
                INNER JOIN semesters vsem ON vsem.semID = md.sem_id
                LEFT JOIN studentaccount_extras se ON se.studentID = s.studentID
                WHERE s.batchID = $request->batchId AND (s.studentID, md.sem_id) IN (
                    SELECT vav.student_id, MAX(vav.sem_id)
                    FROM ec_semster_consolidated_mark_details vav
                    INNER JOIN semesters sem ON sem.semID = vav.sem_id
                    WHERE sem.orderNo <= $semesters->orderNo AND sem.type = '$semesters->type'
                    GROUP BY vav.student_id
                );";
                try {
                    return $this->executeQueryForList($sql);
                } catch (\Exception $e) {
                    throw new ProfessionalException($e->getCode(), $e->getMessage());
                }
            }
        }
    }
     /**
     * @param $applicationId
     * @return string
     * @throws ProfessionalException
     */
    public function getStudentPreviousDetailsForSspForSingleStudent($request)
    {
        $this->realEscapeObject($request);
        if(!empty($request->semId)){
            $semesters = SemesterService::getInstance()->getSemDetailsBySemId($request->semId);
            if(!empty($semesters)){
                $sql = "SELECT
                    s.studentID,s.studentName,s.studentBirthday,s.regNo,s.rollNo,s.studentFather,s.studentMother,s.studentGender,sc.Course_Name,s.studentJoindate,s.`lateral`,s.prev_institute_dateofpassing,s.previousSchool,ct.course_Type,sd.Discipline_Code,sd.Discipline_name, sc.Course_Name,sc.Course_Code,s.studentPhone,se.guardianName, md.mark_details->>'$.totalMaxMark' AS totalMaxMark,md.mark_details->>'$.lastExamYear' AS lastExamYear, md.total_marks AS obtained_mark, md.status,md.percentage,vsem.`year` as exam_year
                FROM studentaccount s
                INNER JOIN ec_semster_consolidated_mark_details md ON md.student_id = s.studentID
                INNER JOIN batches b ON b.batchID = md.batch_id
                INNER JOIN course_type ct ON ct.courseTypeID = b.courseTypeID
                INNER JOIN course_pattern cp ON cp.patternID = b.patternID
                INNER JOIN pattern_deptcourses pd ON pd.patterncourseID = b.patterncourseID AND pd.patternID = cp.patternID
                INNER JOIN ssp_course sc ON sc.Course_Code = cp.ssp_course_id
                INNER JOIN ssp_discipline sd ON sd.id = pd.ssp_discipline_id
                INNER JOIN semesters vsem ON vsem.semID = md.sem_id
                LEFT JOIN studentaccount_extras se ON se.studentID = s.studentID
                WHERE s.batchID = $request->batchId AND (s.studentID, md.sem_id) IN (
                    SELECT vav.student_id, MAX(vav.sem_id)
                    FROM ec_semster_consolidated_mark_details vav
                    INNER JOIN semesters sem ON sem.semID = vav.sem_id
                    WHERE sem.orderNo <= $semesters->orderNo AND sem.type = '$semesters->type' AND s.studentID = $request->studentID
                    GROUP BY vav.student_id
                );";
                try {
                    return $this->executeQueryForList($sql);
                } catch (\Exception $e) {
                    throw new ProfessionalException($e->getCode(), $e->getMessage());
                }
            }
        }
        return [];
    }
    /**
     * @param $applicationId
     * @return string
     * @throws ProfessionalException
     */
    public function getbatchDetailsForSsp($batchId)
    {
        $sql = "SELECT
                    ct.courseTypeID,cp.patternID,pd.patterncourseID,sd.Discipline_Code,sd.Discipline_name, sc.Course_Name,sc.Course_Code
                FROM batches b
                INNER JOIN course_type ct ON ct.courseTypeID = b.courseTypeID
                INNER JOIN course_pattern cp ON cp.patternID = b.patternID
                INNER JOIN pattern_deptcourses pd ON pd.patterncourseID = b.patterncourseID AND pd.patternID = cp.patternID
                LEFT JOIN ssp_course sc ON sc.Course_Code = cp.ssp_course_id
                LEFT JOIN ssp_discipline sd ON sd.id = pd.ssp_discipline_id
                WHERE b.batchID = $batchId;";
        try {
            return $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param $applicationId
     * @return string
     * @throws ProfessionalException
     */
    public function createSppLog($request)
    {
        $studentId = $this->realEscapeString($request->studentId);
        $academicYear = $this->realEscapeString($request->academicYear);
        $properties = $this->realEscapeObject($request->properties);
        $sppRequest = $this->realEscapeObject($request->sppRequest);
        $userId = $this->realEscapeString($request->userId);
        $properties->linways_un_id = uniqid();
        $properties->date = date('d-m-Y h:i A');
        $sppRequest->linways_un_id = $properties->linways_un_id;
        $sppRequest->date = $properties->date;
        $properties = json_encode($properties);
        $sppRequest = json_encode($sppRequest);
        $sql = "INSERT INTO ssp_student_log
            (student_id, academic_year_code, last_log, log,last_request_log,request_log, created_by, updated_by)
            VALUES($studentId, '$academicYear', '$properties', '[$properties]','$sppRequest','[$sppRequest]', $userId,$userId);
            ";
        try {
            $log = $this->selectSppLog($studentId,$academicYear);
            if($log->id){
                $this->updateSppLog($request,$log);
            }else{
                return $this->executeQuery($sql);
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param $applicationId
     * @return string
     * @throws ProfessionalException
     */
    public function updateSppLog($request,$log)
    {
        $studentId = $this->realEscapeString($request->studentId);
        $academicYear = $this->realEscapeString($request->academicYear);
        $properties = $this->realEscapeObject($request->properties);
        $sppRequest = $this->realEscapeObject($request->sppRequest);
        $userId = $this->realEscapeString($request->userId);
        $properties->linways_un_id = uniqid();
        $properties->date = date('d-m-Y h:i A');
        $log->log [] = $properties;
        $sppRequest->linways_un_id = $properties->linways_un_id;
        $sppRequest->date = $properties->date;
        $log->request_log [] = $sppRequest;
        $logData    = json_encode($log->log);
        $properties = json_encode($properties);
        $logRequest = json_encode($log->request_log);
        $sppRequest = json_encode($sppRequest);
        $sql = "UPDATE ssp_student_log
            SET last_log='$properties', log='$logData',last_request_log = '$sppRequest',request_log = '$logRequest', updated_by=$userId
            WHERE student_id=$studentId and academic_year_code='$academicYear';
        ";
        try {
            return $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param $applicationId
     * @return Object
     * @throws ProfessionalException
     */
    public function selectSppLog($studentId,$academicYear)
    {
        $studentId = $this->realEscapeString($studentId);
        $academicYear = $this->realEscapeString($academicYear);
        $sql = "select id,student_id,academic_year_code,log,last_log,last_request_log,request_log,created_date,updated_date from ssp_student_log WHERE student_id=$studentId and academic_year_code='$academicYear';";
        try {
            $data = $this->executeQueryForObject($sql);
            $ssp = new stdClass;
            $ssp->id = $data->id;
            $ssp->student_id = $data->student_id;
            $ssp->academic_year_code = $data->academic_year_code;
            $ssp->log = json_decode($data->log);
            $ssp->last_log = json_decode($data->last_log);
            $ssp->last_request_log = json_decode($data->last_request_log);
            $ssp->request_log = json_decode($data->request_log);
            $ssp->created_date = $data->created_date;
            $ssp->updated_date = $data->updated_date;
            return $ssp;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @param $get last qualification
     * @return Object
     * @throws ProfessionalException
     */
    public function getStudentLastQualification($request)
    {
        $request = $this->realEscapeObject($request);
        $where = [];
        (int) $request->studentId?$where[] = " s.studentID = ".$request->studentId:null;
        (int) $request->batchId?$where[] = " s.batchID = ".$request->batchId:null;
        $sql = "SELECT sped.* from studentaccount s
        INNER JOIN student_previous_education_details sped ON s.studentID = sped.studentId
        INNER JOIN batches b ON b.batchID = s.batchID
        INNER JOIN course_pattern cp ON cp.patternID = b.patternID
        INNER JOIN pattern_deptcourses pd ON pd.patterncourseID = b.patterncourseID AND pd.patternID = cp.patternID
        INNER JOIN ssp_discipline sd ON sd.Discipline_Code = pd.ssp_discipline_id
        INNER JOIN ssp_course sc ON sc.Course_Code = cp.ssp_course_id
        ".($where?" WHERE ".implode(' AND ',$where):"")."
        order by sped.studentId,cast(sped.year as signed) DESC;";
        try {
            $data = $this->executeQueryForList($sql);
            $student = [];
            foreach ($data as $key => $details) {
                if($student [$details->studentId]){
                    if((int)$student [$details->studentId]->year < (int)$details->year){
                        $student [$details->studentId] = $details;
                    }
                }else{
                    $student [$details->studentId] = $details;
                }
            }
            return array_values($student);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getPreviousCollegeWithSspData($university,$institution){
        $sql = "SELECT
            sc.University_Code AS Previous_Year_SSP_University_Code,
            sc.University_Name AS Previous_Year_SSP_University_Name,
            sc.College_Code AS Previous_Year_SSP_College_Code,
            sc.College_Name AS Previous_Year_SSP_College_Name
        from ssp_colleges sc
        where LOWER(sc.State_Name) = 'karnataka' and LOWER(sc.College_Name) = '".addslashes(strtolower($institution))."' and sc.University_Name = '".addslashes(strtolower($university))."'";
        if(empty(trim($institution)) || empty(trim($university))){
            return null;
        }else{
            try {
                return $this->executeQueryForObject($sql);
            } catch (\Exception $e) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        }
    }
    public function getPreviousCourseWithSspData($plus_2_course_code,$plus_2_discipline_code){
        $sql = "SELECT
            sc.Course_Code AS Previous_Year_SSP_Course_Code,
            sc.Course_Name AS Previous_Year_SSP_Course_Name,
            sd.Discipline_Code AS Previous_Year_SSP_Discipline_Code,
            sd.Discipline_name AS Previous_Year_SSP_Discipline_Name
        FROM ssp_course sc
        INNER JOIN ssp_discipline sd ON sc.Course_Code = sd.Course_Code
        WHERE sd.Course_Code = $plus_2_course_code AND sd.Discipline_Code = $plus_2_discipline_code;";
        try {
            return $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getStudentPhotosByBatches($request){
        $request = $this->realEscapeObject($request);
        $where = [];
        $request->courseTypeId?$where[] = " ct.courseTypeID = ".$request->courseTypeId:null;
        $request->deptId?$where[] = " d.deptID = ".$request->deptId:null;
        is_array($request->batchIds) && count($request->batchIds) ? $where[] = " b.batchID in (".implode(",",$request->batchIds).")" : null;
        $request->batchId?$where[] = " b.batchID =".$request->batchId." ":null;
        $request->studentId?$where[] = " s.studentID = ".$request->studentId." ":null;
        is_array($request->studentIds) && count($request->studentIds)? $where[] = " s.studentID in (".implode(",",$request->studentIds).")" : null ;
        $fileName = "studentName";
        switch ($request->fileNameUsing) {
            case 'ADMISSION_NO':
                $fileName = "admissionNo";
                break;
            case 'REG_NO':
                $fileName = "regNo";
                break;
            case 'ROLL_NO':
                $fileName = "rollNo";
                break;
            default:
                $fileName = "studentName";
            break;
        }
        $sql = "SELECT
                    ct.courseTypeID,
                    ct.typeName,
                    d.deptID,
                    d.deptName,
                    b.batchID,
                    b.batchName,
                    s.studentID,
                    s.$fileName as file_name,
                    s.studentName,
                    s.my_image_resource_id,
                    s.myImage,
                    s.studentSignImage,
                    s.my_sign_img_resource_id
                FROM studentaccount s
            INNER JOIN batches b ON b.batchID = s.batchID
            INNER JOIN department d ON d.deptID = b.deptID
            LEFT JOIN course_type ct ON ct.courseTypeID = b.courseTypeID
            ".($where?" WHERE ".implode(' AND ',$where):"").";";
        try {
            $studentDetails = $this->executeQueryForList($sql);
            $batches = [];
            foreach ($studentDetails as $key => $student) {
                if(empty($batches[$student->batchID])){
                    $batches[$student->batchID] = (object) ["name" => $student->batchName, "label" => $student->batchName, "link" => "", "type" => "FOLDER", "id" => $student->batchID, "data" => []];
                }
                $image = $this->getStudentProfilePic($student->studentID);
                if(empty($student->file_name)){
                    $student->file_name = $student->studentName;
                }
                $batches[$student->batchID]->data [$student->studentID] = (object) ["name" => $student->file_name,"label" => $student->studentName ,"link" => $image->docpath, "type" => "FILE", "id" => $student->studentID, "data" => []];
            }
            $batches = array_values($batches);
            foreach ($batches as $key => $batch) {
                $batch->data = array_values($batch->data);
            }
            return $batches;
        } catch (\Throwable $th) {
            throw new ProfessionalException($th->getCode(), $th->getMessage());
        }
    }
    /**
     * get student student photo bluk zip by lin resourse Id
     * @return Object
     * @throws ProfessionalException
     */
    public function getStudentBulkZip($resourseId){
        $sql = " SELECT lr.storage_object as storageObj,lr.path,lr.id as resourceId
                FROM lin_resource lr
                WHERE lr.id = '$resourseId'";
        try {
            $result = $this->executeQueryForObject($sql);
            $fileObj = json_decode(preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $result->storageObj));
            $result->storageObj = $fileObj;
            $result->docpath=S3Utils::getPreSignedURL($fileObj->bucket, $fileObj->key);
            return $result;
        }
        catch(\Exception $e) {
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
    }
    public function createZipWithStructure($request){
        $this->checkPathAndAddIt($request->collegeCode."/".$request->fileName,$request->documentRoot);
        $sourcePath = $request->sourcePath;
        $fileName = $request->fileName;
        $data = $request->data;
        $collegeCode = $request->collegeCode;
        if(empty($fileName)){
            throw new ProfessionalException("FILE_NAME", "Please set any file name");
        }
        if(empty($sourcePath)){
            throw new ProfessionalException("SOURCE_PATH", "Please set source path");
        }
        if(empty($data)){
            throw new ProfessionalException("DATA", "Empty data");
        }
        $isZipCreated = false;
        try {
            $ready = CommonUtil::createFileInAStructure($sourcePath."/".$fileName,$data,$request);
            if($ready ){
                $status = exec("cd ".$sourcePath." && zip -r ".$request->fileName.".zip ".$request->fileName." ");
                $isZipCreated = true;
            }
        } catch (\Throwable $th) {
        }
        if($isZipCreated){
            $uploadResourceRequest = new UploadResourceRequest();
            $uploadResourceRequest->fileName = $request->fileName . ".zip";
            $uploadResourceRequest->filePath = $request->sourcePath."/".$request->fileName . ".zip";
            $uploadResourceRequest->context = ResourceContext::DOWNLOAD_STUDENT_PHOTOS;
            $uploadResourceRequest->backendType = BackendTypes::S3;
            $uploadResourceRequest->s3FolderPath = $collegeCode . "/student_bulk_photos"."/";
            $uploadResourceRequest->bucket = SecurityUtils::decryptAndVerify($request->bucket, "S3-UPLOAD-LINWAYS");
            $uploadResourceRequest->accessKey = SecurityUtils::decryptAndVerify($request->accessKey, "S3-UPLOAD-LINWAYS");
            $uploadResourceRequest->secretKey = SecurityUtils::decryptAndVerify($request->secretKey, "S3-UPLOAD-LINWAYS");
            $uploadResourceRequest->createdBy = $request->userId;
            $uploadResourceRequest->updatedBy = $request->userId;
            try {
                $resourceId = ResourceService::getInstance()->uploadResource($uploadResourceRequest);
                if(!empty($uploadResourceRequest->filePath) && !empty($uploadResourceRequest->fileName) && file_exists($uploadResourceRequest->filePath."/".$uploadResourceRequest->fileName)) {
                    $status = exec("rm -r $uploadResourceRequest->filePath"."/"."$uploadResourceRequest->fileName");
                }
                if(!empty($request->sourcePath) && !empty($request->fileName) && file_exists($request->sourcePath."/".$request->fileName)) {
                    $status = exec("rm -r ".$request->sourcePath."/".$request->fileName);
                }
                $getAsyncReportRequest = new GetAsyncReportRequest();
                $getAsyncReportRequest->asyncReportId = $request->asyncReportId;
                $asyncReport = AsyncReportService::getInstance()->getAsyncReport($getAsyncReportRequest)[0];
                $asyncReport->linResourceId = $resourceId;
                AsyncReportService::getInstance()->saveAsyncReport($asyncReport);
            } catch (\Exception $e) {
                unlink($request->fileName);
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        }
    }
    public function checkPathAndAddIt($path,$documentRoot){
        $return = false;
        $directory = $documentRoot."student_photo_zips/";
        foreach (explode("/",$path) as $key => $dir) {
            if (is_writable($directory)) {
                // Check if the directory already exists
                $directory .= $dir."/";
                if (!is_dir($directory)) {
                    // Create the new directory
                    if (mkdir($directory, 0777)) {
                        // $return = "DIRECTORY_CREATED_SUCCESSFULLY";
                        continue;
                        $return = true;
                    }else{
                        // $return = "FAILED_TO_CREATE_DIRECTORY";
                        continue;
                        $return = true;
                        break;
                    }
                } else {
                    // $return = "DIRECTORY_ALREADY_EXISTS";
                    $return = true;
                    continue;
                }
            }else {
                // $return = "PARENT_DIRECTORY_IS_NOT_WRITABLE";
                $return = false;
                break;
            }
        }
        return $return;
    }
    // for external Api
    public function getStudentDetailsForApi(){
        $sql = "SELECT 
                studentAccount, regNo , admissionNo, studentName, g.name AS BatchName, d.deptName, s.studentPhone, s.studentEmail, s.applicationNo, r.religionName, s.studentGender, s.studentFather, s.studentMother, s.studentAddress, s.studentAdmittedTime AS admissionDate, s.parentPhone, s.bloodGroup, s.plustwo AS plusTwoPercentage, s.aadhaar_no AS adhaarNo, sc.casteName, s.studentBirthday, spa.current_term_id, spa.academic_status 
            FROM
                studentaccount s
            INNER JOIN student_program_account spa ON
                s.studentID = spa.student_id
            INNER JOIN `groups` g ON
                g.id = spa.current_batch_id
            INNER JOIN department d ON
                s.deptID = d.deptID
            LEFT JOIN student_caste sc ON
                sc.casteID = s.casteID
            LEFT JOIN religion r ON
                r.religionID = s.religionID";
        try{
            return $this->executeQueryForList($sql);
        }catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getMultipleStudentDetails($studentIds){
                $condition = "(".implode(",",$studentIds).")";
                $sql = "SELECT * from studentaccount WHERE studentID in ".$condition;
                try{
                    return $this->executeQueryForList($sql);
                }catch (\Exception $e) {
                    throw new ProfessionalException($e->getCode(), $e->getMessage());
                }
            }
    /**
     * @Author Ajay C
     * @params studentID,SemID
     * @return Null
     */
    public function InsertStudentMarkAcknowledgement($studentID,$semID){
        $studentID = $this->realEscapeString($studentID);
        $semID = $this->realEscapeString($semID);
    try{
        $existing = $this->getStudentMarkAcknowledgement($studentID,$semID);
        if($existing)
        {
            $sql = "UPDATE student_mark_acknowledgement SET isConfirmed = '1',updated_by = '$studentID' WHERE semID = '$semID' and studentID = '$studentID'";
            $this->executeQuery($sql);
            return true;
        }
        $sql = "INSERT
                    INTO
                    student_mark_acknowledgement(studentID,
                    semID,
                    created_by,
                    created_date,
                    isConfirmed)
                VALUES('$studentID',
                        '$semID',
                        '$studentID',
                        NOW(),
                        '1')";
            $this->executeQuery($sql);
            return true;
        }catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    function getStudentMarkAcknowledgement($studentID,$semID)
    {
        $studentID = $this->realEscapeString($studentID);
        $semID = $this->realEscapeString($semID);
        $sql = "SELECT DATE_FORMAT(created_date, '%d-%m-%Y') AS created_date,isConfirmed FROM student_mark_acknowledgement WHERE studentID = '$studentID' and semID = '$semID' ORDER BY id DESC";
        try{
            return $this->executeQueryForObject($sql);
        }catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    //api for college
    public function studentDetailsForCollege($date){
        try {
            if(empty($date)){
                throw new ProfessionalException(ProfessionalException::INVALID_DATE, "Date not found");
            }
            $query= "SELECT c.id AS clusterId,c.name AS clusterName,studentName,studentID ,studentEmail,spa.id as studentProgramId,g.name as batchName,tt.hour as timetableHour,
            tt.from_time as fromTime ,tt.to_time as toTime ,'$date' AS date,sub.id as subjectId ,
            sub.name as subjectName,0 AS isPresent, CONCAT(tt.from_time,'-',tt.to_time,'-',c.id,'-',tt.staff_id) as uniqueId,stf.staffID as staffId,stf.staffName as staffName,stf.staffEmail as staffEmail,tt.id as timeTableId FROM studentaccount s
            INNER JOIN student_program_account spa ON spa.student_id = s.studentID
            INNER JOIN `groups` g ON g.id = spa.current_batch_id
            INNER JOIN groups_relations gr ON gr.parent_groups_id = g.id
            INNER JOIN `groups` sg ON sg.id = gr.child_groups_id
            INNER JOIN `group_members` gm ON gm.groups_id = sg.id AND gm.members->>'$.studentId' = spa.id
            INNER JOIN `cm_academic_paper_subjects` aps on aps.id = sg.paperSubjectId
            INNER JOIN `cm_academic_paper` ap on aps.cm_academic_paper_id = ap.id
            INNER JOIN `cm_syllabus_academic_term_settings` str on str.id = ap.cm_syllabus_academic_term_settings_id
            INNER JOIN `v4_ams_subject` sub on sub.id = aps.ams_subject_id
            INNER JOIN `cluster_groups_relations` cg ON cg.groups_id = sg.id
            INNER JOIN cluster c ON c.id = cg.cluster_id
            INNER JOIN v4_timetable tt on tt.cluster_id = c.id
            INNER JOIN staffaccounts stf on stf.staffID = tt.staff_id
            WHERE tt.date = '$date';";
            $studetails = $this->executeQueryForList($query,$this->mapper[StudentServiceMapper::STUDENT_DETAILS_FOR_COLLEGE]);
            // this objct for passing external api
            $responseObj = new \stdClass();
            $responseObj->currentHour = "";
            $responseObj->studentDetails = $studetails;
            return $responseObj;
            } catch (\Exception $e) {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        }
    /**
     * get student details by studentaccount
     * @param $studentAccount
     * @return Object
     * @throws ProfessionalException
     */
    public function getStudentDetailsBystudentAccount($studentAccount){
        $sql = "SELECT studentID FROM studentaccount WHERE studentAccount = '$studentAccount'";
        try {
            return $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * update Student Mark Acknowledgement
     * @param $studentAccount
     * @return Object
     * @throws ProfessionalException
     */
    public function updateStudentMarkAcknowledgement($request){
        $request = $this->realEscapeObject($request);
        try {
            $sql = "UPDATE student_mark_acknowledgement SET isConfirmed = '$request->isConfirmed',updated_by = '$request->updatedBy' WHERE semID = '$request->semId' and studentID = '$request->studentId'";
            $this->executeQuery($sql);
            return true;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getStudentGradeWithExamIdAndStudentId($examID,$studentIDs)
    {
        $examID = $this->realEscapeString($examID);
        $studentIDs = $this->realEscapeString($studentIDs);
        // $studentIDs = implode(",",$studentIDs);
        $sql = "SELECT
                   t1.studentID ,
                    s.regNo,
                    s.studentName,
                    b.semID ,
                    b.isPassOut ,
                    t1.gradeObtained,
                    t1.noOfChances,
                    t1.passType,
                    t2.letterGrade,
                    t2.percentTo,
                    t2.gradePoint
                from
                    university_studentgrade t1,
                    university_gradepoints t2,
                    studentaccount s ,
                    batches b
                where
                    t1.examID = '$examID'
                    and t1.studentID in ($studentIDs)
                    and t1.gradeObtained = t2.gradeID
                    and s.studentID = t1.studentID
                    and b.batchID  = s.batchID
                    and t2.gradePoint = 0 ";
        try {
            return $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getStudentAdmissionYear($studentId){
        $studentId = $this->realEscapeString($studentId);
        $failedInBatchId = $this->getStudentBatchBySemId($studentId,1);
        if($failedInBatchId){
            $batchStartYear = BatchService::getInstance()->getBatchNameById($failedInBatchId)->batchStartYear;
        }
        if(!$batchStartYear){
            $batchId = $this->getStudentBatchIdByStudentId($studentId);
            if($batchId){
                $batchStartYear = BatchService::getInstance()->getBatchNameById($batchId)->batchStartYear;
            }
        }
        return $batchStartYear;
    }
    public function getDynamicDataForDossier($studentID,$batchID = null)
    {
        if(!$batchID)
        {
            $sql = "SELECT
                            cp.patternName,
                            b.batchStartYear ,
                            b.batchEndYear,
                            b.batchName ,
                            pd.patterncourseName,
                            'collegeName' as collegeName,
                            'CollegeAddres' as collegeAddress,
                            'collegeEmail' as collegeEmail
                        from
                            batches b
                        inner join course_pattern cp on
                            cp.patternID = b.patternID
                        inner join studentaccount sa on sa.batchID = b.batchID
                            inner join pattern_deptcourses pd on b.patterncourseID = pd.patterncourseID
                        WHERE sa.studentID = '$studentID'  and b.batchID = sa.batchID
                            ORDER BY b.batchID DESC";
        }
        else
        {
            $sql = "SELECT
                            cp.patternName,
                            b.batchStartYear ,
                            b.batchEndYear,
                            b.batchName ,
                            pd.patterncourseName,
                            'collegeName' as collegeName,
                            'CollegeAddres' as collegeAddress,
                            'collegeEmail' as collegeEmail
                        from
                            batches b
                        inner join course_pattern cp on
                            cp.patternID = b.patternID
                            inner join pattern_deptcourses pd on b.patterncourseID = pd.patterncourseID
                        WHERE b.batchID = '$batchID'
                            ORDER BY b.batchID DESC";
        }
        try
        {
            return $this->executeQueryForObject($sql);
        }
        catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getFailedStudentDetailsWithDiscontinuedStateByStudentId($studentId){
        try {
            $studentId = $this->realEscapeString($studentId);
            $sql = "SELECT
                            s.studentName ,
                            s.batchID ,
                            s.regNo ,
                            s.rollNo ,
                            s.admissionNo ,
                            fs.previousBatch ,
                            fs.reason ,
                            app.status_date as failedDate,
                            fs.failedInSemester ,
                            fs.reason
                    FROM
                        student_program_batch_log app
                    inner join student_program_account spa on
                        spa.id = app.program_student_id
                    inner join studentaccount s on s.studentID = spa.student_id
                    inner join failed_students fs on fs.studentID = s.studentID
                    WHERE s.studentID = '$studentId' order by app.status_date desc LIMIT 0,1;";
            return $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
    }
    public function getFailedBatchAndSemester($semRegID,$studentID)
    {
        $semRegID = $this->realEscapeString($semRegID);
        $studentID = $this->realEscapeString($studentID);
        try{
            $sql = "SELECT sr.batchId ,sr.semId ,sr.batchPromotionDate,sr.classStartDate
                            from failed_students fs
                            inner join semRegistration sr on fs.failedInSemester = sr.semId and  fs.previousBatch = sr.batchId
                            WHERE sr.id ='$semRegID' and fs.studentID = '$studentID'";
            return $this->executeQueryForObject($sql);
        }catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * check student CBE application exists
     * @param $batchId $studentId
     * @return Object
     * @throws ProfessionalException
     */
    public function checkStudentCBEApplicationExists($batchId,$studentId)
    {
        $batchId = $this->realEscapeString($batchId);
        $studentId = $this->realEscapeString($studentId);
        try{
            $sql = "SELECT csra.student_id AS 'studentId' FROM cbe_student_registered_application csra INNER JOIN cbe_application_batches_semesters cabs ON csra.application_id = cabs.application_id INNER JOIN cbe_applications ca ON ca.id = csra.application_id AND cabs.application_id = ca.id WHERE ca.is_published = 1 and cabs.batch_id = $batchId AND csra.student_id = $studentId AND csra.is_registration_completed = 1";
            return $this->executeQueryForObject($sql);
        }catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
     /**
     * List all available domiciles
     * @param NUll
     * @return List
     * @author Ajay-the-dev
     * @throws ProfessionalException
     */
    public function getAllDomicileForStudent()
    {
        try{
            $sql = "SELECT id,name ,isHidden  FROM admission_domicile WHERE isHidden = 0";
            return $this->executeQueryForList($sql);
        }
        catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
     /**
     * Check for duplicate uucms id
     * @param Integer UucmsId
     * @return Boolean
     * @throws ProfessionalException
     */
    public function checkForDuplicateUUCMS($uucmsID)
    {
        try{
            $uucmsID = $this->realEscapeString($uucmsID);
            if($uucmsID)
            {
                $sql = "SELECT studentID FROM studentaccount WHERE uucmsid = '$uucmsID' AND studentID !=".$_SESSION['studentID'];
                $result = $this->executeQueryForObject($sql);
                return $result ? true : false;
            }
            else
            {
                return false;
            }
        }catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getSupplyRegisteredStudentsInBatchSemDetails($batchId, $supplyId,$semId)
    {
        $batchId = $this->realEscapeArray($batchId);
        $batchId = is_array($batchId) ? implode(",", $batchId) : $batchId;
        $supplyId = $this->realEscapeArray($supplyId);
        $semId = $this->realEscapeArray($semId);
        $sql = "SELECT
            sa.studentID AS studentId,
            sa.regNo,
            sa.studentName AS name,
            sa.myImage,
            sa.studentSignImage,
            sa.batchID AS batchId
        FROM
            exam_supplementary_student_details essd
        INNER JOIN studentaccount sa ON
            sa.studentID = essd.studentID
            LEFT JOIN failed_students fs ON fs.studentID = sa.studentID AND FIND_IN_SET('$semId', fs.hisSemestersInThisbatch)
        WHERE
            IF(fs.previousBatch,fs.previousBatch,sa.batchID) IN ($batchId)
            AND essd.exam_supplementary_id = '$supplyId'
            ORDER BY sa.regNo";
        try {
            $students = $this->executeQueryForList($sql);
            return $students;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getUserResidenceDetails($userId,$userType)
    {
        $sql='';
        if($userType==UserType::STUDENT){
            $sql="SELECT c.country_name as country,
            extra_details->>'$.permCity' as city,
            extra_details->>'$.permPin' as zipCode
            FROM studentaccount_extras sae
            LEFT JOIN country c on sae.extra_details->>'$.permCountry'=c.id
            where sae.studentID='$userId';";
        }
        elseif($userType==UserType::ADMISSION_APPLICANT){
            $sql="SELECT c.country_name as country,
            extraDetails->>'$.permCity' as city,
            extraDetails->>'$.permPin' as zipCode
            FROM adm_admission_student_details asd
            LEFT JOIN country c on asd.extraDetails->>'$.permCountry'=c.id
            where asd.admission_applicant_id='$userId';";
        }
        try {
            if($sql){
                $students = $this->executeQueryForObject($sql);
                return $students;
            }
            return null;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
      /**
     * FE community Students Attenfdance Percentage And Internal Mark
     * @param $request
     * @return Object
     * @author Midhun Shaji
     * @throws ProfessionalException
     */
    public function getFeCommunityStudentAttendanceAndInternal($request)
    {
        $request = $this->realEscapeObject($request);
        try{
            $sql = "SELECT arim.mark, arim.cluster_id , at2.properties->>'$.orderNo' from cluster c
                    INNER JOIN cluster_groups_relations cgr  ON cgr.cluster_id = c.id
                    INNER JOIN `groups` sg ON  sg.id = cgr.groups_id
                    INNER JOIN group_members gm ON gm.groups_id = sg.id
                    INNER JOIN cm_academic_paper_subjects caps ON caps.id = sg.paperSubjectId
                    INNER JOIN  academic_term at2 ON at2.id = sg.academic_term_id
                    INNER JOIN am_report_internal_mark arim ON arim.cluster_id = c.id
                    WHERE 1=1 AND arim.confirmed = 1
                    AND caps.id = '$request->paperSubId'  AND gm.student_id = '$request->studentProgramId'
                    ORDER BY at2.properties->>'$.orderNo' desc , arim.created_date DESC LIMIT 1";
            $response = new \stdClass();
            $response->internalMark = $this->executeQueryForObject($sql);
            $query = "SELECT
                        ROUND(IFNULL((COUNT(DISTINCT CASE WHEN va.is_absent = 0 OR va.grant_leave IS NOT NULL THEN CONCAT(va.student_id, va.attendance_date, va.start_time, va.end_time) END) / COUNT(DISTINCT va.student_id, va.attendance_date, va.start_time, va.end_time))*100,0),2) AS attendancePercentage
                        from v4_attendance va
                        INNER JOIN cluster c ON c.id = va.cluster_id
                        INNER JOIN cluster_groups_relations cgr  ON cgr.cluster_id = c.id
                        INNER JOIN `groups` sg ON  sg.id = cgr.groups_id
                        INNER JOIN cm_academic_paper_subjects caps ON caps.id = sg.paperSubjectId
                        INNER JOIN  academic_term at2 ON at2.id = sg.academic_term_id
                        INNER JOIN am_report_internal_mark arim ON arim.cluster_id = c.id  AND arim.confirmed = 1
                        where 1=1
                        AND caps.id = '$request->paperSubId' AND va.student_program_id = '$request->studentProgramId'
                        ORDER BY at2.properties->>'$.orderNo' desc";
            $response->attendancePercentage = $this->executeQueryForObject($query);
            return $response;
        }
        catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
        /**
     * student details by reg no
     * @param string $regNo
     * @return object|NULL|\com\linways\base\util\$objectList[]
     * @throws ProfessionalException
     */
    public function getStudentDetailsByRegNoSem($regNo,$semId)
    {
        $regNo = $this->realEscapeString($regNo);
        $sql = "SELECT
                    sa.studentID as id,
                    sa.studentName as name,
                    dept.deptName,
                    bth.batchName,
                    sa.regNo,
                    sa.rollNo,
                    dept.deptName,
                    bth.batchName,
                    dept.deptID,
                    bth.batchID,
                    bth.patternID as courseTypeId,
                    bth.batchStartYear as startYear,
                    bth.batchEndYear as endYear,
                    dept.departmentDesc,
                    sa.tcIssued,
                    sa.studentAddress,
                    bth.courseTypeID
                FROM
                    studentaccount sa
                INNER JOIN department dept ON
                    sa.deptID = dept.deptID
                LEFT JOIN failed_students fs ON fs.studentID = sa.studentID AND FIND_IN_SET($semId, fs.hisSemestersInThisbatch)
                INNER JOIN batches bth ON
                    IF (fs.previousBatch, fs.previousBatch, sa.batchID) = bth.batchID
                    AND dept.deptID = bth.deptID
                WHERE
                    regNo = \"$regNo\"";
        try {
            $studentDetails = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * Adding student Automatically to subject communities of MAJOR
     *
     * In this case the students are added to the subject community if only there is subject community exists
     * We are identifying the paper subject with number of subjects student can choose is equal to the  number of subjects in a paper of the type MAJOR
     * After Identifying the Paper subjects we are inserting or updating the student status into the subject group members of the subject group of the current batch studet are added
     *
     * @param  $studentId it is the id of the student account table
     * @author Midhun Shaji
     **/
    public function addStudentAutomatcallyToSubjectCommunity($studentId){
        try {
            
            $checkStudentCanAutomaticallyAddedToCommunity = CommonService::getInstance()->getSettings(SettingsConstants::ACADEMICS, SettingsConstants::AUTOMATICALLY_ADDING_STUDENT_TO_SUBJECT_COMMUNITY);
            if($checkStudentCanAutomaticallyAddedToCommunity === '1'){
            
                $sql = " SELECT
                                    caps.id,
                                    cap.properties ->> '$.noOfSubjectThatAStudentCanChoose' AS max_subjects,
                                    spa.id as studentProgramId
                                    FROM
                                    student_program_account spa
                                    INNER JOIN `groups` g ON g.id = spa.current_batch_id
                                    INNER JOIN cm_curriculum cc ON cc.id =  g.cm_curriculum_id
                                    INNER JOIN cm_curriculum_syllabus_relation ccsr ON ccsr.cm_curriculum_id = cc.id
                                    INNER JOIN cm_syllabus cs ON cs.id = ccsr.cm_syllabus_id  AND cs.`type` = 'MAJOR'
                                    INNER JOIN cm_syllabus_academic_term_settings csats ON csats.cm_syllabus_id = cs.id  AND csats.academic_term_id  = spa.current_term_id                                INNER JOIN cm_academic_paper cap ON cap.cm_syllabus_academic_term_settings_id =  csats.id
                                    INNER JOIN cm_academic_paper_subjects caps ON caps.cm_academic_paper_id = cap.id
                                    WHERE     spa.student_id = '$studentId'
                                    GROUP BY cap.id
                                    HAVING CAST(COUNT(DISTINCT caps.id) AS UNSIGNED) <= CAST(max_subjects AS UNSIGNED)";
    
                $paperSubjectDetails = (array)$this->executeQueryForList($sql);
                 
                $paperIdArray = array_map(function($obj) {
                    return $obj->id;
                }, $paperSubjectDetails);
            
                $query = "INSERT INTO group_members (
                            id,
                            groups_id,
                            members,
                            properties,
                            created_by,
                            created_date,
                            updated_by,
                            updated_date
                        )
                        SELECT
                            LEFT(REPLACE(UUID(), '-', ''), 17),
                            sg.id,
                            JSON_OBJECT('studentId', spa.id),
                            JSON_OBJECT('isFailed', false, 'academicStatus', 'ACTIVE', 'automaticallyAddedToCommunity', true),
                            '0',
                            NOW(),
                            '0',
                            NOW()
                        FROM
                            `groups` sg
                        INNER JOIN groups_relations gr ON gr.child_groups_id = sg.id
                        INNER JOIN student_program_account spa ON spa.current_batch_id = gr.parent_groups_id
                        INNER JOIN cluster_groups_relations cgr  ON cgr.groups_id = sg.id
                        INNER JOIN cluster c ON c.id = cgr.cluster_id AND c.trashed IS NULL
                             AND  (c.properties IS NULL OR c.properties ->> '$.clusterCategory' IS NULL OR c.properties ->> '$.clusterCategory' <> 'IRREGULAR')  
                        WHERE
                            sg.paperSubjectId IN ('" . implode("','", $paperIdArray) . "') AND spa.student_id = '$studentId' AND sg.academic_term_id = spa.current_term_id GROUP BY  sg.paperSubjectId
                        ON DUPLICATE KEY UPDATE
                        group_members.properties = JSON_SET(group_members.properties, '$.academicStatus', 'ACTIVE');
                        ";
                        $this->executeQuery($query);
                        
                        AMSLogger::log_info($this->logger, Events::ADD_STUDENT_AUTOMATICALLY_TO_SUBJECT_COMMUNITY, [
                            "studentId" => $studentId,
                            "paperSubjectDetails" => $paperIdArray,
                            "status" => StatusConstants::SUCCESS
                        ]);
            }
                // adding student to cbe if cbe present for the batch
                $request = new AutoAssignmentCbeTermRegistration();
                $request->studentList = [$studentId];
                $this->studentAssignmentToCbe($request);
        }catch (\Exception $e) {
            AMSLogger::log_info($this->logger, Events::ADD_STUDENT_AUTOMATICALLY_TO_SUBJECT_COMMUNITY, [
                "studentId" => $studentId,
                "paperSubjectDetails" => $paperIdArray,
                "status" => StatusConstants::FAILED,
                "error" => $e->getCode(),
                "message" => $e->getMessage()
            ]);
            
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function studentAssignmentToCbe(AutoAssignmentCbeTermRegistration $request){
        $request = $this->realEscapeObject($request);
        if (empty($request->studentList)) {
            throw new ProfessionalException(ProfessionalException::DATA_EMPTY, "StudentId is empty");
        }
        $createdBy = $GLOBALS['userId'] ?? "NULL";
        $sql = "INSERT
                    INTO
                    v4_cbe_application_batch_students (student_program_account_id,
                        student_account_id,
                        application_batch_id,
                        created_by,
                        finalize_status)
                SELECT
                    spa.id,
                    s.studentID,
                    vcab.id ,
                    '$createdBy',
                    'NOT_APPLIED'
                FROM
                    student_program_account spa
                INNER JOIN studentaccount s ON
                    spa.student_id = s.studentID
                INNER JOIN v4_cbe_application_batches vcab ON
                    vcab.groups_id = spa.current_batch_id
                LEFT JOIN v4_cbe_application_batch_students vcabs ON
                    vcabs.student_program_account_id = spa.id
                    AND vcabs.application_batch_id = vcab.id
                WHERE
                    spa.student_id  IN ('" . implode("','", $request->studentList) . "')
                    AND vcab.groups_id = spa.current_batch_id
                    AND vcabs.id IS NULl";
        error_log('before sql');
        error_log($sql);
        try {
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Remove student from all cbe applications of his current batch
     *
     * In case of batch movements this method should be called before batch movement is taking place
     *
     * $request->logContext is used to save to kibana log in which context this removal happened
     *
     * @param RemoveStudentFromAllCbeApplicationsRequest $request
     * @return null
     * @throws ProfessionalException
     **/
    public function removeStudentFromAllCbeApplication(RemoveStudentFromAllCbeApplicationsRequest $request)
    {
        try {
            if (empty($request->studentAccountId) && empty($request->studentProgramAccountId)) {
                throw new ProfessionalException(ProfessionalException::EMPTY_PARAMETERS, "Both student account id and student program account id cannot be empty");
            }
            $whereCond = "";
            if (!empty($request->studentProgramAccountId)) {
                $whereCond .= " AND id = '$request->studentProgramAccountId";
            }
            if (!empty($request->studentAccountId)) {
                $whereCond .= " AND student_id = '$request->studentAccountId";
            }
            $sql = "SELECT
                id as studentProgramAccountId,
                current_batch_id as groupId
            FROM
                student_program_account spa
            WHERE
                1 = 1 $whereCond ";
            $studentData = $this->executeQueryForObject($sql);
            $studentProgramAccountId = $studentData->studentProgramAccountId;
            $groupId = $studentData->groupId;
            // REMOVE FROM FORMED CLUSTER OF CBE
            $removeFromCbeFormedClusterSql = "UPDATE
                `groups` g
            INNER JOIN academic_term batchTerm ON
                batchTerm.id = g.academic_term_id
            INNER JOIN v4_cbe_application_batches vcab ON
                vcab.groups_id = g.id
            INNER JOIN v4_cbe_application vca ON
                vca.id = vcab.application_id
                AND vca.type = 'CBE'
            INNER JOIN academic_term vcabTerm ON
                vcabTerm.id = vcab.current_term_id
                AND CAST(vcabTerm.properties->>'$.orderNo' AS UNSIGNED) >= CAST(batchTerm.properties->>'$.orderNo' AS UNSIGNED)
            INNER JOIN v4_cbe_application_batch_students vcabs ON
                vcabs.application_batch_id = vcab.id
                AND vcabs.student_program_account_id = '$studentProgramAccountId'
            INNER JOIN v4_cbe_student_registered_application vcsra ON
                vcsra.application_id = vcab.application_id
                AND vcsra.student_program_account_id = '$studentProgramAccountId'
            INNER JOIN cluster_groups_relations cgr ON
                cgr.cluster_id = vcsra.cluster_id
            INNER JOIN group_members gm ON
                gm.groups_id = cgr.groups_id
                AND gm.student_id = '$studentProgramAccountId'
            SET
                gm.properties = JSON_SET(gm.properties,
                '$.academicStatus',
                'REMOVED')
            WHERE
                g.id = '$groupId'";
            $this->executeQuery($removeFromCbeFormedClusterSql);
            // DELETE THE APPLIED ENTRIES OF THE SUBJECTS
            $removeAppliedEntriesSql = "DELETE
                vcsra.*
            FROM
                `groups` g
            INNER JOIN academic_term batchTerm ON
                batchTerm.id = g.academic_term_id
            INNER JOIN v4_cbe_application_batches vcab ON
                vcab.groups_id = g.id
            INNER JOIN v4_cbe_application vca ON
                vca.id = vcab.application_id
                AND vca.type = 'CBE'
            INNER JOIN academic_term vcabTerm ON
                vcabTerm.id = vcab.current_term_id
                AND CAST(vcabTerm.properties->>'$.orderNo' AS UNSIGNED) >= CAST(batchTerm.properties->>'$.orderNo' AS UNSIGNED)
            INNER JOIN v4_cbe_application_batch_students vcabs ON
                vcabs.application_batch_id = vcab.id
                AND vcabs.student_program_account_id = '$studentProgramAccountId'
            INNER JOIN v4_cbe_student_registered_application vcsra ON
                vcsra.application_id = vcab.application_id
                AND vcsra.student_program_account_id = '$studentProgramAccountId'
            WHERE
                g.id = '$groupId'";
            $this->executeQuery($removeAppliedEntriesSql);
            // DELETE FROM APPLICATION BATCH STUDENTS
            $removeFromApplicationBatchSql = "DELETE
                vcabs.*
            FROM
                `groups` g
            INNER JOIN academic_term batchTerm ON
                batchTerm.id = g.academic_term_id
            INNER JOIN v4_cbe_application_batches vcab ON
                vcab.groups_id = g.id
            INNER JOIN v4_cbe_application vca ON
                vca.id = vcab.application_id
                AND vca.type = 'CBE'
            INNER JOIN academic_term vcabTerm ON
                vcabTerm.id = vcab.current_term_id
                AND CAST(vcabTerm.properties->>'$.orderNo' AS UNSIGNED) >= CAST(batchTerm.properties->>'$.orderNo' AS UNSIGNED)
            INNER JOIN v4_cbe_application_batch_students vcabs ON
                vcabs.application_batch_id = vcab.id
                AND vcabs.student_program_account_id = '$studentProgramAccountId'
            WHERE
                g.id = '$groupId'";
            $this->executeQuery($removeFromApplicationBatchSql);
            AMSLogger::log_info($this->logger, Events::REMOVE_STUDENT_FROM_ALL_CBE_APPLICATIONS, [
                "request" => $request,
                "status" => StatusConstants::SUCCESS
            ]);
        } catch (\Exception $e) {
            AMSLogger::log_error($this->logger, Events::REMOVE_STUDENT_FROM_ALL_CBE_APPLICATIONS, [
                "request" => $request,
                "errorCode" => $e->getCode(),
                "errorMessage" => $e->getMessage(),
                "status" => StatusConstants::FAILED
            ]);
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
      /**
     * Get Week Student Details
     *
     * @param  $studentIds , $examTypeId, $batchId, $semId, $subjectId
     * @return null
     * @throws ProfessionalException
     **/
    public function getWeekStudentsDetails($studentIds, $examTypeId, $batchId, $semId, $subjectId)
    {
        $examTypeId = $this->realEscapeString($examTypeId);
        $batchId = $this->realEscapeString($batchId);
        $semId = $this->realEscapeString($semId);
        $subjectId = $this->realEscapeString($subjectId);
    
       
        $sql = "
            SELECT 
                sa.studentID, 
                sa.studentName, 
                sa.rollNo,
                e.examID,
                GROUP_CONCAT(DISTINCT e.examID) AS examIds,
                e.examName,
                e.examTypeID,
                e.examTotalMarks,
                e.subbatchID,
                sm.markID,
                sm.batchID,
                sm.studentID,
                sm.examID,
                sm.staffID,
                sm.percentage,
                e.examDate AS dateOfTest,
                im.internalMarks AS final_converted,
                ims.maxInternalMarks AS max_final_converted
            FROM studentaccount sa
            LEFT JOIN student_marks sm ON sa.studentID = sm.studentID
            LEFT JOIN exam e ON e.examID = sm.examID 
                AND e.subjectID = sm.subjectID 
                AND e.examTypeID = sm.examTypeID 
                AND e.batchID = sm.batchID 
            LEFT JOIN internal_marks im ON im.studentID = sm.studentID 
                AND im.batchID = e.batchID 
                AND im.semID = e.semID 
                AND im.subjectID = e.subjectID 
            LEFT JOIN internal_marks_settings ims ON ims.batchID = e.batchID 
                AND ims.semID = e.semID 
                AND ims.subjectID = e.subjectID 
            WHERE sa.studentID IN ($studentIds)
            AND e.examTypeID = $examTypeId
            AND e.batchID = $batchId
            AND e.semID = $semId
            AND e.subjectID = $subjectId
            GROUP BY e.examTypeID, e.batchID, e.semID, sm.studentID";
    
        try {
            $studentDetails = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        
        return $studentDetails;
    }
 
    /**
     * get student details 
     *
     * get student details for tc api 
     *
     * @param Integer $studentID unique integer
     * @return Object
     * @throws ProfessionalException
     **/
    public function getStudentDetailsForApiSecond($studentID)
    {
        try{
            $studentID = $this->realEscapeString($studentID);
            $sql = "SELECT
                        cp.patternName ,
                        cp.patternDesc ,
                        rs.reservationName as category,
                        ss.subcaste_name as subcaste,
                        sr.reservName as seatReservation,
                        u.name as universityName,
                        sped.institution as studentPreviousSchool,
                        b.batchStartYear,
                        b.final_semester as finalSemester,
                        s2.semName as lastSemName,
                        b.batchEndYear 
                    from
                        batches b
                    inner join course_pattern cp on
                        b.patternID = cp.patternID 
                    inner join studentaccount s on s.batchID = b.batchID 
                    left join reservation_students rs on rs.reservationID = s.reservationID
                    left join student_subcaste ss on ss.id = s.student_subcaste_id and s.studentID = $studentID
                    left join student_reservation sr on sr.reservID = s.studentID and s.studentID = $studentID
                    LEFT JOIN university u on u.id = b.universityId 
                    left join student_previous_education_details sped on sped.studentId = s.studentID and s.studentID = $studentID
                    left join semesters s2 on s2.semID = b.final_semester 
                    where s.studentID = $studentID";
            return $this->executeQueryForObject($sql);
        }catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        
        return $studentDetails;
    }
    public function getFailedStudentForMigrationById($studentId)
    {
        $studentDeatils = NULL;
        $sql = "SELECT sa.studentID as id,
        sa.studentName as name,
        sa.regNo, sa.rollNo,
        sa.studentGender,
        sa.admissionNo,
        dept.deptName,
        bth.batchName,
        dept.deptID,
        bth.batchID,
        bth.patternID as courseTypeId,
        bct.type_code as typeCode,
        bct.type_name as typeName,
        bth.batchStartYear as startYear,
        bth.batchEndYear as endYear,
        dept.departmentDesc,
        sa.studentAddress,
        pdc.patterncourseName,
        sl.secondLangaugeName,
        sem.semName,
        sem.orderNo as semOrderNo ,
        sa.studentMother,
        sa.studentJoindate,
        sa.parentAddress1,
        sa.parentAddress2,
        sa.parentCity,
        sa.parentZipCode,
        sa.parentCountry,
        sa.parentState,
        sa.studentFather,
        sa.myImage,
        state.state_name as stateName,
        sa.studentBirthday,
        CONCAT_WS(' ',se.commuhouse,se.currentAddress1,se.currentAddress2,se.currentCity,se.currentCountry,se.currentState,se.currentZipCode) as additional_info_currentAddress,
        CONCAT_WS(' ',se.permaHouse,se.permanentAddress1,se.permanentAddress2,se.permanentCity,se.permanentCountry,se.permanentState,se.permanentZipCode) as additional_info_permanentAddress,sa.tcIssued,nat.nationalityName,caste.casteID,caste.casteName,rs.reservationID,rs.reservationName AS studentReservation, fs.failedInSemester as lastSemId
        FROM studentaccount sa
        INNER JOIN failed_students fs ON fs.studentID=sa.studentID
        INNER JOIN batches bth ON bth.batchID=fs.previousBatch
        INNER JOIN department dept ON dept.deptID=bth.deptID
        LEFT JOIN batch_course_type bct ON bct.id=bth.patternID
        left join pattern_deptcourses pdc ON bth.patterncourseID = pdc.patterncourseID
        left join secondLangauge sl on sl.secondlangaugeID = sa.secondlangaugeID
        left join semesters sem on sem.semID = bth.semID
        left join studentaccount_extras se on se.studentID = sa.studentID
        LEFT JOIN state ON state.id = sa.state_id
        LEFT JOIN nationality nat ON nat.id = sa.nationality_id
        LEFT JOIN student_caste caste ON caste.casteID=sa.casteID
        LEFT JOIN reservation_students rs ON rs.reservationID=sa.reservationID
        WHERE fs.studentID =  $studentId";
        try {
            $studentDeatils = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentDeatils;
    }
    /**
    * updating access card configuration
    *
    * assigning form access card configuration
    *
    * @param String $formID form identifier
    * @return Boolean
    * @throws ProfessionalException
    **/
    public function updateFormToAccesscardConf($formID , $conf)
    {
        try {
            $formID = $this->realEscapeString($formID);
            $conf = $this->realEscapeString($conf);
            $sqlDelete = "DELETE FROM generalcard_conf WHERE formID = $formID";
            $this->executeQuery($sqlDelete);
            
            $formID = $formID ? $formID : 'NULL';
            $sql = "UPDATE generalcard_conf SET formID = $formID WHERE confID in ($conf)";
            $result = $this->executeQuery($sql);
            return $result->sqlResult;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
            
        }
    }
    
    /**
     * GET STUDENT REGISTER NUMBER BY STUDENT ID
     * @param Integer $studentId
     * @return Object
     * @throws ProfessionalException
     * @author Midhun Shaji
     */
    public function getStudentRegNoByStudentId($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        $sql = "SELECT regNo FROM studentaccount WHERE studentID = $studentId";
        try {
            return $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    
    /**
     * ADDING STUDENT ACCOUNT ADDITIONAL DETAILS
     * @param Object $studentExtras
     * @return Boolean
     * @throws ProfessionalException
     * @author Midhun Shaji
     */
    public function updateStudentAccountExtraAdditionalDetails($studentExtras) {
        $studentExtras = $this->realEscapeObject($studentExtras);
        $sql = "UPDATE studentaccount_extras SET 
            program_code = '$studentExtras->programCode',
            tenth_std_max_marks = '$studentExtras->tenthStdMaxMarks',
            tenth_std_total_mark = '$studentExtras->tenthStdTotalMark',
            place_of_12th_std_studied = '$studentExtras->placeOf12thStdStudied',
            twelth_std_max_marks = '$studentExtras->twelthStdMaxMarks',
            twelth_std_total_marks_obtained = '$studentExtras->twelthStdTotalMarksObtained',
            certificates_verified_online = '$studentExtras->certificatesVerifiedOnline',
            course_of_diploma_studied = '$studentExtras->courseOfDiplomaStudied',
            place_of_diploma_studied = '$studentExtras->placeOfDiplomaStudied',
            diploma_registration_no = '$studentExtras->diplomaRegistrationNo',
            diploma_maximum_marks = '$studentExtras->diplomaMaximumMarks',
            diploma_total_marks_obtained = '$studentExtras->diplomaTotalMarksObtained',
            diploma_overall_percentage = '$studentExtras->diplomaOverallPercentage',
            second_third_languages_pu_12th = '$studentExtras->secondThirdLanguagesPu12th',
            pu_12th_board_stream = '$studentExtras->pu12thBoardStream',
            graduation_course = '$studentExtras->graduationCourse',
            first_sem_marks_cgpa = '$studentExtras->firstSemMarksCgpa',
            second_sem_marks_cgpa = '$studentExtras->secondSemMarksCgpa',
            third_sem_marks_cgpa = '$studentExtras->thirdSemMarksCgpa',
            fourth_sem_marks_cgpa = '$studentExtras->fourthSemMarksCgpa',
            fifth_sem_marks_cgpa = '$studentExtras->fifthSemMarksCgpa',
            sixth_sem_marks_cgpa = '$studentExtras->sixthSemMarksCgpa',
            seventh_sem_marks_cgpa = '$studentExtras->seventhSemMarksCgpa',
            eighth_sem_marks_cgpa = '$studentExtras->eighthSemMarksCgpa',
            ninth_sem_marks_cgpa = '$studentExtras->ninthSemMarksCgpa',
            tenth_sem_marks_cgpa = '$studentExtras->tenthSemMarksCgpa',
            total_marks_cgpa_in_graduation = '$studentExtras->totalMarksCgpaInGraduation',
            total_marks_cgpa_in_graduation_obtained = '$studentExtras->totalMarksCgpaInGraduationObtained',
            online_verification = '$studentExtras->onlineVerification',
            status = '$studentExtras->status',
            ug_course_name = '$studentExtras->ugCourseName',
            ug_maximum_marks_cgpa = '$studentExtras->ugMaximumMarksCgpa',
            ug_total_marks_cgpa_obtained = '$studentExtras->ugTotalMarksCgpaObtained',
            pg_course = '$studentExtras->pgCourse',
            pg_maximum_marks_cgpa = '$studentExtras->pgMaximumMarksCgpa',
            pg_total_marks_cgpa_obtained = '$studentExtras->pgTotalMarksCgpaObtained',
            pg_percentage = '$studentExtras->pgPercentage',
            course_of_10th_studied = '$studentExtras->courseOf10thStudied',
            place_of_10th_studied = '$studentExtras->placeOf10thStudied',
            state_of_10th_studied = '$studentExtras->stateOf10thStudied',
            course_of_12th_studied = '$studentExtras->courseOf12thStudied',
            place_of_12th_studied = '$studentExtras->placeOf12thStudied',
            state_of_12th_studied = '$studentExtras->stateOf12thStudied',
            diploma_qualifying_exam_board = '$studentExtras->diplomaQualifyingExamBoard',
            diploma_college_name = '$studentExtras->diplomaCollegeName',
            state_of_diploma_studied = '$studentExtras->stateOfDiplomaStudied',
            diploma_month_year_of_passing = '$studentExtras->diplomaMonthYearOfPassing',
            ug_qualifying_exam_board = '$studentExtras->ugQualifyingExamBoard',
            ug_college_name = '$studentExtras->ugCollegeName',
            course_of_ug_studied = '$studentExtras->courseOfUgStudied',
            place_of_ug_studied = '$studentExtras->placeOfUgStudied',
            state_of_ug_studied = '$studentExtras->stateOfUgStudied',
            ug_registration_no = '$studentExtras->ugRegistrationNo',
            ug_month_year_of_passing = '$studentExtras->ugMonthYearOfPassing',
            pg_qualifying_exam_board = '$studentExtras->pgQualifyingExamBoard',
            pg_college_name = '$studentExtras->pgCollegeName',
            course_of_pg_studied = '$studentExtras->courseOfPgStudied',
            place_of_pg_studied = '$studentExtras->placeOfPgStudied',
            state_of_pg_studied = '$studentExtras->stateOfPgStudied',
            pg_registration_no = '$studentExtras->pgRegistrationNo',
            pg_month_year_of_passing = '$studentExtras->pgMonthYearOfPassing',
            maximum_marks_in_pcm = '$studentExtras->maximumMarksInPcm',
            twelth_month_and_year = '$studentExtras->twelthMonthAndYear',
            chemistry_computer_electronics_marks = '$studentExtras->chemistryComputerElectronicsMarks',
            total_marks_obtained_in_pcm = '$studentExtras->totalMarksObtainedInPcm',
            pcm_percentage = '$studentExtras->pcmPercentage',
            ug_university = '$studentExtras->ugUniversity',
            documents_verification = '$studentExtras->documentsVerification'
            WHERE studentID = '$studentExtras->studentID'";
        try {
            return $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
}