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 / 146
CRAP
0.00% covered (danger)
0.00%
0 / 12416
ExamValuationService
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 146
4802672.00
0.00% covered (danger)
0.00%
0 / 12416
 __construct
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 2
 getAllSubjectsForCreatePacketByExamRegistrationId
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 28
 groupBySubjectId
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 16
 saveSubjectAnswerSheetGroupBySubjects
0.00% covered (danger)
0.00%
0 / 1
110.00
0.00% covered (danger)
0.00%
0 / 88
 getNextPacketNumber
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 14
 saveExamValuationSubjectStaffRelation
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 33
 getFacultiesAssignedForSubjectValuation
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 20
 deleteExamValuationSubjectStaffRelation
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 15
 insertExamValuationSubjectStaffRelation
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 40
 printSubjectPacketReport
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 55
 getpacketAssignedSubjects
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 43
 printAssignedSatffsReport
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 64
 getAssignedStaffsForSubjectPacketByAcademicPaperId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 20
 getAllExternalMarkEntryDetailsForDirectMethod
0.00% covered (danger)
0.00%
0 / 1
600.00
0.00% covered (danger)
0.00%
0 / 97
 getAllStudentExternalMarksByExamRegistrationSubject
0.00% covered (danger)
0.00%
0 / 1
650.00
0.00% covered (danger)
0.00%
0 / 181
 saveAllExternalMarkEntryDetailsForDirectMethod
0.00% covered (danger)
0.00%
0 / 1
1122.00
0.00% covered (danger)
0.00%
0 / 243
 deleteExemptedStudents
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 insertExemptedStudents
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 printExternalMarkEntryDetailsForDirect
0.00% covered (danger)
0.00%
0 / 1
156.00
0.00% covered (danger)
0.00%
0 / 75
 printExternalMarkEntryDetailsForBarcode
0.00% covered (danger)
0.00%
0 / 1
420.00
0.00% covered (danger)
0.00%
0 / 109
 getAllExternalMarkEntryDetailsForBarcodeMethod
0.00% covered (danger)
0.00%
0 / 1
132.00
0.00% covered (danger)
0.00%
0 / 57
 getAllFacultiesFromExternalDepartment
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 18
 insertThirdValStudentRegistration
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 20
 deleteThirdValStudentRegistration
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 getIsTheoryOrNotByExamRegistrationIdAndPaperSubjectId
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 30
 getStudentsExternalMarksByStudentExamDetail
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 75
 getStudentsExternalMarksByStudentExamDetailForExamRegistration
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 49
 updateValuatedStaffToStudentRegistration
0.00% covered (danger)
0.00%
0 / 1
90.00
0.00% covered (danger)
0.00%
0 / 37
 updateisRevaluedFlagStatus
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 19
 getStudentMarkEntryStatusDetailsForBarcodeMethod
0.00% covered (danger)
0.00%
0 / 1
702.00
0.00% covered (danger)
0.00%
0 / 105
 getCountOfValuatedStudentBypacketNo
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 31
 getAllRegisteredStudentByExamRegistrationAndAcademicPaperSubject
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 56
 saveAllExternalMarkEntryDetailsForBarcodeMethod
0.00% covered (danger)
0.00%
0 / 1
462.00
0.00% covered (danger)
0.00%
0 / 122
 saveExamValuationStudentmarksForBarcode
0.00% covered (danger)
0.00%
0 / 1
2256.00
0.00% covered (danger)
0.00%
0 / 295
 getAllStudentsExternalMarksByStudentExamDetailForExamRegistration
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 40
 getFacultiesByFacultyIds
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 18
 getSubjectDetailsByAcademicPaperSubjectIdAndExamRegistrationId
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 40
 getAllStudentsMarksDetailsForExamRegistrationSubject
0.00% covered (danger)
0.00%
0 / 1
1056.00
0.00% covered (danger)
0.00%
0 / 172
 printStudentMarkForEditExtrenalMark
0.00% covered (danger)
0.00%
0 / 1
870.00
0.00% covered (danger)
0.00%
0 / 161
 getSubjectDetailsByAcademicPaperSubjectId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 25
 saveAllEditExternalMarks
0.00% covered (danger)
0.00%
0 / 1
4970.00
0.00% covered (danger)
0.00%
0 / 481
 getFormulaByExamRegId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 21
 getAllSubjectsByStudentRegisterNo
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 46
 saveEditMarkByRegisterNo
0.00% covered (danger)
0.00%
0 / 1
702.00
0.00% covered (danger)
0.00%
0 / 195
 getStaffNameByStaffId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 saveExamEditLog
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getSubjectsForStaffSideMarkEntry
0.00% covered (danger)
0.00%
0 / 1
1560.00
0.00% covered (danger)
0.00%
0 / 136
 getSubjectDetailsForStaffSideMarkEntry
0.00% covered (danger)
0.00%
0 / 1
29412.00
0.00% covered (danger)
0.00%
0 / 543
 getStatusForRegisterNumberOrFalaseNumber
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 44
 getCurrentStaffValuatedStudentDetails
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 64
 getStudentMarkEntryStatusDetailsForStaffSideMarkEntry
0.00% covered (danger)
0.00%
0 / 1
2550.00
0.00% covered (danger)
0.00%
0 / 211
 saveAllExternalMarkDetailsForStaffSideMarkEntry
0.00% covered (danger)
0.00%
0 / 1
4692.00
0.00% covered (danger)
0.00%
0 / 280
 saveExamValuationStudentmarksForStaffSideMarkEntry
0.00% covered (danger)
0.00%
0 / 1
17030.00
0.00% covered (danger)
0.00%
0 / 601
 deleteExtrenalMarkByStaffSide
0.00% covered (danger)
0.00%
0 / 1
420.00
0.00% covered (danger)
0.00%
0 / 115
 submitExtrenalMarkStatusByStaffSide
0.00% covered (danger)
0.00%
0 / 1
182.00
0.00% covered (danger)
0.00%
0 / 90
 updateValuatedStaffToExamRegistraionSubject
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 27
 saveExtrenalMarkStatusByStaffSide
0.00% covered (danger)
0.00%
0 / 1
182.00
0.00% covered (danger)
0.00%
0 / 99
 printExtrenalMarkReportByStaffSide
0.00% covered (danger)
0.00%
0 / 1
506.00
0.00% covered (danger)
0.00%
0 / 147
 getCourseTypeIdByExamRegistrationIdAndPaperSubjectId
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 32
 getAllSubjectsForQPCodeByExamRegistrationId
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 43
 saveAllSubjectqpCodes
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 30
 insertSubjectQpCode
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 printSubjectQpCodeReport
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 56
 getStuentStatusForStaffSideMarkEntry
0.00% covered (danger)
0.00%
0 / 1
210.00
0.00% covered (danger)
0.00%
0 / 49
 getStudentCountForExamRegistrationSubject
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 120
 printStudentDetailsForStaffSideMarkEntry
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 36
 getDetailsForPrintStudentDetailsReport
0.00% covered (danger)
0.00%
0 / 1
1056.00
0.00% covered (danger)
0.00%
0 / 150
 getSubjectDetailsForStaffSideMarkEntryDigitalValuation
0.00% covered (danger)
0.00%
0 / 1
1560.00
0.00% covered (danger)
0.00%
0 / 119
 setAdditionalExaminers
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 4
 isStudentAssignedToSlecetedAdditionalValuer
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 10
 getPreviousMarkEntryConfirmedStatus
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 setBlockValuationMessage
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 6
 getAllStudentByExamRegistrationSubjectInDigitalValuationForCurrentStaff
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 51
 getSubjectsForFinalizeMark
0.00% covered (danger)
0.00%
0 / 1
1406.00
0.00% covered (danger)
0.00%
0 / 175
 getAllStudentByExamRegistrationSubjectForDigitalValuation
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 86
 getAllStudentByRevaluationRegistrationSubjectForDigitalValuation
0.00% covered (danger)
0.00%
0 / 1
90.00
0.00% covered (danger)
0.00%
0 / 118
 getTotalCountOfThirdValuationStudentsForExamRegistrationSubject
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 56
 finalizeDigitalValuationMarks
0.00% covered (danger)
0.00%
0 / 1
2550.00
0.00% covered (danger)
0.00%
0 / 221
 printfinalizeMarkReport
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 39
 getAllPacketDetailsBySubjectForStaffSideMarkEntry
0.00% covered (danger)
0.00%
0 / 1
210.00
0.00% covered (danger)
0.00%
0 / 76
 getAllStudentStaffDetailsWithOrderForStaffSideMarkEntry
0.00% covered (danger)
0.00%
0 / 1
6320.00
0.00% covered (danger)
0.00%
0 / 193
 getAllStudentsMarksWithFalseNumberOrder
0.00% covered (danger)
0.00%
0 / 1
90.00
0.00% covered (danger)
0.00%
0 / 79
 saveStudentMarksDetailsWithOrderForStaffSideMarkEntry
0.00% covered (danger)
0.00%
0 / 1
992.00
0.00% covered (danger)
0.00%
0 / 148
 saveExamValuationStudentmarksWithOrderForStaffSideMarkEntry
0.00% covered (danger)
0.00%
0 / 1
4290.00
0.00% covered (danger)
0.00%
0 / 471
 saveExtrenalMarkStatusByStaffSideWithPacketNo
0.00% covered (danger)
0.00%
0 / 1
132.00
0.00% covered (danger)
0.00%
0 / 57
 printStudentStaffDetailsWithOrderForStaffSideMarkEntry
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 82
 getAllAbsentStudentDetailsForSpecialExam
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 48
 getAllAbsentStudentDetails
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 58
 assignStudentsToSpecialExam
0.00% covered (danger)
0.00%
0 / 1
156.00
0.00% covered (danger)
0.00%
0 / 43
 removeStudentsToSpecialExam
0.00% covered (danger)
0.00%
0 / 1
110.00
0.00% covered (danger)
0.00%
0 / 27
 insertStudentAssessmentResistrationDetails
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 14
 insertExamRegistrationRetestMappingDetails
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 deleteStudentAssessmentResistrationDetails
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 getAllStudentStaffDetailsWithOrderForStaffSideRevaluationMarkEntry
0.00% covered (danger)
0.00%
0 / 1
182.00
0.00% covered (danger)
0.00%
0 / 80
 getAllAvailableStudentDetails
0.00% covered (danger)
0.00%
0 / 1
462.00
0.00% covered (danger)
0.00%
0 / 83
 assignSlNo
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 7
 getAllValuationRule
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 17
 getFinalizedMarkFromValuationRule
0.00% covered (danger)
0.00%
0 / 1
272.00
0.00% covered (danger)
0.00%
0 / 46
 getExternalValuationMarkDifference
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 18
 countOfEvaluatedStudentsByOnlineExam
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 33
 checkIfMarkConfirmForDigitalValuation
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 34
 getSubjectsForStaffSideMarkEntryRevaluation
0.00% covered (danger)
0.00%
0 / 1
462.00
0.00% covered (danger)
0.00%
0 / 84
 getSubjectDetailsForStaffSideMarkEntryDigitalValuationRevaluation
0.00% covered (danger)
0.00%
0 / 1
420.00
0.00% covered (danger)
0.00%
0 / 96
 getMarkLogReport
0.00% covered (danger)
0.00%
0 / 1
90.00
0.00% covered (danger)
0.00%
0 / 70
 getExternalMarkLogReport
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 62
 getAllStudentValuationMarkForDigitalValuation
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 79
 getSubjectsForRemoveMarkEntryConfirmedState
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 24
 getStudentsForRemoveMarkEntryConfirmedState
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 18
 removeStudentsFromConfirmedState
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 34
 getStudentsForRemoveConfirmedState
0.00% covered (danger)
0.00%
0 / 1
90.00
0.00% covered (danger)
0.00%
0 / 85
 saveExamRegistrationAdditionalMark
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 49
 getExamRegistrationAdditionalMark
0.00% covered (danger)
0.00%
0 / 1
110.00
0.00% covered (danger)
0.00%
0 / 59
 saveStudentAssessmentAdditionalMark
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 47
 deleteStudentAssessmentAdditionalMark
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 24
 getStudentDetailsForSgpaDirectEntry
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 61
 saveStudentDetailsForSgpaDirectEntry
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 49
 getSubjectsForVivaValuationStaff
0.00% covered (danger)
0.00%
0 / 1
90.00
0.00% covered (danger)
0.00%
0 / 50
 getStudentDetailsForVivaValuationStaff
0.00% covered (danger)
0.00%
0 / 1
342.00
0.00% covered (danger)
0.00%
0 / 78
 getRegisteredStudentsForVivaValuationStaff
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 70
 saveAllExternalMarkDetailsForVivaValuationStaff
0.00% covered (danger)
0.00%
0 / 1
1056.00
0.00% covered (danger)
0.00%
0 / 158
 getCourseTypeIdByExamRevaluationIdAndPaperSubjectId
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 38
 countOfEvaluatedStudentsConfimeredByOnlineExam
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 34
 copyStudentPreviousDigitalValuationMarks
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 30
 getSubjectDetailsForValuerReviewerMarkEntryDigitalValuation
0.00% covered (danger)
0.00%
0 / 1
4032.00
0.00% covered (danger)
0.00%
0 / 230
 finalizeDigitalValuationMarksWithOutThirdValuation
0.00% covered (danger)
0.00%
0 / 1
1640.00
0.00% covered (danger)
0.00%
0 / 159
 getSubjectPacketIssuedDetails
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 47
 getIssuedPacketDetails
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 25
 issuePacketToStaffForValuation
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 32
 updatePacketIssuedReturnDate
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 16
 getAllStudentStaffDetailsWithOrderForStaffSideMarkEntryRevaluation
0.00% covered (danger)
0.00%
0 / 1
650.00
0.00% covered (danger)
0.00%
0 / 100
 getAllStudentsMarksWithFalseNumberOrderForRevaluation
0.00% covered (danger)
0.00%
0 / 1
72.00
0.00% covered (danger)
0.00%
0 / 178
 saveStudentMarksDetailsWithOrderForStaffSideMarkEntryRevaluation
0.00% covered (danger)
0.00%
0 / 1
182.00
0.00% covered (danger)
0.00%
0 / 113
 saveExtrenalMarkStatusByStaffSideWithPacketNoRevaluation
0.00% covered (danger)
0.00%
0 / 1
132.00
0.00% covered (danger)
0.00%
0 / 59
 saveExamValuationStudentmarksWithOrderForStaffSideMarkEntryRevaluation
0.00% covered (danger)
0.00%
0 / 1
1056.00
0.00% covered (danger)
0.00%
0 / 275
 printPacketIssueRegister
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 56
 getAllFalseNoStudentsMarksDetailsForExamRegistrationSubject
0.00% covered (danger)
0.00%
0 / 1
2352.00
0.00% covered (danger)
0.00%
0 / 216
 checkFalseNumberGenerated
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 9
 saveAllExternalMarks
0.00% covered (danger)
0.00%
0 / 1
5550.00
0.00% covered (danger)
0.00%
0 / 530
 filterOutCurrentValuationConfirmedMarkStudents
0.00% covered (danger)
0.00%
0 / 1
210.00
0.00% covered (danger)
0.00%
0 / 19
 getAllStudentEditExternalMarksByExamRegistrationSubject
0.00% covered (danger)
0.00%
0 / 1
702.00
0.00% covered (danger)
0.00%
0 / 186
 getStudentDigitalValuationMarks
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 10
 getValuatedStaffsFiltered
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 25
 filterStaffsByValuationCount
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 8
 getOeMarksStudentList
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 24
 submitRemunerationBill
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 21
 getFinalizedStatusOfStudentMark
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 49
<?php
namespace com\linways\ec\core\service;
use com\linways\base\util\TwigRenderer;
use com\linways\base\util\SecurityUtils;
use com\linways\base\util\MakeSingletonTrait;
use com\linways\core\ams\professional\util\PdfUtil;
use com\linways\core\ams\professional\util\CommonUtil;
use com\linways\core\ams\professional\constant\ExamType; 
use com\linways\ec\core\service\ExamRegistrationService;
use com\linways\core\ams\professional\service\ExamService;
use com\linways\core\ams\professional\service\MarkService;
use com\linways\ec\core\exception\ExamControllerException;
use com\linways\core\ams\professional\service\CommonService;
use com\linways\core\ams\professional\dto\SettingsConstents;
use com\linways\ec\core\request\SearchExamRegistrationRequest;
use com\linways\ec\core\service\ExamRegistrationSubjectService;
use com\linways\core\ams\professional\service\CourseTypeService;
use com\linways\core\ams\professional\dto\examcontroller\exam\StudentMarkEditLog;
use com\linways\ec\core\service\CommonExamService;
use com\linways\ec\core\service\StudentExamRegistrationService;
use com\linways\core\ams\professional\service\StaffService;
use com\linways\core\ams\professional\request\api\GetAllFacultiesRequest;
use com\linways\oe\core\service\ExamUserMarkService;
use com\linways\oe\core\request\ExamUserMarkRequest;
use com\linways\ec\core\service\StudentsOverAllMarkReportService;
use com\linways\core\ams\professional\logging\AMSLogger;
use com\linways\ec\core\logging\Events;
use com\linways\ec\core\logging\entities\Staff;
use com\linways\ec\core\constant\StatusConstants;
use com\linways\oe\core\request\ExamConfirmRequest;
use com\linways\oe\core\service\ExamUserService;
use com\linways\ec\core\service\ExamRevaluationService;
use com\linways\ec\core\request\SearchRuleRequest;
use com\linways\ec\core\service\RuleService;
use com\linways\core\ams\professional\service\examcontroller\examvaluationrule\ExamValuationRuleService;
use com\linways\ec\core\service\PacketService;
class ExamValuationService extends BaseService
{
    use MakeSingletonTrait;
    private function __construct() {
        $this->logger = AMSLogger::getLogger('exam-controller-log');
    }
     /**
     * get All Subjects For Create Packet
     * @param $examRegistrationId 
     * @param $examRegistrationBatchId
     * @return $subjects 
     */
    public function getAllSubjectsForCreatePacketByExamRegistrationId($searchRequest) {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $subjects =  ExamRegistrationBatchService::getInstance()->getAssignedSubjectByBatchOrExamReg($searchRequest);
            foreach($subjects as $subject){
                $staffIdsArray = [];
                $deptIdsArray = [];
                $subject->answerGroupDetails = ExamRegistrationSubjectService::getInstance()->getAsnwerGroupConfigDetailsByExamRegistrationAndAcademicPaperSubject($searchRequest->examRegistrationId,$subject->id);
                $assignedStaffs = $this->getAssignedStaffsForSubjectPacketByAcademicPaperId($searchRequest->examRegistrationId,$subject->id);
                foreach($assignedStaffs as $staffId){
                    $staffIdsArray[] = $staffId->staffId;
                }
                $subject->staffs = $staffIdsArray;
                if(!empty($staffIdsArray)){
                    $departments = CommonExamService::getInstance()->getDepartmentsByAssignedStaffs($subject->staffs);
                    foreach($departments as $department) {
                        $deptIdsArray[] = $department->deptId;
                    }
                }
                $subject->departments = $deptIdsArray;
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        $subjects = $this->groupBySubjectId($subjects);
        return $subjects;
    }
    private function groupBySubjectId($subjects){
        $groupedSubjects = [];
        foreach($subjects as $subject){
            if(!isset($groupedSubjects[$subject->subjectId])){
                $subject->answerGroupDetails->paperSubjectIds[] = $subject->answerGroupDetails->paperSubjectId;
                $groupedSubjects[$subject->subjectId] = $subject;
                $groupedSubjects[$subject->subjectId]->registeredStudentCounts[$subject->answerGroupDetails->paperSubjectId] = $subject->answerGroupDetails->registeredStudentCount;
            }else{
                if(!$subject->answerGroupDetails->id){
                    $groupedSubjects[$subject->subjectId]->answerGroupDetails->registeredStudentCount = $groupedSubjects[$subject->subjectId]->answerGroupDetails->registeredStudentCount +$subject->answerGroupDetails->registeredStudentCount;
                }
                $groupedSubjects[$subject->subjectId]->registeredStudentCounts[$subject->answerGroupDetails->paperSubjectId] = $subject->answerGroupDetails->registeredStudentCount;
                $groupedSubjects[$subject->subjectId]->answerGroupDetails->paperSubjectIds[] = $subject->answerGroupDetails->paperSubjectId;
            }
        }
        return array_values($groupedSubjects);
    }
    /**
     * save All Subjects For AnswerSheet Group
     * @param $subjects 
     * @return $subjects 
     */
    public function saveSubjectAnswerSheetGroupBySubjects($subjects){
        $subjects = $this->realEscapeArray($subjects);
        $error = 0;
        $noStudentsInSubject = [];
        $configInsertValues  = [];
        try{
            $newSubjects = [];
            $configInsertQuery = "INSERT INTO 
                                        exam_examReg_subject_answerSheet_group_config 
                                        ( ec_exam_registration_id,
                                         cm_academic_paper_subjects_id, 
                                         registeredStudentCount, 
                                         studentsPerAnswerSheetGroup, 
                                         studentsPerAnswerSheetGroupCount, 
                                         createdBy, 
                                         createdDate, 
                                         updatedBy, 
                                         updatedDate) 
                                    VALUES ";
            foreach($subjects as $subject){
                if($subject['answerGroupDetails']['registeredStudentCount'] > 0){
                    $subject['answerGroupDetails']['studentsPerAnswerSheetGroupCount'] = ceil($subject['answerGroupDetails']['registeredStudentCount']/$subject['answerGroupDetails']['studentsPerAnswerSheetGroup']);
                    foreach($subject['answerGroupDetails']['paperSubjectIds'] as $paperSubjectId){
                        $subject['answerGroupDetails']['createdBy'] = $GLOBALS['userId'];
                        $subject['answerGroupDetails']['updatedBy'] = $GLOBALS['userId'];
                        if($subject['answerGroupDetails']['id'] == NULL) {
                            $configInsertValues[] = "(
                                '".$subject['answerGroupDetails']['examRegistrationId']."',
                                '".$paperSubjectId."',
                                ".$subject['answerGroupDetails']['registeredStudentCount'].",
                                ".$subject['answerGroupDetails']['studentsPerAnswerSheetGroup'].",
                                ".$subject['answerGroupDetails']['studentsPerAnswerSheetGroupCount'].",
                                ".$subject['answerGroupDetails']['createdBy'] .",
                                utc_timestamp(),
                                ".$subject['answerGroupDetails']['updatedBy'].",
                                utc_timestamp()
                            )";
                            $newSubjects[$subject['subjectId']][$paperSubjectId] = $subject;
                        }
                    }
                }
                else{
                    $noStudentsInSubject[] = $subject['answerGroupDetails']['examRegistrationId'];
                    $error = 1;
                }
            }
            if(! empty($configInsertValues)){
                $configInsertQuery = $configInsertQuery . implode ( ",", $configInsertValues );
                $this->executeQuery($configInsertQuery);
            }
            else if($error){
                throw new ExamControllerException(ExamControllerException::NO_REGISTERED_STUDENTS_IN_SUBJECTS,"No Registered Students In Subject(s)");
            }
            else{
                throw new ExamControllerException(ExamControllerException::ALREADY_CREATED_SUBJECT_PACKETS,"Already Created Subject Packet For This Exam Registration");
            }
            foreach($newSubjects as $subject){
                foreach($subject as $paperSubjectId => $paperSubject){
                    $examRegistrationId = $paperSubject['answerGroupDetails']['examRegistrationId'];
                    $academicPaperId = $paperSubjectId;
                    $packetNo = $this->getNextPacketNumber ( $examRegistrationId );
                    $getValuesSql ="SELECT 
                                CONCAT('\'', ec_exam_registration_id, '\'') AS ec_exam_registration_id, 
                                CONCAT('\'', cm_academic_paper_subjects_id, '\'') AS cm_academic_paper_subjects_id,
                            @packetNo := @packetNo + 1 packetStartNo, 
                            @packetNo := (@packetNo + studentsPerAnswerSheetGroupCount - 1) packetEndNo, 
                            id 
                        FROM 
                            (SELECT @packetNo:= $packetNo - 1) a, 
                            exam_examReg_subject_answerSheet_group_config 
                        WHERE 
                            ec_exam_registration_id = '$examRegistrationId'  AND 
                            cm_academic_paper_subjects_id = '$academicPaperId' AND 
                            id NOT IN (SELECT examReg_subject_answerSheet_group_config_id 
                                        FROM exam_examReg_subject_answerSheet_group)";
                    $insertValues[] = "(".implode(',',(array)$this->executeQueryForObject($getValuesSql)).")";
                }
                $query = "INSERT INTO 
                exam_examReg_subject_answerSheet_group 
                (ec_exam_registration_id, cm_academic_paper_subjects_id, packet_start_no, packet_end_no, examReg_subject_answerSheet_group_config_id) VALUES".implode(',',$insertValues);
                $this->executeQuery($query);
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $subjects;
       
    }
    /**
     * get Next Packet Number
     * @param $examRegistrationId 
     * @return $packetNo 
     */
    public function getNextPacketNumber($examRegistrationId){
        $examRegistrationId = $this->realEscapeString($examRegistrationId);
        try{
            $query = "SELECT IF(esag.packet_end_no, MAX(esag.packet_end_no) + 1, 1) AS packetNo 
                        FROM 
                            exam_examReg_subject_answerSheet_group esag 
                        WHERE 
                            esag.ec_exam_registration_id = '$examRegistrationId'"; 
            $packetNo = $this->executeQueryForObject($query)->packetNo;
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $packetNo;
        
    }
    /**
     * Save saveExamValuationSubjectStaffRelation
     * @param SubjectId $academicPaperId
     * @param ExamRegistrationId $examRegistrationId
     * @param $staffIds
     */
    public function saveExamValuationSubjectStaffRelation($examRegistrationId,$academicPaperId,$staffIds){
        $examRegistrationId = $this->realEscapeString($examRegistrationId);
        if(is_array($academicPaperId)){
            $academicPaperIds = $this->realEscapeArray($academicPaperId);
        }else{
            $academicPaperId = $this->realEscapeString($academicPaperId);
            $academicPaperIds = [$academicPaperId];
        }
        $staffIds = $this->realEscapeArray($staffIds);
        try{
            foreach($academicPaperIds as $academicPaperId){
                $subjectStaffRelation = new \stdClass;
                $existingValuationStaffArr = [];
                $existingValuationStaff = $this->getFacultiesAssignedForSubjectValuation ($examRegistrationId,$academicPaperId);
                foreach ( $existingValuationStaff as $staff ) {
                    $existingValuationStaffArr[] = $staff->staffId;
                }
                $staffsToBeDeleted = array_diff ( $existingValuationStaffArr, $staffIds );
                $staffsToBeAdded = array_diff ( $staffIds, $existingValuationStaffArr );
                if ( !empty ( $staffsToBeDeleted ) ) {
                    $subjectStaffRelation->staff = $staffsToBeDeleted;
                    $subjectStaffRelation->examRegistrationId = $examRegistrationId; 
                    $subjectStaffRelation->academicPaperId = $academicPaperId; 
                    $this->deleteExamValuationSubjectStaffRelation ( $subjectStaffRelation );
                }
                if ( !empty ( $staffsToBeAdded ) ) {
                    $this->insertExamValuationSubjectStaffRelation ( $staffsToBeAdded,$examRegistrationId,$academicPaperId );
                }
            }
        }
        catch (\Exception $e){
            throw new ExamControllerException(ExamControllerException::ERROR_ASSIGNING_STAFF_TO_SUBJECT_PACKET,"Error While Asigning Staff To Subject. Please Contact Administrator");
        }
       
    }
    /**
     * get Faculties Assigned For Subject Valuation
     * @param SubjectId $academicPaperSubjectsId
     * @param ExamRegistrationId $examRegistrationId
     */
    public function getFacultiesAssignedForSubjectValuation($examRegistrationId,$academicPaperSubjectsId){
        $examRegistrationId = $this->realEscapeString($examRegistrationId);
        $academicPaperSubjectsId = $this->realEscapeString($academicPaperSubjectsId);
        try {
            $query = "SELECT
                        evfp.additionalEvaluator AS staffId,
                        sa.staffName as name
                    FROM
                        examValuationFacultyPackets evfp
                    INNER JOIN staffaccounts sa ON
                        sa.staffID = evfp.additionalEvaluator
                    WHERE
                        cm_academic_paper_subjects_id = '$academicPaperSubjectsId' AND 
                        ec_exam_registration_id = '$examRegistrationId'";
            $assignedStaffs  = $this->executeQueryForList($query);
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $assignedStaffs;
    }
    /**
     * delete Exam Valuation Subject Staff Relation
     * @param subjectStaffRelation $subjectStaffRelation
     */
    public function deleteExamValuationSubjectStaffRelation($subjectStaffRelation){
        $subjectStaffRelation = $this->realEscapeObject($subjectStaffRelation);
        try {
            $condition = null;
            $condition .= " AND additionalEvaluator IN (".implode(',', $subjectStaffRelation->staff ).") ";
            $query = "DELETE FROM 
                        examValuationFacultyPackets 
                    WHERE 
                        cm_academic_paper_subjects_id = '$subjectStaffRelation->academicPaperId' AND
                        ec_exam_registration_id = '$subjectStaffRelation->examRegistrationId$condition ";
            $this->executeQuery($query);
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
     /**
     * insert Exam Valuation Subject Staff Relation
     * @param  $staffsToBeAdded
     * @param ExamRegistrationId $examRegistrationId
     * @param SubjectId  $academicPaperId
     */
    public function insertExamValuationSubjectStaffRelation($staffsToBeAdded,$examRegistrationId,$academicPaperId )
    {
        $examRegistrationId = $this->realEscapeString($examRegistrationId);
        $academicPaperId = $this->realEscapeString($academicPaperId);
        $staffsToBeAdded = $this->realEscapeArray($staffsToBeAdded);
        try 
        {
            $values = [];
            $createdBy = $GLOBALS['userId'];
            $updatedBy = $GLOBALS['userId'];
            foreach($staffsToBeAdded as $staffId)
            {
                $values[] = " (
                    '".$examRegistrationId."',
                    '".$academicPaperId."',
                    ".$staffId.",
                    ".$createdBy.",
                    utc_timestamp(),
                    ".$updatedBy.",
                    utc_timestamp()
                )";
            }
            if ( !empty ( $values ) ) {
                $sql = "INSERT INTO 
                            examValuationFacultyPackets
                             (ec_exam_registration_id, 
                             cm_academic_paper_subjects_id, 
                             additionalEvaluator,
                             created_by, 
                             created_date, 
                             updated_by, 
                             updated_date) 
                        VALUES " . implode ( ",", $values ) ;
                $this->executeQuery($sql);
            }
          
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
     /**
     * print Subject Packet Report
     * @param ExamRegistrationId $examRegistrationId
     */
    public function printSubjectPacketReport($examRegistrationId,$academicTermId = null){
        $examRegistrationId = $this->realEscapeString($examRegistrationId);
        $academicTermId = $this->realEscapeString($academicTermId);
        try{
            $subjects = [];
            $currentExamRegistrationDetails = NULL;
            $subjects = $this->getpacketAssignedSubjects($examRegistrationId,$academicTermId,true);
            usort($subjects, function($a, $b) {
                return (int)$a->answerSheetRangeFrom - (int)$b->answerSheetRangeFrom;
            });
            $subjects = array_values(array_reduce($subjects, function($carry, $subject) {
                $carry[$subject->answerSheetRangeFrom] = $subject;
                return $carry;
            }, []));
            if(empty($subjects)){
                throw new ExamControllerException(ExamControllerException::PACKETS_NOT_GENERATED,"Packets Are Not Generated,Please Assign Subject Packets");
            }
            else{
                $requestForExamRegistration = new SearchExamRegistrationRequest;
                $requestForExamRegistration->id = $examRegistrationId;
                $examRegistration = ExamRegistrationService::getInstance()->searchExamRegistration($requestForExamRegistration);
                if(!empty($examRegistration))
                {
                    $currentExamRegistrationDetails = $examRegistration[0];
                }
                $studentsPerAnswerSheetGroup = CommonService::getInstance()->getSettings("EXAM_VALUATION", "ANSWERSHEETS_PER_PACKET");
                $templateName = "PrintSubjectPacketReport";
                $responseHtml = TwigRenderer::renderTemplateFileToHtml(realpath(DOCUMENT_ROOT."../examcontroller-api/src/com/linways/web/templates/printTwigs/$templateName.twig"), [ 'subjects'=>$subjects ,'studentsPerAnswerSheetGroup'=>$studentsPerAnswerSheetGroup ,'examRegistration'=>$currentExamRegistrationDetails]);
                $prtContent = NULL;
                    $prtContent .= '<html><head>';
                    $prtContent .= "<style>
                        
                        </style>";
                    $prtContent .= '</head><title>Subject Packet Relation Report</title><body>';
                    $prtContent .= $responseHtml;
                    $prtContent .= '</body></html>';
                    $totalWidth = 210;
                    $totalHeight = 297;
                    $options = array(
                        'page-width'     => $totalWidth."mm",
                        'page-height'    => $totalHeight."mm",
                        'dpi'            => 96,
                        'margin-top' => "9mm",
                        'margin-left' => "1mm",
                        'margin-right' => "1mm",
                        'margin-bottom' => "9mm",
                        // 'binary' => "/usr/local/bin/wkhtmltopdf", // For Mac
                        'user-style-sheet' => realpath(DOCUMENT_ROOT . "/libcommon/bootstrap/css/bootstrap.min.css")
                    );
                $programResult = new \stdClass;
                $programResult->displayData = $responseHtml;
                $programResult->pdf = PdfUtil::renderPdf($prtContent, $options);
                return  $programResult;
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * get packet Assigned Subjects
     * @param ExamRegistrationId $examRegistrationId
     */
    public function getpacketAssignedSubjects($examRegistrationId,$academicTermId = null,$groupByAcademicPaperSubject = null){
        $examRegistrationId = $this->realEscapeString($examRegistrationId);
        $academicTermId = $this->realEscapeString($academicTermId);
        $whereQuery = "";
        if($academicTermId) {
            $whereQuery .= " AND eerb.academicTermId IN ('$academicTermId') ";
        }
        $groupBy = '';
        if($groupByAcademicPaperSubject){
            $groupBy = " GROUP BY eers.cm_academic_paper_subjects_id";
        }
        $orderBy =" ORDER BY eers.created_date ASC";
        try{
            $query = "SELECT
                        DISTINCT eers.cm_academic_paper_subjects_id as id,
                        s.code as subjectCode,
                        s.name as subjectName,
                        eers.id as examRegistrationSubjectId,
                        eesagc.registeredStudentCount,
                        eesagc.studentsPerAnswerSheetGroup,
                        eesag.packet_start_no AS answerSheetRangeFrom,
                        eesag.packet_end_no AS answerSheetRangeTo,
                        eesagc.studentsPerAnswerSheetGroupCount
                    FROM
                        ec_exam_registration_subject eers
                    INNER JOIN ec_exam_registration_batch eerb ON
                            eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN  cm_academic_paper_subjects aps ON 
                            eers.cm_academic_paper_subjects_id = aps.id
                    INNER JOIN  v4_ams_subject s ON 
                            aps.ams_subject_id = s.id
                    RIGHT JOIN  exam_examReg_subject_answerSheet_group eesag ON 
                        eesag.cm_academic_paper_subjects_id = aps.id
                    LEFT JOIN  exam_examReg_subject_answerSheet_group_config eesagc ON 
                        eesag.examReg_subject_answerSheet_group_config_id = eesagc.id
                    WHERE
                        eerb.ec_exam_registration_id='$examRegistrationId'";
            $subjects = $this->executeQueryForList($query.$whereQuery.$groupBy.$orderBy);
            return $subjects;
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * print Assigned Satffs Report
     * @param ExamRegistrationId $examRegistrationId
     */
    public function printAssignedSatffsReport($examRegistrationId,$academicTermId = null){
        $examRegistrationId = $this->realEscapeString($examRegistrationId);
        $academicTermId = $this->realEscapeString($academicTermId);
        try{
            $subjects = [];
            $currentExamRegistrationDetails = NULL;
            $searchRequest = new \stdClass;
            $searchRequest->examRegistrationId = $examRegistrationId;
            $searchRequest->academicTermId = $academicTermId;
            $searchRequest->groupByAcademicPaperSubject = true;
            $subjects = $this->getAllSubjectsForCreatePacketByExamRegistrationId($searchRequest);
            if(empty($subjects)){
                throw new ExamControllerException(ExamControllerException::PACKETS_NOT_GENERATED,"Packets Are Not Generated,Please Assign Subject Packets");
            }
            else{
                foreach($subjects as $subject){
                    $assignedstaffNames = [];
                    $assignedStaffs = $this->getAssignedStaffsForSubjectPacketByAcademicPaperId($examRegistrationId,$subject->id);
                    if(empty($assignedStaffs)){
                        $assignedstaffNames[] = "No Staffs Assigned"; 
                    }
                    else{
                        foreach($assignedStaffs as $assignedStaff){
                            $assignedstaffNames[] = $assignedStaff->staffName;
                        }
                    }
                    $subject->assignedStaff = implode ( ",", $assignedstaffNames );
                }
                $requestForExamRegistration = new SearchExamRegistrationRequest;
                $requestForExamRegistration->id = $examRegistrationId;
                $examRegistration = ExamRegistrationService::getInstance()->searchExamRegistration($requestForExamRegistration);
                if(!empty($examRegistration)){
                    $currentExamRegistrationDetails = $examRegistration[0];
                }
                $templateName = "PrintSubjectAssignedStaffReport";
                $responseHtml = TwigRenderer::renderTemplateFileToHtml(realpath(DOCUMENT_ROOT."../examcontroller-api/src/com/linways/web/templates/printTwigs/$templateName.twig"), [ 'subjects'=>$subjects ,'examRegistration'=>$currentExamRegistrationDetails]);
                $prtContent = NULL;
                    $prtContent .= '<html><head>';
                    $prtContent .= "<style>
                        
                        </style>";
                    $prtContent .= '</head><title>Subject Assigned Staff Report </title><body>';
                    $prtContent .= $responseHtml;
                    $prtContent .= '</body></html>';
                    $totalWidth = 210;
                    $totalHeight = 297;
                    $options = array(
                        'page-width'     => $totalWidth."mm",
                        'page-height'    => $totalHeight."mm",
                        'dpi'            => 96,
                        'margin-top' => "9mm",
                        'margin-left' => "1mm",
                        'margin-right' => "1mm",
                        'margin-bottom' => "9mm",
                        // 'binary' => "/usr/local/bin/wkhtmltopdf", // For Mac
                        'user-style-sheet' => realpath(DOCUMENT_ROOT . "/libcommon/bootstrap/css/bootstrap.min.css")
                    );
                $programResult = new \stdClass;
                $programResult->displayData = $responseHtml;
                $programResult->pdf = PdfUtil::renderPdf($prtContent, $options);
                return  $programResult;
            }
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        
    }
    /**
     * get Assigned Staffs For Subject Packet By AcademicPaperId
     * @param ExamRegistrationId $examRegistrationId
     * @param SubjectId $academicPaperSubjectsId
     * @return $assignedStaffs
     */
    public function getAssignedStaffsForSubjectPacketByAcademicPaperId($examRegistrationId,$academicPaperSubjectsId){
        $examRegistrationId = $this->realEscapeString($examRegistrationId);
        $academicPaperSubjectsId = $this->realEscapeString($academicPaperSubjectsId);
        try {
            $query = "SELECT
                        evfp.additionalEvaluator AS staffId,
                        sa.staffName
                    FROM
                        examValuationFacultyPackets evfp
                    INNER JOIN staffaccounts sa ON
                            sa.staffID = evfp.additionalEvaluator
                    WHERE
                        cm_academic_paper_subjects_id = '$academicPaperSubjectsId' AND 
                        ec_exam_registration_id = '$examRegistrationId'";
            $assignedStaffs  = $this->executeQueryForList($query);
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $assignedStaffs;
    }
    /**
     * get All External Mark Entry Details For Direct Method
     * @param Request $searchRequest
     * @return $response
     */
    public function getAllExternalMarkEntryDetailsForDirectMethod($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try {
            $response = new \stdClass;
            $extraMarkObject = new \stdClass;
            $registeredStudentMarkDetails = [];
            $academicPaperId = stripslashes($searchRequest->academicPaperId);
            if($searchRequest->academicPaperIds){
                $academicPaperId = $searchRequest->academicPaperId = $searchRequest->academicPaperIds;
            }
            $markEntryEditSettings = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::EXAM_VALUATION_MARK_EDIT);
            $isFalseNumber = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::IS_FALSE_NUMBER_IN_EXTERNAL_MARK_ENTRY_DIRECT);
            $isRvStatus = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::IS_RC_STATUS_IN_EXTERNAL_MARK_ENTRY_DIRECT);
            $editEnabled = CommonUtil::isEditEnabledInExamValuation ( $markEntryEditSettings, ExamType::EXTERNAL );
            $maxmarkOfSubject = ExamRegistrationSubjectService::getInstance()->getMaxSubjectMarkByAcademicPaperSubjectId($academicPaperId);
            if($editEnabled){
                $request = new \stdClass;
                $request->examRegistrationId = $searchRequest->examRegistrationId;
                $request->academicPaperSubjectId = is_array($searchRequest->academicPaperId) ? $searchRequest->academicPaperId : stripslashes($searchRequest->academicPaperId);
                $request->groupId = $searchRequest->groupId;
                if ( $isFalseNumber == "ROLL_NUMBER"){
                    $request->isOrderByRollNo = 1;
                }
                $request->showFinalizedMarkOnly = 1;
                $registeredStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                if(empty($registeredStudentMarkDetails)){
                    throw new ExamControllerException(ExamControllerException::NO_STUDENTS_REGISTEDED_OR_PAID,"Student(s) Not Registered");
                }
                else if(! reset($registeredStudentMarkDetails)->isExternal){
                    throw new ExamControllerException(ExamControllerException::INTERNAL_ONLY_SUBJECT,"Internal Only Subject");
                }
                elseif(! reset($registeredStudentMarkDetails)->maximumSubjectMark){
                    throw new ExamControllerException(ExamControllerException::MAX_MARK_NOT_CONFIGURED,"Subject not configured");
                }
                $extraMarkObject->hasMultipleMarkEntry = 0;
                if ( reset($registeredStudentMarkDetails)->isTheory == 0 ){
                    $batchRequest = new \stdClass();
                    $batchRequest->groupId = $searchRequest->groupId;
                    $batchRequest->examRegistrationId = $searchRequest->examRegistrationId;
                    $examRegBatchDetail = reset(ExamRegistrationBatchService::getInstance()->searchExamRegistrationBatchDetails($batchRequest));
                    if( $examRegBatchDetail->courseTypeName == "B.Des" && (($examRegBatchDetail->academicTermId > 2 && $examRegBatchDetail->startYear >= 2022) || ($examRegBatchDetail->startYear >= 2023)) ){
                        $extraMarkObject->hasMultipleMarkEntry = 1;
                        if( reset($registeredStudentMarkDetails)->examRegType == "SUPPLEMENTARY"){
                            $extraMarkObject->hideAdditionalMarkSupply = 1;
                        }
                        $totalMark =  reset($registeredStudentMarkDetails)->internalMaxMark +  reset($registeredStudentMarkDetails)->maximumSubjectMark;
                        $extraMarkObject->subjectExternalMaxMarkWithoutViva = ( 40 / 100) *  $totalMark;
                        $extraMarkObject->subjectExternalMaxMarkWithViva = ( 10 / 100) *  $totalMark;
                        $maxmarkOfSubject = $extraMarkObject->subjectExternalMaxMarkWithoutViva;
                    }
                }
                foreach($registeredStudentMarkDetails as $student){
                    $student->isWithHeld  = false;
                    $student->hasMultipleMarkEntry = $extraMarkObject->hasMultipleMarkEntry;
                    if($student->isRevalued == 1){
                        $student->rvStatus = $isRvStatus ? "RV" : "";
                    }
                    if ( $student->isExempted == 1 ) {
                        $student->mark = "EX";
                        $student->oldMark = "Exempted";
                    }
                    else if ( $student->isAbsent == "ABSENT" ) {
                        $student->mark  = "AB";
                        $student->oldMark = "Absent";
                    }  
                    else if ( $student->isAbsent == "INCOMPLETE" ) {
                        $student->mark  = "I";
                        $student->oldMark = "In-complete";
                    } 
                    else if ( $student->isAbsent == "MALPRACTICE" ) {
                        $student->mark  = "MAL";
                        $student->oldMark = "Mal-Practice";
                    } 
                    else if ($student->isAbsent == "WITHHELD") {
                        $student->mark  = $student->finalizedMark;
                        $student->isWithHeld  = true;
                        $student->oldMark = "with held";
                    }
                    else{
                        $student->mark = $student->finalizedMark ? number_format((float)$student->finalizedMark, 2, '.', '') : null;
                        $student->oldMark = $student->mark;
                    }
                   
                }
            }
            $studentsCount = count ( $registeredStudentMarkDetails );
            $response->MarkEntryDetails = $registeredStudentMarkDetails;
            $response->extraMarkObject = $extraMarkObject;
            $response->studentsCount = $studentsCount;
            $response->IsFalseNumberSettings = $isFalseNumber;
            $response->IsRvStatusSettings = (int)$isRvStatus;
            $response->maxMarkOfSubject = (int)$maxmarkOfSubject;
            $response->markEntryMethod = "DIRECT";
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    /**
     * get AllStudent External Marks By ExamRegistrationSubject
     * @param searchRequest $searchRequest
     * @return $studentsMarkDetails
     */
    public function getAllStudentExternalMarksByExamRegistrationSubject($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        $searchRequest->academicPaperSubjectId = is_array($searchRequest->academicPaperSubjectId) ? $searchRequest->academicPaperSubjectId : stripslashes($searchRequest->academicPaperSubjectId);
        $joinQuery = "";
        try {
            $orderBy = " ORDER BY spa.properties->>'$.registerNumber' ASC , s.code ASC";
            $whereQuery = "";
            $groupBy = "";
            if ( $searchRequest->isOrderByRollNo ){
                $orderBy = " ORDER BY spa.properties->>'$.rollNumber' ASC , s.code ASC";
            }
            if(!empty($searchRequest->groupId)) {
                $groupIdString = is_array($searchRequest->groupId) ? "'" . implode("','",$searchRequest->groupId) . "'" : "'".$searchRequest->groupId."'";
                $whereQuery .= " AND eerb.groups_id IN ( $groupIdString )";
            }
            if(!empty($searchRequest->isThirdValuationStudentOnly)) {
                $whereQuery .= " AND ets.thirdvalstudentID IS NOT NULL ";
            }
            if(!empty($searchRequest->examRegistrationId)) {
                $examRegistrationIdString = is_array($searchRequest->examRegistrationId) ? "'" . implode("','",$searchRequest->examRegistrationId) . "'" : "'".$searchRequest->examRegistrationId."'";
                $whereQuery .= " AND eerb.ec_exam_registration_id IN ( $examRegistrationIdString )";
            }
            if(!empty($searchRequest->academicPaperSubjectId)) {
                $academicPaperSubjectIdString = is_array($searchRequest->academicPaperSubjectId) ? "'" . implode("','",$searchRequest->academicPaperSubjectId) . "'" : "'".$searchRequest->academicPaperSubjectId."'";
                $whereQuery .= " AND eers.cm_academic_paper_subjects_id IN ( $academicPaperSubjectIdString )";
            }
            if(!empty($searchRequest->examRegistrationBatchId)) {
                $examRegistrationBatchIdString = is_array($searchRequest->examRegistrationBatchId) ? "'" . implode("','",$searchRequest->examRegistrationBatchId) . "'" : "'".$searchRequest->examRegistrationBatchId."'";
                $whereQuery .= " AND eerb.id IN ( $examRegistrationBatchIdString )";
            }
            if(!empty($searchRequest->studentRegisterNo)) {
                $studentRegisterNoString = is_array($searchRequest->studentRegisterNo) ? "'" . implode("','",$searchRequest->studentRegisterNo) . "'" : "'".$searchRequest->studentRegisterNo."'";
                $whereQuery .= " AND spa.properties->>'$.registerNumber' IN ( $studentRegisterNoString )";
            }
            if(!empty($searchRequest->studentRollNo)) {
                $studentRollNoString = is_array($searchRequest->studentRollNo) ? "'" . implode("','",$searchRequest->studentRollNo) . "'" : "'".$searchRequest->studentRollNo."'";
                $whereQuery .= " AND spa.properties->>'$.rollNumber' IN ( $studentRollNoString )";
            }
            if(!empty($searchRequest->studentFalseNo)) {
                $studentFalseNoString = is_array($searchRequest->studentFalseNo) ? "'" . implode("','",$searchRequest->studentFalseNo) . "'" : "'".$searchRequest->studentFalseNo."'";
                $whereQuery .= " AND esar.properties->>'$.falseNo' IN ( $studentFalseNoString )";
            }
            if(!empty($searchRequest->assessmentId)) {
                $assessmentIdString = is_array($searchRequest->assessmentId) ? "'" . implode("','",$searchRequest->assessmentId) . "'" : "'".$searchRequest->assessmentId."'";
                $whereQuery .= " AND eers.am_assessment_id IN ( $assessmentIdString )";
            }
            if(!empty($searchRequest->isRequiredFalseNo)) {
                $whereQuery .= " AND esar.properties ->> '$.falseNo'  IS NOT NULL ";
                $groupBy = " GROUP BY esar.student_id ";
            }
            $joinConditionMarkFinalized = '';
            if(!empty($searchRequest->showFinalizedMarkOnly)) {
                $joinConditionMarkFinalized .= "  AND  ( ostmf.properties->>'$.isNotConfirm' !=1 OR ostmf.properties->>'$.isNotConfirm' IS NULL ) ";
            }
            if(!empty($searchRequest->isFirstValuatedStudentOnly)) {
                $joinQuery .= " INNER JOIN oe_student_total_mark ostm1 ON 
                                    ostm1.student_id = sa.studentID AND 
                                    ostm1.am_assessment_id = esar.am_assessment_id AND 
                                    (ostm1.valuation_type IS NULL OR ostm1.valuation_type = '' ) AND
                                    ostm1.valuation_count = '1'";
            }
            else{
                $joinQuery .= " LEFT JOIN oe_student_total_mark ostm1 ON 
                                    ostm1.student_id = sa.studentID AND 
                                    ostm1.am_assessment_id = esar.am_assessment_id AND 
                                    (ostm1.valuation_type IS NULL OR ostm1.valuation_type = '') AND
                                    ostm1.valuation_count = '1'";
            }
            if(!empty($searchRequest->isSecondValuatedStudentOnly)) {
                $joinQuery .= " INNER JOIN oe_student_total_mark ostm2 ON 
                                    ostm2.student_id = sa.studentID AND 
                                    ostm2.am_assessment_id = esar.am_assessment_id AND 
                                    (ostm2.valuation_type IS NULL OR ostm2.valuation_type = '') AND
                                    ostm2.valuation_count = '2'";
            }
            else{
                $joinQuery .= " LEFT JOIN oe_student_total_mark ostm2 ON 
                                    ostm2.student_id = sa.studentID AND 
                                    ostm2.am_assessment_id = esar.am_assessment_id AND 
                                    (ostm2.valuation_type IS NULL OR ostm2.valuation_type = '') AND
                                    ostm2.valuation_count = '2'";
            }
              
            $query = "SELECT
                        DISTINCT sa.studentID as id,
                        sa.studentID as studentId, 
                        sa.studentName,
                        aa.properties_value ->>'$.assessmentDate' AS assessmentDate,
                        spa.properties->>'$.registerNumber' as regNo,
                        spa.properties->>'$.rollNumber' as rollNo,
                        sa.myImage as studentImage,
                        g.id AS groupId,
                        g.name AS groupName,
                        eer.type AS examRegType,
                        eerb.properties as batchProperties,
                        s.id as subjectId,
                        s.code as subjectCode,
                        s.name as subjectName,
                        IF(aps.properties ->> '$.classType' = 'THEORY',1,0) AS isTheory,
                        esmel.log,
                        im.internal_mark as internalMark,
                        ostmf.mark_obtained as externalMark,
                        ostmf.id as assessmentStudentTotalMarkId,
                        oe.id AS oeExamId,
                        ostmf.mark_obtained,
                        ostmf.mark_obtained as finalizedMark,
                        ostmf.properties as finalizedMarkProperties,
                        ostmf.exam_additional_marks->>'$.mark1' AS vivaMark,
                        IF(ostmf.properties ->> '$.isNotConfirm' = true,0,1) as finalizedValuationConfirm,
                        ostm1.mark_obtained as firstValuationMark,
                        ostm1.properties as firstValuationMarkProperties,
                        IF(ostm1.properties ->> '$.isNotConfirm' = true,0,1) as firstValuationConfirm,
                        ostm2.mark_obtained as secondValuationMark,
                        ostm2.properties as secondValuationMarkProperties,
                        IF(ostm2.properties ->> '$.isNotConfirm' = true,0,1) as secondValuationConfirm,
                        ostm3.mark_obtained as thirdValuationMark,
                        ostm3.properties as thirdValuationMarkProperties,
                        IF(ostm3.properties ->> '$.isNotConfirm' = true,0,1) as thirdValuationConfirm,
                        ostmf.attendance_status as isAbsent,
                        esar.am_assessment_id as assessmentId,
                        IF(ees.id,1,0) AS isExempted,
                        esar.properties ->> '$.isRevalued' as isRevalued,
                        esar.properties ->> '$.falseNo' as falseNo,
                        esar.properties ->> '$.alphaNumericCode' as alphaNumericCode,
                        esar.valuation_details ->> '$.packetNo' as packetNo,
                        IF(ets.thirdvalstudentID, 1, 0) AS thirdValReq,
                        aps.properties ->> '$.isExternal' as isExternal,
                        aps.properties ->> '$.externalMaxMark' as maximumSubjectMark,
                        aps.properties ->> '$.internalMaxMark' as internalMaxMark,
                        eers.valuation_details,
                        esar.valuation_details as studentValuationDetails
                    FROM
                        ec_student_assessment_registration esar
                    INNER JOIN studentaccount sa ON 
                        sa.studentID = esar.student_id
                    INNER JOIN ec_exam_registration_subject eers ON 
                        eers.am_assessment_id = esar.am_assessment_id
                    INNER JOIN am_assessment aa ON
                        aa.id = eers.am_assessment_id
                    INNER JOIN  cm_academic_paper_subjects aps ON 
                        aps.id = eers.cm_academic_paper_subjects_id
                    INNER JOIN v4_ams_subject s ON 
                        s.id = aps.ams_subject_id
                    INNER JOIN oe_exams oe ON
                            oe.assessment_id = eers.am_assessment_id AND oe.is_deleted = 0
                    INNER JOIN ec_exam_registration_batch eerb ON
                        eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer ON
                        eer.id = eerb.ec_exam_registration_id
                    INNER JOIN `groups` g ON
                        g.id = eerb.groups_id
                    INNER JOIN program p ON 
                        p.id = g.properties->>'$.programId'
                    INNER JOIN `student_program_account` spa ON 
                        spa.current_program_id = p.id AND 
                        spa.student_id = esar.student_id 
                    LEFT JOIN ec_student_mark_edit_log esmel ON
                        esmel.student_id = sa.studentID AND
                        esmel.am_assessment_id = esar.am_assessment_id
                    LEFT JOIN ec_internal_marks im ON
                        im.groups_id = eerb.groups_id AND 
                        im.academic_paper_subjects_id = aps.id AND  im.student_id = sa.studentID
                    LEFT JOIN exam_exempted_students ees ON
                        ees.am_assessment_id  = esar.am_assessment_id AND
                        ees.studentaccount_id =  sa.studentID
                    LEFT JOIN externalexam_thirdvalstudents ets ON 
                            ets.studentID = sa.studentID AND ets.am_assessment_id = eers.am_assessment_id
                    LEFT JOIN oe_student_total_mark ostmf ON 
                        ostmf.student_id = sa.studentID AND ostmf.am_assessment_id = esar.am_assessment_id AND ostmf.valuation_count = 'FINALIZED' AND (ostmf.valuation_type IS NULL OR ostmf.valuation_type = '') $joinConditionMarkFinalized
                    ".$joinQuery."
                    LEFT JOIN oe_student_total_mark ostm3 ON 
                        ostm3.student_id = sa.studentID AND ostm3.am_assessment_id = esar.am_assessment_id AND (ostm3.valuation_type IS NULL OR ostm3.valuation_type = '') AND ostm3.valuation_count = '3'
                    WHERE
                        1=1  AND CAST(esar.properties ->> '$.registrationStatus' AS CHAR) = 'REGISTERED' AND CAST(esar.properties ->> '$.feeStatus' AS CHAR) = 'PAID' AND esar.ec_exam_registration_type = eer.type
                        AND (CAST(esar.properties ->> '$.syllabusSubType' AS CHAR) != 'MOOC' OR esar.properties ->> '$.syllabusSubType' IS NULL) ";
            $studentsMarkDetails = $this->executeQueryForList($query.$whereQuery.$groupBy.$orderBy);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $studentsMarkDetails;
    }
     /**
     * save All External Mark Entry Details For Direct Method
     * @param  $studentMarkDetailsArray
     */
    public function saveAllExternalMarkEntryDetailsForDirectMethod($studentMarkDetailsArray){
        $studentMarkDetailsArray = $this->realEscapeArray($studentMarkDetailsArray);
        try{
            $insertExempted = [];
            $deleteExempted = [];
            $insertionValues = [];
            $deleteMarkTableArray = [];
            $editHistoryLog = [];
            $insertionExtrnalMarkLogTableArray = [];
            $adminId = $GLOBALS['userId'];
            $staffName = $this->getStaffNameByStaffId($adminId);
            $hasVivaMark = reset($studentMarkDetailsArray)['hasMultipleMarkEntry'];
            foreach($studentMarkDetailsArray as $student){
                $maximumSubjectMark =  (float)$student['maximumSubjectMark'];
                if($student['isWithHeld'] != true){
                    // if($student['mark'] != null && $student['mark'] >= 0){
                        // for high lighting edit changes in import mark
                        $editRequest = new \stdClass();
                        $editRequest->groupId = $student['groupId'];
                        $editRequest->studentId = $student['id'];
                        $editRequest->isDirty = 1;
                        $editRequest->staffId = $GLOBALS['userId'];
                        $editHistoryLog[] = $editRequest;
                        if($student['mark'] == "AB"){
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $student['id'];
                                $markEntryObj->assessmentId = $student['assessmentId'];
                                $markEntryObj->oeExamsId = $student['oeExamId'];
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markEntryObj->markObtained = null;
                                $markEntryObj->attendanceStatus = "ABSENT";
                                $markEntryObj->hasVivaMark = $hasVivaMark;
                                if( $hasVivaMark ){
                                    $examMarks = new \stdClass();
                                    $examMarks->mark1 = $student['vivaMark'];
                                    $markEntryObj->examAdditionalMarks  = $examMarks;
                                }
                                $markproperties = "";
                                if($student['markProperties']){
                                    $markproperties = (object)$student['markProperties'];
                                }
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                            $insertionValues[] = $markEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $student['assessmentId'];
                                $deleteMarkEntryObj->studentId = $student['id'];
                                $deleteMarkEntryObj->valuationCount = 1;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $student['assessmentId'];
                                $deleteMarkEntryObj->studentId = $student['id'];
                                $deleteMarkEntryObj->valuationCount = 2;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $student['assessmentId'];
                                $deleteMarkEntryObj->studentId = $student['id'];
                                $deleteMarkEntryObj->valuationCount = 3;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                            $deleteExempted[] = " ( am_assessment_id = '".$student['assessmentId']."' AND studentaccount_id =  '".$student['id']."' ) ";
                        }
                        else if($student['mark'] == "I"){
                            $markEntryObj = new \stdClass();
                            $markEntryObj->studentId = $student['id'];
                            $markEntryObj->assessmentId = $student['assessmentId'];
                            $markEntryObj->oeExamsId = $student['oeExamId'];
                            $markEntryObj->valuationCount = 'FINALIZED';
                            $markEntryObj->markObtained = null;
                            $markEntryObj->attendanceStatus = "INCOMPLETE";
                            $markEntryObj->hasVivaMark = $hasVivaMark;
                            if( $hasVivaMark ){
                                $examMarks = new \stdClass();
                                $examMarks->mark1 = $student['vivaMark'];
                                $markEntryObj->examAdditionalMarks  = $examMarks;
                            }
                            $markproperties = "";
                            if($student['markProperties']){
                                $markproperties = (object)$student['markProperties'];
                            }
                            $markEntryObj->properties  = $markproperties;
                            $markEntryObj->valuationType = null;
                            $insertionValues[] = $markEntryObj;
                            // $deleteMarkEntryObj = new ExamUserMarkRequest;
                            // $deleteMarkEntryObj->assessmentId = $student['assessmentId'];
                            // $deleteMarkEntryObj->studentId = $student['id'];
                            // $deleteMarkEntryObj->valuationCount = 1;
                            // $deleteMarkTableArray[] = $deleteMarkEntryObj;
                            // $deleteMarkEntryObj = new ExamUserMarkRequest;
                            // $deleteMarkEntryObj->assessmentId = $student['assessmentId'];
                            // $deleteMarkEntryObj->studentId = $student['id'];
                            // $deleteMarkEntryObj->valuationCount = 2;
                            // $deleteMarkTableArray[] = $deleteMarkEntryObj;
                            // $deleteMarkEntryObj = new ExamUserMarkRequest;
                            // $deleteMarkEntryObj->assessmentId = $student['assessmentId'];
                            // $deleteMarkEntryObj->studentId = $student['id'];
                            // $deleteMarkEntryObj->valuationCount = 3;
                            // $deleteMarkTableArray[] = $deleteMarkEntryObj;
                            $deleteExempted[] = " ( am_assessment_id = '".$student['assessmentId']."' AND studentaccount_id =  '".$student['id']."' ) ";
                        }
                        else if($student['mark'] == "MAL"){
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $student['assessmentId'];
                                $deleteMarkEntryObj->studentId = $student['id'];
                                $deleteMarkEntryObj->valuationCount = 1;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $student['assessmentId'];
                                $deleteMarkEntryObj->studentId = $student['id'];
                                $deleteMarkEntryObj->valuationCount = 2;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $student['assessmentId'];
                                $deleteMarkEntryObj->studentId = $student['id'];
                                $deleteMarkEntryObj->valuationCount = 3;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $student['id'];
                                $markEntryObj->assessmentId = $student['assessmentId'];
                                $markEntryObj->oeExamsId = $student['oeExamId'];
                                $markEntryObj->markObtained = null;
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markEntryObj->attendanceStatus = "MALPRACTICE";
                                $markEntryObj->hasVivaMark = $hasVivaMark;
                                if( $hasVivaMark ){
                                    $examMarks = new \stdClass();
                                    $examMarks->mark1 = $student['vivaMark'];
                                    $markEntryObj->examAdditionalMarks  = $examMarks;
                                }
                                $markproperties = "";
                                if($student['markProperties']){
                                    $markproperties = (object)$student['markProperties'];
                                }
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                            $insertionValues[] = $markEntryObj;
                            $deleteExempted[] = " ( am_assessment_id = '".$student['assessmentId']."' AND studentaccount_id =  '".$student['id']."' ) ";
                        }
                        else if($student['mark'] == "WH"){
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $student['id'];
                                $markEntryObj->assessmentId = $student['assessmentId'];
                                $markEntryObj->oeExamsId = $student['oeExamId'];
                                $markEntryObj->attendanceStatus = "WITHHELD";
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markproperties = "";
                                $markEntryObj->hasVivaMark = $hasVivaMark;
                                if( $hasVivaMark ){
                                    $examMarks = new \stdClass();
                                    $examMarks->mark1 = $student['vivaMark'];
                                    $markEntryObj->examAdditionalMarks  = $examMarks;
                                }
                                if($student['markProperties']){
                                    $markproperties = (object)$student['markProperties'];
                                }
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                            $insertionValues[] = $markEntryObj;
                            $deleteExempted[] = " ( am_assessment_id = '".$student['assessmentId']."' AND studentaccount_id =  '".$student['id']."' ) ";
                        }
                        else if($student['mark'] == "EX"){
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $student['assessmentId'];
                                $deleteMarkEntryObj->studentId = $student['id'];
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                            $deleteExempted[] = " ( am_assessment_id = '".$student['assessmentId']."' AND studentaccount_id =  '".$student['id']."' ) ";
                            $insertExempted[] = " ( '".$student['id']."', '".$student['assessmentId']."' ,'".$adminId."', utc_timestamp(), '".$adminId."', utc_timestamp() ) ";
                        }
                        else{
                            if(is_numeric($student['mark']) && (float)$student['mark'] <= $maximumSubjectMark) {
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $student['id'];
                                $markEntryObj->assessmentId = $student['assessmentId'];
                                $markEntryObj->oeExamsId = $student['oeExamId'];
                                $markEntryObj->markObtained = $student['mark'];
                                $markEntryObj->attendanceStatus = "PRESENT";
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markEntryObj->hasVivaMark = $hasVivaMark;
                                if( $hasVivaMark ){
                                    $examMarks = new \stdClass();
                                    $examMarks->mark1 = $student['vivaMark'];
                                    $markEntryObj->examAdditionalMarks  = $examMarks;
                                }
                                $markproperties = "";
                                if($student['markProperties']){
                                    $markproperties = (object)$student['markProperties'];
                                }
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                                $insertionValues[] = $markEntryObj;
                                $deleteExempted[] = " ( am_assessment_id = '".$student['assessmentId']."' AND studentaccount_id =  '".$student['id']."' ) ";
                            } 
                            else if(empty($student['mark'])){
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $student['id'];
                                $markEntryObj->assessmentId = $student['assessmentId'];
                                $markEntryObj->oeExamsId = $student['oeExamId'];
                                $markEntryObj->markObtained = null;
                                $markEntryObj->attendanceStatus = "PRESENT";
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markEntryObj->hasVivaMark = $hasVivaMark;
                                if( $hasVivaMark ){
                                    $examMarks = new \stdClass();
                                    $examMarks->mark1 = $student['vivaMark'];
                                    $markEntryObj->examAdditionalMarks  = $examMarks;
                                }
                                $markproperties = "";
                                if($student['markProperties']){
                                    $markproperties = (object)$student['markProperties'];
                                }
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                                $insertionValues[] = $markEntryObj;
                                $deleteExempted[] = " ( am_assessment_id = '".$student['assessmentId']."' AND studentaccount_id =  '".$student['id']."' ) ";
                            }
                        }
                        if($student['oldMark'] != $student['mark']) {
                            $log = new StudentMarkEditLog();
                            $log->oldMark = $student['oldMark'];
                            $log->newMark = $student['mark'];
                            $log->remarks = "Mark changed by Direct Method";
                            $log->markType = "EXTERNAL_MARK";
                            $log->actionTakenTime = date("d-m-Y h:i A");
                            $log->updatedStaffId = $adminId;
                            $log->updatedStaffName = $staffName;
                            $log->updatedStaffType = "EXAM_CONTROLLER";
                            $logRequest = new \stdClass();
                            $logRequest->studentId =  $student['id'];
                            $logRequest->assessmentId = $student['assessmentId'];
                            $logRequest->staffId = $adminId;
                            $logRequest->log = $log;
                            $insertionExtrnalMarkLogTableArray[] = $logRequest;
                        }
                    // }
                }
            }
            if( !empty ( $insertionValues ) ){
                ExamUserMarkService::getInstance()->saveExamUserTotalMark($insertionValues);
            }
            if(! empty($insertionExtrnalMarkLogTableArray)){
                foreach($insertionExtrnalMarkLogTableArray as $logRequest){
                    $this->saveExamEditLog($logRequest);
                }
            }
            if( !empty ( $deleteExempted ) ){
                $this->deleteExemptedStudents($deleteExempted);
            }
            if( !empty ( $insertExempted ) ){
                $this->insertExemptedStudents($insertExempted);
            }
            if(! empty($deleteMarkTableArray)){
                foreach($deleteMarkTableArray as $deleteObj){
                    ExamUserMarkService::getInstance()->deleteExamUserTotalMark($deleteObj);
                }
            }
            if(! empty($editHistoryLog)){
                StudentsOverAllMarkReportService::getInstance()->insertStudentEditStatus($editHistoryLog);
            }
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
     /**
     * delete Exempted Students
     * @param  $deleteExempted
     */
    public function deleteExemptedStudents($deleteExempted){
        try {
            $sql_deleteExempted = "DELETE FROM 
                                    exam_exempted_students
                                 WHERE " . implode ( " OR ", $deleteExempted);
            $this->executeQuery($sql_deleteExempted);
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * insert Exempted Students
     * @param  $insertExempted
     */
    public function insertExemptedStudents($insertExempted){
        try {
              $sql_exempted = "INSERT INTO exam_exempted_students 
                                (studentaccount_id,am_assessment_id, createdBy, createdDate, updatedBy, updatedDate ) 
                                VALUES " . implode ( ",", $insertExempted );
            $this->executeQuery($sql_exempted);
            
            
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * print External Mark Entry Details For Direct
     * @param  $directMarkEntryRequest
     */
    public function printExternalMarkEntryDetailsForDirect($directMarkEntryRequest){
        $directMarkEntryRequest = $this->realEscapeObject($directMarkEntryRequest);
        try{
            $registeredStudentMarkDetails = [];
            $examRegistrationId = $directMarkEntryRequest->examRegistrationId;
            $academicPaperId = $directMarkEntryRequest->academicPaperId;
            $isFalseNumber = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::IS_FALSE_NUMBER_IN_EXTERNAL_MARK_ENTRY_DIRECT);
            $isRvStatus = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::IS_RC_STATUS_IN_EXTERNAL_MARK_ENTRY_DIRECT);
            $request = new \stdClass;
            $request->examRegistrationId = $examRegistrationId;
            $request->academicPaperSubjectId = stripslashes($academicPaperId);
            $request->groupId = $directMarkEntryRequest->groupId;
            if ( $isFalseNumber == "ROLL_NUMBER"){
                $request->isOrderByRollNo = 1;
            }
            $registeredStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
            foreach($registeredStudentMarkDetails as $student){
                if ( $student->isExempted == 1 ) {
                    $student->mark = "EX";
                }
                else if ( $student->isAbsent == "ABSENT" ) {
                    $student->mark  = "AB";
                } 
                else if ( $student->isAbsent == "INCOMPLETE" ) {
                    $student->mark  = "I";
                } 
                else if ($student->isAbsent == "WITHHELD") {
                    $student->mark  = "WH";
                }
                else{
                    $student->mark  = $student->finalizedMark;
                }
                if($isRvStatus){
                    if($student->isRevalued == 1){
                        $student->rvStatus = "RV";
                    }
                }
            }
            if(empty($registeredStudentMarkDetails)){
                throw new ExamControllerException(ExamControllerException::NO_STUDENT_IN_THE_BATCH_SUBJECT,"No Students Registerd In this Exam");
            }
            else{
                $examRegistrationSubject = ExamRegistrationSubjectService::getInstance()->getExamregistrationSubjectDetails($request);
                $examRegistrationSubject->isShowBatch = !empty($request->groupId) ? true : false;
                $templateName = "printExternalMarkEntryDetailsDirect";
                $responseHtml = TwigRenderer::renderTemplateFileToHtml(realpath(DOCUMENT_ROOT."../examcontroller-api/src/com/linways/web/templates/printTwigs/$templateName.twig"), [ 'registeredStudentMarkDetails'=>$registeredStudentMarkDetails ,'examRegistrationSubject'=>$examRegistrationSubject,'isFalseNumber'=>$isFalseNumber,'isRvStatus'=>$isRvStatus]);
                $prtContent = NULL;
                    $prtContent .= '<html><head>';
                    $prtContent .= "<style>
                        
                        </style>";
                    $prtContent .= '</head><title>External Mark Entry Report</title><body>';
                    $prtContent .= $responseHtml;
                    $prtContent .= '</body></html>';
                    $totalWidth = 210;
                    $totalHeight = 297;
                    $options = array(
                        'page-width'     => $totalWidth."mm",
                        'page-height'    => $totalHeight."mm",
                        'dpi'            => 96,
                        'margin-top' => "9mm",
                        'margin-left' => "1mm",
                        'margin-right' => "1mm",
                        'margin-bottom' => "9mm",
                        // 'binary' => "/usr/local/bin/wkhtmltopdf", // For Mac
                        'user-style-sheet' => realpath(DOCUMENT_ROOT . "/libcommon/bootstrap/css/bootstrap.min.css")
                    );
                $programResult = new \stdClass;
                $programResult->displayData = $responseHtml;
                $programResult->pdf = PdfUtil::renderPdf($prtContent, $options);
                return  $programResult;
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        
    }
    /**
     * print External Mark Entry Details For Barcode
     * @param  $markEntryRequest
     */
    public function printExternalMarkEntryDetailsForBarcode($markEntryRequest)
    {
        $markEntryRequest = $this->realEscapeObject($markEntryRequest);
        try
        {
            $condition = "";
            $registeredStudentMarkDetails = [];
            $registeredStudents = [];
            $studentMarkDetails = [];
            $facultyNames = [];
            $examRegistrationId = $markEntryRequest->examRegistrationId;
            $academicPaperId = $markEntryRequest->academicPaperId;
            $academicTermId = $markEntryRequest->academicTermId;
            $packetNumber = $markEntryRequest->packetNumber;
            if($markEntryRequest->academicPaperIds){
                $academicPaperId = $markEntryRequest->academicPaperIds;
            }
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ( $markEntryRequest->courseType );
            $isTheory = $this->getIsTheoryOrNotByExamRegistrationIdAndPaperSubjectId( $examRegistrationId,$academicPaperId);
            if(($courseType->courseTypeMethod != "PG")){
                $currentValuationCount = "FINALIZED";
            }
            else if($courseType->courseTypeMethod == "PG"){
                if(($markEntryRequest->currentValuationCount == 1) && ($isTheory == "0")){
                    $currentValuationCount = "FINALIZED";
                }
            }
            $currentValuationCount =  $markEntryRequest->currentValuationCount;
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ( $markEntryRequest->courseType );
            $academicPaperSubjectIdStr = is_array($academicPaperId) ? "'" . implode("','",$academicPaperId) . "'" : "'".$academicPaperId."'";
            $condition = "( eerb.ec_exam_registration_id = '".$examRegistrationId."' AND  eerb.academicTermId = '".$academicTermId."'  AND  eers.cm_academic_paper_subjects_id IN ($academicPaperSubjectIdStr) AND  esar.valuation_details ->> '$.packetNo' = '".$packetNumber."') ";
            $registeredStudentMarkDetails = $this->getAllStudentsExternalMarksByStudentExamDetailForExamRegistration($condition);
            foreach($registeredStudentMarkDetails as $studentDetail)
            {
                $singleStudentDetail = new \Stdclass();
                $valuatedStaffs = json_decode($studentDetail->valuatedStaffs);
                $singleStudentDetail->studentId = $studentDetail->studentId;
                $singleStudentDetail->registerNumber = $studentDetail->regNo;
                $singleStudentDetail->thirdValReq = $studentDetail->thirdValReq;
                $singleStudentDetail->firsrValuationMark = $studentDetail->firstValuationMark;
                $singleStudentDetail->secondValuationMark = $studentDetail->secondValuationMark;
                $singleStudentDetail->thirdValuationMark = $studentDetail->thirdValuationMark;
                $singleStudentDetail->finalizedMark = $studentDetail->finalizedMark;
                foreach($valuatedStaffs as $valuatedStaff)
                {
                    if($valuatedStaff->valuationCount == $currentValuationCount)
                    {
                        if($valuatedStaff->staffIds)
                        {
                            $facultyIds = explode(',',$valuatedStaff->staffIds);
                            foreach($facultyIds as $facultyId)
                            {
                                $facultyIdArray[$facultyId] = $facultyId;
                            }
                            
                        }
                    }
                }
                $singleStudentDetail->markDiff = 0;
                if($currentValuationCount == 2 && $singleStudentDetail->firsrValuationMark  &&  $singleStudentDetail->secondValuationMark)
                {
                    $singleStudentDetail->markDiff  = abs ($singleStudentDetail->firsrValuationMark - $singleStudentDetail->secondValuationMark);
                }
                $studentMarkDetails[] = $singleStudentDetail;
            }
            if(empty($studentMarkDetails))
            {
                throw new ExamControllerException(ExamControllerException::NO_STUDENT_IN_THE_BATCH_SUBJECT,"No Students Registerd In this Exam");
            }
            else
            {
                $facultyIds = $facultyIdArray ? "sa.staffID = " .implode(" OR sa.staffID = ",$facultyIdArray):"";
                $faculties =  $facultyIds ? $this->getFacultiesByFacultyIds($facultyIds):"";
                foreach($faculties as $faculty)
                {
                    $facultyNames[] =  $faculty->staffName;
                }
                $facultyName = implode(" , ",$facultyNames);
                
                $examRegistrationSubject = $this->getSubjectDetailsByAcademicPaperSubjectIdAndExamRegistrationId($academicPaperId,$examRegistrationId);
                $templateName = "printExternalMarkEntryDetailsBarcode";
                $responseHtml = TwigRenderer::renderTemplateFileToHtml(realpath(DOCUMENT_ROOT."../examcontroller-api/src/com/linways/web/templates/printTwigs/$templateName.twig"), [ 'registeredStudentMarkDetails'=>$studentMarkDetails ,'examRegistrationSubject'=>$examRegistrationSubject,'packetNo'=>$packetNumber,'valuationCount'=>$currentValuationCount,'faculties'=>$facultyName,'courseType'=>$courseType->courseTypeMethod]);
                $prtContent = NULL;
                    $prtContent .= '<html><head>';
                    $prtContent .= "<style>
                        
                        </style>";
                    $prtContent .= '</head><title>Barcode Mark Entry</title><body>';
                    $prtContent .= $responseHtml;
                    $prtContent .= '</body></html>';
                    $totalWidth = 210;
                    $totalHeight = 297;
                    $options = array(
                        'page-width'     => $totalWidth."mm",
                        'page-height'    => $totalHeight."mm",
                        'dpi'            => 96,
                        'margin-top' => "9mm",
                        'margin-left' => "1mm",
                        'margin-right' => "1mm",
                        'margin-bottom' => "9mm",
                        // 'binary' => "/usr/local/bin/wkhtmltopdf", // For Mac
                        'user-style-sheet' => realpath(DOCUMENT_ROOT . "/libcommon/bootstrap/css/bootstrap.min.css")
                    );
                $programResult = new \stdClass;
                $programResult->displayData = $responseHtml;
                $programResult->pdf = PdfUtil::renderPdf($prtContent, $options);
                return  $programResult;
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
     /**
     * get All External Mark Entry Details For Barcode Method
     * @param  $searchRequest
     */
    public function getAllExternalMarkEntryDetailsForBarcodeMethod($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try 
        {
            $response = new \stdClass;
            $studentPerPacket = 0;
            $faculties = [];
            $currentValuationCount = 1;
            $examRegistrationId = $searchRequest->examRegistrationId;
            $academicPaperSubjectId = $searchRequest->academicPaperId;
            $academicPaperSubjectIds = $searchRequest->academicPaperIds;
            $packetNumber = $searchRequest->packetNumber;
            $valuationType = $searchRequest->valuationType;
            $academicPaperSubjectIds = $academicPaperSubjectIds ? $academicPaperSubjectIds:[$academicPaperSubjectId];
            $valuatedStudentCount = 0;
            foreach($academicPaperSubjectIds as $academicPaperSubjectId){
                $studentCount = (int)$this->getCountOfValuatedStudentBypacketNo($examRegistrationId,$academicPaperSubjectId,$packetNumber);
                $valuatedStudentCount = $valuatedStudentCount + $studentCount; 
            }
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ($searchRequest->courseType);
            $maxmarkOfSubject = (int)ExamRegistrationSubjectService::getInstance()->getMaxSubjectMarkByAcademicPaperSubjectId($academicPaperSubjectIds);
            if($courseType->courseTypeMethod == "PG"){
                $currentValuationCount = $searchRequest->currentValuationCount;
            }
            if ( $currentValuationCount == 2 ) {
                $markDiff = CommonExamService::getInstance()->getExternalValuationMarkDiff($searchRequest->courseType,$maxmarkOfSubject);
            }
            if($valuationType == "INTERNAL"){
                // all academic papers ids for the same subject will have same set of faculties assigned,=>> $academicPaperSubjectIds[0]
                $faculties = $this->getFacultiesAssignedForSubjectValuation($examRegistrationId,$academicPaperSubjectIds[0]);
            }
            else if($valuationType == "EXTERNAL"){
                $faculties = $this->getAllFacultiesFromExternalDepartment();
            }
            if( !empty ( $faculties ) ){
                foreach($faculties as $faculty) {
                    $faculty->id = $faculty->staffId;
                    $faculty->text = $faculty->name;
                }
            }
            // all academic papers ids for the same subject will have same set of packets assigned,=>> $academicPaperSubjectIds[0]
            $subjectPacketRelation = ExamRegistrationSubjectService::getInstance()->getAsnwerGroupConfigDetailsByExamRegistrationAndAcademicPaperSubject($examRegistrationId,$academicPaperSubjectId[0]);
            $studentPerPacket = $subjectPacketRelation->studentsPerAnswerSheetGroup;
            if ( !$studentPerPacket ) {
                $studentPerPacket = CommonService::getInstance()->getSettings("EXAM_VALUATION", "ANSWERSHEETS_PER_PACKET");
            }
            $response->markEntryMethod = "BARCODE";
            $response->studentPerPacket = (int)$studentPerPacket;
            $response->faculties = $faculties;
            $response->currentValuationCount = (int)$currentValuationCount;
            $response->valuatedStudentCount = (int)$valuatedStudentCount;
            $response->maxMarkOfSubject = (int)$maxmarkOfSubject;
            $response->markDiff = (int)$markDiff;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
     /**
     * get All Faculties From External Department
     * @return  $assignedStaffs
     */
    public function getAllFacultiesFromExternalDepartment()
    {
        try 
        {
            $query = "SELECT 
                        sa.staffID as staffId,
                        sa.staffName as name
                    FROM staffaccounts sa
                    INNER JOIN department d ON
                         sa.deptID = d.deptID
                WHERE d.type = 'EXTERNAL'" ;
            $assignedStaffs  = $this->executeQueryForList($query);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $assignedStaffs;
    }
    /**
     * insert Third Valuation Student Registration
     * @param  $insertionThirdValStudent
     */
    public function insertThirdValStudentRegistration($insertionThirdValStudent, $examType = null)
    {
        try 
        {
            if( $examType == 'REVALUATION' ){
                $insert_query = "INSERT INTO externalexam_thirdvalstudents
                (am_assessment_id,studentID,revaluation_id)
                VALUES " . implode ( ",", $insertionThirdValStudent ) . " ON DUPLICATE KEY UPDATE studentID = VALUES(studentID)" ;
            }
            else{
                $insert_query = "INSERT INTO externalexam_thirdvalstudents
                (am_assessment_id,studentID)
                VALUES " . implode ( ",", $insertionThirdValStudent ) . " ON DUPLICATE KEY UPDATE studentID = VALUES(studentID)" ;
            }
            $this->executeQuery($insert_query);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * Delete Third Valuation Student Registration
     * @param  $deleteThirdValStudent
     */
    public function deleteThirdValStudentRegistration($deleteThirdValStudent)
    {
        try 
        {
            $sql_deleteExempted = "DELETE FROM 
                                    externalexam_thirdvalstudents
                                 WHERE " . implode ( " OR ", $deleteThirdValStudent);
            $this->executeQuery($sql_deleteExempted);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
     /**
     * get IsTheory Or Not By ExamRegistrationId And PaperSubjectId
     * @param ExamRegistrationId $examRegistrationId
     * @param SubjectId $academicPaperSbjectId
     * @return $subject->isTheory
     */
    public function getIsTheoryOrNotByExamRegistrationIdAndPaperSubjectId($examRegistrationId,$academicPaperSubjectId)
    {
        $examRegistrationId = $this->realEscapeString($examRegistrationId);
        $academicPaperSubjectId = is_array($academicPaperSubjectId) ? $this->realEscapeArray($academicPaperSubjectId):$this->realEscapeString($academicPaperSubjectId);
        $academicPaperSubjectId = is_array($academicPaperSubjectId) ? "'" . implode("','",$academicPaperSubjectId) . "'" : "'".$academicPaperSubjectId."'";
        try
        {
            $query = "SELECT
                        IF(aps.properties ->> '$.classType' LIKE '%THEORY%',1,0) AS isTheory
                    FROM
                        ec_exam_registration_subject eers
                    INNER JOIN ec_exam_registration_batch eerb ON
                            eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN  cm_academic_paper_subjects aps ON 
                            eers.cm_academic_paper_subjects_id = aps.id
                    INNER JOIN  v4_ams_subject s ON 
                            aps.ams_subject_id = s.id
                    INNER JOIN  cm_academic_paper ap ON 
                            aps.cm_academic_paper_id = ap.id
                    WHERE
                        eerb.ec_exam_registration_id='$examRegistrationId' AND
                        eers.cm_academic_paper_subjects_id IN ($academicPaperSubjectId)
                    ORDER BY eers.created_date ASC ";
            $subject = $this->executeQueryForObject($query);
            
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $subject->isTheory;
    }
     /**
     * get Students External Marks By Student Exam Detail
     * @param  $conditions
     * @return $studentDetails
     */
    public function getStudentsExternalMarksByStudentExamDetail($conditions){
        try {
            $query = "SELECT
                        DISTINCT sa.studentID as studentId,
                        spa.properties->>'$.registerNumber' as regNo,
                        spa.properties->>'$.rollNumber' as rollNo,
                        oe.id AS oeExamId,
                        eerb.properties as batchProperties,
                        esar.am_assessment_id as assessmentId,
                        esar.valuation_details ->> '$.packetNo' as packetNo,
                        esar.valuation_details as valuationDetails,
                        esar.valuation_details ->> '$.valuatedStaffs' as valuatedStaffs,
                        esar.valuation_order_details ->> '$.valuationOrder' as valuationOrders,
                        esar.properties as studentProperties,
                        g.properties->>'$.startYear' AS startYear,
                        eerb.properties ->> '$.academicTermId' AS academicTermId,
                        ostmf.mark_obtained as finalizedMark,
                        ostmf.properties as finalizedMarkProperties,
                        ostm1.mark_obtained as firstValuationMark,
                        ostm1.properties as firstValuationMarkProperties,
                        ostm1c.mark_obtained as chiefFirstValuationMark,
                        ostm1c.properties as chiefFirstValuationMarkProperties,
                        ostm2.mark_obtained as secondValuationMark,
                        ostm2.properties as secondValuationMarkProperties,
                        ostm3.mark_obtained as thirdValuationMark,
                        ostm3.properties as thirdValuationMarkProperties,
                        IF(ets.thirdvalstudentID, 1, 0) AS thirdValReq
                    FROM
                        studentaccount sa
                    INNER JOIN  ec_student_assessment_registration esar  ON
                        esar.student_id = sa.studentID AND
                        CAST(esar.properties ->> '$.registrationStatus' AS CHAR) = 'REGISTERED' 
                        AND CAST(esar.properties ->> '$.feeStatus' AS CHAR) = 'PAID' 
                        AND esar.ec_exam_registration_type IN ('REGULAR','SUPPLEMENTARY') 
                    INNER JOIN oe_exams oe ON
                        oe.assessment_id = esar.am_assessment_id AND oe.is_deleted = 0
                    INNER JOIN ec_exam_registration_subject eers ON
                        eers.am_assessment_id = esar.am_assessment_id 
                    INNER JOIN ec_exam_registration_batch eerb ON
                            eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer
                        ON eer.id = eerb.ec_exam_registration_id and eer.trashed IS NULL 
                    INNER JOIN `groups` g ON
                        g.id = eerb.groups_id
                    INNER JOIN program p ON 
                        p.id = g.properties->>'$.programId'
                    INNER JOIN student_program_account spa ON 
                        spa.current_program_id = p.id AND 
                        spa.student_id = esar.student_id 
                    LEFT JOIN oe_student_total_mark ostmf ON 
                        ostmf.student_id = sa.studentID AND ostmf.am_assessment_id = esar.am_assessment_id AND ostmf.valuation_count = 'FINALIZED' AND (ostmf.valuation_type IS NULL OR ostmf.valuation_type = '')
                    LEFT JOIN oe_student_total_mark ostm1 ON 
                        ostm1.student_id = sa.studentID AND ostm1.am_assessment_id = esar.am_assessment_id AND ostm1.valuation_count = '1' AND (ostm1.valuation_type IS NULL OR ostm1.valuation_type = '')
                    LEFT JOIN oe_student_total_mark ostm1c ON 
                        ostm1c.student_id = sa.studentID AND ostm1c.am_assessment_id = esar.am_assessment_id AND ostm1c.valuation_count = 'FIRST_VALUATION_CHIEF_EVALUATOR' AND (ostm1c.valuation_type IS NULL OR ostm1c.valuation_type = '')
                    LEFT JOIN oe_student_total_mark ostm2 ON 
                        ostm2.student_id = sa.studentID AND ostm2.am_assessment_id = esar.am_assessment_id AND ostm2.valuation_count = '2' AND (ostm2.valuation_type IS NULL OR ostm2.valuation_type = '')
                    LEFT JOIN oe_student_total_mark ostm3 ON 
                        ostm3.student_id = sa.studentID AND ostm3.am_assessment_id = esar.am_assessment_id AND ostm3.valuation_count = '3' AND (ostm3.valuation_type IS NULL OR ostm3.valuation_type = '')
                    LEFT JOIN externalexam_thirdvalstudents ets ON 
                        ets.studentID = sa.studentID AND ets.am_assessment_id = esar.am_assessment_id
                    WHERE "  . implode(" OR ", $conditions);
            $studentDetails = $this->executeQueryForList($query);
            array_walk($studentDetails, function($student){
                $student->finalizedMarkProperties = json_decode($student->finalizedMarkProperties);
                $student->firstValuationMarkProperties = json_decode($student->firstValuationMarkProperties);
                $student->chiefFirstValuationMarkProperties = json_decode($student->chiefFirstValuationMarkProperties);
                $student->secondValuationMarkProperties = json_decode($student->secondValuationMarkProperties);
                $student->thirdValuationMarkProperties = json_decode($student->thirdValuationMarkProperties);
            });
            
            
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * get Students External MarksByStudent ExamDetail For ExamRegistration
     * @param  $conditions
     * @return $studentDetails
     */
    public function getStudentsExternalMarksByStudentExamDetailForExamRegistration($conditions){
        try{
            $query = "SELECT
                        sa.studentID as studentId,
                        spa.properties->>'$.registerNumber' as regNo,
                        spa.properties->>'$.rollNumber' as rollNo,
                        esar.am_assessment_id as assessmentId,
                        esar.valuation_details ->> '$.packetNo' as packetNo,
                        esar.valuation_details ->> '$.valuatedStaffs' as valuatedStaffs,
                        esar.properties ->> '$.falseNo' as falseNumber,
                        ostmf.mark_obtained as finalizedMark,
                        ostm1.mark_obtained as firstValuationMark,
                        ostm2.mark_obtained as secondValuationMark,
                        ostm3.mark_obtained as thirdValuationMark,
                        IF(ets.thirdvalstudentID, 1, 0) AS thirdValReq,
                        aps.properties ->> '$.externalMaxMark' as maximumSubjectMark,
                        eers.valuation_details
                    FROM
                        ec_exam_registration_subject eers 
                    INNER JOIN ec_exam_registration_batch eerb ON
                            eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer
                        ON eer.id = eerb.ec_exam_registration_id 
                    INNER JOIN ec_student_assessment_registration esar ON
                        esar.am_assessment_id = eers.am_assessment_id AND esar.ec_exam_registration_type = eer.type
                    INNER JOIN studentaccount sa ON
                        sa.studentID = esar.student_id
                    INNER JOIN student_program_account spa ON 
                        spa.student_id = esar.student_id 
                    INNER JOIN cm_academic_paper_subjects aps ON
                        eers.cm_academic_paper_subjects_id = aps.id
                    LEFT JOIN oe_student_total_mark ostmf ON 
                        ostmf.student_id = sa.studentID AND ostmf.am_assessment_id = esar.am_assessment_id AND ostmf.valuation_count = 'FINALIZED'
                    LEFT JOIN oe_student_total_mark ostm1 ON 
                        ostm1.student_id = sa.studentID AND ostm1.am_assessment_id = esar.am_assessment_id AND ostm1.valuation_count = '1'
                    LEFT JOIN oe_student_total_mark ostm2 ON 
                        ostm2.student_id = sa.studentID AND ostm2.am_assessment_id = esar.am_assessment_id AND ostm2.valuation_count = '2'
                    LEFT JOIN oe_student_total_mark ostm3 ON 
                        ostm3.student_id = sa.studentID AND ostm3.am_assessment_id = esar.am_assessment_id AND ostm3.valuation_count = '3'
                    LEFT JOIN externalexam_thirdvalstudents ets ON 
                            ets.studentID = sa.studentID AND ets.am_assessment_id = eers.am_assessment_id
                    WHERE"  . implode(" OR ", $conditions);
            $studentDetail = $this->executeQueryForObject($query);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $studentDetail;
    }
    /**
     * update Valuated Staff To Student Registration
     * @param  $updateValuatedStaffValues
     */
    public function updateValuatedStaffToStudentRegistration($updateValuatedStaffValues){
        // $updateValuatedStaffValues = $this->realEscapeArray($updateValuatedStaffValues);
        try {
            foreach($updateValuatedStaffValues as $updatedValue){
                $whereQuery = "";
                if(!empty($updatedValue->revaluationType)){
                    $whereQuery = " AND identifying_context->>'$.revaluationType' = '$updatedValue->revaluationType'";
                }
                if(!empty($updatedValue->valuationProperties)){
                    $updatedValue->valuationProperties->listStaffs = [];
                }
                if (is_string($updatedValue->valuationProperties)) {
                    $valuationProperties = $updatedValue->valuationProperties;  
                } else {
                    $valuationProperties = json_encode($updatedValue->valuationProperties);
                }
                if (is_string($updatedValue->valuationOrderDetails)) {
                    $valuationOrderDetails = $updatedValue->valuationOrderDetails;  
                } else {
                    $valuationOrderDetails = json_encode($updatedValue->valuationOrderDetails);
                }
                
                $valuationProperties = !empty($valuationProperties) ? "'" . $valuationProperties . "'" : "NULL";
                $valuationOrderDetails = !empty($valuationOrderDetails) ? "'" . $valuationOrderDetails . "'" : "NULL";
                $update_query = "UPDATE
                            ec_student_assessment_registration
                        SET
                            valuation_details = $valuationProperties,
                            valuation_order_details = $valuationOrderDetails,
                            updated_by = '$updatedValue->updatedBy',                               
                            updated_date = 'utc_timestamp()'
                        WHERE
                        am_assessment_id = '$updatedValue->assessmentId' AND student_id =  '$updatedValue->studentId'".$whereQuery ;
                $this->executeQuery($update_query);
            }
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * update Valuated Staff To Student Registration
     * @param  $updateValuatedStaffValues
     */
    public function updateisRevaluedFlagStatus($updateIsRevaluedStatus){
        $updateIsRevaluedStatus = $this->realEscapeArray($updateIsRevaluedStatus);
        try {
            foreach($updateIsRevaluedStatus as $updatedValue) {
                $updatedValue->updatedBy = $updatedValue->updatedBy ?? $GLOBALS['userId'];
                $isRevalued = $updatedValue->properties->isRevalued ? 'true' : 'false';
                // $properties = !empty($updatedValue->properties) ? "'" . json_encode($updatedValue->properties) . "'" : "NULL";
                $update_query = "UPDATE
                            ec_student_assessment_registration
                        SET
                            properties = JSON_SET(properties, '$.isRevalued',$isRevalued),
                            updated_by = '$updatedValue->updatedBy'                               
                        WHERE
                        am_assessment_id = '$updatedValue->assessmentId' AND student_id =  '$updatedValue->studentId' AND ec_exam_registration_type IN ('REGULAR','SUPPLEMENTARY')";
                $this->executeQuery($update_query);
            }
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * get Student Mark Entry Status Details For Barcode Method
     * @param  $searchRequest
     * @param $registerNumber
     * @return $response
     */
    public function getStudentMarkEntryStatusDetailsForBarcodeMethod($searchRequest,$registerNumber){
        $searchRequest = $this->realEscapeObject($searchRequest);
        $registerNumber = $this->realEscapeString($registerNumber);
        try {
            $conditions = [] ;
            $response = new \stdClass;
            $errorMessage = "";
            $currrentPacketNo = "";
            $examRegistrationId = $searchRequest->examRegistrationId;
            $academicPaperId = $searchRequest->academicPaperId;
            $packetNumber = $searchRequest->packetNumber;
            $isnotPG = false;
            $currentValuationCount =  $searchRequest->currentValuationCount;
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ($searchRequest->courseType);
            if($courseType->courseTypeMethod == "PG"){
                $currentValuationCount = $searchRequest->currentValuationCount;
                $isnotPG = false;
            }
            else{
                $currentValuationCount = null;
                $isnotPG = true;
            }
            if(!empty($searchRequest->academicPaperIds)){
                $searchRequest->academicPaperId = $searchRequest->academicPaperIds;
            }
            $searchRequest->academicPaperId = is_array($searchRequest->academicPaperId) ? "'" . implode("','",$searchRequest->academicPaperId) . "'" : "'".$searchRequest->academicPaperId."'";
            $conditions[] = " (spa.properties->>'$.registerNumber' = '".$registerNumber."' AND  eerb.ec_exam_registration_id = '".$examRegistrationId."' AND  eers.cm_academic_paper_subjects_id IN ($searchRequest->academicPaperId)) ";
            $singleStudentDetail = $this->getStudentsExternalMarksByStudentExamDetailForExamRegistration($conditions);
            if(empty($singleStudentDetail) || $singleStudentDetail == "" || $singleStudentDetail == null){
                $errorMessage = $registerNumber." Is Not Registred For This Exam";
                throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
            }
            else{
                if($currrentPacketNo != $packetNumber && $currrentPacketNo != ""){
                    $errorMessage = "Mark For ".$registerNumber." Is Already Entered In Packet ".$currrentPacketNo;
                    throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
                }
                else{
                    if($isnotPG){
                        if($singleStudentDetail->finalizedMark != null){
                            $response->firstValuationMark = $singleStudentDetail->finalizedMark ? round($singleStudentDetail->finalizedMark, 2) : $singleStudentDetail->finalizedMark;
                        }
                        else{
                            $response->firstValuationMark = null;
                        }
                    }
                    elseif($currentValuationCount == 1){
                        if($singleStudentDetail->firstValuationMark != null){
                            $response->firstValuationMark = $singleStudentDetail->firstValuationMark ? round($singleStudentDetail->firstValuationMark, 2) : $singleStudentDetail->firstValuationMark;
                        }
                        else{
                            $response->firstValuationMark = null;
                        }
                    }
                    elseif($currentValuationCount == 2){
                        if($singleStudentDetail->firstValuationMark == null){
                            $errorMessage = "First Valuation Not Completed For ".$registerNumber;
                            throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
                        }
                        else{
                            $response->firstValuationMark = (int)$singleStudentDetail->firstValuationMark;
                            if($singleStudentDetail->secondValuationMark != null){
                                $response->secondValuationMark = $singleStudentDetail->secondValuationMark ? round($singleStudentDetail->secondValuationMark, 2) : $singleStudentDetail->secondValuationMark;
                            }
                            else{
                                $response->secondValuationMark = null;
                            }
                        }
                    }
                    elseif($currentValuationCount == 3){
                        if($singleStudentDetail->thirdValReq == 0){
                            $errorMessage = $registerNumber." IS Not Eligible For Third Valuation";
                            throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
                        }
                        else{
                            if( $singleStudentDetail->firstValuationMark == null){
                                $errorMessage = "First Valuation Not Completed For ".$registerNumber;
                                throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
                            }
                            else if($singleStudentDetail->secondValuationMark == null){
                                $errorMessage = "Second Valuation Not Completed For ".$registerNumber;
                                throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
                            }
                            else{
                                $response->firstValuationMark = (int)$singleStudentDetail->firstValuationMark;
                                $response->secondValuationMark = (int)$singleStudentDetail->secondValuationMark;
                                if($singleStudentDetail->thirdValuationMark != null){
                                    $response->thirdValuationMark = $singleStudentDetail->thirdValuationMark ? round($singleStudentDetail->thirdValuationMark, 2) : $singleStudentDetail->thirdValuationMark;
                                }
                                else{
                                    $response->thirdValuationMark = null;
                                }
                            }
                        }
                    }
                }
                $response->registerNumber = $registerNumber;
                $response->maximumSubjectMark  = $singleStudentDetail->maximumSubjectMark;
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    /**
     * get Count Of Valuated Student By packetNo
     * @param $examRegistrationId
     * @param $academicPaperSubjectId
     * @param $packetNumber
     * @return $studentDetails->studentCount
     */
    public function getCountOfValuatedStudentBypacketNo($examRegistrationId,$academicPaperSubjectId,$packetNumber)
    {
        $examRegistrationId = $this->realEscapeString($examRegistrationId);
        $academicPaperSubjectId = $this->realEscapeString($academicPaperSubjectId);
        $packetNumber = $this->realEscapeString($packetNumber);
        try
        {
            $query = "SELECT
                       COUNT(DISTINCT esar.student_id) as studentCount
                    FROM
                        ec_student_assessment_registration esar
                    INNER JOIN ec_exam_registration_subject eers ON 
                        eers.am_assessment_id = esar.am_assessment_id
                    INNER JOIN ec_exam_registration_batch eerb ON
                        eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer
                        ON eer.id = eerb.ec_exam_registration_id 
                    WHERE
                        esar.ec_exam_registration_type = eer.type AND
                        CAST(esar.properties ->> '$.registrationStatus' AS CHAR) = 'REGISTERED' AND 
                        CAST(esar.properties ->> '$.feeStatus' AS CHAR) = 'PAID' AND
                        eerb.ec_exam_registration_id='$examRegistrationId' AND 
                        eers.cm_academic_paper_subjects_id = '$academicPaperSubjectId' AND
                        esar.valuation_details ->> '$.packetNo' = '$packetNumber'";
            $studentDetails = $this->executeQueryForObject($query);
            
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $studentDetails->studentCount;
    }
    /**
     * get Count Of Valuated Student By packetNo
     * @param $examRegistrationId
     * @param $academicPaperSubjectId
     * @return $registeredStudentDetails
     */
    public function getAllRegisteredStudentByExamRegistrationAndAcademicPaperSubject($examRegistrationId,$academicPaperSubjectId,$examRegistrationBatchId = null)
    {
        $examRegistrationId = $this->realEscapeString($examRegistrationId);
        if(is_array($academicPaperSubjectId)){
            $academicPaperSubjectId = (array)$this->realEscapeArray($academicPaperSubjectId);
        }
        else{
            $academicPaperSubjectIdStr = $this->realEscapeString($academicPaperSubjectId);
        }
        $academicPaperSubjectIdStr = is_array($academicPaperSubjectId) ? "'" . implode("','",$academicPaperSubjectId) . "'" : "'".$academicPaperSubjectId."'";
        $examRegistrationBatchId = $this->realEscapeString($examRegistrationBatchId);
        try 
        {
            $whereQuery=null;
            if($examRegistrationBatchId)
            {
                $whereQuery .=" AND eerb.id ='$examRegistrationBatchId'";
            }
            $query = "SELECT
                        DISTINCT sa.studentID as studentId,
                        sa.studentName,
                        spa.properties->>'$.registerNumber' as regNo,
                        spa.properties->>'$.rollNumber' as rollNo,
                        esar.properties ->> '$.falseNo' as falseNumber,
                        esar.am_assessment_id as assessmentId
                    FROM
                        ec_student_assessment_registration esar
                    INNER JOIN studentaccount sa ON 
                        sa.studentID = esar.student_id
                    INNER JOIN ec_exam_registration_subject eers ON 
                        eers.am_assessment_id = esar.am_assessment_id
                    INNER JOIN ec_exam_registration_batch eerb ON
                        eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer
                        ON eer.id = eerb.ec_exam_registration_id 
                    INNER JOIN `groups` g ON
                        g.id = eerb.groups_id
                        AND g.`type` = 'BATCH'
                    INNER JOIN program p ON 
                        p.id = g.properties->>'$.programId'
                    INNER JOIN student_program_account spa ON 
                        spa.current_program_id = p.id AND 
                        spa.student_id = esar.student_id 
                    WHERE
                        esar.ec_exam_registration_type = eer.type AND
                        CAST(esar.properties ->> '$.registrationStatus' AS CHAR) = 'REGISTERED' AND 
                        CAST(esar.properties ->> '$.feeStatus' AS CHAR) = 'PAID' AND
                        eerb.ec_exam_registration_id='$examRegistrationId' AND 
                        eers.cm_academic_paper_subjects_id  IN ($academicPaperSubjectIdStr";
            $registeredStudentDetails = $this->executeQueryForList($query.$whereQuery);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $registeredStudentDetails;
    }
     /**
     * save All External Mark Entry Details For Barcode Method
     * @param $studentMarkDetailsArray
     * @param $searchRequest
     * @param $facultyIds
     * @return $response
     */
    public function saveAllExternalMarkEntryDetailsForBarcodeMethod($studentMarkDetailsArray,$searchRequest,$facultyIds){
        $studentMarkDetailsArray = $this->realEscapeArray($studentMarkDetailsArray);
        $searchRequest = $this->realEscapeArray($searchRequest);
        $facultyIds = $this->realEscapeArray($facultyIds);
        try
        {
            $errors = [];
            $success = [];
            $examValuation = new \Stdclass();
            $response = new \Stdclass();
            $regStudentCount = 0;
            $errorFlag = 0;
            $registredStudentsArray = [];
            $unregisteredStudents = [];
            $examRegistrationId = $searchRequest['examRegistrationId'];
            $academicPaperId = $searchRequest['academicPaperId'];
            $academicPaperIds = $searchRequest['academicPaperIds'];
            $packetNumber = $searchRequest['packetNumber'];
            $currentValuationCount =  $searchRequest['currentValuationCount'];
            if ( is_array ( $facultyIds ) ) {
                $facultyId = implode ( ",", $facultyIds );
            }
            if(!empty($academicPaperIds)){
                $academicPaperId = $academicPaperIds;
            }
            $registeredStudents = $this->getAllRegisteredStudentByExamRegistrationAndAcademicPaperSubject($examRegistrationId,$academicPaperId);
            $maxmarkOfSubject = (int)ExamRegistrationSubjectService::getInstance()->getMaxSubjectMarkByAcademicPaperSubjectId($academicPaperId);
            $examValuation->courseType =  $searchRequest['courseType'];
            $examValuation->academicPaperId = $academicPaperId;
            $examValuation->examRegistrationId = $examRegistrationId;
            $examValuation->packetNumber = $packetNumber;
            $examValuation->currentValuationCount = $currentValuationCount ? $currentValuationCount : 1;
            $examValuation->facultyId = $facultyId;
            foreach($registeredStudents as $registeredStudent)
            {
                $registeredStudent->regNo = strtoupper($registeredStudent->regNo);
                $registredStudentsArray[$registeredStudent->regNo] = $registeredStudent->regNo;
                $registeredStudentDetails[$registeredStudent->regNo] = [
                    "studentId" => $registeredStudent->studentId,
                    "assessmentId" => $registeredStudent->assessmentId
                ];
            }
            if(!empty($studentMarkDetailsArray))
            {
                foreach($studentMarkDetailsArray as $student)
                {
                    $valuationStudents = new \Stdclass();
                    $regNo = strtoupper($student['registerNumber']);
                    if ($registredStudentsArray[$regNo]) 
                    {
                        if ( $student->mark > $maxmarkOfSubject )
                        {
                            $markExceedsTotalMark[] = $student['registerNumber'];
                            $errorFlag = 1;
                        }
                        else
                        {
                            $valuationStudents->registerNumber =  $student['registerNumber'];
                            $valuationStudents->studentId =  $registeredStudentDetails[$regNo]["studentId"];
                            $valuationStudents->mark =  $student['mark'];
                            $valuationStudents->assessmentId    = $registeredStudentDetails[$regNo]["assessmentId"];
                            $examValuation->examValuationStudentMarkDetails[] = $valuationStudents;
                            $regStudentCount++;
                        }
                    }
                    else
                    {
                        $unregisteredStudents[] = $student['registerNumber'];
                        $errorFlag = 1;
                    }
                }
                if ( $regStudentCount ) {
                    $response = $this->saveExamValuationStudentmarksForBarcode ( $examValuation );
                }
                if ( $errorFlag || $response->error) 
                {
                    $errors["unregisteredStudent"] = $errors["markExceedsTotalMark"] =$errors["error"] = $errors["success"] = $errors["notEligibleThirdValuation"] = $errors["secondValuationNotCompletedStudents"] = $errors["firstValuationNotCompletedStudents"] = $errors["otherPacketStudents"] ="";
                    if ( !empty ( $unregisteredStudents ) ) {
                        $errors["unregisteredStudent"] = "The student with register number ". implode(", ", $unregisteredStudents)." is/are not registered for exam";
                    }
                    if ( !empty ( $markExceedsTotalMark ) ) {
                        $errors["markExceedsTotalMark"] = "The marks entered for the student(s) with register number ". implode(", ", $markExceedsTotalMark)." exceeds the total mark of exam";
                    }
                    if ( !empty ( $response->otherPacketStudents ) ) {
                        $errors["otherPacketStudents"] = "The marks entered for the student(s) with register number ". implode(", ", $response->otherPacketStudents)." is/are already generated other packet(s)";
                    }
                    if ( !empty ( $response->firstValuationNotCompletedStudents ) ) {
                        $errors["firstValuationNotCompletedStudents"] = "The marks entered for the student(s) with register number ". implode(", ", $response->firstValuationNotCompletedStudents)." is/are not complete first valuation";
                    }
                    if ( !empty ( $response->secondValuationNotCompletedStudents ) ) {
                        $errors["secondValuationNotCompletedStudents"] = "The marks entered for the student(s) with register number ". implode(", ", $response->secondValuationNotCompletedStudents)." is/are not complete second valuation";
                    }
                    if ( !empty ( $response->notEligibleThirdValuation ) ) {
                        $errors["notEligibleThirdValuation"] = "The marks entered for the student(s) with register number ". implode(", ", $response->notEligibleThirdValuation)." is/are not eligible for third valuation";
                    }
                    if($response->updatedStudentCount)
                    {
                        $errors["success"] = "Marks saved successfully for $response->updatedStudentCount student(s)";
                    }
                }
                else
                {
                    $success["success"] = "";
                    if($response->updatedStudentCount)
                    {
                        $success["success"] = "Marks saved successfully for $response->updatedStudentCount student(s)";
                    }
                }
            }
            else
            {
                $errors["unregisteredStudent"] = $errors["markExceedsTotalMark"] =$errors["error"] = $errors["success"] = $errors["notEligibleThirdValuation"] = $errors["secondValuationNotCompletedStudents"] = $errors["firstValuationNotCompletedStudents"] = $errors["otherPacketStudents"] ="";
                $errors["error"] = "No Student Mark Entered";
            }
            $response->errors = $errors;
            $response->success = $success;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    /**
     * save Exam Valuation Studentmarks For Barcode
     * @param $examValuation
     * @return $response
     */
    public function saveExamValuationStudentmarksForBarcode($examValuation){
        $examValuation = $this->realEscapeObject($examValuation);
        try {
            $examValuation = $this->realEscapeObject ( $examValuation );
            $examRegistrationId = $examValuation->examRegistrationId;
            $academicPaperId = $examValuation->academicPaperId;
            $currentValuationCount = $examValuation->currentValuationCount;
            $studentMarkDetailsArray = $examValuation->examValuationStudentMarkDetails;
            $registeredStudentsArray = [];
            $registeredStudentsCurrentMarks = [];
            $error = 0;
            $adminId = $GLOBALS['userId'];
            $updatedStudentCount = 0;
            $insertionMarkTableArray = [];
            $deleteMarkTableArray = [];
            $updateValuatedStaffValues = [];
            $insert_third_val_students = [];
            $delete_third_val_students = [];
            $studentMarkDetails = [];
            $otherPacketStudents = [];
            $notEligibleThirdValuation = [];
            $valuationProperties = new \Stdclass();
            $valuatedStaffObject = new \Stdclass();
            $markEntryObj = new \Stdclass();
            
            $response = new \Stdclass();
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ( $examValuation->courseType );
            $isTheory = $this->getIsTheoryOrNotByExamRegistrationIdAndPaperSubjectId( $examRegistrationId,$academicPaperId);
            $maxmarkOfSubject = (int)ExamRegistrationSubjectService::getInstance()->getMaxSubjectMarkByAcademicPaperSubjectId($academicPaperId);
            $markDiff = CommonExamService::getInstance()->getExternalValuationMarkDiff($examValuation->courseType,$maxmarkOfSubject);
            if(($courseType->courseTypeMethod != "PG")){
                $currentValuationCount = "FINALIZED";
            }
            else if($courseType->courseTypeMethod == "PG"){
                if(($currentValuationCount == 1) && ($isTheory == "0")){
                    $currentValuationCount = "FINALIZED";
                }
            }
            $valuationProperties->packetNo = $examValuation->packetNumber;
            $valuatedStaffObject->staffIds = $examValuation->facultyId;
            $valuatedStaffObject->valuationCount = $currentValuationCount;
            $valuationProperties->valuatedStaffs[]=$valuatedStaffObject;
            foreach($studentMarkDetailsArray as $student){
                if(($student->registerNumber) && ($student->mark != "")){
                    $conditions[] = " (sa.regNo = '".$student->registerNumber."' AND  esar.am_assessment_id = '".$student->assessmentId."') ";
                }
            }
            if(! empty($conditions)){
                $studentDetails = $this->getStudentsExternalMarksByStudentExamDetail($conditions);
                foreach($studentMarkDetailsArray as $student){
                    $registeredStudentsArray[$student->studentId] = $student->studentId;
                    $registeredStudentsCurrentMarks[$student->studentId] = $student->mark;
                }
                foreach($studentDetails as $studentDetail){
                    if ( in_array ( $studentDetail->studentId, $registeredStudentsArray ) ) {
                        if($studentDetail->packetNo == $examValuation->packetNumber || is_null($studentDetail->packetNo)){
                            $singleStudentDetail = new \Stdclass();
                            $facultyUpdated = false;
                            $singleStudentDetail = $studentDetail;
                            $singleStudentDetail->currentMark = $registeredStudentsCurrentMarks[$studentDetail->studentId];
                            if(is_null($studentDetail->valuatedStaffs)){
                                $singleStudentDetail->valuationDetails = $valuationProperties;
                            }
                            else if($studentDetail->valuatedStaffs){
                                $valuatedStaffs = json_decode($studentDetail->valuatedStaffs);
                                foreach($valuatedStaffs as $valuatedStaff){
                                    if($valuatedStaff->valuationCount == $currentValuationCount){
                                        $valuatedStaff->staffIds = $examValuation->facultyId;
                                        $facultyUpdated = true;
                                    }
                                }
                                if(!$facultyUpdated){
                                    $valuatedStaffs[] = $valuatedStaffObject;
                                }
                                $valuationDetails = json_decode($singleStudentDetail->valuationDetails, true);
                                $valuationDetails['valuatedStaffs'] = $valuatedStaffs;
                                $singleStudentDetail->valuationDetails = json_encode($valuationDetails);
                            }
                            if( $singleStudentDetail->studentId){
                                $studentMarkDetails[] = $singleStudentDetail;
                            } 
                        }
                    }
                    else{
                        $otherPacketStudents[] = $studentDetail->regNo;
                        $error = 1;
                    }
                }
                foreach($studentMarkDetails as $studentMarkDetail){
                    $updateMarkValuatedStaff = new \Stdclass();
                    if($currentValuationCount == 'FINALIZED'){
                        $markEntryObj = new \stdClass();
                        $markEntryObj->studentId = $studentMarkDetail->studentId;
                        $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                        $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                        $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                        $markEntryObj->attendanceStatus = "PRESENT";
                        $markEntryObj->valuationCount = 'FINALIZED';
                        $markproperties = "";
                        if($studentMarkDetail->finalizedMarkProperties){
                            $markproperties = (object)$studentMarkDetail->finalizedMarkProperties;
                        }
                        $markEntryObj->properties  = $markproperties;
                        $markEntryObj->valuationType = null;
                        $insertionMarkTableArray[] = $markEntryObj;
                        $updateMarkValuatedStaff->assessmentId = $studentMarkDetail->assessmentId;
                        $updateMarkValuatedStaff->studentId = $studentMarkDetail->studentId;
                        $updateMarkValuatedStaff->valuationProperties = $studentMarkDetail->valuationDetails;
                        $updateMarkValuatedStaff->updatedBy = $adminId;
                        $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                        $updatedStudentCount ++;
                    }
                    if($currentValuationCount == 1){
                        $markEntryObj = new \stdClass();
                        $markEntryObj->studentId = $studentMarkDetail->studentId;
                        $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                        $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                        $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                        $markEntryObj->attendanceStatus = "PRESENT";
                        $markEntryObj->valuationCount = 1;
                        $markproperties = "";
                        if($studentMarkDetail->firstValuationMarkProperties){
                            $markproperties = (object)$studentMarkDetail->firstValuationMarkProperties;
                        }
                        $markEntryObj->properties  = $markproperties;
                        $markEntryObj->valuationType = null;
                        $insertionMarkTableArray[] = $markEntryObj;
                        $updateMarkValuatedStaff->assessmentId = $studentMarkDetail->assessmentId;
                        $updateMarkValuatedStaff->studentId = $studentMarkDetail->studentId;
                        $updateMarkValuatedStaff->valuationProperties = $studentMarkDetail->valuationDetails;
                        $updateMarkValuatedStaff->updatedBy = $adminId;
                        $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                        $updatedStudentCount ++;
                    }
                    if($currentValuationCount == 2){
                        if($studentMarkDetail->firstValuationMark != null){
                            $markEntryObj = new \stdClass();
                            $markEntryObj->studentId = $studentMarkDetail->studentId;
                            $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                            $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                            $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                            $markEntryObj->attendanceStatus = "PRESENT";
                            $markEntryObj->valuationCount = 2;
                            $markproperties = "";
                            if($studentMarkDetail->secondValuationMarkProperties){
                                $markproperties = (object)$studentMarkDetail->secondValuationMarkProperties;
                            }
                            $markEntryObj->properties  = $markproperties;
                            $markEntryObj->valuationType = null;
                            $insertionMarkTableArray[] = $markEntryObj;
                            $updateMarkValuatedStaff->assessmentId = $studentMarkDetail->assessmentId;
                            $updateMarkValuatedStaff->studentId = $studentMarkDetail->studentId;
                            $updateMarkValuatedStaff->valuationProperties = $studentMarkDetail->valuationDetails;
                            $updateMarkValuatedStaff->updatedBy = $adminId;
                            $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                            $studentMarkDiff = abs ($studentMarkDetail->firstValuationMark - $studentMarkDetail->currentMark);
                            $updatedStudentCount ++;
                            $deleteMarkEntryObj = new ExamUserMarkRequest;
                            $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                            $deleteMarkEntryObj->studentId = $studentMarkDetail->studentId;
                            $deleteMarkEntryObj->valuationCount = 3;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                            if( $studentMarkDiff >= $markDiff){
                                // $deleteMarkEntryObj = new ExamUserMarkRequest;
                                // $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                // $deleteMarkEntryObj->studentId = $studentMarkDetail->studentId;
                                // $deleteMarkEntryObj->valuationCount = 'FINALIZED';
                                // $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $studentMarkDetail->studentId;
                                $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                $markEntryObj->markObtained = NULL;
                                $markEntryObj->attendanceStatus = "PRESENT";
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markproperties = "";
                                if($studentMarkDetail->finalizedMarkProperties){
                                    $markproperties = (object)$studentMarkDetail->finalizedMarkProperties;
                                }
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                                $insertionMarkTableArray[] = $markEntryObj;
                                $insert_third_val_students[] = "( '".$studentMarkDetail->assessmentId."', ".$studentMarkDetail->studentId." )";
                            }
                            else{
                                $studentMark =  ($studentMarkDetail->firstValuationMark + $studentMarkDetail->currentMark)/2;
                                    $markEntryObj = new \stdClass();
                                    $markEntryObj->studentId = $studentMarkDetail->studentId;
                                    $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                    $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                    $markEntryObj->markObtained = $studentMark;
                                    $markEntryObj->attendanceStatus = "PRESENT";
                                    $markEntryObj->valuationCount = 'FINALIZED';
                                    $markproperties = "";
                                    if($studentMarkDetail->finalizedMarkProperties){
                                        $markproperties = (object)$studentMarkDetail->finalizedMarkProperties;
                                    }
                                    $markEntryObj->properties  = $markproperties;
                                    $markEntryObj->valuationType = null;
                                $insertionMarkTableArray[] = $markEntryObj;
                                $delete_third_val_students[] = "( am_assessment_id = '$studentMarkDetail->assessmentId' AND studentID = '$studentMarkDetail->studentId' )" ;
                            }
                        }
                        else{
                            $firstValuationNotCompletedStudents[] = $studentDetail->registerNumber;
                            $error = 1;
                        }
                    }
                    if($currentValuationCount == 3){
                        if($studentMarkDetail->thirdValReq == 1){
                            if($studentMarkDetail->firstValuationMark != null || $studentMarkDetail->secondValuationMark != null){
                                    $markEntryObj = new \stdClass();
                                    $markEntryObj->studentId = $studentMarkDetail->studentId;
                                    $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                    $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                    $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                                    $markEntryObj->attendanceStatus = "PRESENT";
                                    $markEntryObj->valuationCount = 3;
                                    $markproperties = "";
                                    if($studentMarkDetail->thirdValuationMarkProperties){
                                        $markproperties = (object)$studentMarkDetail->thirdValuationMarkProperties;
                                    }
                                    $markEntryObj->properties  = $markproperties;
                                    $markEntryObj->valuationType = null;
                                $insertionMarkTableArray[] = $markEntryObj;
                                $updatedStudentCount ++;
                                $updateMarkValuatedStaff->assessmentId = $studentMarkDetail->assessmentId;
                                $updateMarkValuatedStaff->studentId = $studentMarkDetail->studentId;
                                $updateMarkValuatedStaff->valuationProperties = $studentMarkDetail->valuationDetails;
                                $updateMarkValuatedStaff->updatedBy = $adminId;
                                $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                                $studentMark = array($studentMarkDetail->firstValuationMark,$studentMarkDetail->secondValuationMark,$studentMarkDetail->currentMark);
                                sort($studentMark);
                                $diff_01 = abs ( $studentMark[0] - $studentMark[1] );
                                $diff_12 = abs ( $studentMark[1] - $studentMark[2] );
                                if ( $diff_01 < $diff_12 ) {
                                    $nearestTwo = array_slice($studentMark, 0, 2);
                                } else {
                                    $nearestTwo = array_slice($studentMark, 1, 2);
                                }
                                $avgMark = array_sum($nearestTwo) / 2;
                                    $markEntryObj = new \stdClass();
                                    $markEntryObj->studentId = $studentMarkDetail->studentId;
                                    $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                    $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                    $markEntryObj->markObtained = $avgMark;
                                    $markEntryObj->attendanceStatus = "PRESENT";
                                    $markEntryObj->valuationCount = 'FINALIZED';
                                    $markproperties = "";
                                    if($studentMarkDetail->finalizedMarkProperties){
                                        $markproperties = (object)$studentMarkDetail->finalizedMarkProperties;
                                    }
                                    $markEntryObj->properties  = $markproperties;
                                    $markEntryObj->valuationType = null;
                                $insertionMarkTableArray[] = $markEntryObj;
                            }
                            elseif($studentMarkDetail->firstValuationMark == null){
                                $firstValuationNotCompletedStudents[] = $studentDetail->registerNumber;
                                $error = 1;
                            }
                            elseif($studentMarkDetail->secondValuationMark == null){
                                $secondValuationNotCompletedStudents[] = $studentDetail->registerNumber;
                                $error = 1;
                            }
                        }
                        else{
                            $notEligibleThirdValuation[] = $studentDetail->registerNumber;
                            $error = 1;
                        }
                    }
                }
            }
            if(! empty($insertionMarkTableArray)){
                ExamUserMarkService::getInstance()->saveExamUserTotalMark($insertionMarkTableArray);
            }
            if(! empty($deleteMarkTableArray)){
                foreach($deleteMarkTableArray as $deleteObj){
                    ExamUserMarkService::getInstance()->deleteExamUserTotalMark($deleteObj);
                }
            }
            if(! empty($updateValuatedStaffValues)){
                $this->updateValuatedStaffToStudentRegistration($updateValuatedStaffValues);
            }
            if(! empty($insert_third_val_students)){
                $this->insertThirdValStudentRegistration($insert_third_val_students);
            }
            if(! empty($delete_third_val_students)){
                $this->deleteThirdValStudentRegistration($delete_third_val_students);
            }
            $response->error = $error;
            $response->otherPacketStudents = $otherPacketStudents;
            $response->firstValuationNotCompletedStudents = $firstValuationNotCompletedStudents;
            $response->secondValuationNotCompletedStudents = $secondValuationNotCompletedStudents;
            $response->notEligibleThirdValuation = $notEligibleThirdValuation;
            $response->updatedStudentCount = $updatedStudentCount;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
     /**
     * get All Students External Marks By Student Exam Detail For Exam Registration
     * @param $condition
     * @return $studentDetails
     */
    public function getAllStudentsExternalMarksByStudentExamDetailForExamRegistration($condition){
        try{
            $query = "SELECT
                        DISTINCT sa.studentID as studentId,
                        sa.regNo,
                        esar.am_assessment_id as assessmentId,
                        esar.valuation_details ->> '$.packetNo' as packetNo,
                        esar.valuation_details ->> '$.valuatedStaffs' as valuatedStaffs,
                        ostmf.mark_obtained as finalizedMark,
                        ostm1.mark_obtained as firstValuationMark,
                        ostm2.mark_obtained as secondValuationMark,
                        ostm3.mark_obtained as thirdValuationMark,
                        IF(ets.thirdvalstudentID, 1, 0) AS thirdValReq
                    FROM
                        ec_exam_registration_subject eers 
                    INNER JOIN ec_exam_registration_batch eerb ON
                        eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer
                        ON eer.id = eerb.ec_exam_registration_id 
                    INNER JOIN ec_student_assessment_registration esar ON
                        esar.am_assessment_id = eers.am_assessment_id AND  esar.ec_exam_registration_type = eer.type AND CAST(esar.properties ->> '$.registrationStatus' AS CHAR) = 'REGISTERED' AND  CAST(esar.properties ->> '$.feeStatus' AS CHAR) = 'PAID'
                    INNER JOIN studentaccount sa ON
                        sa.studentID = esar.student_id
                    LEFT JOIN oe_student_total_mark ostmf ON 
                            ostmf.student_id = sa.studentID AND ostmf.am_assessment_id = esar.am_assessment_id AND ostmf.valuation_count = 'FINALIZED'
                    LEFT JOIN oe_student_total_mark ostm1 ON 
                            ostm1.student_id = sa.studentID AND ostm1.am_assessment_id = esar.am_assessment_id AND ostm1.valuation_count = '1'
                    LEFT JOIN oe_student_total_mark ostm2 ON 
                            ostm2.student_id = sa.studentID AND ostm2.am_assessment_id = esar.am_assessment_id AND ostm2.valuation_count = '2'
                    LEFT JOIN oe_student_total_mark ostm3 ON 
                            ostm3.student_id = sa.studentID AND ostm3.am_assessment_id = esar.am_assessment_id AND ostm3.valuation_count = '3'
                    LEFT JOIN externalexam_thirdvalstudents ets ON 
                            ets.studentID = sa.studentID AND ets.am_assessment_id = eers.am_assessment_id
                    WHERE"  . $condition ;
            $studentDetails = $this->executeQueryForList($query);
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * get Faculties By FacultyIds
     * @param $condition
     * @return $faculties
     */
    public function getFacultiesByFacultyIds($condition)
    {
        $condition = $this->realEscapeString($condition);
        try
        {
            $query = "SELECT
                        sa.staffName,
                        sa.staffID
                    FROM
                        staffaccounts sa
                   
                    WHERE " .$condition ;
            $faculties = $this->executeQueryForList($query);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $faculties;
    }
     /**
     * get Subject Details By Academic Paper SubjectId And ExamRegistrationId
     * @param $academicPaperSubjectId
     * @param $examRegistrationId
     * @return $subjectDetails
     */
    public function getSubjectDetailsByAcademicPaperSubjectIdAndExamRegistrationId($academicPaperSubjectId,$examRegistrationId)
    {
        $academicPaperSubjectId = is_array($academicPaperSubjectId) ? $this->realEscapeArray($academicPaperSubjectId):$this->realEscapeString($academicPaperSubjectId);
        $examRegistrationId = $this->realEscapeString($examRegistrationId);
        $academicPaperSubjectId = is_array($academicPaperSubjectId) ? "'" . implode("','",$academicPaperSubjectId) . "'" : "'".$academicPaperSubjectId."'";
        try
        {
            $query = "SELECT
                        eer.id as examRegistrationId,
                        eer.name as examRegistrationName,
                        eer.type as examRegistrationType,
                        eer.properties ->> '$.examDate' as examDate,
                        aps.properties ->> '$.externalMaxMark' as maximumSubjectMark,
                        s.code as subjectCode,
                        s.name as subjectName,
                        IF(aps.properties ->> '$.classType' = 'THEORY',1,0) AS isTheory,
                        g.name as groupName,
                        g.id as groupId
                    FROM
                        ec_exam_registration_subject eers
                    INNER JOIN ec_exam_registration_batch eerb ON
                        eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer ON
                        eer.id = eerb.ec_exam_registration_id
                    INNER JOIN `groups` g ON
                        g.id = eerb.groups_id
                    INNER JOIN  cm_academic_paper_subjects aps ON 
                        aps.id = eers.cm_academic_paper_subjects_id
                    INNER JOIN  v4_ams_subject s ON 
                        s.id = aps.ams_subject_id
                    WHERE
                        eerb.ec_exam_registration_id='$examRegistrationId' AND 
                        eers.cm_academic_paper_subjects_id IN ($academicPaperSubjectId)";
            $subjectDetails  = $this->executeQueryForObject($query);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $subjectDetails;
    }
    /**
     * get All Students Marks Details For ExamRegistration Subject
     * @param $searchRequest
     * @return $response
     */
    public function getAllStudentsMarksDetailsForExamRegistrationSubject($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try {
            $response = new \stdClass;
            $registeredStudentMarkDetails = [];
            $isnotPG = false;
            $currentValuationCount = null;
            $academicPaperId = stripslashes($searchRequest->academicPaperId);
            $markEntryEditSettings = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::EXAM_VALUATION_MARK_EDIT);
            $isFalseNumber = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::IS_FALSE_NUMBER_IN_EXTERNAL_MARK_ENTRY_DIRECT);
            $editEnabled = CommonUtil::isEditEnabledInExamValuation ( $markEntryEditSettings, ExamType::EXTERNAL );
            $subjectDetails = $this->getSubjectDetailsByAcademicPaperSubjectId($academicPaperId);
            $maxmarkOfSubject = ExamRegistrationSubjectService::getInstance()->getMaxSubjectMarkByAcademicPaperSubjectId($academicPaperId);
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ($searchRequest->courseType);
            if(! $subjectDetails->isExternal){
                throw new ExamControllerException(ExamControllerException::INTERNAL_ONLY_SUBJECT,"Internal Only Subject");
            }
            elseif(! $subjectDetails->maximumSubjectMark){
                throw new ExamControllerException(ExamControllerException::MAX_MARK_NOT_CONFIGURED,"Subject not configured");
            }
            if($courseType->extValRequired == '1'){
                $currentValuationCount = $searchRequest->currentValuationCount;
                $isnotPG = false;
            }
            else{
                $currentValuationCount = null;
                $isnotPG = true;
            }
            if($editEnabled){
                if($isnotPG){
                    $request = new \stdClass;
                    $request->examRegistrationId = $searchRequest->examRegistrationId;
                    $request->academicPaperSubjectId = stripslashes($searchRequest->academicPaperId);
                    $request->groupId = $searchRequest->groupId;
                    $registeredStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                    foreach($registeredStudentMarkDetails as $student){
                        $student->isWithHeld  = false;
                        if ( $student->isExempted == 1 ) {
                            $student->mark = "EX";
                            $student->oldMark  = 'Exempted';
                        }
                        else if ( $student->isAbsent == "ABSENT" ) {
                            $student->mark  = "AB";
                            $student->oldMark  = 'Absent';
                        } 
                        else if ( $student->isAbsent == "MALPRACTICE" ) {
                            $student->mark  = "MAL";
                            $student->oldMark  = 'Mal-Practice';
                        } 
                        else if ($student->isAbsent == "WITHHELD") {
                            $student->mark  = $student->finalizedMark;
                            $student->isWithHeld  = true;
                            $student->oldMark  = 'with held';
                        }
                        else{
                            $student->mark  = $student->finalizedMark;
                            $student->oldMark  = $student->finalizedMark;
                        }
                    }
                }
                else{
                    if($currentValuationCount == 1){
                        $request = new \stdClass;
                        $request->examRegistrationId = $searchRequest->examRegistrationId;
                        $request->academicPaperSubjectId = stripslashes($searchRequest->academicPaperId);
                        $request->groupId = $searchRequest->groupId;
                        $registeredStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                        foreach($registeredStudentMarkDetails as $student){
                            $student->isWithHeld  = false;
                            if ( $student->isExempted == 1 ) {
                                $student->mark = "EX";
                                $student->oldMark  = 'Exempted';
                            }
                            else if ( $student->isAbsent == "ABSENT" ) {
                                $student->mark  = "AB";
                                $student->oldMark  = 'Absent';
                            } 
                            else if ( $student->isAbsent == "MALPRACTICE" ) {
                                $student->mark  = "MAL";
                                $student->oldMark  = 'Mal-Practice';
                            } 
                            else if ($student->isAbsent == "WITHHELD") {
                                $student->mark  = $student->firstValuationMark;
                                $student->isWithHeld  = true;
                                $student->oldMark  = 'with held';
                            }
                            else{
                                $student->mark  = $student->firstValuationMark;
                            }
                        }
                    }
                    else if($currentValuationCount == 2){
                        $markDiff = CommonExamService::getInstance()->getExternalValuationMarkDiff($searchRequest->courseType,$maxmarkOfSubject);
                        $request = new \stdClass;
                        $request->examRegistrationId = $searchRequest->examRegistrationId;
                        $request->academicPaperSubjectId = stripslashes($searchRequest->academicPaperId);
                        $request->groupId = $searchRequest->groupId;
                        $request->isFirstValuatedStudentOnly = true;
                        $registeredStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                        foreach($registeredStudentMarkDetails as $student){
                            $student->isWithHeld  = false;
                            if ( $student->isExempted == 1 ) {
                                $student->mark = "EX";
                            }
                            else if ( $student->isAbsent == "ABSENT" ) {
                                $student->mark  = "AB";
                            } 
                            else if ( $student->isAbsent == "MALPRACTICE" ) {
                                $student->mark  = "MAL";
                            } 
                            else if ($student->isAbsent == "WITHHELD") {
                                $student->mark  = $student->secondValuationMark." (With Held)";
                                $student->isWithHeld  = true;
                            }
                            else{
                                $student->mark  = $student->secondValuationMark;
                            }
                            if($student->secondValuationMark != null){
                                $studentMarkDiff = abs ($student->firstValuationMark - $student->secondValuationMark);
                                if($studentMarkDiff >= $markDiff){
                                    $student->thirdValRequiredFlag = 1;
                                }
                                else{
                                    $student->thirdValRequiredFlag = 0;
                                }
                            }
                            else{
                                $student->thirdValRequiredFlag = 0;
                            }
                        }
                    }
                    else if($currentValuationCount == 3){
                        $request = new \stdClass;
                        $request->examRegistrationId = $searchRequest->examRegistrationId;
                        $request->academicPaperSubjectId = stripslashes($searchRequest->academicPaperId);
                        $request->groupId = $searchRequest->groupId;
                        $request->isFirstValuatedStudentOnly = true;
                        $request->isSecondValuatedStudentOnly = true;
                        $registeredStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                        foreach($registeredStudentMarkDetails as $student){
                            $student->isWithHeld  = false;
                            if ( $student->isExempted == 1 ) {
                                $student->mark = "EX";
                            }
                            else if ( $student->isAbsent == "ABSENT" ) {
                                $student->mark  = "AB";
                            } 
                            else if ( $student->isAbsent == "MALPRACTICE" ) {
                                $student->mark  = "MAL";
                            } 
                            else if ($student->isAbsent == "WITHHELD") {
                                $student->mark  = $student->thirdValuationMark." (With Held)" ;
                                $student->isWithHeld  = true;
                            }
                            else{
                                $student->mark  = $student->thirdValuationMark;
                            }
                        }
                    } 
                }
            }
            $response->MakEntryDetails = $registeredStudentMarkDetails;
            $response->currentValuationCount = (int)$currentValuationCount;
            $response->IsFalseNumberSettings = $isFalseNumber;
            $response->maxMarkOfSubject = (int)$maxmarkOfSubject;
            $response->markDiff = (int)$markDiff;
            $response->subject = $subjectDetails;
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
      /**
     * print Student Mark For Edit Extrenal Mark
     * @param  $markEntryRequest
     */
    public function printStudentMarkForEditExtrenalMark($searchRequest)
    {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $response = new \stdClass;
            $registeredStudentMarkDetails = [];
            $examRegistrationId = $searchRequest->examRegistrationId;
            $academicPaperId = stripslashes($searchRequest->academicPaperId);
            $currentValuationCount = $searchRequest->currentValuationCount;
            $markEntryEditSettings = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::EXAM_VALUATION_MARK_EDIT);
            $isFalseNumber = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::IS_FALSE_NUMBER_IN_EXTERNAL_MARK_ENTRY_DIRECT);
            $maxmarkOfSubject = (int)ExamRegistrationSubjectService::getInstance()->getMaxSubjectMarkByAcademicPaperSubjectId($academicPaperId);
            // $isFalseNumber = "FALSE_NUMBER";
            $editEnabled = CommonUtil::isEditEnabledInExamValuation ( $markEntryEditSettings, ExamType::EXTERNAL );
            if($editEnabled){
                if($currentValuationCount == 1 || !$currentValuationCount){
                    $request = new \stdClass;
                    $request->examRegistrationId = $searchRequest->examRegistrationId;
                    $request->academicPaperSubjectId = stripslashes($searchRequest->academicPaperId);
                    $request->groupId = $searchRequest->groupId;
                    $registeredStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                    foreach($registeredStudentMarkDetails as $student){
                        $student->isWithHeld  = false;
                        if ( $student->isExempted == 1 ) {
                            $student->firstValuationMark = "Exempted";
                            $student->finalizedMark = "Exempted";
                        }
                        else if ( $student->isAbsent == "ABSENT" ) {
                            $student->firstValuationMark = "Absent";
                            $student->finalizedMark = "Absent";
                        } 
                        else if ( $student->isAbsent == "MALPRACTICE" ) {
                            $student->firstValuationMark = "Mal Practice";
                            $student->finalizedMark = "Mal Practice";
                        } 
                        else if ($student->isAbsent == "WITHHELD") {
                            $student->firstValuationMark = "With Held";
                            $student->finalizedMark = "With Held";
                        }
                        else{
                            if(!$student->firstValuationMark){
                                //for handling ug maks temporary fix
                                $student->firstValuationMark = $student->finalizedMark ? $student->finalizedMark : "";
                            }
                            $student->mark  = $currentValuationCount == 1 ? $student->firstValuationMark : $student->finalizedMark;
                        }
                    }
                }
                else if($currentValuationCount == 2){
                    $markDiff = CommonExamService::getInstance()->getExternalValuationMarkDiff($searchRequest->courseType,$maxmarkOfSubject);
                    $request = new \stdClass;
                    $request->examRegistrationId = $searchRequest->examRegistrationId;
                    $request->academicPaperSubjectId = stripslashes($searchRequest->academicPaperId);
                    $request->groupId = $searchRequest->groupId;
                    $request->isFirstValuatedStudentOnly = true;
                    $registeredStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                    foreach($registeredStudentMarkDetails as $student)
                    {
                        $student->isWithHeld  = false;
                        if ( $student->isExempted == 1 ) {
                            $student->secondValuationMark = "Exempted";
                        }
                        else if ( $student->isAbsent == "ABSENT" ) {
                            $student->secondValuationMark = "Absent";
                        } 
                        else if ( $student->isAbsent == "MALPRACTICE" ) {
                            $student->secondValuationMark = "Mal Practice";
                        } 
                        else if ($student->isAbsent == "WITHHELD") {
                            $student->secondValuationMark = "With Held";
                        }
                        else
                        {
                            $student->mark  = $student->secondValuationMark;
                        }
                        if($student->secondValuationMark != null)
                        {
                            $studentMarkDiff = abs ($student->firstValuationMark - $student->secondValuationMark);
                            if($studentMarkDiff >= $markDiff)
                            {
                                $student->thirdValRequiredFlag = 1;
                            }
                            else
                            {
                                $student->thirdValRequiredFlag = 0;
                            }
                        }
                        else
                        {
                            $student->thirdValRequiredFlag = 0;
                        }
                    }
                }
                else if($currentValuationCount == 3){
                    $request = new \stdClass;
                    $request->examRegistrationId = $searchRequest->examRegistrationId;
                    $request->academicPaperSubjectId = stripslashes($searchRequest->academicPaperId);
                    $request->groupId = $searchRequest->groupId;
                    $request->isFirstValuatedStudentOnly = true;
                    $request->isSecondValuatedStudentOnly = true;
                    $request->isThirdValuationStudentOnly = true;
                    $registeredStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                    foreach($registeredStudentMarkDetails as $student)
                    {
                        $student->isWithHeld  = false;
                        if ( $student->isExempted == 1 ) {
                            $student->thirdValuationMark = "Exempted";
                        }
                        else if ( $student->isAbsent == "ABSENT" ) {
                            $student->thirdValuationMark = "Absent";
                        } 
                        else if ( $student->isAbsent == "MALPRACTICE" ) {
                            $student->thirdValuationMark = "Mal Practice";
                        } 
                        else if ($student->isAbsent == "WITHHELD") {
                            $student->thirdValuationMark = "With Held";
                        }
                        else
                        {
                            $student->mark  = $student->thirdValuationMark;
                        }
                    }
                } 
            }
            if(empty($registeredStudentMarkDetails))
            {
                throw new ExamControllerException(ExamControllerException::NO_STUDENT_IN_THE_BATCH_SUBJECT,"No Students Registerd In this Exam");
            }
            else
            {
                $examRegistrationSubject = $this->getSubjectDetailsByAcademicPaperSubjectIdAndExamRegistrationId($academicPaperId,$examRegistrationId);
                $templateName = "printEditedExternalMarks";
                $templateName = $searchRequest->printTemplate ? $searchRequest->printTemplate : $templateName;
                $responseHtml = TwigRenderer::renderTemplateFileToHtml(realpath(DOCUMENT_ROOT."../examcontroller-api/src/com/linways/web/templates/printTwigs/$templateName.twig"), [ 'registeredStudentMarkDetails'=>$registeredStudentMarkDetails ,'examRegistrationSubject'=>$examRegistrationSubject,'valuationCount'=>$currentValuationCount,'isFalseNumber'=>$isFalseNumber]);
                $prtContent = NULL;
                    $prtContent .= '<html><head>';
                    $prtContent .= "<style>
                        
                        </style>";
                    $prtContent .= '</head><title>Edit External Mark Report</title><body>';
                    $prtContent .= $responseHtml;
                    $prtContent .= '</body></html>';
                    $totalWidth = 210;
                    $totalHeight = 297;
                    $options = array(
                        'page-width'     => $totalWidth."mm",
                        'page-height'    => $totalHeight."mm",
                        'dpi'            => 96,
                        'margin-top' => "9mm",
                        'margin-left' => "1mm",
                        'margin-right' => "1mm",
                        'margin-bottom' => "9mm",
                        // 'binary' => "/usr/local/bin/wkhtmltopdf", // For Mac
                        'user-style-sheet' => realpath(DOCUMENT_ROOT . "/libcommon/bootstrap/css/bootstrap.min.css")
                    );
                $programResult = new \stdClass;
                $programResult->displayData = $responseHtml;
                $programResult->pdf = PdfUtil::renderPdf($prtContent, $options);
                return  $programResult;
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * get SubjectDetails ByA cademic Paper SubjectId
     * @param $academicPaperSubjectId
     * @return $subjectDetails
     */
    public function getSubjectDetailsByAcademicPaperSubjectId($academicPaperSubjectId){
        $academicPaperSubjectId = $this->realEscapeString($academicPaperSubjectId);
        $academicPaperSubjectId = stripslashes($academicPaperSubjectId);
        try 
        {
            $query = "SELECT
                            DISTINCT s.id as id,
                            s.code as code,
                            s.name as name,
                            IF(aps.properties ->> '$.classType' = 'THEORY',1,0) AS isTheory,
                            aps.properties ->> '$.isExternal' as isExternal,
                            aps.properties ->> '$.externalMaxMark' as maximumSubjectMark
                        FROM
                            cm_academic_paper_subjects aps
                        INNER JOIN v4_ams_subject s ON 
                            s.id = aps.ams_subject_id
                        WHERE
                            aps.id IN ('$academicPaperSubjectId')";
            $subjectDetails = $this->executeQueryForObject($query);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $subjectDetails;
    }
     /**
     * save All Edit External Marks
     * @param $studentMarkDetailsArray
     * @param $searchRequest
     * @return $subjectDetails
     */
    public function saveAllEditExternalMarks($studentMarkDetailsArray,$searchRequest){
        $searchRequest = $this->realEscapeArray($searchRequest);
        $studentMarkDetailsArray = $this->realEscapeArray($studentMarkDetailsArray);
        try{
            $adminId =  $GLOBALS['userId'];
            $staffName = $this->getStaffNameByStaffId($adminId);
            $registeredStudentsArray = [];
            $registeredStudentsCurrentMark = [];
            $registeredStudentsAssessmentIds = [];
            $notRegisteredStudents = [];
            $delete_third_val_students = [];
            $editHistoryLog = [];
            $insertionExtrnalMarkLogTableArray = [];
            $examRegistrationId = $searchRequest['examRegistrationId'];
            $academicPaperId = stripslashes($searchRequest['academicPaperId']);
            $currentValuationCount =  1;
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ( $searchRequest['courseType'] );
            $isTheory = $this->getIsTheoryOrNotByExamRegistrationIdAndPaperSubjectId( $examRegistrationId,$academicPaperId);
            $maxmarkOfSubject = ExamRegistrationSubjectService::getInstance()->getMaxSubjectMarkByAcademicPaperSubjectId($academicPaperId);
            $markDiff = CommonExamService::getInstance()->getExternalValuationMarkDiff($searchRequest['courseType'],$maxmarkOfSubject );
            if(($courseType->courseTypeMethod != "PG")){
                $currentValuationCount = "FINALIZED";
            }
            else if($courseType->courseTypeMethod == "PG"){
                $currentValuationCount =  $searchRequest['currentValuationCount'];
                if(($currentValuationCount == 1) && ($isTheory == "0")){
                    $currentValuationCount = "FINALIZED";
                }
            }
            $markProperties = !empty($markProperties) ? "'" . json_encode($markProperties) . "'" : "NULL";
            if( $currentValuationCount == 1 || $currentValuationCount == "FINALIZED"){
                $request = new \stdClass;
                $request->examRegistrationId = $searchRequest['examRegistrationId'];
                $request->academicPaperSubjectId = stripslashes($searchRequest['academicPaperId']);
                $request->groupId = $searchRequest['groupId'];
                $registeredStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                foreach($registeredStudentMarkDetails as $student){
                    $registeredStudentsArray[$student->id] = $student->id;
                    $registeredStudentsAssessmentIds[$student->id] = $student->assessmentId;
                }
                foreach($studentMarkDetailsArray as $studentEntry){
                    if( in_array ( $studentEntry['id'], $registeredStudentsArray ) ) {
                        if($studentEntry['isWithHeld'] != true){
                            if($studentEntry['mark'] != null){
                                $assessmentId = $registeredStudentsAssessmentIds[$studentEntry['id']];
                                $assessmentId = $registeredStudentsAssessmentIds[$studentEntry['id']];
                                $oeExamId = $studentEntry['oeExamId'];
                                $studentId = $studentEntry['id'];
    
                                // for high lighting edit changes in import mark
                                $editRequest = new \stdClass();
                                $editRequest->groupId = $studentEntry['groupId'];
                                $editRequest->studentId = $studentEntry['id'];
                                $editRequest->isDirty = 1;
                                $editRequest->staffId = $GLOBALS['userId'];
                                $editHistoryLog[] = $editRequest;
                                
                                if($studentEntry['mark'] == "AB"){
                                        $markEntryObj = new \stdClass();
                                        $markEntryObj->studentId = $studentEntry['id'];
                                        $markEntryObj->assessmentId = $assessmentId;
                                        $markEntryObj->oeExamsId = $oeExamId;
                                        $markEntryObj->markObtained = null;
                                        $markEntryObj->attendanceStatus = "ABSENT";
                                        $markEntryObj->valuationCount = 'FINALIZED';
                                        $markproperties = "";
                                        if($studentEntry['finalizedMarkProperties']){
                                            $markproperties = (object)$studentEntry['finalizedMarkProperties'];
                                        }
                                        $markEntryObj->properties  = $markproperties;
                                        $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
                                        $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 1;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                        $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 2;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                        $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 3;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                    $deleteExempted[] = " ( am_assessment_id = '".$assessmentId."' AND studentaccount_id =  '".$studentEntry['id']."' ) ";
                                    $delete_third_val_students[] = "( am_assessment_id = '$assessmentId' AND studentID = '".$studentEntry['id']."' )" ;
                                }
                                else if($studentEntry['mark'] == "MAL"){
                                        $markEntryObj = new \stdClass();
                                        $markEntryObj->studentId = $studentEntry['id'];
                                        $markEntryObj->assessmentId = $assessmentId;
                                        $markEntryObj->oeExamsId = $oeExamId;
                                        $markEntryObj->markObtained = null;
                                        $markEntryObj->attendanceStatus = "MALPRACTICE";
                                        $markEntryObj->valuationCount = 'FINALIZED';
                                        $markproperties = "";
                                        if($studentEntry['finalizedMarkProperties']){
                                            $markproperties = (object)$studentEntry['finalizedMarkProperties'];
                                        }
                                        $markEntryObj->properties  = $markproperties;
                                        $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
                                        $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 1;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                        $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 2;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                        $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 3;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                    $deleteExempted[] = " ( am_assessment_id = '".$assessmentId."' AND studentaccount_id =  '".$studentEntry['id']."' ) ";
                                    $delete_third_val_students[] = "( am_assessment_id = '$assessmentId' AND studentID = '".$studentEntry['id']."' )" ;
                                }
                                else if($studentEntry['mark'] == "WH"){
                                        $markEntryObj = new \stdClass();
                                        $markEntryObj->studentId = $studentEntry['id'];
                                        $markEntryObj->assessmentId = $assessmentId;
                                        $markEntryObj->oeExamsId = $oeExamId;
                                        $markEntryObj->markObtained = $studentEntry['finalizedMark'];
                                        $markEntryObj->attendanceStatus = "WITHHELD";
                                        $markEntryObj->valuationCount = 'FINALIZED';
                                        $markproperties = "";
                                        if($studentEntry['finalizedMarkProperties']){
                                            $markproperties = (object)$studentEntry['finalizedMarkProperties'];
                                        }
                                        $markEntryObj->properties  = $markproperties;
                                        $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
                                    $deleteExempted[] = " ( am_assessment_id = '".$assessmentId."' AND studentaccount_id =  '".$studentEntry['id']."' ) ";
                                }
                                else if($studentEntry['mark'] == "EX"){
                                        $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 1;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                    $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 2;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                    $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 3;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                    $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 'FINALIZED';
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                    $deleteExempted[] = " ( am_assessment_id = '".$assessmentId."' AND studentaccount_id =  '".$studentEntry['id']."' ) ";
                                    $insertExempted[] = " ( '".$studentEntry['id']."', '".$assessmentId."' ,'".$adminId."', utc_timestamp(), '".$adminId."', utc_timestamp() ) ";
                                    $delete_third_val_students[] = "( am_assessment_id = '$assessmentId' AND studentID = '".$studentEntry['id']."' )" ;
                                }
                                else{
                                    if(is_numeric($studentEntry['mark']) && $studentEntry['mark'] <= $maxmarkOfSubject){
                                            $markEntryObj = new \stdClass();
                                            $markEntryObj->studentId = $studentEntry['id'];
                                            $markEntryObj->assessmentId = $assessmentId;
                                            $markEntryObj->oeExamsId = $oeExamId;
                                            $markEntryObj->markObtained =  $studentEntry['mark'];
                                            $markEntryObj->attendanceStatus = "PRESENT";
                                            $markEntryObj->valuationCount =  $currentValuationCount == 1 ? 1 : 'FINALIZED';
                                            $markproperties ="";
                                            if($currentValuationCount == 1){
                                                if($studentEntry['firstValuationMarkProperties']){
                                                    $markproperties = (object)$studentEntry['firstValuationMarkProperties'];
                                                } 
                                            }
                                            else{
                                                if($studentEntry['finalizedMarkProperties']){
                                                    $markproperties = (object)$studentEntry['finalizedMarkProperties'];
                                                }
                                            }
                                            $markEntryObj->properties  = $markproperties;
                                            $markEntryObj->valuationType = null;
                                        $insertionMarkTableArray[] = $markEntryObj;
                                        $deleteExempted[] = " ( am_assessment_id = '".$assessmentId."' AND studentaccount_id =  '".$studentEntry['id']."' ) ";
                                    }
                                }
                                if($studentEntry['oldMark'] != $studentEntry['mark']) {
                                    $log = new StudentMarkEditLog();
                                    $log->oldMark = $studentEntry['oldMark'];
                                    $log->newMark = $studentEntry['mark'];
                                    $log->remarks = "Mark changed by edit external mark";
                                    $log->markType = "EXTERNAL_MARK";
                                    $log->actionTakenTime = date("d-m-Y h:i A");
                                    $log->updatedStaffId = $adminId;
                                    $log->updatedStaffName = $staffName;
                                    $log->updatedStaffType = "EXAM_CONTROLLER";
                                    $logRequest = new \stdClass();
                                    $logRequest->studentId =  $studentEntry['id'];
                                    $logRequest->assessmentId = $assessmentId;
                                    $logRequest->staffId = $adminId;
                                    $logRequest->log = $log;
                                    $insertionExtrnalMarkLogTableArray[] = $logRequest;
                                }
                               
                            }
                        }
                    }
                    else{
                        $notRegisteredStudents[] = $studentEntry['regNo'];
                        $error = 1;
                    }
                }
            }
            else if( $currentValuationCount == 2){
                $markDiff = CommonExamService::getInstance()->getExternalValuationMarkDiff($searchRequest['courseType'],$maxmarkOfSubject );
                $request = new \stdClass;
                $request->examRegistrationId = $searchRequest['examRegistrationId'];
                $request->academicPaperSubjectId = stripslashes($searchRequest['academicPaperId']);
                $request->groupId = $searchRequest['groupId'];
                $request->isFirstValuatedStudentOnly = true;
                $registeredStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                foreach($studentMarkDetailsArray as $student){
                    if($student['isWithHeld'] != true){
                        $registeredStudentsArray[$student['studentId']] = $student['studentId'];
                        $registeredStudentsCurrentMark[$student['studentId']] = $student['mark'];
                        $registeredStudentsOldMark[$student['studentId']] = $student['oldMark'];
                    }
                }
                foreach($registeredStudentMarkDetails as $studentEntry){
                    if($studentEntry->isAbsent != "WITHHELD"){
                        if( in_array ( $studentEntry->studentId, $registeredStudentsArray ) ) {
                            $currentMark = $registeredStudentsCurrentMark[$studentEntry->studentId];
                            if($currentMark != null){
                                if((is_numeric($currentMark)) && ($currentMark <= $maxmarkOfSubject)){
                                        // for high lighting edit changes in import mark
                                        $editRequest = new \stdClass();
                                        $editRequest->groupId = $studentEntry->groupId;
                                        $editRequest->studentId = $studentEntry->studentId;
                                        $editRequest->isDirty = 1;
                                        $editRequest->staffId = $GLOBALS['userId'];
                                        $editHistoryLog[] = $editRequest;
                                        
                                        $markEntryObj = new \stdClass();
                                        $markEntryObj->studentId = $studentEntry->studentId;
                                        $markEntryObj->assessmentId = $studentEntry->assessmentId;
                                        $markEntryObj->oeExamsId = $studentEntry->oeExamId;
                                        $markEntryObj->markObtained = $currentMark;
                                        $markEntryObj->attendanceStatus = "PRESENT";
                                        $markEntryObj->valuationCount = 2;
                                        $markproperties = "";
                                        if($studentEntry->secondValuationMarkProperties){
                                            $markproperties = (object)$studentEntry->secondValuationMarkProperties;
                                        }
                                        $markEntryObj->properties  = $markproperties;
                                        $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
        
                                    $studentMarkDiff = abs ($studentEntry->firstValuationMark - $currentMark);
                                    $deleteMarkEntryObj = new ExamUserMarkRequest;
                                    $deleteMarkEntryObj->assessmentId = $studentEntry->assessmentId;
                                    $deleteMarkEntryObj->studentId = $studentEntry->studentId;
                                    $deleteMarkEntryObj->valuationCount = 3;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                    if( $studentMarkDiff >= $markDiff){
                                        // $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        // $deleteMarkEntryObj->assessmentId = $studentEntry->assessmentId;
                                        // $deleteMarkEntryObj->studentId = $studentEntry->studentId;
                                        // $deleteMarkEntryObj->valuationCount = 'FINALIZED';
                                        // $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                        $markEntryObj = new \stdClass();
                                        $markEntryObj->studentId = $studentEntry->studentId;
                                        $markEntryObj->assessmentId = $studentEntry->assessmentId;
                                        $markEntryObj->oeExamsId = $studentEntry->oeExamId;
                                        $markEntryObj->markObtained = null;
                                        $markEntryObj->attendanceStatus = "PRESENT";
                                        $markEntryObj->valuationCount = 'FINALIZED';
                                        $markproperties = "";
                                        if($studentEntry->secondValuationMarkProperties){
                                            $markproperties = (object)$studentEntry->secondValuationMarkProperties;
                                        }
                                        $markEntryObj->properties  = $markproperties;
                                        $markEntryObj->valuationType = null;
                                        $insertionMarkTableArray[] = $markEntryObj;
                                        $insert_third_val_students[] = "( '".$studentEntry->assessmentId."', ".$studentEntry->studentId." )";
                                    }
                                    else{
                                        $studentMark =  ($studentEntry->firstValuationMark + $currentMark)/2;
                                            $markEntryObj = new \stdClass();
                                            $markEntryObj->studentId = $studentEntry->studentId;
                                            $markEntryObj->assessmentId = $studentEntry->assessmentId;
                                            $markEntryObj->oeExamsId = $studentEntry->oeExamId;
                                            $markEntryObj->markObtained = $studentMark;
                                            $markEntryObj->attendanceStatus = "PRESENT";
                                            $markEntryObj->valuationCount = 'FINALIZED';
                                            $markproperties = "";
                                            if($studentEntry->secondValuationMarkProperties){
                                                $markproperties = (object)$studentEntry->secondValuationMarkProperties;
                                            }
                                            $markEntryObj->properties  = $markproperties;
                                            $markEntryObj->valuationType = null;
                                        $insertionMarkTableArray[] = $markEntryObj;
                                        $delete_third_val_students[] = "( am_assessment_id = '$studentEntry->assessmentId' AND studentID = '$studentEntry->studentId' )" ;
                                        if( $registeredStudentsOldMark[$studentEntry->studentId] != $studentMark){
                                            $log = new StudentMarkEditLog();
                                            $log->oldMark = $registeredStudentsOldMark[$studentEntry->studentId];
                                            $log->newMark = $studentMark;
                                            $log->remarks = "Mark changed by edit external mark";
                                            $log->markType = "EXTERNAL_MARK";
                                            $log->actionTakenTime = date("d-m-Y h:i A");
                                            $log->updatedStaffId = $adminId;
                                            $log->updatedStaffName = $staffName;
                                            $log->updatedStaffType = "EXAM_CONTROLLER";
                                            $logRequest = new \stdClass();
                                            $logRequest->studentId =  $studentEntry['id'];
                                            $logRequest->assessmentId = $assessmentId;
                                            $logRequest->staffId = $adminId;
                                            $logRequest->log = $log;
                                            $insertionExtrnalMarkLogTableArray[] = $logRequest;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            $notRegisteredStudents[] = $studentEntry->regNo;
                            $error = 1;
                        }
                    }
                }
            }
            else if($currentValuationCount == 3){
                $markDiff = CommonExamService::getInstance()->getExternalValuationMarkDiff($searchRequest['courseType'],$maxmarkOfSubject );
                $request = new \stdClass;
                $request->examRegistrationId = $searchRequest['examRegistrationId'];
                $request->academicPaperSubjectId = stripslashes($searchRequest['academicPaperId']);
                $request->groupId = $searchRequest['groupId'];
                $request->isFirstValuatedStudentOnly = true;
                $request->isSecondValuatedStudentOnly = true;
                $registeredStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                $examFormula = $this->getFormulaByExamRegId($examRegistrationId);
                $formulaOfExam = explode("|", $examFormula->formula);
                $constants = MarkService::getInstance()->getAllRuleConstants();
                foreach ($constants as $constant) {
                    while (array_search(str_replace(" ", "", $constant->constantName), $formulaOfExam)) {
                        $index = array_search(str_replace(" ", "", $constant->constantName), $formulaOfExam);
                        $formulaOfExam[$index] = $constant->constantValue;
                    }
                }
                foreach($studentMarkDetailsArray as $student)
                {
                    if($student['isWithHeld'] != true)
                    {
                        $registeredStudentsArray[$student['studentId']] = $student['studentId'];
                        $registeredStudentsCurrentMark[$student['studentId']] = $student['mark'];
                        $registeredStudentsOldMark[$student['studentId']] = $student['oldMark'];
                    }
                }
                foreach($registeredStudentMarkDetails as $studentEntry)
                {
                    if($studentEntry->isAbsent != "WITHHELD")
                    {
                        if( in_array ( $studentEntry->studentId, $registeredStudentsArray ) ) 
                        {
                            $currentMark = $registeredStudentsCurrentMark[$studentEntry->studentId];
                            if($currentMark != null){
                                if((is_numeric($currentMark)) && ($currentMark <= $maxmarkOfSubject)){
                                    // for high lighting edit changes in import mark
                                    $editRequest = new \stdClass();
                                    $editRequest->groupId = $studentEntry->groupId;
                                    $editRequest->studentId = $studentEntry->studentId;
                                    $editRequest->isDirty = 1;
                                    $editRequest->staffId = $GLOBALS['userId'];
                                    $editHistoryLog[] = $editRequest;
                                      
                                    $markEntryObj = new \stdClass();
                                    $markEntryObj->studentId = $studentEntry->studentId;
                                    $markEntryObj->assessmentId = $studentEntry->assessmentId;
                                    $markEntryObj->oeExamsId = $studentEntry->oeExamId;
                                    $markEntryObj->markObtained = $currentMark;
                                    $markEntryObj->valuationCount = 3;
                                    $markEntryObj->attendanceStatus = "PRESENT";
                                    $markproperties = "";
                                    if($studentEntry->thirdValuationMarkProperties){
                                        $markproperties = (object)$studentEntry->thirdValuationMarkProperties;
                                    }
                                    $markEntryObj->properties  = $markproperties;
                                    $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
                                    $studentMarkForDifferenceCalc[0] = $studentMarks[1] = $studentEntry->firstValuationMark;
                                    $studentMarkForDifferenceCalc[1] = $studentMarks[2] = $studentEntry->secondValuationMark;
                                    $studentMarkForDifferenceCalc[2] = $studentMarks[3] = $currentMark;
                                    sort($studentMarkForDifferenceCalc);
                                    $diffMark1Mark2 = abs($studentMarkForDifferenceCalc[0] - $studentMarkForDifferenceCalc[1]);
                                    $diffMark2Mark3 = abs($studentMarkForDifferenceCalc[1] - $studentMarkForDifferenceCalc[2]);
                                    if (empty($examFormula)) {
                                        $externalMark = ($studentMarks[1] + $studentMarks[2] + $studentMarks[3]) / 3;
                                    }
                                    else if ($diffMark1Mark2 === $diffMark2Mark3) {
                                        $externalMark = ($studentMarkForDifferenceCalc[1] + $studentMarkForDifferenceCalc[2]) / 2;
                                    }
                                    else{
                                        $formula = $formulaOfExam;
                                        foreach ($studentMarks as $i => $markDetail)
                                        {
                                            while(array_search(str_replace(" ", "", "m".$i),$formula))
                                            {
                                                $index = array_search(str_replace(" ", "","m".$i),$formula);
                                                $formula[$index] = round($markDetail,2);
                                            }
                                        }
                                        $formula = implode("",$formula);
                                        $finalmark = postfix($formula);
                                        $externalMark = $finalmark;
                                    }
                                    $externalMark = round($externalMark);
                                    $markEntryObj = new \stdClass();
                                        $markEntryObj->studentId = $studentEntry->studentId;
                                        $markEntryObj->assessmentId = $studentEntry->assessmentId;
                                        $markEntryObj->oeExamsId = $studentEntry->oeExamId;
                                        $markEntryObj->markObtained = $externalMark;
                                        $markEntryObj->valuationCount = 'FINALIZED';
                                        $markEntryObj->attendanceStatus = "PRESENT";
                                        $markproperties = "";
                                        if($studentEntry->finalizedMarkProperties){
                                            $markproperties = (object)$studentEntry->finalizedMarkProperties;
                                        }
                                        $markEntryObj->properties  = $markproperties;
                                        $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
                                    if( $registeredStudentsOldMark[$studentEntry->studentId] != $externalMark){
                                        $log = new StudentMarkEditLog();
                                        $log->oldMark = $registeredStudentsOldMark[$studentEntry->studentId];
                                        $log->newMark = $externalMark;
                                        $log->remarks = "Mark changed by edit external mark";
                                        $log->markType = "EXTERNAL_MARK";
                                        $log->actionTakenTime = date("d-m-Y h:i A");
                                        $log->updatedStaffId = $adminId;
                                        $log->updatedStaffName = $staffName;
                                        $log->updatedStaffType = "EXAM_CONTROLLER";
                                        $logRequest = new \stdClass();
                                        $logRequest->studentId =  $studentEntry['id'];
                                        $logRequest->assessmentId = $assessmentId;
                                        $logRequest->staffId = $adminId;
                                        $logRequest->log = $log;
                                        $insertionExtrnalMarkLogTableArray[] = $logRequest;
                                    }
                                }
                            }
                        }
                        else
                        {
                            $notRegisteredStudents[] = $studentEntry['regNo'];
                            $error = 1;
                        }
                    }
                }
            }
            if(! empty($insertionMarkTableArray)){
                ExamUserMarkService::getInstance()->saveExamUserTotalMark($insertionMarkTableArray);
            }
            if(! empty($deleteMarkTableArray)){
                foreach($deleteMarkTableArray as $deleteObj){
                    ExamUserMarkService::getInstance()->deleteExamUserTotalMark($deleteObj);
                }
            }
            if(! empty($insertionExtrnalMarkLogTableArray)){
                foreach($insertionExtrnalMarkLogTableArray as $logRequest){
                    $this->saveExamEditLog($logRequest);
                }
            }
            if(! empty($insert_third_val_students)){
                $this->insertThirdValStudentRegistration($insert_third_val_students);
            }
            if(! empty($delete_third_val_students)){
                $this->deleteThirdValStudentRegistration($delete_third_val_students);
            }
            if( !empty ( $deleteExempted ) ){
                $this->deleteExemptedStudents($deleteExempted);
            }
            if( !empty ( $insertExempted ) ){
                $this->insertExemptedStudents($insertExempted);
            }
            if(! empty($editHistoryLog)){
                StudentsOverAllMarkReportService::getInstance()->insertStudentEditStatus($editHistoryLog);
            }
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * get Formula By ExamRegId
     * @param $examRegistrationId
     * @return $formula
     */
    public function getFormulaByExamRegId($examRegistrationId)
    {
        $examRegistrationId = $this->realEscapeString($examRegistrationId);
        try
        {
            $query = "SELECT
                evrf.id,
                evrf.formulaName,
                evrf.formula
            FROM
                exam_valuation_rule_relation evrr
            INNER JOIN exam_valuation_rule_formula evrf ON
                evrf.id = evrr.exam_valuation_rule_formula_id
            WHERE ec_exam_registration_id = '$examRegistrationId'";
            $formula = $this->executeQueryForObject($query);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $formula;
    }
     /**
     * get All Subjects By Student Register No
     * @param $searchRequest
     * @return $response
     */
    public function getAllSubjectsByStudentRegisterNo($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try 
        {
            $response = new \stdClass;
            $request = new \stdClass;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->studentRegisterNo = $searchRequest->registerNumber;
            $subjects = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
            $currentStudentDetails = reset($subjects);
            foreach($subjects as $subject)
            {
                $subject->statusForMark = null;
                if($subject->isAbsent == "ABSENT")
                {
                    $subject->statusForMark = "Absent";
                    $subject->externalMark = "AB";
                }
                else if($subject->isAbsent == "WITHHELD")
                {
                    $subject->statusForMark = "With Held";
                    $subject->externalMark = "WH";
                }
                else if($subject->isAbsent == "MALPRACTICE")
                {
                    $subject->statusForMark = "MAL Practice";
                    $subject->externalMark = "MAL";
                }
                if($subject->isExempted)
                {
                    $subject->statusForMark = "Exempted";
                    $subject->externalMark = "EX";
                }
                $log = json_decode($subject->log);
                usort($log,function($a,$b){
                    return $a->actionTakenTime < $b->actionTakenTime;
                });
                $subject->logs = $log ? $log : [];
            }
            $response->subjects = $subjects;
            $response->studentDetails = $currentStudentDetails;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
      /**
     * save Edit Mark By Register Number
     * @param $currentStudentDetails
     * @param $newMark
     * @return $remarks
     */
    public function saveEditMarkByRegisterNo($currentStudentDetails,$currentSubject) {
        $currentStudentDetails = $this->realEscapeObject($currentStudentDetails);
        $currentSubject = $this->realEscapeObject($currentSubject);
        try{
            $adminId = $GLOBALS['userId'];
            $logRequest = new \Stdclass();
            $insertionValues = [];
            $deleteExempted = [];
            $insertExempted = [];
            $editHistoryLog = [];
            $deleteMarkTableArray = [];
            $staffName = $this->getStaffNameByStaffId($adminId);
            if($currentSubject['newExternalMark'] != null){
                if($currentSubject['remarks'] != null){
                    if($currentSubject['newExternalMark'] != $currentSubject['externalMark']){
                        // for high lighting edit changes in import mark
                        $editRequest = new \stdClass();
                        $editRequest->groupId = $currentSubject['groupId'];
                        $editRequest->studentId = $currentSubject['studentId'];
                        $editRequest->isDirty = 1;
                        $editRequest->staffId = $GLOBALS['userId'];
                        $editHistoryLog[] = $editRequest;
                        if($currentSubject['newExternalMark'] == 'AB'){
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $currentSubject['studentId'];
                                $markEntryObj->assessmentId = $currentSubject['assessmentId'];
                                $markEntryObj->oeExamsId = $currentSubject['oeExamId'];
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markEntryObj->markObtained = null;
                                $markEntryObj->attendanceStatus = "ABSENT";
                                $markproperties = "";
                                if($currentSubject['markProperties']){
                                    $markproperties = (object)$currentSubject['markProperties'];
                                }
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                            $insertionValues[] = $markEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $currentSubject['assessmentId'];
                                $deleteMarkEntryObj->studentId = $currentSubject['studentId'];
                                $deleteMarkEntryObj->valuationCount = 1;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $currentSubject['assessmentId'];
                                $deleteMarkEntryObj->studentId = $currentSubject['studentId'];
                                $deleteMarkEntryObj->valuationCount = 2;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $currentSubject['assessmentId'];
                                $deleteMarkEntryObj->studentId = $currentSubject['studentId'];
                                $deleteMarkEntryObj->valuationCount = 3;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                            $deleteExempted[] = " ( am_assessment_id = '".$currentSubject['assessmentId']."' AND studentaccount_id =  '".$currentStudentDetails['studentId']."' ) ";
                            $currentSubject['newExternalMark'] = "Absent";
                        }
                        else if($currentSubject['newExternalMark'] == 'WH'){
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $currentSubject['studentId'];
                                $markEntryObj->assessmentId = $currentSubject['assessmentId'];
                                $markEntryObj->oeExamsId = $currentSubject['oeExamId'];
                                $markEntryObj->attendanceStatus = "WITHHELD";
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markproperties = "";
                                if($currentSubject['markProperties']){
                                    $markproperties = (object)$currentSubject['markProperties'];
                                }
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                            $insertionValues[] = $markEntryObj;
                            $deleteExempted[] = " ( am_assessment_id = '".$currentSubject['assessmentId']."' AND studentaccount_id =  '".$currentStudentDetails['studentId']."' ) ";
                            $currentSubject['newExternalMark'] = "With Held";
                        }
                        else if($currentSubject['newExternalMark'] == 'MAL'){
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $currentSubject['studentId'];
                                $markEntryObj->assessmentId = $currentSubject['assessmentId'];
                                $markEntryObj->oeExamsId = $currentSubject['oeExamId'];
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markEntryObj->markObtained = null;
                                $markEntryObj->attendanceStatus = "MALPRACTICE";
                                $markproperties = "";
                                if($currentSubject['markProperties']){
                                    $markproperties = (object)$currentSubject['markProperties'];
                                }
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                            $insertionValues[] = $markEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $currentSubject['assessmentId'];
                                $deleteMarkEntryObj->studentId = $currentSubject['studentId'];
                                $deleteMarkEntryObj->valuationCount = 1;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $currentSubject['assessmentId'];
                                $deleteMarkEntryObj->studentId = $currentSubject['studentId'];
                                $deleteMarkEntryObj->valuationCount = 2;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $currentSubject['assessmentId'];
                                $deleteMarkEntryObj->studentId = $currentSubject['studentId'];
                                $deleteMarkEntryObj->valuationCount = 3;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                            $deleteExempted[] = " ( am_assessment_id = '".$currentSubject['assessmentId']."' AND studentaccount_id =  '".$currentStudentDetails['studentId']."' ) ";
                            $currentSubject['newExternalMark'] = "MalPractice";
                        }
                        else if($currentSubject['newExternalMark'] == "EX"){
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $currentSubject['assessmentId'];
                                $deleteMarkEntryObj->studentId = $currentSubject['studentId'];
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                            $deleteExempted[] = " ( am_assessment_id = '".$currentSubject['assessmentId']."' AND studentaccount_id =  '".$currentStudentDetails['studentId']."' ) ";
                            $insertExempted[] = " ( '".$currentStudentDetails['studentId']."', '".$currentSubject['assessmentId']."' ,'".$adminId."', utc_timestamp(), '".$adminId."', utc_timestamp() ) ";
                            $currentSubject['newExternalMark'] = "Exempted";
                        }
                        else{
                            if(is_numeric($currentSubject['newExternalMark']) && $currentSubject['newExternalMark'] <= $currentSubject['maximumSubjectMark'] && $currentSubject['newExternalMark'] >= 0 ){
                                    $markEntryObj = new \stdClass();
                                    $markEntryObj->studentId = $currentSubject['studentId'];
                                    $markEntryObj->assessmentId = $currentSubject['assessmentId'];
                                    $markEntryObj->oeExamsId = $currentSubject['oeExamId'];
                                    $markEntryObj->valuationCount = 'FINALIZED';
                                    $markEntryObj->markObtained = $currentSubject['newExternalMark'];
                                    $markEntryObj->attendanceStatus = "PRESENT";
                                    $markproperties = "";
                                    if($currentSubject['markProperties']){
                                        $markproperties = (object)$currentSubject['markProperties'];
                                    }
                                    $markEntryObj->properties  = $markproperties;
                                    $markEntryObj->valuationType = null;
                                $insertionValues[] = $markEntryObj;
                                $deleteExempted[] = " ( am_assessment_id = '".$currentSubject['assessmentId']."' AND studentaccount_id =  '".$currentStudentDetails['studentId']."' ) ";
                            }
                            else{
                                throw new ExamControllerException(ExamControllerException::NO_MARK_ENTERED,"Please Enter Vaild Mark");
                            }
                        }
                        if($currentSubject['externalMark'] == 'AB'){
                            $currentSubject['externalMark'] = "Absent";
                        }
                        else if($currentSubject['externalMark'] == 'WH'){
                            $currentSubject['externalMark'] = "With Held";
                        }
                        else if($currentSubject['externalMark'] == 'MAL'){
                            $currentSubject['externalMark'] = "MalPractice";
                        }
                        else if($currentSubject['externalMark'] == "EX"){
                            $currentSubject['externalMark'] = "Exempted";
                        }
                        $log = new StudentMarkEditLog();
                        $log->oldMark = $currentSubject['externalMark'];
                        $log->newMark = $currentSubject['newExternalMark'];
                        $log->remarks = $currentSubject['remarks'];
                        $log->markType = "EXTERNAL_MARK";
                        $log->actionTakenTime = date("d-m-Y h:i A");
                        $log->updatedStaffId = $adminId;
                        $log->updatedStaffName = $staffName;
                        $log->updatedStaffType = "EXAM_CONTROLLER";
                        $logRequest->studentId = $currentStudentDetails['studentId'];
                        $logRequest->assessmentId = $currentSubject['assessmentId'];
                        $logRequest->staffId = $adminId;
                        $logRequest->log = $log;
                    }
                    else{
                        throw new ExamControllerException(ExamControllerException::NO_MARK_ENTERED,"Mark not changed!");
                    }
                }
                else{
                    throw new ExamControllerException(ExamControllerException::NO_REASON_ENTERED,"Reason for mark change not entered");
                }
            }
            else{
                throw new ExamControllerException(ExamControllerException::NO_MARK_ENTERED,"No Mark Entered");
            }
            if( !empty ( $insertionValues ) ){
                ExamUserMarkService::getInstance()->saveExamUserTotalMark($insertionValues);
            }
            if( !empty ( $deleteExempted ) ){
                $this->deleteExemptedStudents($deleteExempted);
            }
            if( !empty ( $insertExempted ) ) {
                $this->insertExemptedStudents($insertExempted);
            }
             if(! empty($deleteMarkTableArray)){
                foreach($deleteMarkTableArray as $deleteObj){
                    ExamUserMarkService::getInstance()->deleteExamUserTotalMark($deleteObj);
                }
            }
            if(! empty($editHistoryLog)){
                StudentsOverAllMarkReportService::getInstance()->insertStudentEditStatus($editHistoryLog);
            }
            $this->saveExamEditLog($logRequest);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
     /**
     * get StaffName By StaffId
     * @return staffDetails details
     */
    public function getStaffNameByStaffId($staffId)
    {
        $staffDetails = null;
        $sql = "SELECT sa.staffName as staffName from staffaccounts sa where staffID = $staffId";
        try {
            $staffDetails = $this->executeQueryForObject($sql)->staffName;
        } catch (\Exception $e) {
            throw new ExamControllerException ($e->getCode(), $e->getMessage());
        }
        return $staffDetails;
    }
    /**
     * save Exam Edit Log
     * @return staffDetails details
     */
    public function saveExamEditLog($logRequest)
    {
        $logRequest = $this->realEscapeObject($logRequest);
        $id = SecurityUtils::getRandomString();
        $log = json_encode($logRequest->log);
        $sql = "INSERT INTO ec_student_mark_edit_log (id,am_assessment_id,student_id,log,created_by,created_date)
            VALUES ('$id','$logRequest->assessmentId','$logRequest->studentId','[$log]','$logRequest->staffId',now()) ON DUPLICATE KEY UPDATE `log` = JSON_MERGE(`log`,'$log'), updated_by = VALUES(created_by)";
               
        try {
            $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ExamControllerException ($e->getCode(), $e->getMessage());
        }
    }
     /**
     * get Subjects For Staff Side Mark Entry
     * @return staffDetails details
     */
    public function getSubjectsForStaffSideMarkEntry($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $digitalValuationProperties = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_CONTROLLER, SettingsConstents::DIGITAL_VALUATION_PROPERTIES);
            $digitalValuationProperties = $digitalValuationProperties ? json_decode($digitalValuationProperties) : "";
            $searchRuleRequest = new SearchRuleRequest;
            $searchRuleRequest->name = "EXAM_VALUATION_PROCEDURE_RULE";
            $examValuationProcedureRule = reset(RuleService::getInstance()->searchRule($searchRuleRequest))->rule;
            $templateName = $examValuationProcedureRule->templateName ;
            // $isCentralizedSession is false for now becaue of college requirement (SJU )
            $isCentralizedSession =  false; 
            $staffSideMarkEntryUItype = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::STAFF_SIDE_MARK_ENTRY_UI_FORMAT);
            $response = new \stdClass;
            $request = new \stdClass;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $userId = $GLOBALS['userId'];
            $isQPCodeDisplayInStaffSideMarkEntry = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::IS_DISPALY_QP_CODE_IN_STAFF_SIDE_MARK_ENTRY);
            // $request->batchOrSubjectWise = "BATCH_WISE";
            $request->batchOrSubjectWise = "SUBJECT_WISE";
            $today = date("Y-m-d H:i");
            $assignedSubjects = ExamRegistrationSubjectService::getInstance()->getSubjectForCurrentStaffs($request);
            $subjectArray = [];
            if($request->batchOrSubjectWise == "SUBJECT_WISE"){
                foreach($assignedSubjects as $subject){
                    $subject->isExpand = false;
                    $subject->valuationDetails = json_decode($subject->valuationDetails);
                    $subject->errorMessage = null;
                    $subject->errorMessageInfo = null;
                    if($isCentralizedSession){
                        $subject->errorMessage = "Permission denied";
                        $subject->errorMessageInfo = "You can't view mark entry using centralized session.";
                    }
                    else{
                        if($templateName == 'TEMPLATE_WITH_DIGITAL_VALUATION'){
                            if($searchRequest->currentValuationCount == '2'){
                                if($subject->courseType == 'PG'){
                                    $valuationDate = reset(array_filter($subject->valuationDetails->valuationDates,function($value){
                                        return $value->count == '1' && !empty($value->staffId);
                                    }));
                                }
                                else{
                                    $secondValuationStaffDetails = reset(array_filter($subject->valuationDetails->valuationStaffs,function($value){
                                        return $value->count == '2' && !empty($value->addiitonalExamniners);
                                    }));
                                    if(count($secondValuationStaffDetails->addiitonalExamniners) > 1){
                                        $currentValuationDate = reset(array_filter($subject->valuationDetails->valuationDates,function($value)use($searchRequest,$userId){
                                            return $value->count == $searchRequest->currentValuationCount && $value->staffId == $userId;
                                        }));
                                        $viewerIds = $currentValuationDate->viewerIds;
                                        $valuationDate = reset(array_filter($subject->valuationDetails->valuationDates,function($value)use($viewerIds,$userId){
                                            return $value->count == '1' && in_array($value->staffId,$viewerIds);
                                        }));
                                    }
                                    else{
                                        usort($subject->valuationDetails->valuationDates, function($a, $b) {
                                            return strtotime($b->endDate) - strtotime($a->endDate);
                                        });
                                        $valuationDate = reset(array_filter($subject->valuationDetails->valuationDates,function($value){
                                            return $value->count == '1' && !empty($value->staffId);
                                        }));
                                    }
                                    if(!empty($digitalValuationProperties->noOfDaysInBufferForReviewer)){
                                        $addOndaysForReviewer = (($digitalValuationProperties->noOfDaysInBufferForReviewer ?? 0) - $digitalValuationProperties->noOfDaysInBufferForValuer);
                                        if($addOndaysForReviewer > 0){
                                            $valuationDate->endDate = date("Y-m-d H:i", strtotime($valuationDate->endDate . " +$addOndaysForReviewer days"));
                                        }
                                    }
                                }
                            }
                            else{
                                $valuationDate = reset(array_filter($subject->valuationDetails->valuationDates,function($value)use($searchRequest,$userId){
                                    return $value->count == $searchRequest->currentValuationCount && $value->staffId == $userId;
                                }));
                            }
                        }
                        else{
                            $valuationDate = reset(array_filter($subject->valuationDetails->valuationDates,function($value)use($searchRequest){
                                return $value->count == $searchRequest->currentValuationCount;
                            }));
                        }
                        if(!empty($valuationDate)){
                            $subject->valuationStartDate = $valuationDate->startDate;
                            $subject->valuationEndDate = $valuationDate->endDate;
                            $subject->valuationStartDateTime = date("d-m-Y h:i A", strtotime($valuationDate->startDate));
                            $subject->valuationEndDateTime = date("d-m-Y h:i A", strtotime($valuationDate->endDate));
                            if(strtotime($today) < strtotime($subject->valuationStartDate)){
                                $subject->errorMessage = "Valuation Start On ".date("d-m-Y h:i A", strtotime($valuationDate->startDate));
                            }
                            else if(strtotime($today) > strtotime($subject->valuationEndDate)){
                                $subject->errorMessage = "Valuation Date Expired";
                            }
                            else if($staffSideMarkEntryUItype == 'DIGITAL_VALUATION' && $subject->isValidatedDetails){
                                foreach($subject->isValidatedDetails as $isValidated){
                                    if($isValidated == '0' || $isValidated == 0){
                                        $subject->errorMessage = "Exam Not Validated";
                                        $subject->errorMessageInfo = " Valuation blocked. Contact Exam Administration Team to get the exam validated and continue";
                                    }
                                }
                            }
                        }
                        else{
                            $subject->errorMessage = "Valuation not configured";
                        }
                    }
                    $requestForPapersEvaluated = new \stdClass;
                    $requestForPapersEvaluated->onlineExamId = $subject->onlineExamId;
                    $requestForPapersEvaluated->valuationCount = $searchRequest->currentValuationCount;
                    $requestForPapersEvaluated->staffId = $GLOBALS['userId'];
                    if($templateName == 'TEMPLATE_WITH_DIGITAL_VALUATION' && $subject->courseType != 'PG' && $searchRequest->currentValuationCount == '2'){
                        $requestForPapersEvaluated->valuationCount = '1';
                        $requestForPapersEvaluated->isReviewer = true;
                    }
                    $subject->papersEvaluvated = $this->countOfEvaluatedStudentsConfimeredByOnlineExam($requestForPapersEvaluated);
                    // $subject->papersEvaluvated = $this->countOfEvaluatedStudentsByOnlineExam($requestForPapersEvaluated);
                   
                    if ( $staffSideMarkEntryUItype == "NO_PREFETCH_STUDENTS" || $staffSideMarkEntryUItype == "PREFETCH_STUDENTS" || $staffSideMarkEntryUItype == "STUDENT_WITH_PACKET" || ($staffSideMarkEntryUItype == 'DIGITAL_VALUATION')){
                        if( $subjectArray[$subject->subjectId]){
                            $subjectArray[$subject->subjectId]->subjectIdArr[] = $subject->academicPaperSubjectId;
                            $subjectArray[$subject->subjectId]->papersEvaluvated += $subject->papersEvaluvated;
                        }
                        else{
                            $subject->subjectIdArr[] = $subject->academicPaperSubjectId;
                            $subjectArray[$subject->subjectId] = $subject;
                        }
                    }
                }
            }
            $response->staffSideMarkEntryUItype = $staffSideMarkEntryUItype;
            $response->isValuerReviewerValuation = false;
            if ( $staffSideMarkEntryUItype == "NO_PREFETCH_STUDENTS" || $staffSideMarkEntryUItype == "PREFETCH_STUDENTS" || $staffSideMarkEntryUItype == "STUDENT_WITH_PACKET"  || ($staffSideMarkEntryUItype == 'DIGITAL_VALUATION')){
                $response->subjects = array_values($subjectArray);
            }
            else{
                $response->subjects = $assignedSubjects;
            }
            if($templateName == 'TEMPLATE_WITH_DIGITAL_VALUATION'){
                $response->isValuerReviewerValuation = true;
            }
            $response->batchOrSubjectWise = $request->batchOrSubjectWise;
            $response->currentValuationCount = $searchRequest->currentValuationCount;
            $response->isQPCodeDisplay = $isQPCodeDisplayInStaffSideMarkEntry;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
     /**
     * get Subjects For Staff Side Mark Entry
     * @return staffDetails details
     */
    public function getSubjectDetailsForStaffSideMarkEntry($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $registeredStudentMarkDetails = [];
            $markEntryBasedOn = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::MARK_ENTRY_BASED_ON);
            $enableValuatedCountCheck = NULL;
            $enableValuatedCountCheck = (int) CommonService::getInstance()->getSettings(SettingsConstents::EXAM_CONTROLLER, SettingsConstents::ENABLE_VALUATED_ANSWER_SHEET_COUNT_CHECK);
            $staffSideMarkEntryUItype = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::STAFF_SIDE_MARK_ENTRY_UI_FORMAT);
            $staffSideMarkEntryType = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::STAFF_SIDE_MARK_ENTRY_TYPE);
            $isQPCodeDisplayInStaffSideMarkEntry = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::IS_DISPALY_QP_CODE_IN_STAFF_SIDE_MARK_ENTRY);
            $isRevaluedStatus = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::IS_RC_STATUS_IN_EXTERNAL_MARK_ENTRY_DIRECT);
            $searchRuleRequest = new SearchRuleRequest;
            $searchRuleRequest->name = "EXAM_VALUATION_PROCEDURE_RULE";
            $examValuationProcedureRule = reset(RuleService::getInstance()->searchRule($searchRuleRequest))->rule;
            $considerAdditionalAndChiefValuationForUg = $examValuationProcedureRule->considerAdditionalAndChiefValuationForUg ? true : false;  
  
            $searchRuleRequest = new SearchRuleRequest;
            $searchRuleRequest->name = "FALSE_NUMBER_AND_ALPHA_NUMERIC_CODE_SETTINGS";
            $falseNoAndAlphaNumericCodeSettings = reset(RuleService::getInstance()->searchRule($searchRuleRequest));
            $isShowBookLetNumber = $falseNoAndAlphaNumericCodeSettings->rule->isShowBookLetNumber == '1' ? true : false;
            $response = new \stdClass;
            $request = new \stdClass;
            $request->paperSubjectId = $searchRequest->paperSubjectId;
            $request->academicPaperSubjectId = $searchRequest->paperSubjectId;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->examRegistrationBatchId = $searchRequest->examRegistrationBatchesArray;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $academicPaperId = stripslashes($searchRequest->paperSubjectId);
            $paperSubjectIdArray = $searchRequest->paperSubjectIdArr;
            $request->sortBy = $searchRequest->sortBy;
            $courseTypeId = $this->getCourseTypeIdByExamRegistrationIdAndPaperSubjectId($searchRequest->examRegistrationId,$searchRequest->paperSubjectId);
            $markDiffDetails = $courseTypeId ? $this->getExternalValuationMarkDifference($courseTypeId) : '';
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ($courseTypeId);
            $today = date("Y-m-d H:i");
            // $markDiff = ExamService::getInstance()->getExternalValuationMarkDiff($courseTypeId);
            $isTheory = $this->getIsTheoryOrNotByExamRegistrationIdAndPaperSubjectId( $request->examRegistrationId,$academicPaperId);
            if( $considerAdditionalAndChiefValuationForUg && !$courseType->extValRequired){
                if ( $searchRequest->currentValuationCount == 1 ){
                    if( $isTheory ){
                        $staffSideMarkEntryUItype = "NO_PREFETCH_STUDENTS";
                    }
                    else{
                        $staffSideMarkEntryUItype = "PREFETCH_STUDENTS";
                        $markEntryBasedOn = "REGISTER_NUMBER";
                    }
                }
                else{
                    $staffSideMarkEntryUItype = "PREFETCH_STUDENTS_WITH_ADDITIONAL_VALUATION_MARKS";
                }
            }
            $subject = ExamRegistrationSubjectService::getInstance()->getcurrentExamSubjectForCurrentStaff($request);
            if($subject){
                $subject->hasMultipleMarkEntry = 0;
                if ( $courseType->typeName == 'B.Des' && $isTheory == 0){
                    $batchRequest = new \stdClass();
                    $batchRequest->groupId = $subject->groupId;
                    $batchRequest->examRegistrationId = $request->examRegistrationId;
                    $examRegBatchDetail = reset(ExamRegistrationBatchService::getInstance()->searchExamRegistrationBatchDetails($batchRequest));
                    if(($examRegBatchDetail->academicTermId > 2 && $examRegBatchDetail->startYear >= 2022) || ($examRegBatchDetail->startYear >= 2023) ){
                        $subject->hasMultipleMarkEntry = 1;
                        if( $subject->examRegistrationType == "SUPPLEMENTARY" ){
                            $subject->hideAdditionalMarkSupply = 1;
                        }
                        $totalMark = $subject->internalMaxMark + $subject->externalMaxMark;
                        $subject->subjectExternalMaxMarkWithoutViva = ( 40 / 100) *  $totalMark;
                        $subject->subjectExternalMaxMarkWithViva = ( 10 / 100) *  $totalMark;
                    }
                }
                if($markDiffDetails->scheme == "PERCENTAGE"){
                    $markDiff = ( $markDiffDetails->markDiff * $subject->externalMaxMark ) / 100;
                }
                else{
                    $markDiff = $markDiffDetails->markDiff;
                }
                if(!$markDiff && $request->currentValuationCount == '2' && !( $considerAdditionalAndChiefValuationForUg && !$courseType->extValRequired)){
                    $errorMsg = "Valuation margin not defined, please contact exam administrator.";
                    throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMsg);
                }
                $subject->markEntryBasedOn = $markEntryBasedOn ?? 'REGISTER_NUMBER';
                $subject->sortBy = $request->sortBy ?? 'falseNumber';
                $subject->assessmentProperties = json_decode($subject->assessmentProperties);
                $subject->valuationDetails = json_decode($subject->valuationDetails);
                $subject->examDate = $subject->assessmentProperties->assessmentDate;
                $subject->errorMessage = null;
                $subject->isConfiremed = "";
                $subject->externalMaxMark = (int)$subject->externalMaxMark;
                $subject->valuationCount = $searchRequest->currentValuationCount;
                $subject->studentMarkDetails = [];
                foreach($subject->valuationDetails->valuationDates as $valuationDate){
                    if( $considerAdditionalAndChiefValuationForUg && $searchRequest->currentValuationCount == 2 && !$courseType->extValRequired && $isTheory){
                        if($valuationDate->count == 1){
                            $filteredValuatedStaffs = array_filter($subject->valuationDetails->valuatedStaffs, function($valuatedStaff) {
                                return $valuatedStaff->count == 1;
                            });
                            $filteredValuationStaffs = reset(array_filter($subject->valuationDetails->valuationStaffs, function($valuatedStaff) {
                                return $valuatedStaff->count == 1;
                            }));
                            if( empty($subject->valuationDetails->valuatedStaffs) || count($filteredValuatedStaffs) != count($filteredValuationStaffs->addiitonalExamniners) ){
                                $subject->additionalValuationNotCompleted = "1";
                                $response->subject = $subject;
                                $response->staffSideMarkEntryUItype = $staffSideMarkEntryUItype;
                                $response->staffSideMarkEntryType = $staffSideMarkEntryType;
                                $response->courseType = $courseType->courseTypeMethod;
                                $response->currentValuationCount = $searchRequest->currentValuationCount;
                                return $response;
                                // $errorMsg = "Mark entry not confirmed by the additional valuator.";
                                // throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMsg);
                            }
                            foreach($subject->valuationDetails->valuatedStaffs as $valuatedStaff){
                                if($valuatedStaff->markEntryStatus != "CONFIRMED" && $valuatedStaff->count == 1){
                                    $subject->additionalValuationNotCompleted = "1";
                                    $response->subject = $subject;
                                    $response->staffSideMarkEntryUItype = $staffSideMarkEntryUItype;
                                    $response->staffSideMarkEntryType = $staffSideMarkEntryType;
                                    $response->courseType = $courseType->courseTypeMethod;
                                    $response->currentValuationCount = $searchRequest->currentValuationCount;
                                    return $response;
                                    // $errorMsg = "Mark entry not confirmed by the additional valuator.";
                                    // throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMsg);
                                }
                            }
                        }
                    }
                    if($valuationDate->count == $searchRequest->currentValuationCount){
                        $subject->valuationStartDate = $valuationDate->startDate;
                        $subject->valuationEndDate = $valuationDate->endDate;
                        if(strtotime($today) < strtotime($subject->valuationStartDate)){
                            $subject->errorMessage = "Valuation Not Started";
                        }
                        else if((strtotime($today) > strtotime($subject->valuationEndDate)) && $searchRequest->isAvoidValuationEndDateCondition != true){
                            $subject->errorMessage = "Valuation Date Expired";
                        }
                        else{
                            $hasConfimed = 0;
                            $hasSaved = 0;
                            foreach($subject->valuationDetails->valuatedStaffs as $valuatedStaff){
                                if($staffSideMarkEntryUItype == 'NO_PREFETCH_STUDENTS' || $staffSideMarkEntryUItype == 'PREFETCH_STUDENTS' || $staffSideMarkEntryUItype == 'PREFETCH_STUDENTS_WITH_ADDITIONAL_VALUATION_MARKS'){
                                    if($valuatedStaff->count == $request->currentValuationCount){
                                        if( $considerAdditionalAndChiefValuationForUg && !$courseType->extValRequired && $isTheory){
                                            if( $valuatedStaff->staffId == $GLOBALS['userId']){
                                                if($valuatedStaff->markEntryStatus == "CONFIRMED"){
                                                    $hasConfimed = 1;
                                                }
                                                if($valuatedStaff->markEntryStatus == "SAVED"){
                                                    $hasSaved = 1;
                                                }
                                            }
                                        }
                                        else{
                                            if($valuatedStaff->staffId == $GLOBALS['userId']){
                                                if($valuatedStaff->markEntryStatus == "CONFIRMED"){
                                                    $hasConfimed = 1;
                                                }
                                                if($valuatedStaff->markEntryStatus == "SAVED"){
                                                    $hasSaved = 1;
                                                }
                                            }
                                        }
                                    }
                                }
                                else{
                                     if($valuatedStaff->count == $request->currentValuationCount  && $valuatedStaff->staffId == $GLOBALS['userId']){
                                        if($valuatedStaff->markEntryStatus){
                                            $subject->isConfiremed = $valuatedStaff->markEntryStatus;
                                            $subject->valuatedCount = $valuatedStaff->valuatedAnsweSheetCount;
                                        }
                                    }
                                }
                            }
                            if($staffSideMarkEntryUItype == 'NO_PREFETCH_STUDENTS' || $staffSideMarkEntryUItype == 'PREFETCH_STUDENTS' || $staffSideMarkEntryUItype == 'PREFETCH_STUDENTS_WITH_ADDITIONAL_VALUATION_MARKS'){
                                if( $hasConfimed ){
                                    $subject->isConfiremed = "CONFIRMED";
                                }
                                else if( $hasSaved ){
                                    $subject->isConfiremed = "SAVED";
                                }
                            }
                            if($markEntryBasedOn == 'FALSE_NUMBER/REGISTER_NUMBER'){
                                if($request->sortBy == 'regNumber'){
                                    $subject->falseNoRegNoStatus = "regNumber";
                                }
                                else{
                                    $subject->falseNoRegNoStatus = $this->getStatusForRegisterNumberOrFalaseNumber($request);
                                }
                                $request->falseNoRegNoStatus = $subject->falseNoRegNoStatus;
                               
                            }
                            elseif($markEntryBasedOn == 'FALSE_NUMBER'){
                                $subject->falseNoRegNoStatus = "falseNumber";
                                $request->falseNoRegNoStatus = $subject->falseNoRegNoStatus;
                            }
                            elseif($markEntryBasedOn == 'REGISTER_NUMBER'){
                                $subject->falseNoRegNoStatus = "regNumber";
                                $request->falseNoRegNoStatus = $subject->falseNoRegNoStatus;
                            }
                            elseif($markEntryBasedOn == 'ROLL_NUMBER'){
                                $subject->falseNoRegNoStatus = "rollNumber";
                                $request->falseNoRegNoStatus = $subject->falseNoRegNoStatus;
                            }
                            $subject->enableValuatedCountCheck =  $enableValuatedCountCheck;
                            if($staffSideMarkEntryUItype == 'PREFETCH_STUDENTS_NOT_USING'){
                                if($subject->valuationCount == "3"){
                                    $request->isFirstValuatedStudentOnly =  true;
                                    $request->isSecondValuatedStudentOnly =  true;
                                    $request->isThirdValuationStudentOnly =  true;
                                    $allStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                                }
                                else{
                                    $allStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                                }
                                foreach($allStudentMarkDetails as $student){
                                    $student->batchProperties = json_decode($student->batchProperties);
                                    if($student->batchProperties->valuationRule){
                                        $student->selectedSecondValuationRule = reset(array_filter($student->batchProperties->valuationRule, function ($rule) {
                                            return $rule->count == 2;
                                        }));
                                        $student->selectedThirdValuationRule = reset(array_filter($student->batchProperties->valuationRule, function ($rule) {
                                            return $rule->count == 3;
                                        }));
                                    }
                                    if($request->currentValuationCount == '2' && empty($student->selectedSecondValuationRule)){
                                        $errorMsg = "Second valuation mark rule not defined, please contact exam administrator.";
                                        throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMsg);
                                    }
                                    if($request->currentValuationCount == '3' && empty($student->selectedThirdValuationRule)){
                                        $errorMsg = "Third valuation mark rule not defined, please contact exam administrator.";
                                        throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMsg);
                                    }
                                    if($subject->falseNoRegNoStatus == "regNumber"){
                                        if($student->regNo != null){
                                            $registeredStudentMarkDetails[] =  $student;
                                        }
                                    }
                                    else if($subject->falseNoRegNoStatus == "falseNumber"){
                                        if($student->falseNo != null){
                                            $registeredStudentMarkDetails[] =  $student;
                                        }
                                    }
                                }
                                foreach($registeredStudentMarkDetails as $student){
                                    $student->rvStatus = $student->isRevalued == 'true' ? true : false;
                                    if ( $student->isExempted == 1 ) {
                                        $student->mark = "EX";
                                        $student->errorMessage  = "";
                                        $student->errorMessage  = $request->currentValuationCount == '1' ? '' : 'Exempted';
                                    }
                                    else if ( $student->isAbsent == "ABSENT" ) {
                                        $student->mark  = "AB";
                                        $student->errorMessage  = $request->currentValuationCount == '1' ? '' : 'Absent';
                                    } 
                                    else if ( $student->isAbsent == "MALPRACTICE" ) {
                                        $student->mark  = "MAL";
                                        $student->errorMessage  = $request->currentValuationCount == '1' ? '' : 'Mal practice';
                                    } 
                                    else if ($student->isAbsent == "WITHHELD") {
                                        $student->mark  = "WH";
                                        $student->isWithHeld  = true;
                                        $student->errorMessage  = $request->currentValuationCount == '1' ? '' : 'with held';
                                    }
                                    else{
                                        if($subject->valuationCount == "1"){
                                            if((!$courseType->extValRequired) ){
                                                $student->mark  = $student->finalizedMark;
                                                $student->errorMessage  = "";
                                            }
                                            elseif($courseType->extValRequired && $isTheory == '0'){
                                                $student->mark  = $student->finalizedMark;
                                                $student->errorMessage  = "";
                                            }
                                            else{
                                                $student->mark  = $student->firstValuationMark;
                                                $student->errorMessage  = "";
                                            }
                                        }
                                        else if($subject->valuationCount == "2"){
                                            if($student->firstValuationMark == null  || $student->firstValuationConfirm == '0'){
                                                $student->firstValuationMark = null;
                                                $student->errorMessage  = "1st Valuation Pending"; 
                                                $student->mark  = null;
                                            }
                                            else{
                                                $studentMarkDiff = abs ($student->firstValuationMark - $student->secondValuationMark);
                                                if($studentMarkDiff >= $markDiff) {
                                                    $student->thirdValRequiredFlag = 1;
                                                }
                                                else{
                                                    $student->thirdValRequiredFlag = 0;
                                                }
                                                $student->mark  = $student->secondValuationMark;
                                                $student->errorMessage  = "";
                                            }
                                        }
                                        else if($subject->valuationCount == "3"){
                                            if($student->firstValuationMark == null || $student->firstValuationConfirm == '0'){
                                                $student->errorMessage  = "1st Valuation Pending";
                                                $student->secondValuationMark = null; 
                                                $student->firstValuationMark = null;
                                                $student->mark  = null;
                                            }
                                            elseif($student->secondValuationMark == null || $student->secondValuationConfirm == '0'){
                                                $student->errorMessage  = "2nd Valuation Pending"; 
                                                $student->secondValuationMark = null; 
                                                $student->mark  = null;
                                            }
                                            elseif($student->thirdValReq == 0){
                                                $student->errorMessage  = "3rd Valuation Not Eligible"; 
                                                $student->mark  = null;
                                            }
                                            else{
                                                $student->mark  = $student->thirdValuationMark;
                                                $student->errorMessage  = "";
                                            }
                                        }
                                    }
                                }
                                if($staffSideMarkEntryType =='BATCH_WISE')
                                {
                                    $batches =[];
                                    foreach($registeredStudentMarkDetails as $student)
                                    {
                                        $batches[$student->groupId]->groupName = $student->groupName;
                                        $batches[$student->groupId]->students[] = $student;
                                    }
                                    foreach($batches as $batch)
                                    {
                                        $subject->batches[] = $batch;
                                    }
                                }
                                else if($staffSideMarkEntryType =='SUBJECT_WISE')
                                {
                                    $subject->batches[0]->students = $registeredStudentMarkDetails;
                                }
                            }
                            else if($staffSideMarkEntryUItype == 'NO_PREFETCH_STUDENTS' || $staffSideMarkEntryUItype == 'PREFETCH_STUDENTS' || $staffSideMarkEntryUItype == 'PREFETCH_STUDENTS_WITH_ADDITIONAL_VALUATION_MARKS')
                            {
                                if ( $staffSideMarkEntryUItype != 'PREFETCH_STUDENTS' && $staffSideMarkEntryUItype != 'PREFETCH_STUDENTS_WITH_ADDITIONAL_VALUATION_MARKS' ){
                                    $request->isRequiredFalseNo =  true;
                                }
                                if($staffSideMarkEntryUItype == 'PREFETCH_STUDENTS_WITH_ADDITIONAL_VALUATION_MARKS' && $subject->valuationCount == "2" && $request->falseNoRegNoStatus == "falseNumber"){
                                    $request->isRequiredFalseNo =  true;
                                }
                                $request->academicPaperSubjectId =  $paperSubjectIdArray ? $paperSubjectIdArray : $request->academicPaperSubjectId;
                                if($subject->valuationCount == "3"){
                                    $request->isThirdValuationStudentOnly =  true;
                                }
                                $subject->studentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                                if( $markEntryBasedOn == 'ROLL_NUMBER' ){
                                    uasort($subject->studentMarkDetails, function($a, $b) {
                                        return ($a->rollNo > $b->rollNo);
                                    });
                                }
                                $currentStaffId = $GLOBALS['userId'];
                                foreach($subject->studentMarkDetails as $key => $student)
                                {
                                    $found = 0;
                                    $valuationDetails = json_decode($student->valuation_details);
                                    $studentValuationDetails = json_decode($student->studentValuationDetails);
                                    foreach($valuationDetails->valuationStaffs as $valuationStaff){
                                        if( $valuationStaff->count == $request->currentValuationCount && in_array($currentStaffId, $valuationStaff->addiitonalExamniners)){
                                            $found = 1;
                                        }
                                    }
                        
                                    if(  $found == 0 ){
                                        unset($subject->studentMarkDetails[$key]);
                                        continue;
                                    }
                                    $differentStaff = 0;
                                    foreach ($studentValuationDetails->valuatedStaffs as $valuatedStaff){
                                        if($valuatedStaff->valuationCount == $searchRequest->currentValuationCount && $valuatedStaff->staffIds != $GLOBALS['userId']){
                                            $differentStaff = 1;
                                        }
                                    }
                                    if($differentStaff){
                                        unset($subject->studentMarkDetails[$key]);
                                        continue;
                                    }
                                    if( $considerAdditionalAndChiefValuationForUg && !$courseType->extValRequired && $isTheory && $studentValuationDetails->valuatedStaffs){
                                        $differentStaff = 0;
                                        foreach ($studentValuationDetails->valuatedStaffs as $valuatedStaff){
                                            if($valuatedStaff->valuationCount == $searchRequest->currentValuationCount && $valuatedStaff->staffIds != $GLOBALS['userId']){
                                                $differentStaff = 1;
                                            }
                                        }
                                        if($differentStaff){
                                            unset($subject->studentMarkDetails[$key]);
                                            continue;
                                        }
                                    }
                                    if ( $student->isExempted == 1 ) {
                                        $student->mark = "EX";
                                    }
                                    else if ( $student->isAbsent == "ABSENT" ) {
                                        $student->mark  = "AB";
                                    } 
                                    else if ( $student->isAbsent == "MALPRACTICE" ) {
                                        $student->mark  = "MAL";
                                    } 
                                    else if ($student->isAbsent == "WITHHELD") {
                                        $student->mark  = $student->firstValuationMark;
                                        $student->isWithHeld  = true;
                                    }
                                    else
                                    {
                                        if($subject->valuationCount == "1")
                                        {
                                            if((!$courseType->extValRequired))
                                            {
                                                if( $considerAdditionalAndChiefValuationForUg  && $isTheory  ){
                                                    $student->mark  = $student->firstValuationMark;
                                                }
                                                else{
                                                    $student->mark  = $student->finalizedMark;
                                                }
                                            }
                                            else
                                            {
                                                $student->mark  = $student->firstValuationMark;
                                                if ( $student->isTheory == 0 ){
                                                    $student->mark  = $student->finalizedMark;
                                                }
                                            }
                                            
                                        }
                                        else if($subject->valuationCount == "2")
                                        {
                                            $student->mark  = $student->secondValuationMark;
                                            if ($staffSideMarkEntryUItype == 'PREFETCH_STUDENTS_WITH_ADDITIONAL_VALUATION_MARKS'  ){
                                                $student->mark  = $student->secondValuationMark ? $student->secondValuationMark : $student->firstValuationMark;
                                            }
                                        }
                                        else if($subject->valuationCount == "3")
                                        {
                                            $student->mark  = $student->thirdValuationMark;
                                        }
                                        
                                    }
                                    $student->errorMessage  = "";
                                    $student->currentStatus = 'SAVED';  
                                    if ( $staffSideMarkEntryUItype != 'PREFETCH_STUDENTS'  && $staffSideMarkEntryUItype != 'PREFETCH_STUDENTS_WITH_ADDITIONAL_VALUATION_MARKS' ){
                                        if( empty($student->mark) ){
                                            unset($subject->studentMarkDetails[$key]);
                                        }
                                    }
                                }
                                $subject->studentMarkDetails = array_values($subject->studentMarkDetails);
                            }
                            elseif($staffSideMarkEntryUItype == 'DIGITAL_VALUATION' && $subject->isTheory == '0'){
                                $request->academicPaperSubjectId =  $paperSubjectIdArray ? $paperSubjectIdArray : $request->academicPaperSubjectId;
                                $currentStaffId = $GLOBALS['userId'];
                                $allStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                                foreach($allStudentMarkDetails as $student){
                                    $student->studentValuationDetails = json_decode($student->studentValuationDetails);
                                    if($student->studentValuationDetails){
                                        $currentValuationStaffDetails = reset(array_filter($student->studentValuationDetails->assignedValuationStaffs,function($value)use($searchRequest){
                                            return $value->count == '1';
                                        }));
                                        if(!empty($currentValuationStaffDetails->addiitonalExamniners)){
                                            if(in_array($currentStaffId,$currentValuationStaffDetails->addiitonalExamniners)){
                                                $registeredStudentMarkDetails[$student->studentId] = $student;
                                            }
                                        }
                                    }
                                }
                                foreach($registeredStudentMarkDetails as $student){
                                    $student->rvStatus = $student->isRevalued == 'true' ? true : false;
                                    if ( $student->isExempted == 1 ) {
                                        $student->mark = "EX";
                                        $student->errorMessage  = "";
                                        $student->errorMessage  = $request->currentValuationCount == '1' ? '' : 'Exempted';
                                    }
                                    else if ( $student->isAbsent == "ABSENT" ) {
                                        $student->mark  = "AB";
                                        $student->errorMessage  = $request->currentValuationCount == '1' ? '' : 'Absent';
                                    } 
                                    else if ( $student->isAbsent == "MALPRACTICE" ) {
                                        $student->mark  = "MAL";
                                        $student->errorMessage  = $request->currentValuationCount == '1' ? '' : 'Mal practice';
                                    } 
                                    else if ($student->isAbsent == "WITHHELD") {
                                        $student->mark  = "WH";
                                        $student->isWithHeld  = true;
                                        $student->errorMessage  = $request->currentValuationCount == '1' ? '' : 'with held';
                                    }
                                    else{
                                        $student->mark  = $student->finalizedMark;
                                        $student->errorMessage  = "";
                                    }
                                }
                                if($staffSideMarkEntryType =='BATCH_WISE'){
                                    $batches =[];
                                    foreach($registeredStudentMarkDetails as $student){
                                        $batches[$student->groupId]->groupName = $student->groupName;
                                        $batches[$student->groupId]->students[] = $student;
                                    }
                                    foreach($batches as $batch){
                                        $subject->batches[] = $batch;
                                    }
                                }
                                else if($staffSideMarkEntryType =='SUBJECT_WISE'){
                                    $subject->batches[0]->students = $registeredStudentMarkDetails;
                                }
                                if($subject->isConfiremed == 'CONFIRMED'){
                                    if($staffSideMarkEntryType == 'BATCH_WISE'){
                                        $currentUserId = $GLOBALS['userId'];
                                        $facultyNames = [];
                                        $facultyIdArray[$currentUserId]= $currentUserId;
                                        $facultyIds = "sa.staffID = " .implode(" OR sa.staffID = ",$facultyIdArray);
                                        $faculties =  $this->getFacultiesByFacultyIds($facultyIds);
                                        foreach($faculties as $faculty)
                                        {
                                            $facultyNames[] =  $faculty->staffName;
                                        }
                                        $facultyName = implode(" , ",$facultyNames);
                                        $templateName = "printDigitalValuationPracticalSubjectMarkEntry";
                                        $responseHtml = TwigRenderer::renderTemplateFileToHtml(realpath(DOCUMENT_ROOT."../examcontroller-api/src/com/linways/web/templates/printTwigs/$templateName.twig"), [ 'subject'=>$subject,'faculties'=>$facultyName]);
                                        $prtContent = NULL;
                                            $prtContent .= '<html><head>';
                                            $prtContent .= "<style>
                                                
                                                </style>";
                                            $prtContent .= '</head><title>Mark Entry Report</title><body>';
                                            $prtContent .= $responseHtml;
                                            $prtContent .= '</body></html>';
    
                                            $totalWidth = 210;
                                            $totalHeight = 297;
                                            $options = array(
                                                'page-width'     => $totalWidth."mm",
                                                'page-height'    => $totalHeight."mm",
                                                'dpi'            => 96,
                                                'margin-top' => "9mm",
                                                'margin-left' => "1mm",
                                                'margin-right' => "1mm",
                                                'margin-bottom' => "9mm",
                                                // 'binary' => "/usr/local/bin/wkhtmltopdf", // For Mac
                                                'user-style-sheet' => realpath(DOCUMENT_ROOT . "/libcommon/bootstrap/css/bootstrap.min.css")
                                            );
                                        $subject->displayData = $responseHtml;
                                        $subject->printData = PdfUtil::renderPdf($prtContent, $options);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            $response->subject = $subject;
            $response->isRemoveBookLetNumberToFalseNumber =  $isShowBookLetNumber;
            $response->staffSideMarkEntryUItype = $staffSideMarkEntryUItype;
            $response->staffSideMarkEntryType = $staffSideMarkEntryType;
            $response->isRevaluedStatus = $isRevaluedStatus;
            $response->isQPCodeDisplay = $isQPCodeDisplayInStaffSideMarkEntry;
            $response->courseType = $courseType->courseTypeMethod;
            $response->currentValuationCount = $searchRequest->currentValuationCount;
            $response->markDiff = (int)$markDiff;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    /**
     * getStatusForRegisterNumberOrFalaseNumberfalseNumber
     */
    public function getStatusForRegisterNumberOrFalaseNumber($request)
    {
        $request = $this->realEscapeObject($request);
        $whereQuery = null;
        try 
        { 
            $isFalseNo = false;
            if($request->examRegistrationBatchId)
            {
                $whereQuery .= "AND eers.ec_exam_registration_batch_id = '$request->examRegistrationBatchId'" ;
            }
            $query = "SELECT
                        DISTINCT esar.student_id as id,
                        esar.properties ->> '$.falseNo' as falseNo
                    FROM
                        ec_student_assessment_registration esar
                    INNER JOIN ec_exam_registration_subject eers ON 
                        eers.am_assessment_id = esar.am_assessment_id
                    INNER JOIN ec_exam_registration_batch eerb ON
                        eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer
                        ON eer.id = eerb.ec_exam_registration_id
                WHERE
                    esar.ec_exam_registration_type = eer.type AND
                    eerb.ec_exam_registration_id='$request->examRegistrationId' AND
                    eers.cm_academic_paper_subjects_id='$request->paperSubjectId'  ";
            
            $studentDetails = $this->executeQueryForList($query.$whereQuery);
            foreach($studentDetails as $student){
                if($student->falseNo){
                    $isFalseNo = true;
                }
            }
            if($isFalseNo){
                $falseNoRegNoStatus = "falseNumber";
            }
            else{
                $falseNoRegNoStatus = "regNumber";
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $falseNoRegNoStatus;
    }
     /**
     * get Current Staff Valuated Student Details
     * @param  $request
     * @return $response
     */
    public function getCurrentStaffValuatedStudentDetails($request)
    {
        $request = $this->realEscapeObject($request);
        $currentUerId = $GLOBALS['userId'];
        $whereQuery = null;
        try { 
          
            $orderBy =" ORDER BY esar.updated_date DESC ";
            if($request->examRegistrationBatchId)
            {
                $whereQuery .= "AND eers.ec_exam_registration_batch_id = '$request->examRegistrationBatchId'" ;
            }
            $query = "SELECT
                        DISTINCT sa.studentID as id,
                        sa.studentName,
                        sa.regNo,
                        ostmf.mark_obtained,
                        ostmf.mark_obtained as finalizedMark,
                        ostm1.mark_obtained as firstValuationMark,
                        ostm2.mark_obtained as secondValuationMark,
                        ostm3.mark_obtained as thirdValuationMark,
                        ostmf.attendance_status as isAbsent,
                        esar.am_assessment_id as assessmentId,
                        IF(ees.id,1,0) AS isExempted,
                        esar.properties ->> '$.isRevalued' as isRevalued,
                        esar.properties ->> '$.falseNo' as falseNo,
                        IF(ets.thirdvalstudentID, 1, 0) AS thirdValReq
                    FROM
                        ec_student_assessment_registration esar
                    INNER JOIN studentaccount sa ON 
                        sa.studentID = esar.student_id
                    LEFT JOIN oe_student_total_mark ostmf ON 
                        ostmf.student_id = sa.studentID AND ostmf.am_assessment_id = esar.am_assessment_id AND ostmf.valuation_type = 'FINALIZED'
                    LEFT JOIN oe_student_total_mark ostm1 ON 
                        ostm1.student_id = sa.studentID AND ostm1.am_assessment_id = esar.am_assessment_id AND ostm1.valuation_type = 'FIRST_VALUATION'
                    LEFT JOIN oe_student_total_mark ostm2 ON 
                        ostm2.student_id = sa.studentID AND ostm2.am_assessment_id = esar.am_assessment_id AND ostm2.valuation_type = 'SECOND_VALUATION'
                    LEFT JOIN oe_student_total_mark ostm3 ON 
                        ostm3.student_id = sa.studentID AND ostm3.am_assessment_id = esar.am_assessment_id AND ostm3.valuation_type = 'THIRD_VALUATION'
                    INNER JOIN ec_exam_registration_subject eers ON 
                        eers.am_assessment_id = esar.am_assessment_id
                    INNER JOIN ec_exam_registration_batch eerb ON
                        eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer
                        ON eer.id = eerb.ec_exam_registration_id 
                    LEFT JOIN exam_exempted_students ees ON
                        ees.am_assessment_id  = esar.am_assessment_id AND
                        ees.studentaccount_id =  sa.studentID
                    LEFT JOIN externalexam_thirdvalstudents ets ON 
                            ets.studentID = sa.studentID AND ets.am_assessment_id = eers.am_assessment_id
                WHERE
                    esar.ec_exam_registration_type = eer.type AND
                    CAST(esar.properties ->> '$.registrationStatus' AS CHAR) = 'REGISTERED' AND 
                    CAST(esar.properties ->> '$.feeStatus' AS CHAR) = 'PAID' AND
                    eerb.ec_exam_registration_id='$request->examRegistrationId' AND
                    eers.cm_academic_paper_subjects_id='$request->paperSubjectId' AND
                    JSON_CONTAINS(JSON_EXTRACT(esar.valuation_details ,'$.valuatedStaffs'),JSON_OBJECT('staffIds', '$currentUerId')) AND
                    JSON_CONTAINS(JSON_EXTRACT(esar.valuation_details ,'$.valuatedStaffs'),JSON_OBJECT('valuationCount', '$request->currentValuationCount')) ";
            
            $subjectDetails = $this->executeQueryForList($query.$whereQuery.$orderBy);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $subjectDetails;
        
       
    }
    
      /**
     * get Student Mark Entry Status Details For Staff Side 
     * @param  $request
     * @return $response
     */
    public function getStudentMarkEntryStatusDetailsForStaffSideMarkEntry($request){
        $request = $this->realEscapeObject($request);
        try {
            $conditions = [] ;
            $response = new \stdClass;
            $errorMessage = "";
            $examRegistrationId = $request->examRegistrationId;
            $academicPaperSubjectId = $request->academicPaperSubjectId;
            $paperIdArray = $request->paperIdArray;
            $courseTypeId = $this->getCourseTypeIdByExamRegistrationIdAndPaperSubjectId($examRegistrationId,$academicPaperSubjectId);
            $currentValuationCount =  1;
            $isnotPG = false;
            $examRegistrationBatchId =  $request->examRegistrationBatchId;
            $registerNumber=$request->registerNumber;
            $falseNumber=$request->falseNumber;
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ($courseTypeId);
            $paperIdCond = is_array($paperIdArray) ? "'" . implode("','",$paperIdArray) . "'" : "'".$academicPaperSubjectId."'";
            $paperIdCond = stripslashes($paperIdCond);
            if($courseType->extValRequired)
            {
                $currentValuationCount = $request->currentValuationCount;
                $isnotPG = false;
            }
            else
            {
                $currentValuationCount = 1;
                $isnotPG = true;
            }
            if($registerNumber)
            {
                if($examRegistrationBatchId)
                {
                    $conditions[] = " (spa.properties->>'$.registerNumber' = '".$registerNumber."' AND  eerb.ec_exam_registration_id = '".$examRegistrationId."' AND  eers.cm_academic_paper_subjects_id IN ($paperIdCond) AND eerb.id = '".$examRegistrationBatchId."') ";
                }
                else
                {
                    $conditions[] = " (spa.properties->>'$.registerNumber' = '".$registerNumber."' AND  eerb.ec_exam_registration_id = '".$examRegistrationId."' AND  eers.cm_academic_paper_subjects_id IN ($paperIdCond)) ";
                }
            }
            if($falseNumber)
            {
                if($examRegistrationBatchId)
                {
                    $conditions[] = " (esar.properties ->> '$.falseNo' = '".$falseNumber."' AND  eerb.ec_exam_registration_id = '".$examRegistrationId."' AND  eers.cm_academic_paper_subjects_id IN ($paperIdCond) AND eerb.id = '".$examRegistrationBatchId."') ";
                }
                else
                {
                    $conditions[] = " (esar.properties ->> '$.falseNo' = '".$falseNumber."' AND  eerb.ec_exam_registration_id = '".$examRegistrationId."' AND  eers.cm_academic_paper_subjects_id IN ($paperIdCond)) ";
                }
            }
            $singleStudentDetail = $this->getStudentsExternalMarksByStudentExamDetailForExamRegistration($conditions);
            $valuationDetails = json_decode($singleStudentDetail->valuation_details);
            $valuatedStaffs = json_decode($singleStudentDetail->valuatedStaffs);
            foreach($valuatedStaffs as $valuatedStaff){
                if( $valuatedStaff->valuationCount == $request->currentValuationCount ){
                    if($valuatedStaff->staffIds != $GLOBALS['userId']){
                        $errorMessage = $falseNumber ?? $registerNumber;
                        $errorMessage = $errorMessage." is already added by another staff";
                        throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
                    }
                    
                }
            }
            
            $currentStaffId = $GLOBALS['userId'];
            $found = 0;
            foreach($valuationDetails->valuationStaffs as $valuationStaff){
                if( $valuationStaff->count == $request->currentValuationCount && in_array($currentStaffId, $valuationStaff->addiitonalExamniners)){
                    $found = 1;
                }
            }
            $found = $request->excludeAssignedStaffChecking ? 1 : $found;
            $dateError = 0;
            $today = date("Y-m-d H:i");
            foreach($valuationDetails->valuationDates as $valuationDate){
                if( $valuationDate->count == $request->currentValuationCount && (strtotime($today) >= strtotime($valuationDate->startDate)) && (strtotime($today) <= strtotime($valuationDate->endDate))){
                    $dateError = 1;
                }
            }
            
            if(  $found == 0 || $dateError == 0 ){
                $singleStudentDetail = "";
            }
            if(empty($singleStudentDetail) || $singleStudentDetail == "" || $singleStudentDetail == null)
            {
                if($registerNumber)
                {
                    $errorMessage = $registerNumber." Is Not Registered For This Exam";
                    throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
                }
                else if($falseNumber)
                {
                    $errorMessage = $falseNumber." Is Not Registered For This Exam";
                    throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
                }
                
            }
            else
            {
                if($isnotPG)
                {
                    if($singleStudentDetail->finalizedMark != null)
                    {
                        $response->firstValuationMark = $singleStudentDetail->finalizedMark ? round($singleStudentDetail->finalizedMark, 2) : $singleStudentDetail->finalizedMark;
                    }
                    else
                    {
                        $response->firstValuationMark = null;
                    }
                }
                elseif($currentValuationCount == 1)
                {
                    if($singleStudentDetail->firstValuationMark != null)
                    {
                        $response->firstValuationMark = $singleStudentDetail->firstValuationMark ? round($singleStudentDetail->firstValuationMark, 2) : $singleStudentDetail->firstValuationMark;
                    }
                    else
                    {
                        $response->firstValuationMark = null;
                    }
                }
                elseif($currentValuationCount == 2)
                {
                    if($singleStudentDetail->firstValuationMark == null)
                    {
                        if($registerNumber)
                        {
                            $errorMessage = "First Valuation Not Completed For ".$registerNumber;
                            throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
                        }
                        else if($falseNumber)
                        {
                            $errorMessage = "First Valuation Not Completed For ".$falseNumber;
                            throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
                        }
                       
                    }
                    else
                    {
                        $response->firstValuationMark = (int)$singleStudentDetail->firstValuationMark;
                        if($singleStudentDetail->secondValuationMark != null)
                        {
                            $response->secondValuationMark = $singleStudentDetail->secondValuationMark ? round($singleStudentDetail->secondValuationMark, 2) : $singleStudentDetail->secondValuationMark;
                        }
                        else
                        {
                            $response->secondValuationMark = null;
                        }
                    }
                }
                elseif($currentValuationCount == 3)
                {
                    if($singleStudentDetail->thirdValReq == 0)
                    {
                        if($registerNumber)
                        {
                            $errorMessage = $registerNumber." IS Not Eligible For Third Valuation";
                            throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
                        }
                        else if($falseNumber)
                        {
                            $errorMessage = $falseNumber." IS Not Eligible For Third Valuation";
                            throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
                        }
                    }
                    else
                    {
                        if( $singleStudentDetail->firstValuationMark == null)
                        {
                            if($registerNumber)
                            {
                                $errorMessage =  "First Valuation Not Completed For ".$registerNumber;
                                throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
                            }
                            else if($falseNumber)
                            {
                                $errorMessage =  "First Valuation Not Completed For ".$falseNumber;
                                throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
                            }
                        }
                        else if($singleStudentDetail->secondValuationMark == null)
                        {
                            if($registerNumber)
                            {
                                $errorMessage =  "Second Valuation Not Completed For ".$registerNumber;
                                throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
                            }
                            else if($falseNumber)
                            {
                                $errorMessage =  "Second Valuation Not Completed For ".$falseNumber;
                                throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMessage);
                            }
                        }
                        else
                        {
                            $response->firstValuationMark = (int)$singleStudentDetail->firstValuationMark;
                            $response->secondValuationMark = (int)$singleStudentDetail->secondValuationMark;
                            if($singleStudentDetail->thirdValuationMark != null)
                            {
                                $response->thirdValuationMark = $singleStudentDetail->thirdValuationMark ? round($singleStudentDetail->thirdValuationMark, 2) : $singleStudentDetail->thirdValuationMark;
                            }
                            else
                            {
                                $response->thirdValuationMark = null;
                            }
                        }
                    }
                }
                
                $response->registerNumber = $registerNumber;
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
       /**
     * Save Student Mark Entry  Details For Staff Side 
     * @param  $request
     * @return $response
     */
    public function saveAllExternalMarkDetailsForStaffSideMarkEntry($request){
        $request = $this->realEscapeObject($request);
        try {
            $conditions = [] ;
            $response = new \stdClass;
            $examValuation = new \Stdclass();
            $errorMessage = "";
            $regStudentCount = 0;
            $registredStudentsRegNoArray = [];
            $registredStudentsFalseNoArray = [];
            $registeredStudentDetailsByRegNo = [];
            $registeredStudentDetailsByFalseNo =[];
            $registredStudentsRolNoArray = [];
            $registeredStudentDetailsByRollNo = [];
            $examRegistrationId = $request->examRegistrationId;
            $academicPaperSubjectId = $request->academicPaperSubjectId;
            $paperSubjectIdArray = $request->paperSubjectIdArr;
            $currentValuationCount =  $request->currentValuationCount;
            $examRegistrationBatchId =  $request->examRegistrationBatchId;
            $falseNoOrRegNoStatus =  $request->falseNoOrRegNoStatus;
            $studentMarkArray=$request->studentMarkArray;
            $examValuation->academicPaperSubjectId = $academicPaperSubjectId;
            $examValuation->examRegistrationId = $examRegistrationId;
            $examValuation->examRegistrationBatchId = $examRegistrationBatchId;
            $examValuation->savingType = $request->savingType;
            $examValuation->falseNoOrRegNoStatus = $request->falseNoOrRegNoStatus;
            $examValuation->currentValuationCount = $currentValuationCount ? $currentValuationCount : 1;
            $registeredStudents = $this->getAllRegisteredStudentByExamRegistrationAndAcademicPaperSubject($examRegistrationId,$paperSubjectIdArray,$examRegistrationBatchId);
            $maxmarkOfSubject = ExamRegistrationSubjectService::getInstance()->getMaxSubjectMarkByAcademicPaperSubjectId(stripslashes($request->academicPaperSubjectId));
            $isRevaluedStatus = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::IS_RC_STATUS_IN_EXTERNAL_MARK_ENTRY_DIRECT);
            $courseTypeId = $this->getCourseTypeIdByExamRegistrationIdAndPaperSubjectId($examRegistrationId,$academicPaperSubjectId);
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ($courseTypeId);
            $searchRuleRequest = new SearchRuleRequest;
            $searchRuleRequest->name = "EXAM_VALUATION_PROCEDURE_RULE";
            $examValuationProcedureRule = reset(RuleService::getInstance()->searchRule($searchRuleRequest))->rule;
            $considerAdditionalAndChiefValuationForUg = $examValuationProcedureRule->considerAdditionalAndChiefValuationForUg ? true : false;  
            $isTheory = $this->getIsTheoryOrNotByExamRegistrationIdAndPaperSubjectId( $examRegistrationId,stripslashes($academicPaperSubjectId));
            foreach($registeredStudents as $registeredStudent){
                if($registeredStudent->regNo){
                    $registeredStudent->regNo = strtoupper($registeredStudent->regNo);
                    $registredStudentsRegNoArray[$registeredStudent->regNo] = $registeredStudent->regNo;
                    $registeredStudentDetailsByRegNo[$registeredStudent->regNo] = [
                        "studentId" => $registeredStudent->studentId,
                        "assessmentId" => $registeredStudent->assessmentId,
                        "registerNo" => $registeredStudent->regNo,
                        "falseNo" => $registeredStudent->falseNumber
                    ];
                }
                if($registeredStudent->falseNumber){
                    $registeredStudent->falseNumber = strtoupper($registeredStudent->falseNumber);
                    $registredStudentsFalseNoArray[$registeredStudent->falseNumber] = $registeredStudent->falseNumber;
                    $registeredStudentDetailsByFalseNo[$registeredStudent->falseNumber] = [
                        "studentId" => $registeredStudent->studentId,
                        "assessmentId" => $registeredStudent->assessmentId,
                        "registerNo" => $registeredStudent->regNo,
                        "falseNo" => $registeredStudent->falseNumber
                    ];
                }
                if($registeredStudent->rollNo){
                    $registeredStudent->rollNo = strtoupper($registeredStudent->rollNo);
                    $registredStudentsRolNoArray[$registeredStudent->rollNo] = $registeredStudent->rollNo;
                    $registeredStudentDetailsByRollNo[$registeredStudent->rollNo] = [
                        "studentId" => $registeredStudent->studentId,
                        "assessmentId" => $registeredStudent->assessmentId,
                        "rollNo" => $registeredStudent->rollNo
                    ];
                }
                
            }
            if(!empty($studentMarkArray)){
                foreach($studentMarkArray as $student){
                    if($falseNoOrRegNoStatus == 'falseNumber'){
                        $valuationStudents = new \Stdclass();
                        $falseNo = strtoupper($student['falseNo']);
                        if ( in_array ( $falseNo, $registredStudentsFalseNoArray ) ) {
                            if($student['mark'] == "AB" || $student['mark'] == "MAL" || $student['mark'] == "WH" || $student['mark'] == "EX"){
                                if($currentValuationCount == '1'){
                                    if($isRevaluedStatus == '1'){
                                        $valuationStudents->rvStatus =  $student['rvStatus'];
                                    }
                                    $valuationStudents->falseNumber =  $student['falseNo'];
                                    $valuationStudents->studentId =  $registeredStudentDetailsByFalseNo[$falseNo]["studentId"];
                                    $valuationStudents->mark =  $student['mark'];
                                    $valuationStudents->firstValMark = $student['firstValuationMark'];
                                    $valuationStudents->assessmentId    = $registeredStudentDetailsByFalseNo[$falseNo]["assessmentId"];
                                    $valuationStudents->registerNumber    = $registeredStudentDetailsByFalseNo[$falseNo]["registerNo"];
                                    $examValuation->examValuationStudentMarkDetails[] = $valuationStudents;
                                    $regStudentCount++;
                                }
                            }
                            else if ( $student['mark'] > $maxmarkOfSubject ){
                                $markExceedsTotalMark[] = $student['falseNo'];
                                $errorFlag = 1;
                            }
                            else{
                                if($isRevaluedStatus == '1'){
                                    $valuationStudents->rvStatus =  $student['rvStatus'];
                                }
                                $valuationStudents->falseNumber =  $student['falseNo'];
                                $valuationStudents->studentId =  $registeredStudentDetailsByFalseNo[$falseNo]["studentId"];
                                $valuationStudents->mark =  $student['mark'];
                                $valuationStudents->firstValMark = $student['firstValuationMark'];
                                $valuationStudents->assessmentId    = $registeredStudentDetailsByFalseNo[$falseNo]["assessmentId"];
                                $valuationStudents->registerNumber    = $registeredStudentDetailsByFalseNo[$falseNo]["registerNo"];
                                $examValuation->examValuationStudentMarkDetails[] = $valuationStudents;
                                $regStudentCount++;
                            }
                        }
                        else{
                            $unregisteredStudents[] = $student['falseNo'];
                            $errorFlag = 1;
                        }
                    }
                    else if($falseNoOrRegNoStatus == 'regNumber'){
                        $valuationStudents = new \Stdclass();
                        $regNo = strtoupper($student['regNo']);
                        if ( in_array ( $regNo, $registredStudentsRegNoArray ) ) {
                            if($student['mark'] == "AB" || $student['mark'] == "MAL" || $student['mark'] == "WH" || $student['mark'] == "EX"){
                                if($currentValuationCount == '1'){
                                    if($isRevaluedStatus == '1'){
                                        $valuationStudents->rvStatus =  $student['rvStatus'];
                                    }
                                    $valuationStudents->registerNumber =  $student['regNo'];
                                    $valuationStudents->studentId =  $registeredStudentDetailsByRegNo[$regNo]["studentId"];
                                    $valuationStudents->mark =  $student['mark'];
                                    $valuationStudents->firstValMark = $student['firstValuationMark'];
                                    if ($student['vivaMark'] || $student['vivaMark'] == 0) {
                                        $valuationStudents->vivaMark =  $student['vivaMark'];
                                    }
                                    $valuationStudents->assessmentId    = $registeredStudentDetailsByRegNo[$regNo]["assessmentId"];
                                    $valuationStudents->falseNumber    = $registeredStudentDetailsByRegNo[$regNo]["falseNo"];
                                    $examValuation->examValuationStudentMarkDetails[] = $valuationStudents;
                                    $regStudentCount++;
                                }
                            }
                            else if ( $student['mark'] > $maxmarkOfSubject ){
                                $markExceedsTotalMark[] = $student['regNo'];
                                $errorFlag = 1;
                            }
                            else{
                                if($isRevaluedStatus == '1'){
                                    $valuationStudents->rvStatus =  $student['rvStatus'];
                                }
                                $valuationStudents->registerNumber =  $student['regNo'];
                                $valuationStudents->studentId =  $registeredStudentDetailsByRegNo[$regNo]["studentId"];
                                $valuationStudents->mark =  $student['mark'];
                                $valuationStudents->firstValMark = $student['firstValuationMark'];
                                if ($student['vivaMark'] || $student['vivaMark'] == 0) {
                                    $valuationStudents->vivaMark =  $student['vivaMark'];
                                }
                                $valuationStudents->assessmentId    = $registeredStudentDetailsByRegNo[$regNo]["assessmentId"];
                                $valuationStudents->falseNumber    = $registeredStudentDetailsByRegNo[$regNo]["falseNo"];
                                $examValuation->examValuationStudentMarkDetails[] = $valuationStudents;
                                $regStudentCount++;
                            }
                        }
                        else{
                            $unregisteredStudents[] = $student['registerNumber'];
                            $errorFlag = 1;
                        }
                    }
                    else if($falseNoOrRegNoStatus == 'rollNumber'){
                        $valuationStudents = new \Stdclass();
                        $rollNo = strtoupper($student['rollNo']);
                        if ( in_array ( $rollNo, $registredStudentsRolNoArray ) ) {
                            if($student['mark'] == "AB" || $student['mark'] == "MAL" || $student['mark'] == "WH" || $student['mark'] == "EX"){
                                if($currentValuationCount == '1'){
                                    if($isRevaluedStatus == '1'){
                                        $valuationStudents->rvStatus =  $student['rvStatus'];
                                    }
                                    $valuationStudents->rollNumber =  $student['rollNo'];
                                    $valuationStudents->studentId =  $registeredStudentDetailsByRollNo[$rollNo]["studentId"];
                                    $valuationStudents->mark =  $student['mark'];
                                    $valuationStudents->firstValMark = $student['firstValuationMark'];
                                    $valuationStudents->assessmentId    = $registeredStudentDetailsByRollNo[$rollNo]["assessmentId"];
                                    $examValuation->examValuationStudentMarkDetails[] = $valuationStudents;
                                    $regStudentCount++;
                                }
                            }
                            else if ( $student['mark'] > $maxmarkOfSubject ){
                                $markExceedsTotalMark[] = $student['rollNo'];
                                $errorFlag = 1;
                            }
                            else{
                                if($isRevaluedStatus == '1'){
                                    $valuationStudents->rvStatus =  $student['rvStatus'];
                                }
                                $valuationStudents->rollNumber =  $student['rollNo'];
                                $valuationStudents->studentId =  $registeredStudentDetailsByRollNo[$rollNo]["studentId"];
                                $valuationStudents->mark =  $student['mark'];
                                $valuationStudents->firstValMark = $student['firstValuationMark'];
                                $valuationStudents->assessmentId    = $registeredStudentDetailsByRollNo[$rollNo]["assessmentId"];
                                $examValuation->examValuationStudentMarkDetails[] = $valuationStudents;
                                $regStudentCount++;
                            }
                        }
                        else{
                            $unregisteredStudents[] = $student['rollNo'];
                            $errorFlag = 1;
                        }
                    } 
                }
                if ( $regStudentCount ) {
                    $response = $this->saveExamValuationStudentmarksForStaffSideMarkEntry ( $examValuation );
                    if($request->savingType == "SAVE_MARK"  || $request->savingType == 'ADD_MARK'){
                        $searchRequest = new \Stdclass();
                        $searchRequest->examRegistrationId = $request->examRegistrationId;
                        $searchRequest->academicPaperSubjectId =  $paperSubjectIdArray ? $paperSubjectIdArray : $request->academicPaperSubjectId;
                        $searchRequest->currentValuationCount =  $request->currentValuationCount;
                        $searchRequest->examRegistrationBatchId =  $request->examRegistrationBatchId;
                        $searchRequest->answerSheetGroupCount =  $request->answerSheetGroupCount;
                        if( $considerAdditionalAndChiefValuationForUg && !$courseType->extValRequired && $isTheory){
                            $searchRequest->considerMultipleStaffValuated =  1;
                        }
                        $searchRequest->considerMultipleStaffValuated =  1;
                        $this->saveExtrenalMarkStatusByStaffSide( $searchRequest );
                    }
                    else if($request->savingType == "CONFIRM_MARK"){
                        $searchRequest = new \Stdclass();
                        $searchRequest->examRegistrationId = $request->examRegistrationId;
                        $searchRequest->academicPaperSubjectId =  $paperSubjectIdArray ? $paperSubjectIdArray : $request->academicPaperSubjectId;
                        $searchRequest->currentValuationCount =  $request->currentValuationCount;
                        $searchRequest->examRegistrationBatchId =  $request->examRegistrationBatchId;
                        $searchRequest->answerSheetGroupCount =  $request->answerSheetGroupCount;
                        $searchRequest->answerSheetGroupCount =  $request->answerSheetGroupCount;
                        if( $considerAdditionalAndChiefValuationForUg && !$courseType->extValRequired && $isTheory){
                            $searchRequest->considerMultipleStaffValuated =  1;
                        }
                        $searchRequest->considerMultipleStaffValuated =  1;
                        $this->submitExtrenalMarkStatusByStaffSide( $searchRequest );
                    }
                }
                if ( $errorFlag || $response->error) {
                    $errors["unregisteredStudent"] = $errors["markExceedsTotalMark"] =$errors["error"] = $errors["success"] = $errors["notEligibleThirdValuation"] = $errors["secondValuationNotCompletedStudents"] = $errors["firstValuationNotCompletedStudents"] = $errors["otherPacketStudents"] ="";
                   
                    if($falseNoOrRegNoStatus == 'rollNumber'){
                        if ( !empty ( $unregisteredStudents ) ) {
                            $errors["unregisteredStudent"] = "The student with roll number ". implode(", ", $unregisteredStudents)." is/are not registered for exam";
                        }
                        if ( !empty ( $markExceedsTotalMark ) ) {
                            $errors["markExceedsTotalMark"] = "The marks entered for the student(s) with roll number ". implode(", ", $markExceedsTotalMark)." exceeds the total mark of exam";
                        }
                    }
                    else{
                        if ( !empty ( $unregisteredStudents ) ) {
                            $errors["unregisteredStudent"] = "The student with register number ". implode(", ", $unregisteredStudents)." is/are not registered for exam";
                        }
                        if ( !empty ( $markExceedsTotalMark ) ) {
                            $errors["markExceedsTotalMark"] = "The marks entered for the student(s) with register number ". implode(", ", $markExceedsTotalMark)." exceeds the total mark of exam";
                        }
                    }
                    if ( !empty ( $response->firstValuationNotCompletedStudents ) ) {
                        $errors["firstValuationNotCompletedStudents"] = "The marks entered for the student(s) with register number ". implode(", ", $response->firstValuationNotCompletedStudents)." is/are not complete first valuation";
                    }
                    if ( !empty ( $response->secondValuationNotCompletedStudents ) ) {
                        $errors["secondValuationNotCompletedStudents"] = "The marks entered for the student(s) with register number ". implode(", ", $response->secondValuationNotCompletedStudents)." is/are not complete second valuation";
                    }
                    if ( !empty ( $response->notEligibleThirdValuation ) ) {
                        $errors["notEligibleThirdValuation"] = "The marks entered for the student(s) with register number ". implode(", ", $response->notEligibleThirdValuation)." is/are not eligible for third valuation";
                    }
                    if($response->updatedStudentCount){
                        $errors["success"] = "Marks saved successfully for $response->updatedStudentCount student(s)";
                    }
                }
                else{
                    $success["success"] = "";
                    if($response->updatedStudentCount){
                        $success["success"] = "Marks saved successfully for $response->updatedStudentCount student(s)";
                    }
                }
            }
            else{
                $errors["unregisteredStudent"] = $errors["markExceedsTotalMark"] =$errors["error"] = $errors["success"] = $errors["notEligibleThirdValuation"] = $errors["secondValuationNotCompletedStudents"] = $errors["firstValuationNotCompletedStudents"] = $errors["otherPacketStudents"] ="";
                $errors["error"] = "No Student Mark Entered";
            }
            $response->errors = $errors;
            $response->success = $success;
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    
      /**
     * save Exam Valuation Studentmarks For Staff Side Mark Entry
     * @param $examValuation
     * @return $response
     */
    public function saveExamValuationStudentmarksForStaffSideMarkEntry($examValuation){
        $examValuation = $this->realEscapeObject($examValuation);
        try {
            $examRegistrationId = $examValuation->examRegistrationId;
            $savingType = $examValuation->savingType;
            $academicPaperSubjectId = $examValuation->academicPaperSubjectId;
            $examRegistrationBatchId = $examValuation->examRegistrationBatchId;
            $currentValuationCount = $examValuation->currentValuationCount;
            $studentMarkDetailsArray = $examValuation->examValuationStudentMarkDetails;
            $courseTypeId = $this->getCourseTypeIdByExamRegistrationIdAndPaperSubjectId($examRegistrationId,$academicPaperSubjectId);
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ($courseTypeId);
            $registeredStudentsArray = [];
            $registeredStudentsCurrentMarks = [];
            $registeredStudentsvivaMarks = [];
            $hasVivaMark = 0;
            $registeredStudentsRVStatus = [];
            $error = 0;
            $currentStaffId = $GLOBALS['userId'];
            $updatedStudentCount = 0;
            $insertionMarkTableArray = [];
            $deleteMarkTableArray = [];
            $updateValuatedStaffValues = [];
            $updateIsRevaluedStatus = [];
            $insert_third_val_students = [];
            $delete_third_val_students = [];
            $studentMarkDetails = [];
            $insertionWithHeldMarkTableArray =[];
            $notEligibleThirdValuation = [];
            $valuationProperties = new \Stdclass();
            $valuatedStaffObject = new \Stdclass();
            $properties = new \Stdclass();
            $response = new \Stdclass();
            $maxmarkOfSubject = ExamRegistrationSubjectService::getInstance()->getMaxSubjectMarkByAcademicPaperSubjectId($academicPaperSubjectId);
            $isTheory = $this->getIsTheoryOrNotByExamRegistrationIdAndPaperSubjectId( $examRegistrationId,stripslashes($academicPaperSubjectId));
            $markDiffDetails = $courseTypeId ? $this->getExternalValuationMarkDifference($courseTypeId) : '';
            $searchRuleRequest = new SearchRuleRequest;
            $searchRuleRequest->name = "EXAM_VALUATION_PROCEDURE_RULE";
            $examValuationProcedureRule = reset(RuleService::getInstance()->searchRule($searchRuleRequest))->rule;
            $considerAdditionalAndChiefValuationForUg = $examValuationProcedureRule->considerAdditionalAndChiefValuationForUg ? true : false;  
            if($markDiffDetails->scheme == "PERCENTAGE"){   
                $markDiff = ( $markDiffDetails->markDiff * $maxmarkOfSubject ) / 100;
            }
            else{
                $markDiff = $markDiffDetails->markDiff;
            }
            
            //get valuation rules
            $searchRuleRequest = new SearchRuleRequest;
            $searchRuleRequest->name = "EXAM_VALUATION_PROCEDURE_RULE";
            $examValuationProcedureRule = reset(RuleService::getInstance()->searchRule($searchRuleRequest))->rule;
            $examValuationProcedureRule->isExcatFinalizeMark = $examValuationProcedureRule->isExcatFinalizeMark ? $examValuationProcedureRule->isExcatFinalizeMark : false;
            $examValuationProcedureRule->roundOffDigits = $examValuationProcedureRule->roundOffDigits ? $examValuationProcedureRule->roundOffDigits : 0;
            // $markDiff = ExamService::getInstance()->getExternalValuationMarkDiff($courseTypeId);
            $valuatedStaffObject->staffIds = $currentStaffId;
            $valuatedStaffObject->valuationCount = $examValuation->currentValuationCount;
            $valuationProperties->valuatedStaffs[]=$valuatedStaffObject;
            if( $considerAdditionalAndChiefValuationForUg && !$courseType->extValRequired && $isTheory){
                //do nothing
            }
            else{
                if((!$courseType->extValRequired)){
                    $currentValuationCount = "FINALIZED";
                }
                else if($courseType->extValRequired){
                    if(($currentValuationCount == 1) && ($isTheory == "0")){
                        $currentValuationCount = "FINALIZED";
                    }
                }
            }
            foreach($studentMarkDetailsArray as $student){
                if( $considerAdditionalAndChiefValuationForUg && !$courseType->extValRequired && $isTheory && $currentValuationCount == 2 ){
                    if( $examValuation->falseNoOrRegNoStatus == "rollNumber" ){
                        if(($student->rollNumber) && ($student->mark != "" || $student && $student->firstValMark != '')){
                            $conditions[] = " (spa.properties->>'$.rollNumber' = '".$student->rollNumber."' AND  esar.am_assessment_id = '".$student->assessmentId."') ";
                        }
                    }
                    if( $examValuation->falseNoOrRegNoStatus == "falseNumber" ){
                        if(($student->falseNumber) && ($student->mark != "" || $student && $student->firstValMark != '')){
                            $conditions[] = " (esar.properties ->> '$.falseNo' = '".$student->falseNumber."' AND  esar.am_assessment_id = '".$student->assessmentId."') ";
                        }
                    }
                    else{
                        if((($student->registerNumber) && ($student->mark != "" || $student && $student->firstValMark != '') || (($student->registerNumber) && ($student->vivaMark || $student->vivaMark == 0)))){
                            $conditions[] = " (spa.properties->>'$.registerNumber' = '".$student->registerNumber."' AND  esar.am_assessment_id = '".$student->assessmentId."') ";
                        }
                    }
                }
                else{
                    if( $examValuation->falseNoOrRegNoStatus == "rollNumber" ){
                        if(($student->rollNumber) && ($student->mark != "")){
                            $conditions[] = " (spa.properties->>'$.rollNumber' = '".$student->rollNumber."' AND  esar.am_assessment_id = '".$student->assessmentId."') ";
                        }
                    }
                    if( $examValuation->falseNoOrRegNoStatus == "falseNumber" ){
                        if(($student->falseNumber) && ($student->mark != "")){
                            $conditions[] = " (esar.properties ->> '$.falseNo' = '".$student->falseNumber."' AND  esar.am_assessment_id = '".$student->assessmentId."') ";
                        }
                    }
                    else{
                        if((($student->registerNumber) && ($student->mark != "") || (($student->registerNumber) && ($student->vivaMark || $student->vivaMark == 0)))){
                            $conditions[] = " (spa.properties->>'$.registerNumber' = '".$student->registerNumber."' AND  esar.am_assessment_id = '".$student->assessmentId."') ";
                        }
                    }
                }
            }
            if(! empty($conditions)){
                $valuationRules =  (array) $this->getAllValuationRule();
                $studentDetails = $this->getStudentsExternalMarksByStudentExamDetail($conditions);
                foreach($studentMarkDetailsArray as $student){
                    $registeredStudentsArray[$student->studentId] = $student->studentId;
                    $registeredStudentsCurrentMarks[$student->studentId] = $student->mark;
                    $registeredStudentsvivaMarks[$student->studentId] = $student->vivaMark;
                    $registeredStudentsRVStatus[$student->studentId] = $student->rvStatus;
                }
                foreach($studentDetails as $studentDetail){
                    if ( $courseType->typeName == 'B.Des' && $isTheory == 0 && (($studentDetail->academicTermId > 2 && $studentDetail->startYear >= 2022) || ($studentDetail->startYear >= 2023))){
                        $hasVivaMark = 1;
                    }
                    $studentDetail->valuationDetails = json_decode($studentDetail->valuationDetails);
                    if($studentDetail->valuationDetails){
                        $valuationProperties = new \Stdclass();
                        $valuationProperties = $studentDetail->valuationDetails;
                        $valuatedStaffObject->staffIds = $currentStaffId;
                        $valuatedStaffObject->valuationCount = $examValuation->currentValuationCount;
                        $valuationProperties->valuatedStaffs[]=$valuatedStaffObject;
                    }
                    else{
                        $valuationProperties = new \Stdclass();
                        $valuatedStaffObject->staffIds = $currentStaffId;
                        $valuatedStaffObject->valuationCount = $examValuation->currentValuationCount;
                        $valuationProperties->valuatedStaffs[]=$valuatedStaffObject;
                    }
                    $studentDetail->batchProperties = json_decode($studentDetail->batchProperties);
                    if($studentDetail->batchProperties->valuationRule){
                        $selectedSecondValuationRule = reset(array_filter($studentDetail->batchProperties->valuationRule, function ($rule) {
                            return $rule->count == 2;
                        }));
                        $selectedThirdValuationRule = reset(array_filter($studentDetail->batchProperties->valuationRule, function ($rule) {
                            return $rule->count == 3;
                        }));
                        $secondValuationRuleKey =  array_search($selectedSecondValuationRule->ruleId, array_column( $valuationRules, "id"));
                        $thirdValuationRuleKey =  array_search($selectedThirdValuationRule->ruleId, array_column( $valuationRules, "id"));
                        if($secondValuationRuleKey !== false){
                            $studentDetail->secondValuationRule = $valuationRules[$secondValuationRuleKey];
                        }
                        if($thirdValuationRuleKey !== false){
                            $studentDetail->thirdValuationRule = $valuationRules[$thirdValuationRuleKey];
                        }
                    }
                    if ( in_array ( $studentDetail->studentId, $registeredStudentsArray ) ) {
                        $singleStudentDetail = new \Stdclass();
                        $facultyUpdated = false;
                        $singleStudentDetail= $studentDetail;
                        if( $examValuation->falseNoOrRegNoStatus == "rollNumber" ){
                            $singleStudentDetail->rollNumber = $studentDetail->rollNo;
                        }
                        else{
                            $singleStudentDetail->registerNumber = $studentDetail->regNo;
                        }
                        $singleStudentDetail->currentMark = $registeredStudentsCurrentMarks[$studentDetail->studentId];
                        $singleStudentDetail->vivaMark = $registeredStudentsvivaMarks[$studentDetail->studentId];
                        $studentDetail->studentProperties = json_decode($studentDetail->studentProperties);
                        $studentDetail->studentProperties->isRevalued = $registeredStudentsRVStatus[$studentDetail->studentId] ? true : false;
                        $singleStudentDetail->studentProperties = $studentDetail->studentProperties;
                        if(is_null($studentDetail->valuatedStaffs)){
                            $singleStudentDetail->valuationDetails = $valuationProperties;
                        }
                        else if($studentDetail->valuatedStaffs){
                            $valuatedStaffs = json_decode($studentDetail->valuatedStaffs);
                            foreach($valuatedStaffs as $valuatedStaff){
                                if($valuatedStaff->valuationCount == $currentValuationCount){
                                    $valuatedStaff->staffIds = $currentStaffId;
                                    $facultyUpdated = true;
                                }
                            }
                            if(!$facultyUpdated){
                                $valuatedStaffs[] = $valuatedStaffObject;
                            }
                            $singleStudentDetail->valuationDetails->valuatedStaffs = $valuatedStaffs;
                        }
                        if( $singleStudentDetail->studentId){
                            $studentMarkDetails[] = $singleStudentDetail;
                        } 
                    }
                }
                foreach($studentMarkDetails as $studentMarkDetail){
                    $updateMarkValuatedStaff = new \Stdclass();
                    $updateIsRevaluved = new \Stdclass();
                    if($currentValuationCount == 1 || $currentValuationCount == 'FINALIZED'){
                        if((!$courseType->extValRequired)){
                            $updateIsRevaluved->assessmentId = $studentMarkDetail->assessmentId;
                            $updateIsRevaluved->studentId = $studentMarkDetail->studentId;
                            $updateIsRevaluved->properties = $studentMarkDetail->studentProperties;
                            $updateIsRevaluedStatus[] = $updateIsRevaluved;
                        }
                        if($studentMarkDetail->currentMark == "AB"){
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $studentMarkDetail->studentId;
                                $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                $markEntryObj->markObtained = null;
                                $markEntryObj->attendanceStatus = "ABSENT";
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markEntryObj->hasVivaMark = $hasVivaMark;
                                $markproperties = "";
                                if($studentMarkDetail->finalizedMarkProperties){
                                    $markproperties = (object)$studentMarkDetail->finalizedMarkProperties;
                                }
                                if( $hasVivaMark ){
                                    $examMarks = new \stdClass();
                                    $examMarks->mark1 = $studentMarkDetail->vivaMark;
                                    $markEntryObj->examAdditionalMarks  = $examMarks;
                                }
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                            $insertionMarkTableArray[] = $markEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $deleteMarkEntryObj->studentId =  $studentMarkDetail->studentId;
                                $deleteMarkEntryObj->valuationCount = 1;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $deleteMarkEntryObj->studentId =  $studentMarkDetail->studentId;
                                $deleteMarkEntryObj->valuationCount = 2;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $deleteMarkEntryObj->studentId =  $studentMarkDetail->studentId;
                                $deleteMarkEntryObj->valuationCount = 3;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                            $deleteExempted[] = " ( am_assessment_id = '".$studentMarkDetail->assessmentId."' AND studentaccount_id =  '".$studentMarkDetail->studentId."' ) ";
                        }
                        else if($studentMarkDetail->currentMark == "MAL"){
                            $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $studentMarkDetail->studentId;
                                $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                $markEntryObj->hasVivaMark = $hasVivaMark;
                                $markEntryObj->markObtained = null;
                                $markEntryObj->attendanceStatus = "MALPRACTICE";
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markproperties = "";
                                if($studentMarkDetail->finalizedMarkProperties){
                                    $markproperties = (object)$studentMarkDetail->finalizedMarkProperties;
                                }
                                if( $hasVivaMark ){
                                    $examMarks = new \stdClass();
                                    $examMarks->mark1 = $studentMarkDetail->vivaMark;
                                    $markEntryObj->examAdditionalMarks  = $examMarks;
                                }
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                            $insertionMarkTableArray[] = $markEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $deleteMarkEntryObj->studentId =  $studentMarkDetail->studentId;
                                $deleteMarkEntryObj->valuationCount = 1;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $deleteMarkEntryObj->studentId =  $studentMarkDetail->studentId;
                                $deleteMarkEntryObj->valuationCount = 2;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $deleteMarkEntryObj->studentId =  $studentMarkDetail->studentId;
                                $deleteMarkEntryObj->valuationCount = 3;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                            $deleteExempted[] = " ( am_assessment_id = '".$studentMarkDetail->assessmentId."' AND studentaccount_id =  '".$studentMarkDetail->studentId."' ) ";
                        }
                        else if($studentMarkDetail->currentMark == "WH"){
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $studentMarkDetail->studentId;
                                $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                $markEntryObj->markObtained = $studentMarkDetail->finalizedMark;
                                $markEntryObj->attendanceStatus = "MALPRACTICE";
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markEntryObj->hasVivaMark = $hasVivaMark;
                                $markproperties = "";
                                if($studentMarkDetail->finalizedMarkProperties){
                                    $markproperties = (object)$studentMarkDetail->finalizedMarkProperties;
                                }
                                if( $hasVivaMark ){
                                    $examMarks = new \stdClass();
                                    $examMarks->mark1 = $studentMarkDetail->vivaMark;
                                    $markEntryObj->examAdditionalMarks  = $examMarks;
                                }
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                            $insertionMarkTableArray[] = $markEntryObj;
                            $insertionWithHeldMarkTableArray[] = " ('". $studentMarkDetail->studentId."', '0', 'WITHHELD','".$studentMarkDetail->assessmentId."',$finalizedproperties,'".$currentStaffId."', utc_timestamp(), '".$currentStaffId."', utc_timestamp() ) ";
                            $deleteExempted[] = " ( am_assessment_id = '".$studentMarkDetail->assessmentId."' AND studentaccount_id =  '".$studentMarkDetail->studentId."' ) ";
                        }
                        else if($studentMarkDetail->currentMark == "EX"){
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $deleteMarkEntryObj->studentId =  $studentMarkDetail->studentId;
                                $deleteMarkEntryObj->valuationCount = 1;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $deleteMarkEntryObj->studentId =  $studentMarkDetail->studentId;
                                $deleteMarkEntryObj->valuationCount = 2;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $deleteMarkEntryObj->studentId =  $studentMarkDetail->studentId;
                                $deleteMarkEntryObj->valuationCount = 3;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                            //     $deleteMarkEntryObj = new ExamUserMarkRequest;
                            //     $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                            //     $deleteMarkEntryObj->studentId =  $studentMarkDetail->studentId;
                            //     $deleteMarkEntryObj->valuationCount = 'FINALIZED';
                            // $deleteMarkTableArray[] = $deleteMarkEntryObj;
                            $deleteExempted[] = " ( am_assessment_id = '".$studentMarkDetail->assessmentId."' AND studentaccount_id =  '".$studentMarkDetail->studentId."' ) ";
                            $insertExempted[] = " ( '".$studentMarkDetail->studentId."', '".$studentMarkDetail->assessmentId."' ,'".$currentStaffId."', utc_timestamp(), '".$currentStaffId."', utc_timestamp() ) ";
                        }
                        else{
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $studentMarkDetail->studentId;
                                $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                                $markEntryObj->hasVivaMark = $hasVivaMark;
                                $markEntryObj->attendanceStatus = "PRESENT";
                                $markEntryObj->valuationCount = $currentValuationCount == 1 ? 1 : 'FINALIZED';
                                $markproperties = "";
                                if($currentValuationCount == 1){
                                    if($studentMarkDetail->firstValuationMarkProperties){
                                        $markproperties = (object)$studentMarkDetail->firstValuationMarkProperties;
                                    } 
                                }
                                else{
                                    if($studentMarkDetail->finalizedMarkProperties){
                                        $markproperties = (object)$studentMarkDetail->finalizedMarkProperties;
                                    }
                                }
                                if( $hasVivaMark ){
                                    $examMarks = new \stdClass();
                                    $examMarks->mark1 = $studentMarkDetail->vivaMark;
                                    $markEntryObj->examAdditionalMarks  = $examMarks;
                                }
                                    $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                            $insertionMarkTableArray[] = $markEntryObj;
                            // if(  $currentValuationCount == 1 ){
                            //     $deleteMarkEntryObj = new ExamUserMarkRequest;
                            //     $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                            //     $deleteMarkEntryObj->studentId =  $studentMarkDetail->studentId;
                            //     $deleteMarkEntryObj->valuationCount = 'FINALIZED';
                            //     $deleteMarkTableArray[] = $deleteMarkEntryObj;
                            // }
                        }
                        $updateMarkValuatedStaff->assessmentId = $studentMarkDetail->assessmentId;
                        $updateMarkValuatedStaff->studentId = $studentMarkDetail->studentId;
                        $updateMarkValuatedStaff->valuationProperties = $studentMarkDetail->valuationDetails;
                        $updateMarkValuatedStaff->updatedBy = $currentStaffId ;
                        $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                        $updatedStudentCount ++;
                    }
                    if($currentValuationCount == 2){
                        if( $considerAdditionalAndChiefValuationForUg && !$courseType->extValRequired && $isTheory){
                            if ( $studentMarkDetail->currentMark ){
                                // second valuation mark entry
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $studentMarkDetail->studentId;
                                $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                                $markEntryObj->attendanceStatus = "PRESENT";
                                $markEntryObj->valuationCount = 2;
                                $markproperties = "";
                                if($studentMarkDetail->secondValuationMarkProperties){
                                    $markproperties = (object)$studentMarkDetail->secondValuationMarkProperties;
                                } 
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                                $insertionMarkTableArray[] = $markEntryObj;
                                // finalizing mark entry if chief evaluator mark entered students
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $studentMarkDetail->studentId;
                                $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                                $markEntryObj->attendanceStatus = "PRESENT";
                                $markEntryObj->valuationCount = "FINALIZED";
                                $markproperties = "";
                                if($studentMarkDetail->secondValuationMarkProperties){
                                    $markproperties = (object)$studentMarkDetail->secondValuationMarkProperties;
                                } 
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                                $insertionMarkTableArray[] = $markEntryObj;
                            }
                            else if($studentMarkDetail->firstValuationMark != null){
                                // finalizing mark entry if not chief evaluator mark entered and considering additional valuator mark
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $studentMarkDetail->studentId;
                                $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                $markEntryObj->markObtained = $studentMarkDetail->firstValuationMark;
                                $markEntryObj->attendanceStatus = "PRESENT";
                                $markEntryObj->valuationCount = "FINALIZED";
                                $markproperties = "";
                                if($studentMarkDetail->secondValuationMarkProperties){
                                    $markproperties = (object)$studentMarkDetail->secondValuationMarkProperties;
                                } 
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                                $insertionMarkTableArray[] = $markEntryObj;
                            }
                        }
                        else{
                            if($studentMarkDetail->firstValuationMark != null){
                                    $markEntryObj = new \stdClass();
                                    $markEntryObj->studentId = $studentMarkDetail->studentId;
                                    $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                    $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                    $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                                    $markEntryObj->attendanceStatus = "PRESENT";
                                    $markEntryObj->valuationCount = 2;
                                    $markproperties = "";
                                    if($studentMarkDetail->secondValuationMarkProperties){
                                        $markproperties = (object)$studentMarkDetail->secondValuationMarkProperties;
                                    } 
                                    $markEntryObj->properties  = $markproperties;
                                    $markEntryObj->valuationType = null;
                                $insertionMarkTableArray[] = $markEntryObj;
                                $updateMarkValuatedStaff->assessmentId = $studentMarkDetail->assessmentId;
                                $updateMarkValuatedStaff->studentId = $studentMarkDetail->studentId;
                                $updateMarkValuatedStaff->valuationProperties = $studentMarkDetail->valuationDetails;
                                $updateMarkValuatedStaff->updatedBy = $currentStaffId ;
                                $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                                $studentMarkDiff = abs ($studentMarkDetail->firstValuationMark - $studentMarkDetail->currentMark);
                                $updatedStudentCount ++;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $deleteMarkEntryObj->studentId =  $studentMarkDetail->studentId;
                                $deleteMarkEntryObj->valuationCount = 3;
                                $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                if( $studentMarkDiff >= $markDiff){
                                    //     $deleteMarkEntryObj = new ExamUserMarkRequest;
                                    //     $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                    //     $deleteMarkEntryObj->studentId =  $studentMarkDetail->studentId;
                                    //     $deleteMarkEntryObj->valuationCount = 'FINALIZED';
                                    // $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                    $insert_third_val_students[] = "( '".$studentMarkDetail->assessmentId."', ".$studentMarkDetail->studentId." )";
                                    $markEntryObj = new \stdClass();
                                    $markEntryObj->studentId = $studentMarkDetail->studentId;
                                    $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                    $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                    $markEntryObj->markObtained = null;
                                    $markEntryObj->attendanceStatus = "PRESENT";
                                    $markEntryObj->valuationCount = 'FINALIZED';
                                    $markproperties = "";
                                    if($studentMarkDetail->secondValuationMarkProperties){
                                        $markproperties = (object)$studentMarkDetail->secondValuationMarkProperties;
                                    } 
                                    $markEntryObj->properties  = $markproperties;
                                    $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
                                }
                                else{
                                    // $studentMark =  ($studentMarkDetail->firstValuationMark + $studentMarkDetail->currentMark)/2;
                                    $studentMarks = [];
                                    $studentMarks[0] = $studentMarkDetail->firstValuationMark;
                                    $studentMarks[1] = $studentMarkDetail->currentMark;
                                    if(empty($studentMarkDetail->secondValuationRule) || empty($studentMarkDetail->secondValuationRule->code)){
                                        $errorMsg = "Second valuation mark rule not defined, please contact exam administrator.";
                                        throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMsg);
                                    }
                                    $studentMark = $this->getFinalizedMarkFromValuationRule($studentMarks, $studentMarkDetail->secondValuationRule->code,$examValuationProcedureRule->isExcatFinalizeMark);
                                    if($examValuationProcedureRule->roundOffDigits){
                                        $studentMark = round($studentMark,$examValuationProcedureRule->roundOffDigits);
                                    }
                                        $markEntryObj = new \stdClass();
                                        $markEntryObj->studentId = $studentMarkDetail->studentId;
                                        $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                        $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                        $markEntryObj->markObtained = $studentMark;
                                        $markEntryObj->attendanceStatus = "PRESENT";
                                        $markEntryObj->valuationCount = 'FINALIZED';
                                        $markproperties = "";
                                        if($studentMarkDetail->secondValuationMarkProperties){
                                            $markproperties = (object)$studentMarkDetail->secondValuationMarkProperties;
                                        } 
                                        $markEntryObj->properties  = $markproperties;
                                        $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
                                    $delete_third_val_students[] = "( am_assessment_id = '$studentMarkDetail->assessmentId' AND studentID = '$studentMarkDetail->studentId' )" ;
                                }
                            }
                            else{
                                if( $examValuation->falseNoOrRegNoStatus == "rollNumber" ){
                                    $firstValuationNotCompletedStudents[] = $studentDetail->rollNumber;
                                }
                                else{
                                    $firstValuationNotCompletedStudents[] = $studentDetail->registerNumber;
                                }
                                $error = 1;
                            }
                        }
                    }
                    if($currentValuationCount == 3){
                        if($studentMarkDetail->thirdValReq == 1){
                            if($studentMarkDetail->firstValuationMark != null || $studentMarkDetail->secondValuationMark != null) {
                                    $markEntryObj = new \stdClass();
                                    $markEntryObj->studentId = $studentMarkDetail->studentId;
                                    $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                    $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                    $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                                    $markEntryObj->attendanceStatus = "PRESENT";
                                    $markEntryObj->valuationCount = 3;
                                    $markproperties = "";
                                    if($studentMarkDetail->thirdValuationMarkProperties){
                                        $markproperties = (object)$studentMarkDetail->thirdValuationMarkProperties;
                                    } 
                                    $markEntryObj->properties  = $markproperties;
                                    $markEntryObj->valuationType = null;
                                $insertionMarkTableArray[] = $markEntryObj;
                                $updatedStudentCount ++;
                                $updateMarkValuatedStaff->assessmentId = $studentMarkDetail->assessmentId;
                                $updateMarkValuatedStaff->studentId = $studentMarkDetail->studentId;
                                $updateMarkValuatedStaff->valuationProperties = $studentMarkDetail->valuationDetails;
                                $updateMarkValuatedStaff->updatedBy = $currentStaffId ;
                                $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                                $studentMark = array($studentMarkDetail->firstValuationMark,$studentMarkDetail->secondValuationMark,$studentMarkDetail->currentMark);
                                // sort($studentMark);
                                // $diff_01 = abs ( $studentMark[0] - $studentMark[1] );
                                // $diff_12 = abs ( $studentMark[1] - $studentMark[2] );
                                // if ( $diff_01 < $diff_12 ) {
                                //     $nearestTwo = array_slice($studentMark, 0, 2);
                                // } else {
                                //     $nearestTwo = array_slice($studentMark, 1, 2);
                                // }
                                // $avgMark = array_sum($nearestTwo) / 2;
                                if(empty($studentMarkDetail->thirdValuationRule) || empty($studentMarkDetail->thirdValuationRule->code)){
                                    $errorMsg = "Third valuation mark rule defined, please contact exam administrator.";
                                    throw new ExamControllerException(ExamControllerException::CUSTOM_ERROR_MESSAGE_FOR_EXTERNAL_MARK_ENTRY,$errorMsg);
                                }
                                $avgMark = $this->getFinalizedMarkFromValuationRule($studentMark, $studentMarkDetail->thirdValuationRule->code,$examValuationProcedureRule->isExcatFinalizeMark);
                                if($examValuationProcedureRule->roundOffDigits){
                                    $avgMark = round($avgMark,$examValuationProcedureRule->roundOffDigits);
                                }
                                    $markEntryObj = new \stdClass();
                                    $markEntryObj->studentId = $studentMarkDetail->studentId;
                                    $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                    $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                    $markEntryObj->markObtained = $avgMark;
                                    $markEntryObj->attendanceStatus = "PRESENT";
                                    $markEntryObj->valuationCount = 'FINALIZED';
                                    $markproperties = "";
                                    if($studentMarkDetail->secondValuationMarkProperties){
                                        $markproperties = (object)$studentMarkDetail->secondValuationMarkProperties;
                                    } 
                                    $markEntryObj->properties  = $markproperties;
                                    $markEntryObj->valuationType = null;
                                $insertionMarkTableArray[] = $markEntryObj;
                            }
                            elseif($studentMarkDetail->firsrValuationMark == null){
                                if( $examValuation->falseNoOrRegNoStatus == "rollNumber" ){
                                    $firstValuationNotCompletedStudents[] = $studentDetail->rollNumber;
                                }
                                else{
                                    $firstValuationNotCompletedStudents[] = $studentDetail->registerNumber;
                                }
                                $error = 1;
                            }
                            elseif($studentMarkDetail->secondValuationMark == null) {
                                if( $examValuation->falseNoOrRegNoStatus == "rollNumber" ){
                                    $secondValuationNotCompletedStudents[] = $studentDetail->rollNumber;
                                }
                                else{
                                    $secondValuationNotCompletedStudents[] = $studentDetail->registerNumber;
                                }
                                $error = 1;
                            }
                        }
                        else{
                            if( $examValuation->falseNoOrRegNoStatus == "rollNumber" ){
                                $notEligibleThirdValuation[] = $studentDetail->rollNumber;
                            }
                            else{
                                $notEligibleThirdValuation[] = $studentDetail->registerNumber;
                            }
                            $error = 1;
                        }
                    }
                }
            }
            if(! empty($deleteMarkTableArray)){
                foreach($deleteMarkTableArray as $deleteObj){
                    ExamUserMarkService::getInstance()->deleteExamUserTotalMark($deleteObj);
                }
            }
            if(! empty($insertionMarkTableArray)){
                array_walk($insertionMarkTableArray,function($studentTotalMark,$key) use($savingType,$currentStaffId){
                    $studentTotalMark->createdBy = $currentStaffId;
                    if($savingType == 'SAVE_MARK' || $savingType == 'ADD_MARK'){
                        $studentTotalMark->properties->isNotConfirm = true;
                    }
                    else{
                        unset($studentTotalMark->properties->isNotConfirm);
                    }
                });
                ExamUserMarkService::getInstance()->saveExamUserTotalMark($insertionMarkTableArray);
            }
            if(! empty($updateValuatedStaffValues)){
                $this->updateValuatedStaffToStudentRegistration($updateValuatedStaffValues);
            }
            if( !empty ( $deleteExempted ) ){
                $this->deleteExemptedStudents($deleteExempted);
            }
            if( !empty ( $insertExempted ) ){
                $this->insertExemptedStudents($insertExempted);
            }
            if(! empty($insert_third_val_students)){
                $this->insertThirdValStudentRegistration($insert_third_val_students);
            }
            if(! empty($delete_third_val_students)){
                $this->deleteThirdValStudentRegistration($delete_third_val_students);
            }
            if(! empty($updateIsRevaluedStatus)){
                $this->updateisRevaluedFlagStatus($updateIsRevaluedStatus);
            }
            $response->error = $error;
            $response->firstValuationNotCompletedStudents = $firstValuationNotCompletedStudents;
            $response->secondValuationNotCompletedStudents = $secondValuationNotCompletedStudents;
            $response->notEligibleThirdValuation = $notEligibleThirdValuation;
            $response->updatedStudentCount = $updatedStudentCount;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
      /**
     * get Student Mark Entry Status Details For Staff Side 
     * @param  $request
     * @return $response
     */
    public function deleteExtrenalMarkByStaffSide($request) {
        $request = $this->realEscapeObject($request);
        try {
            $conditions = [] ;
            $response = new \stdClass;
            $errorMessage = "";
            $examRegistrationId = $request->examRegistrationId;
            $academicPaperSubjectId = $request->academicPaperSubjectId;
            $courseTypeId = $this->getCourseTypeIdByExamRegistrationIdAndPaperSubjectId($examRegistrationId,$academicPaperSubjectId);
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ($courseTypeId);
            $currentValuationCount = 1;
            $examRegistrationBatchId =  $request->examRegistrationBatchId;
            $registerNumber=$request->registerNumber;
            $falseNumber=$request->falseNumber;
            if(($courseType->courseTypeMethod != "PG")){
                $currentValuationCount = 1;
            }
            else if($courseType->courseTypeMethod == "PG"){
                $currentValuationCount =  $request->currentValuationCount;
            }
            if($registerNumber){
                if($examRegistrationBatchId){
                    $conditions[] = " (sa.regNo = '".$registerNumber."' AND  eerb.ec_exam_registration_id = '".$examRegistrationId."' AND  eers.cm_academic_paper_subjects_id = '".$academicPaperSubjectId."' AND eerb.id = '".$examRegistrationBatchId."') ";
                }
                else{
                    $conditions[] = " (sa.regNo = '".$registerNumber."' AND  eerb.ec_exam_registration_id = '".$examRegistrationId."' AND  eers.cm_academic_paper_subjects_id = '".$academicPaperSubjectId."') ";
                }
            }
            if($falseNumber){
                if($examRegistrationBatchId){
                    $conditions[] = " (esar.properties ->> '$.falseNo' = '".$falseNumber."' AND  eerb.ec_exam_registration_id = '".$examRegistrationId."' AND  eers.cm_academic_paper_subjects_id = '".$academicPaperSubjectId."' AND eerb.id = '".$examRegistrationBatchId."') ";
                }
                else{
                    $conditions[] = " (esar.properties ->> '$.falseNo' = '".$falseNumber."' AND  eerb.ec_exam_registration_id = '".$examRegistrationId."' AND  eers.cm_academic_paper_subjects_id = '".$academicPaperSubjectId."') ";
                }
            }
            $singleStudentDetail = $this->getStudentsExternalMarksByStudentExamDetailForExamRegistration($conditions);
            if($singleStudentDetail){
                $updateMarkValuatedStaff = new \Stdclass();
                $valuationProperties = new \Stdclass();
                $valuatedStaffObject = new \Stdclass();
                $valuatedStaffObject->staffIds = "";
                $valuatedStaffObject->valuationCount = $currentValuationCount;
                $valuationProperties->valuatedStaffs[]=$valuatedStaffObject;
                if(is_null($singleStudentDetail->valuatedStaffs))
                {
                    $singleStudentDetail->valuationDetails = $valuationProperties;
                }
                else if($singleStudentDetail->valuatedStaffs){
                    $valuatedStaffs = json_decode($singleStudentDetail->valuatedStaffs);
                    foreach($valuatedStaffs as $valuatedStaff){
                        if($valuatedStaff->valuationCount == $currentValuationCount){
                            $valuatedStaff->staffIds = "";
                            $facultyUpdated = true;
                        }
                    }
                    if(!$facultyUpdated){
                        $valuatedStaffs[] = $valuatedStaffObject;
                    }
                    $singleStudentDetail->valuationDetails->valuatedStaffs = $valuatedStaffs;
                }
                $updateMarkValuatedStaff->assessmentId = $singleStudentDetail->assessmentId;
                $updateMarkValuatedStaff->studentId = $singleStudentDetail->studentId;
                $updateMarkValuatedStaff->valuationProperties = $singleStudentDetail->valuationDetails;
                $updateMarkValuatedStaff->updatedBy = $GLOBALS['userId'];
                $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                $thirdValuationString = '"THIRD_VALUATION"';
                $secondValuationString = '"SECOND_VALUATION"';
                $firstValuationString = '"FIRST_VALUATION"';
                $finalizedString = '"FINALIZED"';
                if($currentValuationCount == 1)
                {
                    if(($courseType->courseTypeMethod != "PG")){
                            $deleteMarkEntryObj = new ExamUserMarkRequest;
                            $deleteMarkEntryObj->assessmentId = $singleStudentDetail->assessmentId;
                            $deleteMarkEntryObj->studentId = $singleStudentDetail->studentId;
                            $deleteMarkEntryObj->valuationCount = 'FINALIZED';
                        $deleteMarkTableArray[] = $deleteMarkEntryObj;
                    }
                    else{
                            $deleteMarkEntryObj = new ExamUserMarkRequest;
                            $deleteMarkEntryObj->assessmentId = $singleStudentDetail->assessmentId;
                            $deleteMarkEntryObj->studentId = $singleStudentDetail->studentId;
                            $deleteMarkEntryObj->valuationCount = 1;
                        $deleteMarkTableArray[] = $deleteMarkEntryObj;
                    }
                }
                elseif($currentValuationCount == 2){
                    $deleteMarkEntryObj = new ExamUserMarkRequest;
                        $deleteMarkEntryObj->assessmentId = $singleStudentDetail->assessmentId;
                        $deleteMarkEntryObj->studentId = $singleStudentDetail->studentId;
                        $deleteMarkEntryObj->valuationCount = 2;
                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                    $deleteExempted[] = " ( am_assessment_id = '".$singleStudentDetail->assessmentId."' AND studentaccount_id =  '".$singleStudentDetail->studentId."' ) ";
                }
                elseif($currentValuationCount == 3){
                    $deleteMarkEntryObj = new ExamUserMarkRequest;
                        $deleteMarkEntryObj->assessmentId = $singleStudentDetail->assessmentId;
                        $deleteMarkEntryObj->studentId = $singleStudentDetail->studentId;
                        $deleteMarkEntryObj->valuationCount = 3;
                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                }
            }
            if( !empty ( $deleteExempted ) ){
                $this->deleteExemptedStudents($deleteExempted);
            }
            // if(! empty($deleteMarkTableArray)){
            //     foreach($deleteMarkTableArray as $deleteObj){
            //         ExamUserMarkService::getInstance()->deleteExamUserTotalMark($deleteObj);
            //     }
            // }
            if(! empty($updateValuatedStaffValues)){
                $this->updateValuatedStaffToStudentRegistration($updateValuatedStaffValues);
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
     /**
     * submit Extrenal Mark Status By StaffSide
     * @param  $request
     * @return $response
     */
    public function submitExtrenalMarkStatusByStaffSide($request)
    {
        $searchRequest = $this->realEscapeObject($request);
        try 
        {
            $enableValuatedCountCheck = NULL;
            $enableValuatedCountCheck = (int) CommonService::getInstance()->getSettings(SettingsConstents::EXAM_CONTROLLER, SettingsConstents::ENABLE_VALUATED_ANSWER_SHEET_COUNT_CHECK);
            $updateValuatedStaffValues = [];
            $request = new \stdClass;
            $request->paperSubjectId = $searchRequest->academicPaperSubjectId;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->examRegistrationBatchId = $searchRequest->examRegistrationBatchId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $valuatedStaffs =  new \stdClass;
            $valuationProperties =  new \stdClass;
            $valuatedStaffs->staffId = $GLOBALS['userId'];
            $valuatedStaffs->markEntryStatus = "CONFIRMED";
            $valuatedStaffs->count = $request->currentValuationCount;
            if($enableValuatedCountCheck)
            {
                $valuatedStaffs->valuatedAnsweSheetCount = (int)$searchRequest->answerSheetGroupCount;
            }
            else
            {
                $valuatedStaffs->valuatedAnsweSheetCount = 0;
            }
            $valuationProperties->valuatedStaffs = $valuatedStaffs;
            $subjects = ExamRegistrationSubjectService::getInstance()->getAllSubjectForCurrentStaff($request);
            foreach($subjects as $subject){
                $updateSubjectValuationDetals = new \stdClass;
                $facultyUpdated = false;
                if(is_null($subject->valuationDetails)){
                    $subject->valuationDetails = $valuationProperties;
                }
                else{
                    $subject->valuationDetails = json_decode($subject->valuationDetails);
                    if(is_null($subject->valuationDetails->valuatedStaffs)){
                        $subject->valuationDetails->valuatedStaffs[] = $valuatedStaffs;
                    }
                    else{
                        foreach($subject->valuationDetails->valuatedStaffs as $valuatedStaff){
                            if($valuatedStaff->count == $request->currentValuationCount){
                                if ( $searchRequest->considerMultipleStaffValuated ){
                                    if( $valuatedStaff->staffId != $GLOBALS['userId'] ){
                                        continue;
                                    }
                                }
                                $valuatedStaff->staffId = $GLOBALS['userId'];
                                $valuatedStaff->markEntryStatus = "CONFIRMED";
                                if($enableValuatedCountCheck){
                                    $valuatedStaff->valuatedAnsweSheetCount = (int)$searchRequest->answerSheetGroupCount;
                                }
                                else{
                                    $valuatedStaff->valuatedAnsweSheetCount = 0;
                                }
                                $facultyUpdated = true;
                            }
                        }
                        if(!$facultyUpdated)
                        {
                            $subject->valuationDetails->valuatedStaffs[] = $valuatedStaffs;
                        }
                    }
                }
                $updateSubjectValuationDetals->assessmentId = $subject->assessmentId;
                $updateSubjectValuationDetals->valuationDetails = $subject->valuationDetails;
                $updateSubjectValuationDetals->examRegSubjectId = $subject->ec_exam_registration_subject_id;
                $updateValuatedStaffValues[]=$updateSubjectValuationDetals;
            }
            if(!empty($updateValuatedStaffValues))
            {
                $this->updateValuatedStaffToExamRegistraionSubject($updateValuatedStaffValues);
                AMSLogger::log_info($this->logger,Events::EC_CONFIRM_STAFF_SIDE_MARK_ENTRY, [
                    "staff" => new Staff(["id" => $valuatedStaffs->staffId]),
                    "request" => $updateValuatedStaffValues,
                    "status" => StatusConstants::SUCCESS
                ]);
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
            AMSLogger::log_error($this->logger,Events::EC_CONFIRM_STAFF_SIDE_MARK_ENTRY, [
                "staff" => new Staff(["id" => $valuatedStaffs->staffId]),
                "request" => $updateValuatedStaffValues,
                "errorCode" => $e->getCode(),
                "errorMessage" => $e->getMessage(),
                "status" => StatusConstants::FAILED
            ]);
        }
    }
     /**
     * update Valuated Staff To Student Registration
     * @param  $updateValuatedStaffValues
     */
    public function updateValuatedStaffToExamRegistraionSubject($updateValuatedStaffValues){
        $updateValuatedStaffValues = $this->realEscapeArray($updateValuatedStaffValues);
        try {
            foreach($updateValuatedStaffValues as $updatedValue){
                if(!empty($updatedValue->valuationDetails)){
                    $updatedValue->valuationDetails->listStaffs = [];
                }
                $valuationDetails = !empty($updatedValue->valuationDetails) ? "'" . json_encode($updatedValue->valuationDetails) . "'" : "NULL";
                $condition = "";
                if( !empty($updatedValue->examRegSubjectId) ){
                    $condition = " AND id = '$updatedValue->examRegSubjectId'";
                }
                $update_query = "UPDATE
                            ec_exam_registration_subject
                        SET
                            valuation_details = $valuationDetails,
                            updated_by = '$updatedValue->updatedBy',                               
                            updated_date = 'utc_timestamp()'
                        WHERE
                            am_assessment_id = '$updatedValue->assessmentId$condition";
                $this->executeQuery($update_query);
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
     /**
     * Save Extrenal Mark Status By StaffSide
     * @param  $request
     * @return $response
     */
    public function saveExtrenalMarkStatusByStaffSide($request)
    {
        $searchRequest = $this->realEscapeObject($request);
        try 
        {
            $enableValuatedCountCheck = NULL;
            $enableValuatedCountCheck = (int) CommonService::getInstance()->getSettings(SettingsConstents::EXAM_CONTROLLER, SettingsConstents::ENABLE_VALUATED_ANSWER_SHEET_COUNT_CHECK);
            $updateValuatedStaffValues = [];
            $request = new \stdClass;
            $request->paperSubjectId = $searchRequest->academicPaperSubjectId;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->examRegistrationBatchId = $searchRequest->examRegistrationBatchId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $valuatedStaffs =  new \stdClass;
            $valuationProperties =  new \stdClass;
            $valuatedStaffs->staffId = $GLOBALS['userId'];
            $valuatedStaffs->markEntryStatus = "SAVED";
            $valuatedStaffs->count = $request->currentValuationCount;
            if($enableValuatedCountCheck)
            {
                $valuatedStaffs->valuatedAnsweSheetCount = (int)$searchRequest->answerSheetGroupCount;
            }
            else
            {
                $valuatedStaffs->valuatedAnsweSheetCount = 0;
            }
            $valuationProperties->valuatedStaffs = $valuatedStaffs;
            $subjects = ExamRegistrationSubjectService::getInstance()->getAllSubjectForCurrentStaff($request);
            foreach($subjects as $subject)
            {
                $facultyUpdated = false;
                if(is_null($subject->valuationDetails))
                {
                    $subject->valuationDetails = $valuationProperties;
                }
                else
                {
                    $subject->valuationDetails = json_decode($subject->valuationDetails);
                    if(is_null($subject->valuationDetails->valuatedStaffs))
                    {
                        $subject->valuationDetails->valuatedStaffs[] = $valuatedStaffs;
                    }
                    else
                    {
                        foreach($subject->valuationDetails->valuatedStaffs as $valuatedStaff)
                        {
                            if($valuatedStaff->count == $request->currentValuationCount)
                            {
                                if ( $searchRequest->considerMultipleStaffValuated ){
                                    if( $valuatedStaff->staffId != $GLOBALS['userId'] ){
                                        continue;
                                    }
                                }
                                $valuatedStaff->staffId = $GLOBALS['userId'];
                                $valuatedStaff->markEntryStatus = "SAVED";
                                if($enableValuatedCountCheck)
                                {
                                    $valuatedStaff->valuatedAnsweSheetCount = (int)$searchRequest->answerSheetGroupCount;
                                }
                                else
                                {
                                    $valuatedStaff->valuatedAnsweSheetCount = 0;
                                }
                                $facultyUpdated = true;
                            }
                        }
                        if(!$facultyUpdated)
                        {
                            $subject->valuationDetails->valuatedStaffs[] = $valuatedStaffs;
                        }
                    }
                }
                $updateSubjectValuationDetals = new \stdClass;
                $updateSubjectValuationDetals->assessmentId = $subject->assessmentId;
                $updateSubjectValuationDetals->examRegSubjectId = $subject->ec_exam_registration_subject_id;
                $updateSubjectValuationDetals->valuationDetails = $subject->valuationDetails;
                $updateValuatedStaffValues[]=$updateSubjectValuationDetals;
            }
            if(!empty($updateValuatedStaffValues))
            {
                $this->updateValuatedStaffToExamRegistraionSubject($updateValuatedStaffValues);
                AMSLogger::log_info($this->logger,Events::EC_SAVE_STAFF_SIDE_MARK_ENTRY, [
                    "staff" => new Staff(["id" => $valuatedStaffs->staffId]),
                    "request" => $updateValuatedStaffValues,
                    "status" => StatusConstants::SUCCESS
                ]);
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
            AMSLogger::log_error($this->logger,Events::EC_SAVE_STAFF_SIDE_MARK_ENTRY, [
                "staff" => new Staff(["id" => $valuatedStaffs->staffId]),
                "request" => $updateValuatedStaffValues,
                "errorCode" => $e->getCode(),
                "errorMessage" => $e->getMessage(),
                "status" => StatusConstants::FAILED
            ]);
        }
    }
      /**
     * print External Mark Entry report For Staff Side
     * @param  $markEntryRequest
     */
    public function printExtrenalMarkReportByStaffSide($request)
    {
        $searchRequest = $this->realEscapeObject($request);
        try
        {
            $enableValuatedCountCheck = NULL;
            $enableValuatedCountCheck = (int) CommonService::getInstance()->getSettings(SettingsConstents::EXAM_CONTROLLER, SettingsConstents::ENABLE_VALUATED_ANSWER_SHEET_COUNT_CHECK);
            $request = new \stdClass;
            $request->academicPaperSubjectId = $searchRequest->academicPaperSubjectId;
            $request->paperSubjectId = $searchRequest->paperSubjectId;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->examRegistrationBatchId = $searchRequest->examRegistrationBatchId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $courseTypeId = $this->getCourseTypeIdByExamRegistrationIdAndPaperSubjectId($searchRequest->examRegistrationId,$searchRequest->academicPaperSubjectId);
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ($courseTypeId);
            $today = date("Y-m-d H:i");
            $subject = ExamRegistrationSubjectService::getInstance()->getcurrentExamSubjectForCurrentStaff($request);
            if($subject)
            {
                $subject->assessmentProperties = json_decode($subject->assessmentProperties);
                $subject->valuationDetails = json_decode($subject->valuationDetails);
                $subject->examDate = $subject->assessmentProperties->assessmentDate;
                $subject->errorMessage = null;
                $subject->isConfiremed = "SUBMITED";
                $subject->externalMaxMark = (int)$subject->externalMaxMark;
                $subject->valuationCount = $searchRequest->currentValuationCount;
                $subject->studentMarkDetails = [];
                foreach($subject->valuationDetails->valuationDates as $valuationDate)
                {
                    if($valuationDate->count == $searchRequest->currentValuationCount)
                    {
                        $subject->valuationStartDate = $valuationDate->startDate;
                        $subject->valuationEndDate = $valuationDate->endDate;
                        if(strtotime($today) < strtotime($subject->valuationStartDate))
                        {
                            $subject->errorMessage = "Valuation Not Started";
                        }
                        else if(strtotime($today) > strtotime($subject->valuationEndDate))
                        {
                            $subject->errorMessage = "Valuation Date Expired";
                        }
                        else
                        {
                            foreach($subject->valuationDetails->valuatedStaffs as $valuatedStaff)
                            {
                                if($valuatedStaff->count == $request->currentValuationCount  && $valuatedStaff->staffId == $GLOBALS['userId'])
                                {
                                    if($valuatedStaff->markEntryStatus)
                                    {
                                        $subject->isConfiremed = $valuatedStaff->markEntryStatus;
                                        $subject->valuatedCount = $valuatedStaff->valuatedAnsweSheetCount;
                                    }
                                }
                            }
                            $subject->enableValuatedCountCheck =  $enableValuatedCountCheck;
                            $subject->falseNoRegNoStatus = $this->getStatusForRegisterNumberOrFalaseNumber($request);
                            $subject->studentMarkDetails = $this->getCurrentStaffValuatedStudentDetails($request);
                            foreach($subject->studentMarkDetails as $student)
                            {
                                if ( $student->isExempted == 1 ) {
                                    $student->mark = "EX";
                                }
                                else if ( $student->isAbsent == "ABSENT" ) {
                                    $student->mark  = "AB";
                                } 
                                else if ( $student->isAbsent == "MALPRACTICE" ) {
                                    $student->mark  = "MAL";
                                } 
                                else if ($student->isAbsent == "WITHHELD") {
                                    $student->mark  = $student->firstValuationMark;
                                    $student->isWithHeld  = true;
                                }
                                else
                                {
                                    if($subject->valuationCount == "1")
                                    {
                                        if(($courseType->courseTypeMethod != "PG"))
                                        {
                                            $student->mark  = $student->finalizedMark;
                                        }
                                        else
                                        {
                                            $student->mark  = $student->firstValuationMark;
                                        }
                                        
                                    }
                                    else if($subject->valuationCount == "2")
                                    {
                                        $student->mark  = $student->secondValuationMark;
                                    }
                                    else if($subject->valuationCount == "3")
                                    {
                                        $student->mark  = $student->thirdValuationMark;
                                    }
                                    
                                }
                                $student->errorMessage  = "";
                            }
                        }
                    }
                }
            }
            $currentUserId = $GLOBALS['userId'];
            $facultyNames = [];
            $facultyIdArray[$currentUserId]= $currentUserId;
            $facultyIds = "sa.staffID = " .implode(" OR sa.staffID = ",$facultyIdArray);
            $faculties =  $this->getFacultiesByFacultyIds($facultyIds);
            foreach($faculties as $faculty)
            {
                $facultyNames[] =  $faculty->staffName;
            }
            $facultyName = implode(" , ",$facultyNames);
            if(empty($subject->studentMarkDetails))
            {
                throw new ExamControllerException(ExamControllerException::NO_STUDENT_MARK_ENTERED_IN_THIS_EXAM,"No Students Mark Entered In this Exam");
            }
            else
            {
                $templateName = "printExternalMarkEntryByStaffSide";
                $responseHtml = TwigRenderer::renderTemplateFileToHtml(realpath(DOCUMENT_ROOT."../examcontroller-api/src/com/linways/web/templates/printTwigs/$templateName.twig"), [ 'subject'=>$subject ,'faculties'=>$facultyName]);
                $prtContent = NULL;
                    $prtContent .= '<html><head>';
                    $prtContent .= "<style>
                        
                        </style>";
                    $prtContent .= '</head><title>Mark Entry Report</title><body>';
                    $prtContent .= $responseHtml;
                    $prtContent .= '</body></html>';
                    $totalWidth = 210;
                    $totalHeight = 297;
                    $options = array(
                        'page-width'     => $totalWidth."mm",
                        'page-height'    => $totalHeight."mm",
                        'dpi'            => 96,
                        'margin-top' => "9mm",
                        'margin-left' => "1mm",
                        'margin-right' => "1mm",
                        'margin-bottom' => "9mm",
                        // 'binary' => "/usr/local/bin/wkhtmltopdf", // For Mac
                        'user-style-sheet' => realpath(DOCUMENT_ROOT . "/libcommon/bootstrap/css/bootstrap.min.css")
                    );
                $programResult = new \stdClass;
                $programResult->displayData = $responseHtml;
                $programResult->pdf = PdfUtil::renderPdf($prtContent, $options);
                return  $programResult;
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
       /**
     * getCourseTypeIdByExamRegistrationIdAndPaperSubjectId
     * @param ExamRegistrationId $examRegistrationId
     * @param SubjectId $academicPaperSbjectId
     * @return $subject->isTheory
     */
    public function getCourseTypeIdByExamRegistrationIdAndPaperSubjectId($examRegistrationId,$academicPaperSbjectId)
    {
        $examRegistrationId = $this->realEscapeString($examRegistrationId);
        if(is_array($academicPaperSbjectId)){
            $academicPaperSbjectId = $this->realEscapeArray($academicPaperSbjectId);
            $academicPaperSbjectId = implode("','",$academicPaperSbjectId);
        }
        else{
            $academicPaperSbjectId = stripslashes($academicPaperSbjectId);
        }
        try
        {
            $query = "SELECT
                        p.course_type_id as courseTypeId
                    FROM
                        ec_exam_registration_subject eers
                    INNER JOIN ec_exam_registration_batch eerb ON
                            eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN  `groups` g ON 
                            g.id = eerb.groups_id
                    INNER JOIN program p ON 
                        p.id = g.properties->>'$.programId'
                    WHERE
                        eerb.ec_exam_registration_id='$examRegistrationId' AND
                        eers.cm_academic_paper_subjects_id IN ('$academicPaperSbjectId')";
            $courseType = $this->executeQueryForObject($query);
            
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $courseType->courseTypeId;
    }
     /**
     * get All Subjects For QP Code By Exam Registration Id
     * @param $examRegistrationId 
     * @param $examRegistrationBatchId
     * @return $subjects 
     */
    public function getAllSubjectsForQPCodeByExamRegistrationId($request)
    {
        $request = $this->realEscapeObject($request);
        
        try
        {
            $whereQuery = null;
            if($request->examRegistrationBatchId)
            {
                $whereQuery = "AND eers.ec_exam_registration_batch_id = '$request->examRegistrationBatchId'";
            }
            $groupBySubjectId = '';
            if($request->groupBySubjectId)
            {
                $groupBySubjectId = " GROUP BY s.id ";
            }
            $query = "SELECT
                        DISTINCT (aps.id) as id,
                        aps.id as academicPaperSubjectId,
                        s.code as code,
                        s.name as name,
                        s.id as subjectId,
                        IF(aps.properties ->> '$.classType' = 'THEORY',1,0) AS isTheory,
                        eqc.qpCode, 
                        eqc.qpCode as oldQpCode
                    FROM
                        ec_exam_registration_subject eers
                    INNER JOIN ec_exam_registration_batch eerb ON
                            eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN  cm_academic_paper_subjects aps ON 
                            eers.cm_academic_paper_subjects_id = aps.id
                    INNER JOIN  v4_ams_subject s ON 
                            aps.ams_subject_id = s.id
                    LEFT JOIN examQpCodes eqc ON
                        eqc.cm_academic_paper_subjects_id = aps.id AND eqc.ec_exam_registration_id = eerb.ec_exam_registration_id
                    WHERE
                        eerb.ec_exam_registration_id='$request->examRegistrationId'" .$whereQuery. $groupBySubjectId. " ORDER BY s.code ASC ";
            $subjects = $this->executeQueryForList($query);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $subjects;
    }
    /**
     * save All Subject qpCodes
     * @param $subjects 
     * @return $subjects 
     */
    public function saveAllSubjectqpCodes($request)
    {
        $request = $this->realEscapeObject($request);
        $examRegistrationId = $request->examRegistrationId;
        $subjects = $request->subjects;
        $staffId = $GLOBALS['userId'];
        $insertionMarkTableArray = [];
        $error = 0;
        try
        {
            foreach($subjects as $subject)
            {
                $subject = (object)$subject;
                if($subject->qpCode != null || $subject->oldQpCode != null)
                {
                    foreach($subject->academicPaperIds as $academicPaperId){
                        $insertionMarkTableArray[] = " ('".$examRegistrationId."', '".$academicPaperId."', '".$subject->qpCode."','".$staffId."' ) ";
                    }
                }
            }
            if(! empty($insertionMarkTableArray))
            {
                $this->insertSubjectQpCode($insertionMarkTableArray);
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $subjects;
       
    }
     /**
     * insert With Held Student Total Mark Details
     * @param  $insertionValues
     */
    public function insertSubjectQpCode($insertSubjectQpCodeTableArray)
    {
        try 
        {
            $insert_query = "INSERT INTO examQpCodes
                                (ec_exam_registration_id,cm_academic_paper_subjects_id,qpCode,created_by)
                                VALUES " . implode ( ",", $insertSubjectQpCodeTableArray ) . "ON DUPLICATE KEY UPDATE qpCode = VALUES(qpCode),updated_by = VALUES(created_by)" ;
            $this->executeQuery($insert_query);
            
            
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    
     /**
     * print Subject QP code
     * @param request $request
     */
    public function printSubjectQpCodeReport($request)
    {
        $request = $this->realEscapeObject($request);
        $examRegistrationId = $request->examRegistrationId;
        try
        {
            $subjects = [];
            $currentExamRegistrationDetails = NULL;
            $requestForSubjects = new \stdClass();
            $requestForSubjects->examRegistrationId = $examRegistrationId;
            $requestForSubjects->groupBySubjectId = 1;
            $subjects = $this->getAllSubjectsForQPCodeByExamRegistrationId($requestForSubjects);
            if(empty($subjects))
            {
                throw new ExamControllerException(ExamControllerException::NO_SUBJECTS,"No Subjects Founds");
            }
            else
            {
                $requestForExamRegistration = new SearchExamRegistrationRequest;
                $requestForExamRegistration->id = $examRegistrationId;
                $examRegistration = ExamRegistrationService::getInstance()->searchExamRegistration($requestForExamRegistration);
                if(!empty($examRegistration))
                {
                    $currentExamRegistrationDetails = $examRegistration[0];
                }
                $templateName = "PrintSubjectQPCodeReport";
                $responseHtml = TwigRenderer::renderTemplateFileToHtml(realpath(DOCUMENT_ROOT."../examcontroller-api/src/com/linways/web/templates/printTwigs/$templateName.twig"), [ 'subjects'=>$subjects ,'examRegistration'=>$currentExamRegistrationDetails]);
                $prtContent = NULL;
                    $prtContent .= '<html><head>';
                    $prtContent .= "<style>
                        
                        </style>";
                    $prtContent .= '</head><title>QP Code Report</title><body>';
                    $prtContent .= $responseHtml;
                    $prtContent .= '</body></html>';
                    $totalWidth = 210;
                    $totalHeight = 297;
                    $options = array(
                        'page-width'     => $totalWidth."mm",
                        'page-height'    => $totalHeight."mm",
                        'dpi'            => 96,
                        'margin-top' => "9mm",
                        'margin-left' => "1mm",
                        'margin-right' => "1mm",
                        'margin-bottom' => "9mm",
                        // 'binary' => "/usr/local/bin/wkhtmltopdf", // For Mac
                        'user-style-sheet' => realpath(DOCUMENT_ROOT . "/libcommon/bootstrap/css/bootstrap.min.css")
                    );
                $programResult = new \stdClass;
                $programResult->displayData = $responseHtml;
                $programResult->pdf = PdfUtil::renderPdf($prtContent, $options);
                return  $programResult;
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        
    }
     /**
     * get Stuent Status For Staff Side Mark Entry
     * @param request $request
     */
    public function getStuentStatusForStaffSideMarkEntry($request)
    {
        $request = $this->realEscapeObject($request);
        $requestForStdentStatus = new \stdClass();
        try {
            $academicPaperSubjectId = $request->paperIdArray ? $request->paperIdArray : $request->academicPaperSubjectId;
            $markEntryBasedOn = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::MARK_ENTRY_BASED_ON);
            $courseTypeId = $this->getCourseTypeIdByExamRegistrationIdAndPaperSubjectId($request->examRegistrationId,$academicPaperSubjectId);
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ($courseTypeId);
            $searchRuleRequest = new SearchRuleRequest;
            $searchRuleRequest->name = "EXAM_VALUATION_PROCEDURE_RULE";
            $examValuationProcedureRule = reset(RuleService::getInstance()->searchRule($searchRuleRequest))->rule;
            $considerAdditionalAndChiefValuationForUg = $examValuationProcedureRule->considerAdditionalAndChiefValuationForUg ? true : false;  
            $isTheory = $this->getIsTheoryOrNotByExamRegistrationIdAndPaperSubjectId( $request->examRegistrationId,$academicPaperSubjectId);
            if( $considerAdditionalAndChiefValuationForUg && !$courseType->extValRequired){
                if ( $request->currentValuationCount == 1 ){
                    if( $isTheory ){
                        //do nothing
                    }
                    else{
                        $markEntryBasedOn = "REGISTER_NUMBER";
                    }
                }
            }
            $requestForStdentStatus->type = $markEntryBasedOn;
            $requestForStdentStatus->examRegistrationId = $request->examRegistrationId;
            $requestForStdentStatus->academicPaperSubjectId = $request->academicPaperSubjectId;
            $requestForStdentStatus->paperIdArray = $request->paperIdArray;
            $studentCount = $this->getStudentCountForExamRegistrationSubject($requestForStdentStatus);
            if($studentCount->countOfStudent == '0'){
                if($markEntryBasedOn == "FALSE_NUMBER"){
                    throw new ExamControllerException(ExamControllerException::FALSE_NUMBER_NOT_GENERATED,"No False Number Generated");
                }
                if($markEntryBasedOn == "REGISTER_NUMBER"){
                    throw new ExamControllerException(ExamControllerException::NO_REGISTERED_STUDENTS_IN_SUBJECTS,"No Student Registred In This Exam");
                }
                 if($markEntryBasedOn == "ROLL_NUMBER"){
                    throw new ExamControllerException(ExamControllerException::NO_REGISTERED_STUDENTS_IN_SUBJECTS,"No Student Registred In This Exam");
                }
                if($markEntryBasedOn == "FALSE_NUMBER/REGISTER_NUMBER"){
                    if($studentCount->countOfStudentByRegNo == '0'){
                        throw new ExamControllerException(ExamControllerException::NO_REGISTERED_STUDENTS_IN_SUBJECTS,"No Student Registred In This Exam");
                    }
                }
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
     /**
     * get Student Count For ExamRegistrationSubject
     * @param request $request
     */
    public function getStudentCountForExamRegistrationSubject($request)
    {
        $request = $this->realEscapeObject($request);
        $markEntryBasedOn = $request->type;
        try 
        {
            $paperId = is_array($request->paperIdArray) ? "'" . implode("','",$request->paperIdArray) . "'" : "'".$request->academicPaperSubjectId."'";
            if($markEntryBasedOn == 'FALSE_NUMBER'){
                $query = "SELECT
                        COUNT(DISTINCT esar.properties ->> '$.falseNo') as countOfStudent
                    FROM
                        ec_student_assessment_registration esar
                    INNER JOIN ec_exam_registration_subject eers ON 
                        eers.am_assessment_id = esar.am_assessment_id
                    INNER JOIN ec_exam_registration_batch eerb ON
                        eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer
                        ON eer.id = eerb.ec_exam_registration_id 
                    WHERE
                        esar.ec_exam_registration_type = eer.type AND
                        CAST(esar.properties ->> '$.registrationStatus' AS CHAR) = 'REGISTERED' AND 
                        CAST(esar.properties ->> '$.feeStatus' AS CHAR) = 'PAID' AND
                        eerb.ec_exam_registration_id='$request->examRegistrationId' AND 
                        eers.cm_academic_paper_subjects_id IN ($paperId)";
                $studentStatus = $this->executeQueryForObject($query);
            }
            elseif($markEntryBasedOn == 'REGISTER_NUMBER'){
                $query = "SELECT
                        COUNT(DISTINCT spa.properties->>'$.registerNumber') as countOfStudent
                    FROM
                        ec_student_assessment_registration esar
                    INNER JOIN studentaccount sa ON 
                        sa.studentID = esar.student_id
                    INNER JOIN ec_exam_registration_subject eers ON 
                        eers.am_assessment_id = esar.am_assessment_id
                    INNER JOIN ec_exam_registration_batch eerb ON
                        eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer
                        ON eer.id = eerb.ec_exam_registration_id 
                    INNER JOIN `groups` g ON
                        g.id = eerb.groups_id
                        AND g.`type` = 'BATCH'
                    INNER JOIN program p ON 
                        p.id = g.properties->>'$.programId'
                    INNER JOIN student_program_account spa ON 
                        spa.current_program_id = p.id AND 
                        spa.student_id = esar.student_id 
                    WHERE
                        esar.ec_exam_registration_type = eer.type AND
                        CAST(esar.properties ->> '$.registrationStatus' AS CHAR) = 'REGISTERED' AND 
                        CAST(esar.properties ->> '$.feeStatus' AS CHAR) = 'PAID' AND
                        eerb.ec_exam_registration_id='$request->examRegistrationId' AND 
                        eers.cm_academic_paper_subjects_id IN ($paperId)";
                $studentStatus = $this->executeQueryForObject($query);
            }
            elseif($markEntryBasedOn == 'ROLL_NUMBER'){
                $query = "SELECT
                        COUNT(DISTINCT spa.properties->>'$.rollNumber') as countOfStudent
                    FROM
                        ec_student_assessment_registration esar
                    INNER JOIN studentaccount sa ON 
                        sa.studentID = esar.student_id
                    INNER JOIN ec_exam_registration_subject eers ON 
                        eers.am_assessment_id = esar.am_assessment_id
                    INNER JOIN ec_exam_registration_batch eerb ON
                        eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer
                        ON eer.id = eerb.ec_exam_registration_id 
                    INNER JOIN `groups` g ON
                        g.id = eerb.groups_id
                        AND g.`type` = 'BATCH'
                    INNER JOIN program p ON 
                        p.id = g.properties->>'$.programId'
                    INNER JOIN student_program_account spa ON 
                        spa.current_program_id = p.id AND 
                        spa.student_id = esar.student_id 
                    WHERE
                        esar.ec_exam_registration_type = eer.type AND
                        CAST(esar.properties ->> '$.registrationStatus' AS CHAR) = 'REGISTERED' AND 
                        CAST(esar.properties ->> '$.feeStatus' AS CHAR) = 'PAID' AND
                        eerb.ec_exam_registration_id='$request->examRegistrationId' AND 
                        eers.cm_academic_paper_subjects_id IN ($paperId)";
                $studentStatus = $this->executeQueryForObject($query);
            }
            elseif($markEntryBasedOn == 'FALSE_NUMBER/REGISTER_NUMBER'){
                $query = "SELECT
                        COUNT(DISTINCT esar.properties ->> '$.falseNo') as countOfStudent,
                        COUNT(DISTINCT spa.properties->>'$.registerNumber') as countOfStudentByRegNo
                    FROM
                        ec_student_assessment_registration esar
                    INNER JOIN studentaccount sa ON 
                        sa.studentID = esar.student_id
                    INNER JOIN ec_exam_registration_subject eers ON 
                        eers.am_assessment_id = esar.am_assessment_id
                    INNER JOIN ec_exam_registration_batch eerb ON
                        eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer
                        ON eer.id = eerb.ec_exam_registration_id 
                    INNER JOIN `groups` g ON
                        g.id = eerb.groups_id
                        AND g.`type` = 'BATCH'
                    INNER JOIN program p ON 
                        p.id = g.properties->>'$.programId'
                    INNER JOIN student_program_account spa ON 
                        spa.current_program_id = p.id AND 
                        spa.student_id = esar.student_id 
                    WHERE
                        esar.ec_exam_registration_type = eer.type AND
                        CAST(esar.properties ->> '$.registrationStatus' AS CHAR) = 'REGISTERED' AND 
                        CAST(esar.properties ->> '$.feeStatus' AS CHAR) = 'PAID' AND
                        eerb.ec_exam_registration_id='$request->examRegistrationId' AND 
                        eers.cm_academic_paper_subjects_id IN ($paperId)";
                $studentStatus = $this->executeQueryForObject($query);
            }
            
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $studentStatus;
    }
     /**
     * print Student details For Staff Side mark entry
     * @param request $request
     */
    public function printStudentDetailsForStaffSideMarkEntry($searchRequest)
    {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try
        {
            $responseData = $this->getDetailsForPrintStudentDetailsReport($searchRequest);
            $templateName = "PrintStudentMarkReportForTemplate2";
            $responseHtml = TwigRenderer::renderTemplateFileToHtml(realpath(DOCUMENT_ROOT."../examcontroller-api/src/com/linways/web/templates/printTwigs/$templateName.twig"), [ 'responseData'=>$responseData ]);
            $prtContent = NULL;
                $prtContent .= '<html><head>';
                $prtContent .= "<style>
                    
                    </style>";
                $prtContent .= '</head><title>Student Mark Report</title><body>';
                $prtContent .= $responseHtml;
                $prtContent .= '</body></html>';
                $totalWidth = 210;
                $totalHeight = 297;
                $options = array(
                    'page-width'     => $totalWidth."mm",
                    'page-height'    => $totalHeight."mm",
                    'dpi'            => 96,
                    'margin-top' => "9mm",
                    'margin-left' => "1mm",
                    'margin-right' => "1mm",
                    'margin-bottom' => "9mm",
                    // 'binary' => "/usr/local/bin/wkhtmltopdf", // For Mac
                    'user-style-sheet' => realpath(DOCUMENT_ROOT . "/libcommon/bootstrap/css/bootstrap.min.css")
                );
            $programResult = new \stdClass;
            $programResult->displayData = $responseHtml;
            $programResult->pdf = PdfUtil::renderPdf($prtContent, $options);
            return  $programResult;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
     /**
     * Get Student details For Print Mark Report
     * @param request $request
     */
    public function getDetailsForPrintStudentDetailsReport($searchRequest){
        try{
            $registeredStudentMarkDetails = [];
            $markEntryBasedOn = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::MARK_ENTRY_BASED_ON);
            $isQPCodeDisplayInStaffSideMarkEntry = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::IS_DISPALY_QP_CODE_IN_STAFF_SIDE_MARK_ENTRY);
            $isRevaluedStatus = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::IS_RC_STATUS_IN_EXTERNAL_MARK_ENTRY_DIRECT);
            $response = new \stdClass;
            $request = new \stdClass;
            $request->paperSubjectId = $searchRequest->paperSubjectId;
            $request->academicPaperSubjectId = $searchRequest->paperSubjectId;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->examRegistrationBatchId = $searchRequest->examRegistrationBatchId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $request->examRegistrationBatchesArray = $searchRequest->examRegistrationBatchesArray;
            $request->sortBy = $searchRequest->sortBy;
            $courseTypeId = $this->getCourseTypeIdByExamRegistrationIdAndPaperSubjectId($searchRequest->examRegistrationId,$searchRequest->paperSubjectId);
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ($courseTypeId);
            $maxmarkOfSubject = (int)ExamRegistrationSubjectService::getInstance()->getMaxSubjectMarkByAcademicPaperSubjectId($searchRequest->paperSubjectId);
            $markDiff = CommonExamService::getInstance()->getExternalValuationMarkDiff($courseTypeId,$maxmarkOfSubject);
            $isTheory = $this->getIsTheoryOrNotByExamRegistrationIdAndPaperSubjectId( $request->examRegistrationId,$request->paperSubjectId);
            $subject = ExamRegistrationSubjectService::getInstance()->getcurrentExamSubjectForCurrentStaff($request);
            if($subject){
                $subject->assessmentProperties = json_decode($subject->assessmentProperties);
                $subject->valuationDetails = json_decode($subject->valuationDetails);
                $subject->examDate = $subject->assessmentProperties->assessmentDate;
                $subject->errorMessage = null;
                foreach($subject->valuationDetails->valuatedStaffs as $valuatedStaff){
                    if($valuatedStaff->count == $request->currentValuationCount  && $valuatedStaff->staffId == $GLOBALS['userId']){
                        if($valuatedStaff->markEntryStatus){
                            $subject->isConfiremed = $valuatedStaff->markEntryStatus;
                            $subject->valuatedCount = $valuatedStaff->valuatedAnsweSheetCount;
                        }
                    }
                }
                if($markEntryBasedOn == 'FALSE_NUMBER/REGISTER_NUMBER'){
                    $subject->falseNoRegNoStatus = $this->getStatusForRegisterNumberOrFalaseNumber($request);
                    $request->falseNoRegNoStatus = $subject->falseNoRegNoStatus;
                }
                elseif($markEntryBasedOn == 'FALSE_NUMBER'){
                    $subject->falseNoRegNoStatus = "falseNumber";
                    $request->falseNoRegNoStatus = $subject->falseNoRegNoStatus;
                }
                elseif($markEntryBasedOn == 'REGISTER_NUMBER'){
                    $subject->falseNoRegNoStatus = "regNumber";
                    $request->falseNoRegNoStatus = $subject->falseNoRegNoStatus;
                }
                if($searchRequest->currentValuationCount == "3"){
                    $request->isFirstValuatedStudentOnly =  true;
                    $request->isSecondValuatedStudentOnly =  true;
                    $allStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                }
                else{
                    $allStudentMarkDetails = $this->getAllStudentExternalMarksByExamRegistrationSubject($request);
                }
                foreach($allStudentMarkDetails as $student){
                    if($subject->falseNoRegNoStatus == "regNumber"){
                        if($student->regNo != null){
                            $registeredStudentMarkDetails[] =  $student;
                        }
                    }
                    else if($subject->falseNoRegNoStatus == "falseNumber"){
                        if($student->falseNo != null){
                            $registeredStudentMarkDetails[] =  $student;
                        }
                    }
                }
                foreach($registeredStudentMarkDetails as $student){
                    if ( $student->isExempted == 1 ) {
                        $student->mark = "EX";
                        $student->errorMessage  = "";
                    }
                    else if ( $student->isAbsent == "ABSENT" ) {
                        $student->mark  = "AB";
                        $student->errorMessage  = "";
                    } 
                    else if ( $student->isAbsent == "MALPRACTICE" ) {
                        $student->mark  = "MAL";
                        $student->errorMessage  = "";
                    } 
                    else if ($student->isAbsent == "WITHHELD") {
                        $student->mark  = "WH";
                        $student->isWithHeld  = true;
                        $student->errorMessage  = "";
                    }
                    else{
                        if($searchRequest->currentValuationCount == "1"){
                            if(($courseType->courseTypeMethod != "PG") ){
                                $student->mark  = $student->finalizedMark;
                                $student->errorMessage  = "";
                            }
                            elseif(($courseType->courseTypeMethod == "PG") && $isTheory == '0'){
                                $student->mark  = $student->finalizedMark;
                                $student->errorMessage  = "";
                            }
                            else{
                                $student->mark  = $student->firstValuationMark;
                                $student->errorMessage  = "";
                            }
                        }
                        else if($searchRequest->currentValuationCount == "2"){
                            if($student->firstValuationMark == null){
                                $student->errorMessage  = "1st Valuation Pending"; 
                                $student->mark  = null;
                            }
                            else{
                                $studentMarkDiff = abs ($student->firstValuationMark - $student->secondValuationMark);
                                if($studentMarkDiff >= $markDiff){
                                    $student->thirdValRequiredFlag = 1;
                                }
                                else{
                                    $student->thirdValRequiredFlag = 0;
                                }
                                $student->mark  = $student->secondValuationMark;
                                $student->errorMessage  = "";
                            }
                        }
                        else if($searchRequest->currentValuationCount == "3"){
                            if($student->firstValuationMark == null){
                                $student->errorMessage  = "1st Valuation Pending"; 
                                $student->mark  = null;
                            }
                            elseif($student->secondValuationMark == null){
                                $student->errorMessage  = "2nd Valuation Pending"; 
                                $student->mark  = null;
                            }
                            elseif($student->thirdValReq == 0){
                                $student->errorMessage  = "3rd Valuation Not Eligible"; 
                                $student->mark  = null;
                            }
                            else{
                                $student->mark  = $student->thirdValuationMark;
                                $student->errorMessage  = "";
                            }
                        }
                        
                        $subject->students = $registeredStudentMarkDetails;
                    }
                }
            }
            $response->subject = $subject;
            $response->isRevaluedStatus = $isRevaluedStatus;
            $response->courseType = $courseType->courseTypeMethod;
            $response->currentValuationCount = $searchRequest->currentValuationCount;
            $response->currentValuationCount = $searchRequest->currentValuationCount;
            $response->isQPCodeDisplay = $isQPCodeDisplayInStaffSideMarkEntry;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
   
     /**
     * get Subjects For Staff Side Mark Entry Digital Valuation
     * @return staffDetails details
     */
    public function getSubjectDetailsForStaffSideMarkEntryDigitalValuation($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $showStudentsByFalseNumber = (int)CommonService::getInstance()->getSettings(SettingsConstents::EXAM_CONTROLLER, SettingsConstents::SHOW_STUDENTS_FOR_VALUATION_BY_FALSE_NUMBER);
            $searchRuleRequest = new SearchRuleRequest;
            $searchRuleRequest->name = "EXAM_VALUATION_PROCEDURE_RULE";
            $examValuationProcedureRule = reset(RuleService::getInstance()->searchRule($searchRuleRequest))->rule;
            $isChiefValuationEnabled = $examValuationProcedureRule->isChiefValuationEnabled ? 1 : 0;
            $checkPreviousValuationConfirmedStatus = $examValuationProcedureRule->checkPreviousValuationConfirmedStatus ? true : false;
            $registeredStudents = [];
            $response = new \stdClass;
            $request = new \stdClass;
            $searchRequest->paperSubjectId = (array) $searchRequest->paperSubjectIdArr ? $searchRequest->paperSubjectIdArr : $searchRequest->paperSubjectId;
            $request->paperSubjectId = $searchRequest->paperSubjectId;
            $request->academicPaperSubjectId = $searchRequest->paperSubjectId;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $request->valuationCount = $searchRequest->currentValuationCount;
            $isChiefValuationEnabledUrl = ($isChiefValuationEnabled && $request->valuationCount == 2) ? "&ceId=" . $isChiefValuationEnabled :'';
            // $request->assessmentId = $searchRequest->assessmentId;
            $today = date("Y-m-d H:i");
            $currentSubject = ExamRegistrationSubjectService::getInstance()->getcurrentExamSubjectForCurrentStaff($request);
            $subject = ExamRegistrationSubjectService::getInstance()->getAllExamSubjectForCurrentStaffDigitalValuation($request);
            $studentIdentifier = $showStudentsByFalseNumber ? "falseNumber" : "registerNo";
            $studentIdentifierForPath = $showStudentsByFalseNumber ? "flNo" : "rgNo";
            $topMarkStatusPercentage = $examValuationProcedureRule->topMarkStatusPercentageForDigitalValuation ?? 90;
            if($currentSubject){
                //set valuation rule settings
                $currentSubject->isChiefValuationEnabled = $isChiefValuationEnabled;
                $currentSubject->enableAutoRefreshOnTabChange = $examValuationProcedureRule->enableAutoRefreshOnTabChange ? 1 :0;
                $currentSubject->enableFilterByAdditionalValuers = $examValuationProcedureRule->enableFilterByAdditionalValuers ? 1 :0;
                $currentSubject->highlightTopMarkStudentsInDigitalValuation = $examValuationProcedureRule->highlightTopMarkStudentsInDigitalValuation ? 1 :0;
                $currentSubject->topMarkStatusPercentage = $topMarkStatusPercentage;
                
                $currentSubject->assessmentProperties = json_decode($currentSubject->assessmentProperties);
                $currentSubject->valuationDetails = json_decode($currentSubject->valuationDetails);
                $currentSubject->examDate = $currentSubject->assessmentProperties->assessmentDate;
                $currentSubject->errorMessage = null;
                $currentSubject->isConfiremed = "";
                $currentSubject->externalMaxMark = (int)$currentSubject->externalMaxMark;
                $currentSubject->valuationCount = $searchRequest->currentValuationCount;
                $currentValuationDateDetails = reset(array_filter($currentSubject->valuationDetails->valuationDates,function($value)use($searchRequest){
                    return $value->count == $searchRequest->currentValuationCount;
                }));
                if(!empty($currentValuationDateDetails)){
                    $currentSubject->valuationStartDate = $currentValuationDateDetails->startDate;
                    $currentSubject->valuationEndDate = $currentValuationDateDetails->endDate;
                    if(strtotime($today) < strtotime($currentSubject->valuationStartDate)){
                        $currentSubject->errorMessage = "Valuation Not Started";
                    }
                    else if((strtotime($today) > strtotime($currentSubject->valuationEndDate))){
                        $currentSubject->errorMessage = "Valuation Date Expired";
                    }
                }
            }
            if(empty($subject) || $currentSubject->errorMessage != null) {
                $registeredStudents = [];
            }
            else{
                if($showStudentsByFalseNumber){
                    $request->falseNoRegNoStatus = "falseNumber";
                }
                else{
                    $request->falseNoRegNoStatus = "registerNo";
                }
                $studentDetails = StudentExamRegistrationService::getInstance()->getRegisteredStudentsValuationDetails($request);
                foreach($studentDetails as $student){
                    $requestForMarkConfirm = new \stdClass;
                    $requestForMarkConfirm->onlineExamId = $student->onlineExamId;
                    $requestForMarkConfirm->valuationCount = $searchRequest->currentValuationCount;
                    $requestForMarkConfirm->studentId = $student->studentId;
                    $requestForMarkConfirm->staffId = $GLOBALS['userId'];
                    $student->markConfirmObj = $this->checkIfMarkConfirmForDigitalValuation($requestForMarkConfirm);
                    $student->isMarkConfirm = !empty($student->markConfirmObj) ? '1' : '0';
                    if($student->isMarkConfirm != '1'){
                        $requestForPapersEvaluated = new \stdClass;
                        $requestForPapersEvaluated->onlineExamId = $student->onlineExamId;
                        $requestForPapersEvaluated->valuationCount = $searchRequest->currentValuationCount;
                        $requestForPapersEvaluated->studentId = $student->studentId;
                        $requestForPapersEvaluated->staffId = $GLOBALS['userId'];
                        $student->papersEvaluvated = (int)$this->countOfEvaluatedStudentsByOnlineExam($requestForPapersEvaluated);
                        $student->markEntryStarted = $student->papersEvaluvated > 0 ? 1 : 0;
                    }
                    //valuation count 1 mark confirmation is mandatory for valuation 2 mark entry
                    if($checkPreviousValuationConfirmedStatus && $searchRequest->currentValuationCount == 2){
                        $prevMarkConfirmObj = $this->getPreviousMarkEntryConfirmedStatus($student,$searchRequest->currentValuationCount);
                        $student->isPreviousMarkEntryConfirmed = !empty($prevMarkConfirmObj) ? true : false;
                        $student->blockValuation = $student->isPreviousMarkEntryConfirmed ? 0 : 1;
                        $student->blockValuationReason = $this->setBlockValuationMessage($student,$studentIdentifier);
                        $student->mark1Percent = ($prevMarkConfirmObj->markConfirm && $student->externalMaxMark ) ? $prevMarkConfirmObj->mark * 100 / $student->externalMaxMark :0;
                        $student->topMarkStatus = ($student->mark1Percent >= $topMarkStatusPercentage) ? 1 : 0;
                    }
                    $student->filePath = "examId=".$student->assessmentId. "&vlc=". $request->valuationCount."&". $studentIdentifierForPath."=". $student->$studentIdentifier ."".$isChiefValuationEnabledUrl;
                    $student->valuationDetails = empty($student->valuationDetails) ? null : json_decode($student->valuationDetails);
                    if($student->valuationDetails){
                        $currentValuationStaffDetails = reset(array_filter($student->valuationDetails->assignedValuationStaffs,function($value)use($searchRequest){
                            return $value->count == $searchRequest->currentValuationCount;
                        }));
                        if(!empty($currentValuationStaffDetails->addiitonalExamniners)){
                            $additionalExaminerIds[] = ($searchRequest->additionalExaminer || $searchRequest->currentValuationCount == 1) ? []:$this->setAdditionalExaminers($student,$searchRequest);
                            if(in_array($searchRequest->staffId,$currentValuationStaffDetails->addiitonalExamniners)){
                                //if chief examiner choosed a valuer ,filter out that valuer students from the list
                                if($searchRequest->additionalExaminer){
                                    if($this->isStudentAssignedToSlecetedAdditionalValuer($student,$searchRequest)){
                                        //only selectedAdditionalExaminerStudent will be filtererd in
                                        $registeredStudents[] = $student;
                                    }
                                }else{
                                    $registeredStudents[] = $student;
                                }
                            }
                        }
                    }
                }
                $additionalExaminerIds = array_unique(array_merge(...$additionalExaminerIds));
            }
            $response->additionalExaminerNames = empty($additionalExaminerIds) ?  [] : StaffService::getInstance()->getStaffByIds($additionalExaminerIds);
            $response->subject = $currentSubject;
            $response->students = $registeredStudents;
            $response->showStudentsByFalseNumber = $showStudentsByFalseNumber;
            $response->currentValuationCount = $searchRequest->currentValuationCount;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    private function setAdditionalExaminers($student,$searchRequest){
        $additionalExaminerDetails = reset(array_filter($student->valuationDetails->assignedValuationStaffs,function($value)use($searchRequest){
            return $value->count == 1;
        }));
        return $additionalExaminerDetails->addiitonalExamniners;
    }
    private function isStudentAssignedToSlecetedAdditionalValuer($student,$searchRequest){
        $result = false;
        $additionalExaminerDetails = reset(array_filter($student->valuationDetails->assignedValuationStaffs,function($value)use($searchRequest){
            return $value->count == 1;
        }));
        if(!empty($additionalExaminerDetails->addiitonalExamniners)){
            if(in_array($searchRequest->additionalExaminer,$additionalExaminerDetails->addiitonalExamniners)){
                $result = true;
            }
        }
        return $result;
    }
    private function getPreviousMarkEntryConfirmedStatus($student,$valuationCount){
        $previousValuationCount = $valuationCount - 1;
        $isMarkConfirm = false;
        if($previousValuationCount){
            $requestForMarkConfirm = new \stdClass;
            $requestForMarkConfirm->onlineExamId = $student->onlineExamId;
            $requestForMarkConfirm->valuationCount = $previousValuationCount;
            $requestForMarkConfirm->studentId = $student->studentId;
            $markConfirmObj = $this->checkIfMarkConfirmForDigitalValuation($requestForMarkConfirm);
        }
        return $markConfirmObj;
    }
    private function setBlockValuationMessage($student,$studentIdentifier){
        $blockValuationReason = "";
        if(!$student->isPreviousMarkEntryConfirmed){
            $blockValuationReason = "Can't proceed as valuation 1 mark not confirmed for ". $student->$studentIdentifier ."";
        }
        return $blockValuationReason;
    }
    /**
     * get AllStudent By ExamRegistrationSubject For Digital Valuation
     * @param request $request
     * @return $studentsMarkDetails
     */
    public function getAllStudentByExamRegistrationSubjectInDigitalValuationForCurrentStaff($request)
    {
        $request = $this->realEscapeObject($request);
        try 
        {
            $orderBy = null;
            $whereQuery = null;
            if($request->packetNos)
            {
                $request->packetNos = is_array($request->packetNos) ? "'" . implode("','",$request->packetNos) . "'" : '$packetNos';
                $whereQuery .= " AND esar.valuation_details ->> '$.packetNo' IN($request->packetNos)";
            }
            
            $query = "SELECT
                        DISTINCT sa.studentID as id,
                        sa.studentID ,
                        sa.studentName,
                        sa.regNo,
                        esar.am_assessment_id as assessmentId,
                        esar.properties ->> '$.falseNo' as falseNo,
                        e.examID as examId, 
                        oec.is_confirmed as markConfirm
                    FROM
                        ec_student_assessment_registration esar
                    INNER JOIN studentaccount sa ON 
                        sa.studentID = esar.student_id
                    INNER JOIN ec_exam_registration_subject eers ON 
                        eers.am_assessment_id = esar.am_assessment_id
                    INNER JOIN ec_exam_registration_batch eerb ON
                        eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer
                        ON eer.id = eerb.ec_exam_registration_id 
                    INNER JOIN exam e ON
                        e.am_assessment_id = esar.am_assessment_id
                    LEFT JOIN oe_exams oe ON 
                        JSON_UNQUOTE(JSON_EXTRACT(oe.identifying_context, '$.assessmentId')) = esar.am_assessment_id
                    LEFT JOIN oe_exam_marks_confirm oec ON
                        oec.oe_exams_id = oe.id AND 
                        oec.valuation_count = '$request->currentValuationCount'  AND 
                        oec.oe_users_id = sa.studentID
                        AND oec.is_confirmed = '1'
                    WHERE
                        esar.ec_exam_registration_type = eer.type AND
                        eerb.ec_exam_registration_id='$request->examRegistrationId' AND 
                        eers.cm_academic_paper_subjects_id = '$request->paperSubjectId";
            $studentsMarkDetails = $this->executeQueryForList($query.$whereQuery.$orderBy);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $studentsMarkDetails;
    }
    
     /**
     * get Subjects For Staff Side Mark Entry
     * @return staffDetails details
     */
    public function getSubjectsForFinalizeMark($searchRequest)
    {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try
        {
            $showStudentsByFalseNumber = (int)CommonService::getInstance()->getSettings(SettingsConstents::EXAM_CONTROLLER, SettingsConstents::SHOW_STUDENTS_FOR_VALUATION_BY_FALSE_NUMBER);
            $studentIdentifier = $showStudentsByFalseNumber ? "falseNumber" : "registerNo";
            $studentIdentifierForPath = $showStudentsByFalseNumber ? "flNo" : "rgNo";
            $digitalValuationProperties = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_CONTROLLER, SettingsConstents::DIGITAL_VALUATION_PROPERTIES);
            $digitalValuationProperties = $digitalValuationProperties ? json_decode($digitalValuationProperties) : "";
            $registeredStudentMarkDetails = [];
            $thirdValStudentCount = 0;
            $response = new \stdClass;
            $response->templateName = "default-template";
            $response->isHideFinalizeBtn = false;
            $response->isHideRevaluationFinalizeBtn = false;
            $searchRuleRequest = new SearchRuleRequest;
            $searchRuleRequest->name = "EXAM_VALUATION_PROCEDURE_RULE";
            $examValuationProcedureRule = reset(RuleService::getInstance()->searchRule($searchRuleRequest))->rule;
            $templateName = $examValuationProcedureRule->templateName ;
            if($templateName == 'TEMPLATE_WITH_DIGITAL_VALUATION'){
                $response->templateName = "template-without-third-valuation";
            }
            $request = new \stdClass;
            $request->academicPaperSubjectId = $searchRequest->paperSubjectId;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->id = $searchRequest->examRegistrationId;
            $request->falseNoRegNoStatus = $studentIdentifier;
            $examRegistration = reset(ExamRegistrationService::getInstance()->searchExamRegistrationByOtherDetails($request));
            $searchRuleRequest = new SearchRuleRequest;
            $searchRuleRequest->name = "EXAM_VALUATION_PROCEDURE_RULE";
            $examValuationProcedureRule = reset(RuleService::getInstance()->searchRule($searchRuleRequest))->rule;
            if($examRegistration->type == "REVALUATION"){
                $request->academicPaperSubjectId = $searchRequest->paperSubjectId;
                $subject = reset(ExamRegistrationSubjectService::getInstance()->getAllSubjectDetailsByRevaluation($request));
            }
            else{
                $request->academicPaperSubjectId = $searchRequest->paperSubjectId;
                $subject = ExamRegistrationSubjectService::getInstance()->getCurrentSubjectDetailsByExamRegistrationIdAndPaperSubjectId($request);
            }
            if($subject){
                $request->academicPaperSubjectId = $searchRequest->paperSubjectId;
                $subject->errorMessage == null;
                $subject->externalMaxMark = (int)$subject->externalMaxMark;
                $revaluationTypeId = null;
                $request->isValuerReviewerCriteria = ($templateName == 'TEMPLATE_WITH_DIGITAL_VALUATION' && $subject->courseType == 'UG');
                if($examRegistration->type == "REVALUATION"){
                    $registeredStudentMarkDetails = (array) $this->getAllStudentByRevaluationRegistrationSubjectForDigitalValuation($request);
                    $revaluationTypeId = reset(array_filter(array_column( $registeredStudentMarkDetails, "revaluation_id")));
                }
                else{
                    $registeredStudentMarkDetails = $this->getAllStudentByExamRegistrationSubjectForDigitalValuation($request);
                }
                if($templateName == 'TEMPLATE_WITH_DIGITAL_VALUATION'){
                    $studentsByStaffDetails = [];
                    $registeredStudents = [];
                    $absentStudents = [];
                    $s3FileRequest = new \stdClass;
                    $s3FileRequest->folderPath = $GLOBALS['COLLEGE_CODE'] . "/Digital Evaluation" . "/" . $subject->examRegistrationName . "/" . $subject->subjectCode;
                    $s3DocStudentKeyList = ExamValuationRuleService::getInstance()->getS3FileDetails($s3FileRequest);
                    foreach($registeredStudentMarkDetails as $student){
                        $firstValuationStaffId = "";
                        $student->valuationDetails = json_decode($student->valuationDetails);
                        $valuationStaff = reset(array_filter($student->valuationDetails->assignedValuationStaffs ,function($value)use($searchRequest){
                            return $value->count == '1' && !empty($value->addiitonalExamniners);
                        }));
                        $firstValuationStaffId = !empty($valuationStaff->addiitonalExamniners) ? reset($valuationStaff->addiitonalExamniners) : "NOT_ASSIGNED";
                        $studentsByStaffDetails[$firstValuationStaffId]->students[] = $student;
                    }
                    if($examRegistration->type == "REVALUATION"){
                        $registeredStudents = $registeredStudentMarkDetails;
                        $absentStudents = [];
                        $response->isHideRevaluationFinalizeBtn = true;
                    }
                    else{
                        foreach($studentsByStaffDetails as $staffId => $studentMarkDetails){
                            foreach($studentMarkDetails->students as $student){
                                $student->path = $GLOBALS['COLLEGE_CODE'] . "/Digital Evaluation" . "/" . $subject->examRegistrationName . "/" . $subject->subjectCode . "/" . $student->$studentIdentifier . ".PDF";
                                if (in_array($student->path, $s3DocStudentKeyList)) {
                                    if($subject->courseType == 'PG'){
                                        $registeredStudents[] = $student;
                                    }
                                    else{
                                        $registeredStaffStudents[$staffId]->students[] = $student;
                                    }
                                   
                                }
                                else {
                                    $absentStudents[] = $student;
                                }
                            }
                        }
                    }
                    if($examRegistration->type == "REVALUATION"){
                        $studentListSet[0]->students = $registeredStudents;
                        $studentListSet[0]->allowFinalizeSet = '1';
                    }
                    else if($subject->courseType == 'PG'){
                        $studentListSet[0]->students = $registeredStudents;
                        $studentListSet[0]->allowFinalizeSet = '1';
                    }
                    else{
                        $setKey = 0;
                        foreach($registeredStaffStudents as $registeredStaff){
                            $studentListSetArray  = array_chunk($registeredStaff->students, $digitalValuationProperties->noOfValScriptsInset);
                            foreach ($studentListSetArray as $set) {
                                $studentListSet[$setKey]->students = $set;
                                $studentListSet[$setKey]->allowFinalizeSet = 1;
                                $studentListSet[$setKey]->totalStudent = count($set);
                                $studentListSet[$setKey]->mark1ConfirmStudentCount = count(array_filter($set,function($value){
                                    return $value->mark1Confirm == '1';
                                }));
                                $studentListSet[$setKey]->mark2ConfirmStudentCount = count(array_filter($set,function($value){
                                    return $value->mark2Confirm == '1';
                                }));
                                $studentListSet[$setKey]->minVal1Scripts = $studentListSet[$setKey]->totalStudent;
                                $studentListSet[$setKey]->minVal2Scripts = ceil($studentListSet[$setKey]->totalStudent *  (int)$digitalValuationProperties->minValScriptsPercentForReviewer) / 100;
                                if($studentListSet[$setKey]->minVal1Scripts > $studentListSet[$setKey]->mark1ConfirmStudentCount){
                                    $studentListSet[$setKey]->allowFinalizeSet = 0;
                                    $studentListSet[$setKey]->errorMsg1 = "Pending First Valuation";
                                    $response->isHideFinalizeBtn = true;
                                }
                                else if($studentListSet[$setKey]->minVal2Scripts > $studentListSet[$setKey]->mark2ConfirmStudentCount){
                                    $studentListSet[$setKey]->allowFinalizeSet = 0;
                                    $studentListSet[$setKey]->errorMsg2 = "Pending Second Valuation";
                                    $response->isHideFinalizeBtn = true;
                                }
                                $setKey ++;
                            }
                        }
                    }
                    $slNo = 1;
                    foreach($studentListSet as $studentSet){
                       foreach($studentSet->students as $student){
                            $student->slNo = $slNo++;
                        }
                    }
                }
                else{
                    $request->academicPaperSubjectId = $searchRequest->paperSubjectId;
                    $request->examType = $examRegistration->type;
                    $request->revaluationId = $revaluationTypeId;
                    $thirdValStudentCount = $this->getTotalCountOfThirdValuationStudentsForExamRegistrationSubject($request);
                }
            }
            if( $examValuationProcedureRule->allowOnlyIfTwoValuationsCompleted && $examRegistration->type != "REVALUATION"){
                $response->examValuationProcedureRule->allowFinalize = 1;
                $response->examValuationProcedureRule->allowOnlyIfTwoValuationsCompleted = 1;
                foreach($registeredStudentMarkDetails as $student){
                    if($student->attendanceStatus == "PRESENT"){
                        if($student->mark1Confirm == '1' && $student->mark2Confirm == '1'){
                        }
                        else{
                            $response->examValuationProcedureRule->allowFinalize = 0;
                            break;
                        }
                    }
                }
                if($response->examValuationProcedureRule->allowFinalize == 1){
                    $finalizeRequest = new \stdClass;
                    $finalizeRequest->academicPaperSubjectId = $searchRequest->paperSubjectId;
                    $finalizeRequest->examRegistrationId = $searchRequest->examRegistrationId;
                    $finalizeRequest->id = $searchRequest->examRegistrationId;
                    $finalizedDetails = $this->getFinalizedStatusOfStudentMark($finalizeRequest);
                    $response->examValuationProcedureRule->isShowFinalizeAgain = $finalizedDetails ? 1 : 0;
                }
            }
            $response->subject = $subject;
            $response->students = $templateName == 'TEMPLATE_WITH_DIGITAL_VALUATION' ? $studentListSet : $registeredStudentMarkDetails;
            $response->absentStudents = $absentStudents;
            $response->thirdValStudentCount = (int)$thirdValStudentCount;
            $response->examValuationProcedureRule->isChiefValuationEnabled = $examValuationProcedureRule->isChiefValuationEnabled;
            //setting 3 as default number of valuation count(s)
            $response->examValuationProcedureRule->numberOfValuations = $examValuationProcedureRule->numberOfValuations ? $examValuationProcedureRule->numberOfValuations : 3;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    /**
     * get AllStudent By ExamRegistrationSubject For Digital Valuation
     * @param request $request
     * @return $studentsMarkDetails
     */
    private function getAllStudentByExamRegistrationSubjectForDigitalValuation($request)
    {
        $request = $this->realEscapeObject($request);
        $request->academicPaperSubjectId = is_array($request->academicPaperSubjectId) ? "'" . implode("','",$request->academicPaperSubjectId) . "'" : "'".$request->academicPaperSubjectId."'";
        try 
        {
            $whereQuery = null;
            if( $request->falseNoRegNoStatus == "falseNumber") {
                $whereQuery .= " AND esar.falseNo IS NOT NULL ";
                $orderBy = " ORDER BY esar.falseNo ASC";
            }
            else{
                $orderBy = " ORDER BY spa.properties->>'$.registerNumber' ASC ";
            }
            if($request->isValuerReviewerCriteria){
                $joinQuery = " LEFT JOIN oe_exam_marks_confirm oec1 ON oec1.oe_exams_id = oe.id AND oec1.oe_users_id = sa.studentID AND oec1.valuation_count = 1 AND oec1.review_id IS NULL AND (oec1.revaluation_id IS NULL OR oec1.revaluation_id = '') AND oec1.is_confirmed = '1'
                                LEFT JOIN oe_exam_marks_confirm oec2 ON oec2.oe_exams_id = oe.id AND oec2.oe_users_id = sa.studentID AND oec2.valuation_count = 1 AND oec2.review_id IS NOT NULL AND (oec2.revaluation_id IS NULL OR oec2.revaluation_id = '') AND oec2.is_confirmed = '1'";
            }
            else{
                $joinQuery = " LEFT JOIN oe_exam_marks_confirm oec1 ON oec1.oe_exams_id = oe.id AND oec1.oe_users_id = sa.studentID AND oec1.valuation_count = 1 AND (oec1.revaluation_id IS NULL OR oec1.revaluation_id = '') AND oec1.is_confirmed = '1'
                                LEFT JOIN oe_exam_marks_confirm oec2 ON oec2.oe_exams_id = oe.id AND oec2.oe_users_id = sa.studentID AND oec2.valuation_count = 2 AND (oec2.revaluation_id IS NULL OR oec2.revaluation_id = '') AND oec2.is_confirmed = '1'";
            }
            if($request->groupsId){
                $groupsIds = is_array($request->groupsId) ? "'" . implode("','",$request->groupsId) . "'" : "'".$request->groupsId."'";
                $whereQuery .= " AND g.id IN ( $groupsIds )";
            }
            $query = "SELECT
                        DISTINCT sa.studentID as id,
                        sa.studentID as studentId,
                        sa.studentName,
                        spa.properties->>'$.registerNumber' AS regNo,
                        esar.am_assessment_id as assessmentId,
                        esar.properties ->> '$.falseNo' as falseNo,
                        esar.properties ->> '$.falseNo' as falseNumber,
                        esar.valuation_details as valuationDetails,
                        eerb.properties ->> '$.valuationRule' as valuationRule,
                        eer.type as examRegistrationType,
                        oe.id as oeExamId,
                        oec1.is_confirmed as mark1Confirm,
                        oec1.exam_mark as mark1,
                        oec2.is_confirmed as mark2Confirm,
                        oec2.exam_mark as mark2,
                        oec2.valuation_details as valuation2Details,
                        oec3.is_confirmed as mark3Confirm,
                        oec3.exam_mark as mark3,
                        caps.properties ->> '$.externalMaxMark' as externalMaxMark,
                        ostmf.attendance_status as attendanceStatus
                    FROM
                        ec_student_assessment_registration esar
                    INNER JOIN studentaccount sa ON 
                        sa.studentID = esar.student_id
                    INNER JOIN ec_exam_registration_subject eers ON 
                        eers.am_assessment_id = esar.am_assessment_id
                    INNER JOIN ec_exam_registration_batch eerb ON
                        eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer
                        ON eer.id = eerb.ec_exam_registration_id 
                    INNER JOIN cm_academic_paper_subjects caps ON
                        caps.id = eers.cm_academic_paper_subjects_id
                    INNER JOIN `groups` g ON
                        g.id = eerb.groups_id
                        AND g.`type` = 'BATCH'
                    INNER JOIN program p ON 
                        p.id = g.properties->>'$.programId'
                    INNER JOIN student_program_account spa ON 
                        spa.current_program_id = p.id AND 
                        spa.student_id = esar.student_id 
                    INNER JOIN oe_exams oe ON 
                        JSON_UNQUOTE(JSON_EXTRACT(oe.identifying_context, '$.assessmentId')) = esar.am_assessment_id
                    $joinQuery                     
                    LEFT JOIN oe_exam_marks_confirm oec3 ON oec3.oe_exams_id = oe.id AND oec3.oe_users_id = sa.studentID AND oec3.valuation_count = 3 AND (oec3.revaluation_id IS NULL OR oec3.revaluation_id = '') AND oec3.is_confirmed = '1'
                    LEFT JOIN oe_student_total_mark ostmf ON 
                        ostmf.student_id = sa.studentID AND ostmf.am_assessment_id = esar.am_assessment_id AND ostmf.valuation_count = 'FINALIZED' AND (ostmf.valuation_type IS NULL OR ostmf.valuation_type = '')
                    WHERE
                        esar.ec_exam_registration_type = eer.type AND
                        esar.properties ->>'$.feeStatus' = 'PAID' AND 
                        esar.properties ->>'$.registrationStatus' = 'REGISTERED' AND 
                        eerb.ec_exam_registration_id='$request->examRegistrationId' AND 
                        eers.cm_academic_paper_subjects_id IN ( $request->academicPaperSubjectId ) ";
            $studentsMarkDetails = $this->executeQueryForList($query.$whereQuery.$orderBy);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $studentsMarkDetails;
    }
    /**
     * get AllStudent By Revaluation Subject For Digital Valuation
     * @param request $request
     * @return $studentsMarkDetails
     */
    public function getAllStudentByRevaluationRegistrationSubjectForDigitalValuation($searchRequest)
    {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try 
        {
            $orderBy = " ORDER BY s.name ASC , spa.properties->>'$.registerNumber' ASC";
            $whereQuery = "";
            if(!empty($searchRequest->examRegistrationId)) {
                $whereQuery .= " AND eer.id IN ( '$searchRequest->examRegistrationId' )";
            }
            if(!empty($searchRequest->revaluationType)) {
                $whereQuery .= " AND esar.identifying_context->>'$.revaluationType' IN ( '$searchRequest->revaluationType' )";
            }
            if(!empty($searchRequest->studentId)) {
                $whereQuery .= " AND esar.student_id IN ( '$searchRequest->studentId' )";
            }
            if(!empty($searchRequest->assessmentId)) {
                $whereQuery .= " AND esar.am_assessment_id IN ( '$searchRequest->assessmentId' )";
            }
            if(!empty($searchRequest->orderByHighestMark)){
                $orderBy = " ORDER BY ostm.mark_obtained DESC";
            }
            if(!empty($searchRequest->academicPaperSubjectId)) {
                $academicPaperSubjectIdString = is_array($searchRequest->academicPaperSubjectId) ? "'" . implode("','",$searchRequest->academicPaperSubjectId) . "'" : "'".$searchRequest->academicPaperSubjectId."'";
                $whereQuery .= " AND caps.id IN ( $academicPaperSubjectIdString )";
            }
            $query = "SELECT 
                DISTINCT spa.student_id as id,
                spa.student_id as studentId,
                sa.studentName,
                spa.properties->>'$.registerNumber' AS regNo,
                esar.am_assessment_id as assessmentId,
                esarParent.falseNo as falseNumber,
                esar.valuation_details as valuationDetails,
                esar.properties ->> '$.falseNo' as falseNo,
                eerb.properties ->> '$.valuationRule' as valuationRule,
                eer.type as examRegistrationType,
                oe.id as oeExamId,
                s.name as subjectName,
                s.code as subjectCode,
                IF( ostm2.mark_obtained,1,0) AS mark1Confirm,
                ostm2.mark_obtained as mark1,
                oec2.is_confirmed as mark2Confirm,
                oec2.exam_mark as mark2,
                oec3.is_confirmed as mark3Confirm,
                oec3.exam_mark as mark3,
                p.course_type_id as courseTypeId,
                oec2.revaluation_id,
                caps.properties ->> '$.externalMaxMark' as externalMaxMark
            FROM
                ec_student_assessment_registration esar
            INNER JOIN ec_exam_registration eer ON
                eer.`type` = esar.ec_exam_registration_type AND eer.id = CAST(esar.identifying_context->>'$.examRegistrationId' AS CHAR)
            INNER JOIN ec_exam_registration_batch eerb ON
                eerb.ec_exam_registration_id = eer.id 
            INNER JOIN ec_exam_registration eer2 ON
                eer2.id = eer.properties->>'$.parentExamRegistrationId' AND 
                eer2.trashed IS NULL
            INNER JOIN ec_exam_registration_batch eerbParent ON
                eerbParent.ec_exam_registration_id = eer2.id  AND 
                eerb.groups_id = eerbParent.groups_id
            INNER JOIN ec_exam_registration_subject eers2 ON     
                eers2.ec_exam_registration_batch_id = eerbParent.id 
            INNER JOIN cm_academic_paper_subjects caps ON
                caps.id = eers2.cm_academic_paper_subjects_id AND eers2.am_assessment_id = esar.am_assessment_id 
            INNER JOIN ec_student_assessment_registration esarParent ON
                esarParent.am_assessment_id = eers2.am_assessment_id AND esarParent.ec_exam_registration_type = eer2.type
                AND esarParent.student_id = esar.student_id
            INNER JOIN oe_exams oe ON
                oe.assessment_id = esar.am_assessment_id AND oe.is_deleted = 0
            INNER JOIN v4_ams_subject s ON
                s.id = caps.ams_subject_id
            INNER JOIN `groups` g ON
                g.id = eerb.groups_id
                AND g.`type` = 'BATCH'
            INNER JOIN department d ON
                d.deptID = g.properties ->> '$.departmentId'
            INNER JOIN studentaccount sa ON
                sa.studentID = esar.student_id
            INNER JOIN program p ON 
                p.id = g.properties->>'$.programId'
            INNER JOIN student_program_account spa ON 
                spa.current_program_id = p.id AND 
                spa.student_id = esar.student_id 
            INNER JOIN exam_feestype ef ON
                ef.examfeesID = CAST(esar.identifying_context->>'$.revaluationType' AS CHAR)
            LEFT JOIN ec_internal_marks im ON
                im.groups_id = eerb.groups_id AND 
                im.academic_paper_subjects_id = caps.id AND 
                im.academic_term_id = CAST(eerb.properties ->> '$.academicTermId' AS CHAR) AND im.student_id = sa.studentID
            LEFT JOIN 
                oe_exam_marks_confirm oec2 ON 
                oec2.oe_exams_id = oe.id AND 
                oec2.oe_users_id = sa.studentID AND 
                oec2.is_confirmed = '1' AND
                oec2.valuation_count = 1 AND JSON_SEARCH( eer.properties ->>'$.revaluationFeeTypeIds', 'one',  oec2.revaluation_id)
            LEFT JOIN 
                oe_exam_marks_confirm oec3 ON 
                oec3.oe_exams_id = oe.id AND 
                oec3.oe_users_id = sa.studentID AND 
                oec3.is_confirmed = '1' AND
                oec3.valuation_count = 2 AND JSON_SEARCH( eer.properties ->>'$.revaluationFeeTypeIds', 'one',  oec3.revaluation_id)
            LEFT JOIN oe_student_total_mark ostm2 ON 
                ostm2.student_id = sa.studentID AND
                ostm2.am_assessment_id = esar.am_assessment_id AND 
                (ostm2.valuation_type IS NULL OR ostm2.valuation_type = '') AND 
                ostm2.valuation_count = 'FINALIZED'
            WHERE eer.type = 'REVALUATION' AND 
                esar.properties ->>'$.feeStatus' = 'PAID' AND 
                esar.properties ->>'$.registrationStatus' = 'REGISTERED' AND 
                eer.trashed IS NULL ";
            $studentsMarkDetails = $this->executeQueryForList($query.$whereQuery.$orderBy);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $studentsMarkDetails;
    }
    /**
     * get AllStudent By ExamRegistrationSubject For Digital Valuation
     * @param request $request
     * @return $studentsMarkDetails
     */
    public function getTotalCountOfThirdValuationStudentsForExamRegistrationSubject($request)
    {
        $request = $this->realEscapeObject($request);
        $request->academicPaperSubjectId = is_array($request->academicPaperSubjectId) ? "'" . implode("','",$request->academicPaperSubjectId) . "'" : "'".$request->academicPaperSubjectId."'";
        try 
        {
            $orderBy = null;
            $whereQuery = null;
            if( $request->examType == "REVALUATION" ){
                $whereQuery = " AND ets.revaluation_id = '$request->revaluationId'";
            }
            else{
                $whereQuery= " AND (ets.revaluation_id IS NULL OR ets.revaluation_id = '')";
            }
            if(!empty($request->groupId)) {
                $groupIdString = is_array($request->groupId) ? "'" . implode("','",$request->groupId) . "'" : "'".$request->groupId."'";
                $whereQuery .= " AND eerb.groups_id IN ( $groupIdString )";
            }
            if( $request->examType == "REVALUATION" ){
                $query = "SELECT
                            COUNT(ets.thirdvalstudentID) as thirdValStudentCount
                        FROM
                            externalexam_thirdvalstudents ets
                        INNER JOIN ec_exam_registration_subject eers ON 
                                eers.am_assessment_id = ets.am_assessment_id
                        INNER JOIN ec_exam_registration_batch eerb ON
                            eerb.id = eers.ec_exam_registration_batch_id
                        INNER JOIN ec_exam_registration eerReval ON
                            eerReval.properties->>'$.parentExamRegistrationId' = eerb.ec_exam_registration_id 
                            AND eerReval.trashed IS NULL
                        INNER JOIN ec_exam_registration_batch eerbReval On 
                            eerbReval.groups_id = eerb.groups_id AND eerbReval.ec_exam_registration_id = eerReval.id
                        WHERE
                            eerbReval.ec_exam_registration_id='$request->examRegistrationId' AND 
                            eers.cm_academic_paper_subjects_id IN ( $request->academicPaperSubjectId ) ";
            }
            else{
                $query = "SELECT
                            COUNT(ets.thirdvalstudentID) as thirdValStudentCount
                        FROM
                            externalexam_thirdvalstudents ets
                        INNER JOIN ec_exam_registration_subject eers ON 
                                eers.am_assessment_id = ets.am_assessment_id
                        INNER JOIN ec_exam_registration_batch eerb ON
                            eerb.id = eers.ec_exam_registration_batch_id
                        WHERE
                            eerb.ec_exam_registration_id='$request->examRegistrationId' AND 
                            eers.cm_academic_paper_subjects_id IN ( $request->academicPaperSubjectId ) ";
            }
            $thirdValStudentCount = $this->executeQueryForObject($query.$whereQuery.$orderBy);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $thirdValStudentCount->thirdValStudentCount;
    }
     /**
     * Finalize Digital Valuation Marks
     * 
     */
    public function finalizeDigitalValuationMarks($searchRequest)
    {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try
        {
            $registeredStudentMarkDetails = [];
            $insertionMarkTableArray = [];
            $deleteMarkTableArray = [];
            $insert_third_val_students = [];
            $delete_third_val_students = [];
            $currentStaffId = $GLOBALS['userId'];
            $searchRuleRequest = new SearchRuleRequest;
            $searchRuleRequest->name = "EXAM_VALUATION_PROCEDURE_RULE";
            $examValuationProcedureRule = reset(RuleService::getInstance()->searchRule($searchRuleRequest))->rule;
            $request = new \stdClass;
            $finalizedMarkProperties = new \Stdclass();
            $finalizedMarkProperties->valuationType = "FINALIZED";
            $finalizedMarkProperties = !empty($finalizedMarkProperties) ? "'" . json_encode($finalizedMarkProperties) . "'" : "NULL";
            $searchRequest->academicPaperSubjectIdArray = explode(",",$searchRequest->academicPaperSubjectId);
            $request->academicPaperSubjectId = $searchRequest->academicPaperSubjectIdArray;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->id = $searchRequest->examRegistrationId;
            $examRegistration = reset(ExamRegistrationService::getInstance()->searchExamRegistrationByOtherDetails($request));
            
            if($examRegistration->type != "REVALUATION"){
                $courseTypeId = $this->getCourseTypeIdByExamRegistrationIdAndPaperSubjectId($request->examRegistrationId,$request->academicPaperSubjectId);
            }
            if($examRegistration->type == "REVALUATION"){
                $registeredStudentMarkDetails = $this->getAllStudentByRevaluationRegistrationSubjectForDigitalValuation($request);
                $courseTypeId = reset($registeredStudentMarkDetails)->courseTypeId;
            }
            else{
                $registeredStudentMarkDetails = $this->getAllStudentByExamRegistrationSubjectForDigitalValuation($request);
            }
            $markDiffDetails = $courseTypeId ? $this->getExternalValuationMarkDifference($courseTypeId) : '';
            $markDiff = $markDiffDetails->markDiff;
            $valuationRules =  (array) $this->getAllValuationRule();
            $definedValuationRule = json_decode(reset($registeredStudentMarkDetails)->valuationRule);
            $examValuationProcedureRule->isExcatFinalizeMark = $examValuationProcedureRule->isExcatFinalizeMark ? $examValuationProcedureRule->isExcatFinalizeMark : false;
            $examValuationProcedureRule->roundOffDigits = $examValuationProcedureRule->roundOffDigits ? $examValuationProcedureRule->roundOffDigits : 0;
            $selectedFirstValuationRule = reset(array_filter($definedValuationRule, function ($rule) {
                return $rule->count == 1;
            }));
            $selectedSecondValuationRule = reset(array_filter($definedValuationRule, function ($rule) {
                return $rule->count == 2;
            }));
            $selectedThirdValuationRule = reset(array_filter($definedValuationRule, function ($rule) {
                return $rule->count == 3;
            }));
            $firstValuationRuleKey =  array_search($selectedFirstValuationRule->ruleId, array_column( $valuationRules, "id"));
            $secondValuationRuleKey =  array_search($selectedSecondValuationRule->ruleId, array_column( $valuationRules, "id"));
            $thirdValuationRuleKey =  array_search($selectedThirdValuationRule->ruleId, array_column( $valuationRules, "id"));
            if($firstValuationRuleKey !== false){
                $firstValuationRule = $valuationRules[$firstValuationRuleKey];
            }
            if($secondValuationRuleKey !== false){
                $secondValuationRule = $valuationRules[$secondValuationRuleKey];
            }
            if($thirdValuationRuleKey !== false){
                $thirdValuationRule = $valuationRules[$thirdValuationRuleKey];
            }
            if( empty($definedValuationRule) ){
                return 1;
            }
            foreach($registeredStudentMarkDetails as $student)
            {
                $studentMark = [];
                $student->hasMark1Mark2 = 0;
                if (is_numeric($student->mark1) && is_numeric($student->mark2) && $student->mark1Confirm && $student->mark2Confirm) {
                    $student->hasMark1Mark2 = 1;
                }
                $student->hasMark3 = 0;
                if (is_numeric($student->mark3)&& $student->mark3Confirm) {
                    $student->hasMark3 = 1;
                }
                $student->hasMark1 = 0;
                if (is_numeric($student->mark1)&& $student->mark1Confirm) {
                    $student->hasMark1 = 1;
                }
                //to finalize first valuation mark as final mark if rule is marked as single evaluation
                if($firstValuationRule->code == "SINGLE_EVALUATION" && $student->hasMark1){
                    $studentMark[0] = $student->mark1;
                    $finalizedMark = $this->getFinalizedMarkFromValuationRule($studentMark, $firstValuationRule->code,$examValuationProcedureRule->isExcatFinalizeMark);
                    if($examValuationProcedureRule->roundOffDigits){
                        $finalizedMark = round($finalizedMark,$examValuationProcedureRule->roundOffDigits);
                    }else{
                        $finalizedMark = round($finalizedMark);
                    }
                    $markEntryObj = new ExamUserMarkRequest();
                    $markEntryObj->studentId = $student->studentId;
                    $markEntryObj->assessmentId = $student->assessmentId;
                    $markEntryObj->oeExamsId = $student->oeExamId;
                    if($examRegistration->type == "REVALUATION"){
                        $markEntryObj->valuationType = 'REVALUATION';
                    }
                    $markEntryObj->attendanceStatus = "PRESENT";
                    $markEntryObj->valuationCount = 'FINALIZED';
                    $markEntryObj->markObtained = $finalizedMark;
                    $markEntryObj->staffId = $GLOBALS['userId'];
                    $examMarkEntryArray[] = $markEntryObj;
                }
                //to finalize chief valuer mark as final mark
                if($examValuationProcedureRule->isChiefValuationEnabled && $student->hasMark1Mark2 && $examValuationProcedureRule->numberOfValuations == 2){
                    $studentMark = [];
                    $studentMark[0] = $student->mark1;
                    $studentMark[1] = $student->mark2;
                    $finalizedMark = $this->getFinalizedMarkFromValuationRule($studentMark, $secondValuationRule->code,false,$examValuationProcedureRule);
                    $markEntryObj = new ExamUserMarkRequest();
                    $markEntryObj->studentId = $student->studentId;
                    $markEntryObj->assessmentId = $student->assessmentId;
                    $markEntryObj->oeExamsId = $student->oeExamId;
                    if($examRegistration->type == "REVALUATION"){
                        $markEntryObj->valuationType = 'REVALUATION';
                    }
                    $markEntryObj->attendanceStatus = "PRESENT";
                    $markEntryObj->valuationCount = 'FINALIZED';
                    $markEntryObj->markObtained = $finalizedMark;
                    $markEntryObj->staffId = $GLOBALS['userId'];
                    $examMarkEntryArray[] = $markEntryObj;
                }
                else if($student->hasMark1Mark2){
                    $student->eligibleForThirdVal = 0;
                    $student->markDifference = abs($student->mark1 - $student->mark2);
                    if($markDiffDetails->scheme == "PERCENTAGE"){
                        $percentMark1 = ( $student->mark1 / $student->externalMaxMark ) * 100;
                        $percentMark2 = ( $student->mark2 / $student->externalMaxMark ) * 100;
                        $student->markDifference = abs($percentMark1 - $percentMark2);
                    }
                    if (($markDiff <= $student->markDifference)) {
                        $student->eligibleForThirdVal = 1;
                    }
                    if (($student->eligibleForThirdVal && $student->hasMark3)) {
                        $studentMark = [];
                        $studentMark[0] = $student->mark1;
                        $studentMark[1] = $student->mark2;
                        $studentMark[2] = $student->mark3;
                        if( empty($thirdValuationRule) ){
                            return 3;
                        }
                        $finalizedMark = $this->getFinalizedMarkFromValuationRule($studentMark, $thirdValuationRule->code,true);
                        $markEntryObj = new ExamUserMarkRequest();
                        $markEntryObj->studentId = $student->studentId;
                        $markEntryObj->assessmentId = $student->assessmentId;
                        $markEntryObj->oeExamsId = $student->oeExamId;
                        if($examRegistration->type == "REVALUATION"){
                            $markEntryObj->valuationType = 'REVALUATION';
                        }
                        $markEntryObj->attendanceStatus = "PRESENT";
                        $markEntryObj->valuationCount = 'FINALIZED';
                        $markEntryObj->markObtained = $finalizedMark;
                        $markEntryObj->staffId = $GLOBALS['userId'];
                        $examMarkEntryArray[] = $markEntryObj;
                    }
                    if($student->hasMark1Mark2 ) {
                        if ($student->eligibleForThirdVal == 1 && !$student->hasMark3) {
                            $deleteMarkEntryObj = new ExamUserMarkRequest;
                            $deleteMarkEntryObj->assessmentId = $student->assessmentId;
                            $deleteMarkEntryObj->studentId = $student->studentId;
                            $deleteMarkEntryObj->valuationCount = 'FINALIZED';
                            if($examRegistration->type == "REVALUATION"){
                                $deleteMarkEntryObj->valuationType = 'REVALUATION';
                            }
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                            $markEntryObj = new ExamUserMarkRequest();
                            $markEntryObj->studentId = $student->studentId;
                            $markEntryObj->assessmentId = $student->assessmentId;
                            $markEntryObj->oeExamsId = $student->oeExamId;
                            $markEntryObj->attendanceStatus = "PRESENT";
                            $markEntryObj->valuationCount = 'FINALIZED';
                            if($examRegistration->type == "REVALUATION"){
                                $markEntryObj->valuationType = 'REVALUATION';
                            }
                            $markEntryObj->markObtained = NULL;
                            $markEntryObj->staffId = $GLOBALS['userId'];
                            $examMarkEntryArray[] = $markEntryObj;
                            if($examRegistration->type == "REVALUATION"){
                                $insert_third_val_students[] = "( '".$student->assessmentId."', ".$student->studentId."," .$student->revaluation_id.")";
                            }
                            else{
                                $insert_third_val_students[] = "( '".$student->assessmentId."', ".$student->studentId." )";
                            }
                            // if($examRegistration->type == "REVALUATION"){
                            //     $delete_third_val_students[] = "( am_assessment_id = '$student->assessmentId' AND studentID = '$student->studentId' AND revaluation_id = '$student->revaluation_id' )" ;
                            // }
                            // else{
                            //     $delete_third_val_students[] = "( am_assessment_id = '$student->assessmentId' AND studentID = '$student->studentId' )" ;
                            // }
                            
                        } elseif ($student->hasMark1Mark2 && $student->eligibleForThirdVal == 0) {
                            if( empty($secondValuationRule) ){
                                return 2;
                            }
                            $studentMark = [];
                            $studentMark[0] = $student->mark1;
                            $studentMark[1] = $student->mark2;
                          
                            $finalizedMark = $this->getFinalizedMarkFromValuationRule($studentMark, $secondValuationRule->code,true);
                            $markEntryObj = new ExamUserMarkRequest();
                            $markEntryObj->studentId = $student->studentId;
                            $markEntryObj->assessmentId = $student->assessmentId;
                            $markEntryObj->oeExamsId = $student->oeExamId;
                            $markEntryObj->attendanceStatus = "PRESENT";
                            $markEntryObj->valuationCount = 'FINALIZED';
                            if($examRegistration->type == "REVALUATION"){
                                $markEntryObj->valuationType = 'REVALUATION';
                            }
                            $markEntryObj->markObtained = $finalizedMark;
                            $markEntryObj->staffId = $GLOBALS['userId'];
                            $examMarkEntryArray[] = $markEntryObj;
                            if($examRegistration->type == "REVALUATION"){
                                $delete_third_val_students[] = "( am_assessment_id = '$student->assessmentId' AND studentID = '$student->studentId' AND revaluation_id = '$student->revaluation_id' )" ;
                            }
                            else{
                                $delete_third_val_students[] = "( am_assessment_id = '$student->assessmentId' AND studentID = '$student->studentId' )" ;
                            }
                        }
                    }
                }
            }
            // if(! empty($deleteMarkTableArray)){
            //     foreach($deleteMarkTableArray as $deleteObj){
            //         ExamUserMarkService::getInstance()->deleteExamUserTotalMark($deleteObj);
            //     }
            // }
            if( !empty ( $examMarkEntryArray ) ){
                ExamUserMarkService::getInstance()->saveExamUserTotalMark($examMarkEntryArray);
            }
            if(! empty($delete_third_val_students))
            {
                $this->deleteThirdValStudentRegistration($delete_third_val_students);
            }
            if(! empty($insert_third_val_students))
            {
                $this->insertThirdValStudentRegistration($insert_third_val_students, $examRegistration->type);
            }
           
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
     /**
     * print Finalize Mark Report
     * @param request $request
     */
    public function printfinalizeMarkReport($searchRequest)
    {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try
        {
            $request = new \stdClass;
            $request->paperSubjectId = $searchRequest->paperSubjectId;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $responseData = $this->getSubjectsForFinalizeMark($request);
            $templateName = "PrintFinalizeMarkReport";
            $responseHtml = TwigRenderer::renderTemplateFileToHtml(realpath(DOCUMENT_ROOT."../examcontroller-api/src/com/linways/web/templates/printTwigs/$templateName.twig"), [ 'responseData'=>$responseData ]);
            $prtContent = NULL;
                $prtContent .= '<html><head>';
                $prtContent .= "<style>
                    
                    </style>";
                $prtContent .= '</head><title>Finalize Mark Report</title><body>';
                $prtContent .= $responseHtml;
                $prtContent .= '</body></html>';
                $totalWidth = 210;
                $totalHeight = 297;
                $options = array(
                    'page-width'     => $totalWidth."mm",
                    'page-height'    => $totalHeight."mm",
                    'dpi'            => 96,
                    'margin-top' => "9mm",
                    'margin-left' => "1mm",
                    'margin-right' => "1mm",
                    'margin-bottom' => "9mm",
                    // 'binary' => "/usr/local/bin/wkhtmltopdf", // For Mac
                    'user-style-sheet' => realpath(DOCUMENT_ROOT . "/libcommon/bootstrap/css/bootstrap.min.css")
                );
            $programResult = new \stdClass;
            $programResult->displayData = $responseHtml;
            $programResult->pdf = PdfUtil::renderPdf($prtContent, $options);
            return  $programResult;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
     /**
     * get all Packets For Staff Side Mark Entry
     * @return staffDetails details
     */
    public function getAllPacketDetailsBySubjectForStaffSideMarkEntry($searchRequest)
    {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try
        {
            $response = new \stdClass;
            $request = new \stdClass;
            $packetNos=[];
            $request->paperSubjectId = $searchRequest->paperSubjectId;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $today = date("Y-m-d H:i");
            $currentSubject = ExamRegistrationSubjectService::getInstance()->getcurrentExamSubjectForCurrentStaff($request);
            $subject = ExamRegistrationSubjectService::getInstance()->getAllExamSubjectForCurrentStaffDigitalValuation($request);
            if($currentSubject)
            {
                $currentSubject->assessmentProperties = json_decode($currentSubject->assessmentProperties);
                $currentSubject->valuationDetails = json_decode($currentSubject->valuationDetails);
                $currentSubject->examDate = $currentSubject->assessmentProperties->assessmentDate;
                $currentSubject->errorMessage = null;
                $currentSubject->isConfiremed = "";
                $currentSubject->externalMaxMark = (int)$currentSubject->externalMaxMark;
                $currentSubject->valuationCount = $searchRequest->currentValuationCount;
                foreach($currentSubject->valuationDetails->valuationDates as $valuationDate)
                {
                    if($valuationDate->count == $searchRequest->currentValuationCount)
                    {
                        $currentSubject->valuationStartDate = $valuationDate->startDate;
                        $currentSubject->valuationEndDate = $valuationDate->endDate;
                        if(strtotime($today) < strtotime($currentSubject->valuationStartDate))
                        {
                            $currentSubject->errorMessage = "Valuation Not Started";
                        }
                        else if((strtotime($today) > strtotime($currentSubject->valuationEndDate)))
                        {
                            $currentSubject->errorMessage = "Valuation Date Expired";
                        }
                    }
                }
            }
            if($subject)
            {
                $subject->packetDetails = json_decode($subject->packetDetails);
                foreach($subject->packetDetails->packetDetails as $packetDetail)
                {
                    if(!empty($packetDetail->valuationStaffs))
                    {
                        foreach($packetDetail->valuationStaffs as $valuationStaff)
                        {
                            if( $valuationStaff->count == $request->currentValuationCount && in_array($GLOBALS['userId'],$valuationStaff->addiitonalExamniners))
                            {
                                $packetNo =  new \stdClass;
                                $packetNo->id = $packetDetail->name;
                                $packetNo->text = $packetDetail->name;
                                $packetNos[] = $packetNo;
                            }
                        }
                    }
                }
            }
            if(empty($packetNos))
            {
                throw new ExamControllerException(ExamControllerException::NO_PACKETS_IN_THIS_SUBJECT,"No Packet Generated In This Subject");
            }
            else
            {
                $response->subject = $currentSubject;
                $response->packetNos = $packetNos;
                $response->currentValuationCount = $searchRequest->currentValuationCount;
            }
            
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
     /**
     * get all Packets For Staff Side Mark Entry
     * @return staffDetails details
     */
    public function getAllStudentStaffDetailsWithOrderForStaffSideMarkEntry($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $response = new \stdClass;
            $request = new \stdClass;
            $request->paperSubjectId = $searchRequest->paperSubjectId;
            $request->academicPaperSubjectIds = $searchRequest->academicPaperSubjectIds;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $request->packetNo = $searchRequest->packetNo;
            $currentValuationCount = (int)$request->currentValuationCount ;
            $today = date("Y-m-d H:i");
            $isChiefExaminer = 0;
            $studentMarkDetails = [];
            $thirdValuatedStudentMarkDetails = [];
            $valuatedStudents = [];
            $isAdditonalExamniner = 0;
            $currentStaffId = $GLOBALS['userId'];
            $request->isChiefExaminer = false;
            $courseTypeId = $this->getCourseTypeIdByExamRegistrationIdAndPaperSubjectId($request->examRegistrationId,$request->academicPaperSubjectIds);
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ($courseTypeId);
            $request->courseType = $courseType->courseTypeMethod;
            $currentSubject = ExamRegistrationSubjectService::getInstance()->getcurrentExamSubjectForCurrentStaff($request);
            if($currentSubject)
            {
                $currentSubject->isConfiremed = "";
                $currentSubject->isPrint = 1;
                $currentSubject->assessmentProperties = json_decode($currentSubject->assessmentProperties);
                $currentSubject->valuationDetails = json_decode($currentSubject->valuationDetails);
                $currentSubject->examDate = $currentSubject->assessmentProperties->assessmentDate;
                $currentSubject->errorMessage = null;
                $currentSubject->isConfiremed = "";
                $currentSubject->externalMaxMark = (int)$currentSubject->externalMaxMark;
                $currentSubject->valuationCount = $searchRequest->currentValuationCount;
                $currentSubject->courseType = $courseType->courseTypeMethod;
                foreach($currentSubject->valuationDetails->valuationDates as $valuationDate){
                    if($valuationDate->count == $searchRequest->currentValuationCount){
                        $currentSubject->valuationStartDate = $valuationDate->startDate;
                        $currentSubject->valuationEndDate = $valuationDate->endDate;
                        if(strtotime($today) < strtotime($currentSubject->valuationStartDate)){
                            $currentSubject->errorMessage = "Valuation Not Started";
                        }
                        else if((strtotime($today) > strtotime($currentSubject->valuationEndDate))){
                            $currentSubject->errorMessage = "Valuation Date Expired";
                        }
                        else{
                            foreach($currentSubject->valuationDetails->valuationStaffs as $valuationStaffs){
                                if($valuationStaffs->count == $request->currentValuationCount && $request->packetNo == $valuationStaffs->packetNo){
                                    foreach($valuationStaffs->chiefExaminers as $chiefExaminer){
                                        if($chiefExaminer == $GLOBALS['userId'] ){
                                            $isChiefExaminer = 1;
                                        }
                                    }
                                    foreach($valuationStaffs->addiitonalExamniners as $addiitonalExamniners){
                                        $currentSubject->addiitonalExamniners[] = $addiitonalExamniners;
                                        if($addiitonalExamniners == $GLOBALS['userId']){
                                            $isAdditonalExamniner = 1;
                                        }
                                    }
                                }
                            }
                            if($isChiefExaminer && $isAdditonalExamniner == 0){
                                $currentSubject->isChiefExaminer = true;
                                foreach($currentSubject->valuationDetails->valuatedStaffs as $valuatedStaff){
                                    if($valuatedStaff->count == $request->currentValuationCount  && $valuatedStaff->packetNo == $request->packetNo && $valuatedStaff->valuationStaffType == 'ADDITIONAL_EVALUVATOR'){
                                        if($valuatedStaff->markEntryStatus){
                                            $additinalExaminerConfiremedStatus = $valuatedStaff->markEntryStatus;
                                        }
                                    }
                                    if($valuatedStaff->count == $request->currentValuationCount  && $valuatedStaff->packetNo == $request->packetNo && $valuatedStaff->valuationStaffType == 'CHIEF_EVALUVATOR' && $valuatedStaff->staffId == $currentStaffId){
                                        if($valuatedStaff->markEntryStatus){
                                            $currentSubject->isConfiremed = $valuatedStaff->markEntryStatus;
                                        }
                                    }
                                }
                                if($additinalExaminerConfiremedStatus != 'CONFIRMED') {
                                    $currentSubject->errorMessage = "Adiitional Evaluator Valuation Pending !";
                                    $currentSubject->students = [];
                                }
                                else{
                                    $request->isChiefExaminer = true;
                                    $studentMarkDetails = $this->getAllStudentsMarksWithFalseNumberOrder($request);
                                }
                            }
                            elseif($isAdditonalExamniner)
                            {
                                $currentSubject->isChiefExaminer = false;
                                if($currentValuationCount == 1){
                                    $previousValuationStatus = 'NO_PREVIOUS_VALUATIONS';
                                }
                                foreach($currentSubject->valuationDetails->valuatedStaffs as $valuatedStaff){
                                    if($valuatedStaff->count == $request->currentValuationCount  && $valuatedStaff->packetNo == $request->packetNo && $valuatedStaff->valuationStaffType == 'ADDITIONAL_EVALUVATOR' && $valuatedStaff->staffId == $currentStaffId){
                                        if($valuatedStaff->markEntryStatus){
                                            $currentSubject->isConfiremed = $valuatedStaff->markEntryStatus;
                                        }
                                    }
                                    if($currentValuationCount > 1){    
                                        if($courseType->courseTypeMethod == "UG") {
                                            if($valuatedStaff->count == $currentValuationCount-1  && $valuatedStaff->packetNo == $request->packetNo && $valuatedStaff->valuationStaffType == 'CHIEF_EVALUVATOR'){
                                                if($valuatedStaff->markEntryStatus){
                                                    $previousValuationStatus = $valuatedStaff->markEntryStatus;
                                                }
                                            }
                                        }
                                        else if($courseType->courseTypeMethod == "PG"){
                                            if($valuatedStaff->count == $currentValuationCount-1  && $valuatedStaff->packetNo == $request->packetNo ){
                                                if($valuatedStaff->markEntryStatus){
                                                    $previousValuationStatus = $valuatedStaff->markEntryStatus;
                                                }
                                            }
                                        }
                                    }
                                }
                                if($previousValuationStatus == 'CONFIRMED' || $previousValuationStatus == 'NO_PREVIOUS_VALUATIONS'){
                                    $studentMarkDetails = $this->getAllStudentsMarksWithFalseNumberOrder($request);
                                }
                                else{
                                    $currentSubject->errorMessage = "Previous Valuation Pending ";
                                    $currentSubject->students = [];
                                }
                            }
                            foreach($currentSubject->valuationDetails->valuatedStaffs as $valuatedStaff){
                                if($valuatedStaff->count == '2' && $courseType->courseTypeMethod == "UG" && $valuatedStaff->packetNo == $request->packetNo ){
                                    if($valuatedStaff->markEntryStatus){
                                        $secondValuationStatus = $valuatedStaff->markEntryStatus; 
                                    }
                                }
                                if($valuatedStaff->count == '3' && $courseType->courseTypeMethod == "PG" && $valuatedStaff->packetNo == $request->packetNo ){
                                    if($valuatedStaff->markEntryStatus){
                                        $thirdValuationStatus = $valuatedStaff->markEntryStatus; 
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if($currentValuationCount == 1 && !$currentSubject->isChiefExaminer && $currentSubject->courseType == 'UG'){
                // if the current staff is not chief examiner and the course type is UG then the staff can not print the report
                $currentSubject->isPrint = 0;
            }
            elseif($currentValuationCount == 1 && $currentSubject->isChiefExaminer && $currentSubject->courseType == 'UG'){
                $requestForThirdValuation = new \stdClass;
                $requestForThirdValuation = $request;
                $requestForThirdValuation->currentValuationCount = 2;
                $thirdValuatedStudentMarkDetails = $this->getAllStudentsMarksWithFalseNumberOrder($requestForThirdValuation);
                if(count($thirdValuatedStudentMarkDetails) >= 1 && $secondValuationStatus != 'CONFIRMED'){
                    // if the current staff is chief examiner and the course type is UG and the third valuation is not confirmed then the staff can not print the report
                    $currentSubject->isPrint = 0;
                }
            }
            else if($currentValuationCount == 1  && $currentSubject->courseType == 'PG'){
                // if the course type is PG then the staff can not print the report
                $currentSubject->isPrint = 1;
            }
            else if($currentValuationCount == 2  && $currentSubject->courseType == 'PG'){
                $requestForThirdValuation = new \stdClass;
                $requestForThirdValuation = $request;
                $requestForThirdValuation->currentValuationCount = 2;
                $thirdValuatedStudentMarkDetails = $this->getAllStudentsMarksWithFalseNumberOrder($requestForThirdValuation);
                $thirdValuatedStudentMarkDetails = array_filter($thirdValuatedStudentMarkDetails, function($student) {
                    return $student->thirdValReq == "1";
                });
                if(count($thirdValuatedStudentMarkDetails) >= 1 && $thirdValuationStatus != 'CONFIRMED'){
                    // if the current staff is chief examiner and the course type is PG and the third valuation is not confirmed then the staff can not print the report
                    $currentSubject->isPrint = 0;
                }
            }
            foreach($studentMarkDetails as $student){
                $student->staffRevaluatedType = $student->secondValuationStaffRevaluatedType;
                $student->alphaNumericCode = $student->alphaNumericCode;
                if($student->falseNoOrder != null){
                    $valuatedStudents[]= $student;
                }
                if($currentValuationCount == 1 && $currentSubject->isChiefExaminer != true){
                    $student->mark = $student->firstValuationMark;
                }
                if($currentValuationCount == 1 && $currentSubject->isChiefExaminer == true){
                    $student->mark = $student->secondValuationMark ;
                    $student->markDifference = abs ($student->secondValuationMark - $student->firstValuationMark) ;
                }
                if($currentValuationCount == 2 ){
                    $student->mark =  $currentSubject->courseType == 'UG' ? $student->thirdValuationMark : $student->secondValuationMark ;
                }
                if($currentValuationCount == 3){
                    $student->mark = $student->thirdValuationMark ;
                }
            }
            $response->maxStudentsCount = count($studentMarkDetails);
            $response->subject = $currentSubject;
            $response->allStudentMarkDetails = $studentMarkDetails;
            $response->valuatedStudents = $valuatedStudents;
            $response->currentValuationCount = $searchRequest->currentValuationCount;
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
     /**
     * get AllStudent By ExamRegistrationSubject For Digital Valuation
     * @param request $request
     */
    public function getAllStudentsMarksWithFalseNumberOrder($request)
    {
        $request = $this->realEscapeObject($request);
        try {
            $joinQuery = null;
            $orderBy = null;
            $whereQuery = null;
            if($request->currentValuationCount == 1 &&  $request->isChiefExaminer){
                $joinQuery .= "INNER JOIN oe_student_total_mark ostm1 ON 
                                ostm1.student_id = sa.studentID AND ostm1.am_assessment_id = esar.am_assessment_id AND ostm1.valuation_count = '1'";
            }
            else{
                $joinQuery .= "LEFT JOIN oe_student_total_mark ostm1 ON 
                                ostm1.student_id = sa.studentID AND ostm1.am_assessment_id = esar.am_assessment_id AND ostm1.valuation_count = '1'";
            }
            if(($request->currentValuationCount == 2 &&  $request->courseType == 'UG') || ($request->currentValuationCount == 3)){
                $joinQuery .= "INNER JOIN externalexam_thirdvalstudents ets ON 
                ets.studentID = sa.studentID AND ets.am_assessment_id = eers.am_assessment_id";
            }
            else{
                $joinQuery .= "LEFT JOIN externalexam_thirdvalstudents ets ON 
                            ets.studentID = sa.studentID AND ets.am_assessment_id = eers.am_assessment_id";
            }
            if(!empty($request->academicPaperSubjectIds)) {
                $academicPaperSubjectIdsString = is_array($request->academicPaperSubjectIds) ? "'" . implode("','",$request->academicPaperSubjectIds) . "'" : "'".$request->academicPaperSubjectIds."'";
                $whereQuery .= " AND eers.cm_academic_paper_subjects_id IN ( $academicPaperSubjectIdsString )";
            }
            
            $query = "SELECT
                            DISTINCT sa.studentID as id,
                            sa.studentID ,
                            sa.studentName,
                            sa.regNo,
                            esar.am_assessment_id as assessmentId,
                            esar.properties ->> '$.falseNo' as falseNo,
                            esar.properties ->> '$.alphaNumericCode' as alphaNumericCode,
                            ostmf.mark_obtained as finalizedMark,
                            ostmf.attendance_status as isAbsent,
                            ostm1.mark_obtained as firstValuationMark,
                            ostm1.properties ->> '$.staffRevaluatedType' as firstValuationStaffRevaluatedType,
                            
                            ostm2.mark_obtained as secondValuationMark,
                            ostm2.properties ->> '$.staffRevaluatedType' as secondValuationStaffRevaluatedType,
                            ostm3.mark_obtained as thirdValuationMark,
                            ostm2.properties ->> '$.staffRevaluatedType' as thirdValuationStaffRevaluatedType,
                           
                            @path_to_count := JSON_UNQUOTE(JSON_SEARCH(esar.valuation_order_details ->>'$.valuationOrder', 'one', '$request->currentValuationCount', NULL, '$[*].count')) AS path_to_count,
                            @path_to_parent := trim(TRAILING '.count' from @path_to_count) AS path_to_parent,
                            @current_object := JSON_EXTRACT(esar.valuation_order_details ->>'$.valuationOrder', @path_to_parent ) as current_object,
                            CAST(json_extract(@current_object, '$.falseNoOrder')AS UNSIGNED) as falseNoOrder,
                            IF(ets.thirdvalstudentID, 1, 0) AS thirdValReq
                        FROM
                            ec_student_assessment_registration esar
                        INNER JOIN studentaccount sa ON 
                            sa.studentID = esar.student_id
                        LEFT JOIN oe_student_total_mark ostmf ON 
                            ostmf.student_id = sa.studentID AND ostmf.am_assessment_id = esar.am_assessment_id AND ostmf.valuation_count = 'FINALIZED' AND (ostmf.valuation_type IS NULL OR ostmf.valuation_type = '')
                        LEFT JOIN oe_student_total_mark ostm2 ON 
                            ostm2.student_id = sa.studentID AND ostm2.am_assessment_id = esar.am_assessment_id AND ostm2.valuation_count = '2'
                        LEFT JOIN oe_student_total_mark ostm3 ON 
                            ostm3.student_id = sa.studentID AND ostm3.am_assessment_id = esar.am_assessment_id AND ostm3.valuation_count = '3'
                        INNER JOIN ec_exam_registration_subject eers ON 
                            eers.am_assessment_id = esar.am_assessment_id
                        INNER JOIN ec_exam_registration_batch eerb ON
                            eerb.id = eers.ec_exam_registration_batch_id 
                        INNER JOIN ec_exam_registration eer ON
                            eer.id = eerb.ec_exam_registration_id $joinQuery
                        WHERE
                            esar.ec_exam_registration_type = eer.type AND
                            CAST(esar.properties ->> '$.registrationStatus' AS CHAR) = 'REGISTERED' AND 
                            CAST(esar.properties ->> '$.feeStatus' AS CHAR) = 'PAID' AND
                            eerb.ec_exam_registration_id='$request->examRegistrationId' AND 
                            esar.valuation_details ->> '$.packetNo' = '$request->packetNo'
                            $whereQuery  
                        ORDER BY CAST(json_extract(@current_object, '$.falseNoOrder') AS UNSIGNED)";
            $studentsMarkDetails = $this->executeQueryForList($query.$orderBy);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $studentsMarkDetails;
    }
    /**
     * get all Packets For Staff Side Mark Entry
     * @return staffDetails details
     */
    public function saveStudentMarksDetailsWithOrderForStaffSideMarkEntry($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $response = new \stdClass;
            $request = new \stdClass;
            $regStudentCount = 0;
            // $request->paperSubjectId = $searchRequest->paperSubjectId;
            $request->academicPaperSubjectIds = $searchRequest->paperSubjectId;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $request->packetNo = $searchRequest->packetNo;
            $request->markSaveType = $searchRequest->markSaveType;
            $studentMarkArray = $searchRequest->studentsMarkDetails;
            $maxmarkOfSubject = 0;
            $maximumStudentsInPacket = 0;
            $registredStudentsFalseNoArray = [];
            $registeredStudentDetailsByFalseNo =[];
            $request->isChiefExaminer = false;
            $request->isBothExaminer = false;
            $examValuation = new \Stdclass();
            $examValuation->academicPaperSubjectId = $request->academicPaperSubjectIds;
            $examValuation->packetNo = $request->packetNo;
            $examValuation->examRegistrationId = $request->examRegistrationId;
            $examValuation->currentValuationCount =$request->currentValuationCount  ? $request->currentValuationCount  : 1;
            $courseTypeId = $this->getCourseTypeIdByExamRegistrationIdAndPaperSubjectId($request->examRegistrationId,$request->academicPaperSubjectIds);
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ($courseTypeId);
            $request->courseType = $courseType->courseTypeMethod;
            $currentSubject = ExamRegistrationSubjectService::getInstance()->getcurrentExamSubjectForCurrentStaff($request);
            if($currentSubject){
                $currentSubject->isConfiremed = "";
                $currentSubject->assessmentProperties = json_decode($currentSubject->assessmentProperties);
                $currentSubject->valuationDetails = json_decode($currentSubject->valuationDetails);
                $maxmarkOfSubject = (int)$currentSubject->externalMaxMark;
                foreach($currentSubject->valuationDetails->valuationStaffs as $valuationStaffs){
                    if($valuationStaffs->count == $request->currentValuationCount && $valuationStaffs->packetNo == $request->packetNo){
                        foreach($valuationStaffs->chiefExaminers as $chiefExaminer){
                            if($chiefExaminer == $GLOBALS['userId']){
                                $isChiefExaminer = 1;
                            }
                        }
                        foreach($valuationStaffs->addiitonalExamniners as $addiitonalExamniners){
                            if($addiitonalExamniners == $GLOBALS['userId']){
                                $isAdditonalExamniner = 1;
                            }
                        }
                    }
                }
                if($isChiefExaminer && $isAdditonalExamniner){
                    $request->isChiefExaminer = false;
                    $request->isBothExaminer = true;
                    $allStudentMarkDetails = $this->getAllStudentsMarksWithFalseNumberOrder($request);
                }
                elseif($isChiefExaminer){
                    $request->isChiefExaminer = true;
                    $allStudentMarkDetails = $this->getAllStudentsMarksWithFalseNumberOrder($request);
                }
                elseif($isAdditonalExamniner){
                    $request->isChiefExaminer = false;
                    $allStudentMarkDetails = $this->getAllStudentsMarksWithFalseNumberOrder($request);
                }
            }
            $maximumStudentsInPacket = count($allStudentMarkDetails);
            foreach($allStudentMarkDetails as $registeredStudent){
                $registeredStudent->falseNo = strtoupper($registeredStudent->falseNo);
                $registredStudentsFalseNoArray[$registeredStudent->falseNo] = $registeredStudent->falseNo;
                $registeredStudentDetailsByFalseNo[$registeredStudent->falseNo] = [
                    "studentId" => $registeredStudent->studentID,
                    "assessmentId" => $registeredStudent->assessmentId,
                    "registerNo" => $registeredStudent->regNo,
                    "falseNo" => $registeredStudent->falseNo
                ];
            }
            if(!empty($studentMarkArray)){
                foreach($studentMarkArray as $student){
                    $valuationStudents = new \Stdclass();
                    $falseNo = strtoupper($student['falseNo']);
                    if ( in_array ( $falseNo, $registredStudentsFalseNoArray ) ) {
                        if(isset($student['mark']) && $student['mark'] !== null){
                            if ( $student['mark'] > $maxmarkOfSubject ){
                                $markExceedsTotalMark[] = $student['falseNo'];
                                $errorFlag = 1;
                            }
                            else{
                                if($request->currentValuationCount == 1 && $request->isChiefExaminer && $courseType->courseTypeMethod == "UG" &&  $student['staffRevaluatedType'] == ""){
                                    throw new ExamControllerException(ExamControllerException::NOT_ENTERED_ALL_REVALUATION_TYPE,"Revaluation type is mandatory!");
                                }
                                else{
                                    $valuationStudents->falseNumber = $student['falseNo'];
                                    $valuationStudents->studentId = $registeredStudentDetailsByFalseNo[$falseNo]["studentId"];
                                    $valuationStudents->mark = $student['mark'];
                                    $valuationStudents->falseNoOrder =  $student['falseNoOrder'];
                                    $valuationStudents->staffRevaluatedType =  $student['staffRevaluatedType'];
                                    $valuationStudents->assessmentId = $registeredStudentDetailsByFalseNo[$falseNo]["assessmentId"];
                                    $valuationStudents->registerNumber = $registeredStudentDetailsByFalseNo[$falseNo]["registerNo"];
                                    $examValuation->examValuationStudentMarkDetails[] = $valuationStudents;
                                    $regStudentCount++;
                                }
                            }
                        }
                    }
                    else{
                        $unregisteredStudents[] = $student['falseNo'];
                        $errorFlag = 1;
                    }
                }
                if($request->markSaveType == "CONFIRM"){
                    if($regStudentCount != $maximumStudentsInPacket){
                        throw new ExamControllerException(ExamControllerException::NOT_ENTERED_ALL_MARKS,"Please Enter All The Marks!");
                    }
                    else{
                        $examValuation->isChiefExaminer = $request->isChiefExaminer;
                        $examValuation->isBothExaminer = $request->isBothExaminer;
                        $examValuation->markSaveType = $request->markSaveType;
                        $response = $this->saveExamValuationStudentmarksWithOrderForStaffSideMarkEntry ( $examValuation );
                        $searchRequest = new \Stdclass();
                        $searchRequest->examRegistrationId = $request->examRegistrationId;
                        $searchRequest->academicPaperSubjectId = $request->academicPaperSubjectIds;
                        $searchRequest->currentValuationCount = $request->currentValuationCount;
                        $searchRequest->packetNo =  $request->packetNo;
                        $searchRequest->markEntryStatus = "CONFIRMED";
                        $searchRequest->valuationStaffType =  $request->isChiefExaminer ? 'CHIEF_EVALUVATOR' : 'ADDITIONAL_EVALUVATOR';
                        $this->saveExtrenalMarkStatusByStaffSideWithPacketNo( $searchRequest );
                    }
                }
                elseif($regStudentCount) {
                    $examValuation->isChiefExaminer = $request->isChiefExaminer;
                    $examValuation->isBothExaminer = $request->isBothExaminer;
                    $examValuation->markSaveType = $request->markSaveType;
                    $response = $this->saveExamValuationStudentmarksWithOrderForStaffSideMarkEntry ( $examValuation );
                    $searchRequest = new \Stdclass();
                    $searchRequest->examRegistrationId = $request->examRegistrationId;
                    $searchRequest->academicPaperSubjectId = $request->academicPaperSubjectIds;
                    $searchRequest->currentValuationCount = $request->currentValuationCount;
                    $searchRequest->packetNo =  $request->packetNo;
                    $searchRequest->markEntryStatus = "SAVED";
                    $searchRequest->valuationStaffType =  $request->isChiefExaminer ? 'CHIEF_EVALUVATOR' : 'ADDITIONAL_EVALUVATOR';
                    $this->saveExtrenalMarkStatusByStaffSideWithPacketNo( $searchRequest );
                }
            }
            else{
                $errors["unregisteredStudent"] = $errors["markExceedsTotalMark"] =$errors["error"] = $errors["success"] = $errors["notEligibleThirdValuation"] = $errors["secondValuationNotCompletedStudents"] = $errors["firstValuationNotCompletedStudents"] = $errors["otherPacketStudents"] ="";
                $errors["error"] = "No Student Mark Entered";
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    /**
     * save Exam Valuation Studentmarks For Staff Side Mark Entry
     * @param $examValuation
     * @return $response
     */
    public function saveExamValuationStudentmarksWithOrderForStaffSideMarkEntry($examValuation){
        $examValuation = $this->realEscapeObject($examValuation);
        try {
            $examRegistrationId = $examValuation->examRegistrationId;
            $academicPaperSubjectId = $examValuation->academicPaperSubjectId;
            $currentValuationCount = $examValuation->currentValuationCount;
            $studentMarkDetailsArray = $examValuation->examValuationStudentMarkDetails;
            $markSaveType = $examValuation->markSaveType;
            $courseTypeId = $this->getCourseTypeIdByExamRegistrationIdAndPaperSubjectId($examRegistrationId,$academicPaperSubjectId);
            $maxmarkOfSubject = (int)ExamRegistrationSubjectService::getInstance()->getMaxSubjectMarkByAcademicPaperSubjectId($academicPaperSubjectId);
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ($courseTypeId);
            $registeredStudentsArray = [];
            $registeredStudentsCurrentMarks = [];
            $registeredStudentsFalseNumberOrder = [];
            $registeredStudentsStaffRevaluvatedType = [];
            $insertionMarkTableWithOutFinalizeArray = [];
            $deleteAllFinalizeMarkTableArray = [];
            $registeredStudentsRVStatus = [];
            $notEligibleThirdValuation = [];
            $insert_all_third_val_students = [];
            $error = 0;
            $currentStaffId = $GLOBALS['userId'];
            $updatedStudentCount = 0;
            $insertionMarkTableArray = [];
            $updateValuatedStaffValues = [];
            $studentMarkDetails = [];
            $valuationProperties = new \Stdclass();
            $valuatedStaffObject = new \Stdclass();
            $markProperties = new \Stdclass();
            $response = new \Stdclass();
            $valuatedStaffObject->staffIds = $currentStaffId;
            $markDiff = CommonExamService::getInstance()->getExternalValuationMarkDiff($courseTypeId,$maxmarkOfSubject);
            $valuatedStaffObject->valuationCount = $examValuation->currentValuationCount;
            $valuationProperties->valuatedStaffs[]=$valuatedStaffObject;
            $valuationProperties->packetNo = $examValuation->packetNo;
            foreach($studentMarkDetailsArray as $student){
                if(($student->registerNumber) && ($student->mark != "")){
                    $conditions[] = " (sa.regNo = '".$student->registerNumber."' AND  esar.am_assessment_id = '".$student->assessmentId."') ";
                }
            }
            if(! empty($conditions)){
                $studentDetails = $this->getStudentsExternalMarksByStudentExamDetail($conditions);
                foreach($studentMarkDetailsArray as $student){
                    $registeredStudentsArray[$student->studentId] = $student->studentId;
                    $registeredStudentsCurrentMarks[$student->studentId] = $student->mark;
                    $registeredStudentsFalseNumberOrder[$student->studentId] = $student->falseNoOrder;
                    $registeredStudentsStaffRevaluvatedType[$student->studentId] = $student->staffRevaluatedType;
                    $registeredStudentsRVStatus[$student->studentId] = $student->rvStatus;
                }
                foreach($studentDetails as $studentDetail){
                    if ( in_array ( $studentDetail->studentId, $registeredStudentsArray ) ) {
                        $singleStudentDetail = new \Stdclass();
                        $facultyUpdated = false;
                        $orderUpdated = false;
                        $singleStudentDetail->studentId = $studentDetail->studentId;
                        $singleStudentDetail->registerNumber = $studentDetail->regNo;
                        $singleStudentDetail->assessmentId = $studentDetail->assessmentId;
                        $singleStudentDetail->oeExamId = $studentDetail->oeExamId;
                        $singleStudentDetail->currentMark = $registeredStudentsCurrentMarks[$studentDetail->studentId];
                        $singleStudentDetail->falseNoOrder = $registeredStudentsFalseNumberOrder[$studentDetail->studentId];
                        $singleStudentDetail->staffRevaluatedType = $registeredStudentsStaffRevaluvatedType[$studentDetail->studentId];
                        $singleStudentDetail->firsrValuationMark = $studentDetail->firstValuationMark;
                        $singleStudentDetail->secondValuationMark = $studentDetail->secondValuationMark;
                        $singleStudentDetail->thirdValuationMark = $studentDetail->thirdValuationMark;
                        $singleStudentDetail->finalizedMark = $studentDetail->finalizedMark;
                        $singleStudentDetail->thirdValReq = $studentDetail->thirdValReq;
                        $valuatedOrderObject = new \Stdclass();
                        $valuationOrderProperties = new \Stdclass();
                        $valuatedOrderObject->count = $currentValuationCount;
                        $valuatedOrderObject->falseNoOrder = (int)$singleStudentDetail->falseNoOrder;
                        $valuationOrderProperties->valuationOrder[]= $valuatedOrderObject;
                        $valuationDetails =  json_decode($studentDetail->valuationDetails);
                        $singleStudentDetail->valuationDetails = $valuationDetails;
                        if(is_null($studentDetail->valuationOrders)){
                            $singleStudentDetail->valuationOrderDetails = $valuationOrderProperties;
                        }
                        else if($studentDetail->valuationOrders){
                            $valuationOrders = json_decode($studentDetail->valuationOrders);
                            foreach($valuationOrders as $valuationOrder){
                                if($valuationOrder->count == $currentValuationCount){
                                    $valuationOrder->falseNoOrder = (int)$singleStudentDetail->falseNoOrder;
                                    $orderUpdated = true;
                                }
                            }
                            if(!$orderUpdated){
                                $valuationOrders[] = $valuatedOrderObject;
                            }
                            $singleStudentDetail->valuationOrderDetails->valuationOrder = $valuationOrders;
                        }
                        if(is_null($studentDetail->valuatedStaffs)){
                            $singleStudentDetail->valuationDetails = $valuationProperties;
                        }
                        else if($studentDetail->valuatedStaffs){
                            $valuatedStaffs = json_decode($studentDetail->valuatedStaffs);
                            foreach($valuatedStaffs as $valuatedStaff){
                                if($valuatedStaff->valuationCount == $currentValuationCount){
                                    $valuatedStaff->staffIds = $currentStaffId;
                                    $facultyUpdated = true;
                                }
                            }
                            if(!$facultyUpdated){
                                $valuatedStaffs[] = $valuatedStaffObject;
                            }
                            $singleStudentDetail->valuationDetails->valuatedStaffs = $valuatedStaffs;
                        }
                        if( $singleStudentDetail->studentId){
                            $studentMarkDetails[] = $singleStudentDetail;
                        }
                    }
                }
                foreach($studentMarkDetails as $studentMarkDetail){
                    if($markSaveType == "CONFIRM"){
                        if($currentValuationCount == 1 && !$examValuation->isChiefExaminer && $examValuation->isBothExaminer){
                            $markEntryObj = new \stdClass();
                            $markEntryObj->studentId = $studentMarkDetail->studentId;
                            $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                            $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                            $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                            $markEntryObj->attendanceStatus = "PRESENT";
                            $markEntryObj->valuationCount = '1';
                            $markproperties = "";
                            $markEntryObj->properties  = $markproperties;
                            $markEntryObj->valuationType = null;
                            $insertionMarkTableArray[] = $markEntryObj;
                            $markEntryObj = new \stdClass();
                            $markEntryObj->studentId = $studentMarkDetail->studentId;
                            $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                            $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                            $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                            $markEntryObj->attendanceStatus = "PRESENT";
                            $markEntryObj->valuationCount = 'FINALIZED';
                            $markproperties = "";
                            $markEntryObj->properties  = $markproperties;
                            $markEntryObj->valuationType = null;
                            $insertionMarkTableArray[] = $markEntryObj;
                            
                            $updateMarkValuatedStaff = new \Stdclass();
                            $updateMarkValuatedStaff->assessmentId = $studentMarkDetail->assessmentId;
                            $updateMarkValuatedStaff->studentId = $studentMarkDetail->studentId;
                            $updateMarkValuatedStaff->valuationProperties = $studentMarkDetail->valuationDetails;
                            $updateMarkValuatedStaff->valuationOrderDetails = $studentMarkDetail->valuationOrderDetails;
                            $updateMarkValuatedStaff->updatedBy = $currentStaffId ;
                            $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                            $updatedStudentCount ++;
                        }
                        elseif($currentValuationCount == 1 && !$examValuation->isChiefExaminer && !$examValuation->isBothExaminer){
                            $markEntryObj = new \stdClass();
                            $markEntryObj->studentId = $studentMarkDetail->studentId;
                            $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                            $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                            $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                            $markEntryObj->attendanceStatus = "PRESENT";
                            $markEntryObj->valuationCount = '1';
                            $markproperties = "";
                            $markEntryObj->properties  = $markproperties;
                            $markEntryObj->valuationType = null;
                            $insertionMarkTableArray[] = $markEntryObj;
                            $updateMarkValuatedStaff = new \Stdclass();
                            $updateMarkValuatedStaff->assessmentId = $studentMarkDetail->assessmentId;
                            $updateMarkValuatedStaff->studentId = $studentMarkDetail->studentId;
                            $updateMarkValuatedStaff->valuationProperties = $studentMarkDetail->valuationDetails;
                            $updateMarkValuatedStaff->valuationOrderDetails = $studentMarkDetail->valuationOrderDetails;
                            $updateMarkValuatedStaff->updatedBy = $currentStaffId ;
                            $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                            $updatedStudentCount ++;
                        }
                        elseif($currentValuationCount == 1 && $examValuation->isChiefExaminer && $courseType->courseTypeMethod == "UG"){
                            $markEntryObj = new \stdClass();
                            $markEntryObj->studentId = $studentMarkDetail->studentId;
                            $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                            $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                            $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                            $markEntryObj->attendanceStatus = "PRESENT";
                            $markEntryObj->valuationCount = '2';
                            $markproperties =  new \stdClass();
                            $markproperties->staffRevaluatedType = $studentMarkDetail->staffRevaluatedType;
                            $markEntryObj->properties  = $markproperties;
                            $markEntryObj->valuationType = null;
                            $insertionMarkTableArray[] = $markEntryObj;
                            $insertionMarkTableWithOutFinalizeArray[] = $markEntryObj; 
                            $finalized = '"FINALIZED"';
                            $insert_all_third_val_students[] = "( '".$studentMarkDetail->assessmentId."', ".$studentMarkDetail->studentId." )";
                            // $deleteMarkEntryObj = new ExamUserMarkRequest;
                            // $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                            // $deleteMarkEntryObj->studentId = $studentMarkDetail->studentId;
                            // $deleteMarkEntryObj->valuationCount = 'FINALIZED';
                            // $deleteAllFinalizeMarkTableArray[] = $deleteMarkEntryObj;
                            $updateMarkValuatedStaff = new \Stdclass();
                            $updateMarkValuatedStaff->assessmentId = $studentMarkDetail->assessmentId;
                            $updateMarkValuatedStaff->studentId = $studentMarkDetail->studentId;
                            $updateMarkValuatedStaff->valuationProperties = $studentMarkDetail->valuationDetails;
                            $updateMarkValuatedStaff->valuationOrderDetails = $studentMarkDetail->valuationOrderDetails;
                            $updateMarkValuatedStaff->updatedBy = $currentStaffId ;
                            $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                            $updatedStudentCount ++;
                            $studentMarkDiff = abs ($studentMarkDetail->firsrValuationMark - $studentMarkDetail->currentMark);
                            if( $studentMarkDiff >= $markDiff){
                                // $deleteMarkEntryObj = new ExamUserMarkRequest;
                                // $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                // $deleteMarkEntryObj->studentId = $studentMarkDetail->studentId;
                                // $deleteMarkEntryObj->valuationCount = 'FINALIZED';
                                // $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $studentMarkDetail->studentId;
                                $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                $markEntryObj->markObtained = null;
                                $markEntryObj->attendanceStatus = "PRESENT";
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markproperties = "";
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                                $insertionMarkTableArray[] = $markEntryObj;
                                $deleteMarkEntryObj = new ExamUserMarkRequest;
                                $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $deleteMarkEntryObj->studentId = $studentMarkDetail->studentId;
                                $deleteMarkEntryObj->valuationCount = 3;
                                $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $insert_third_val_students[] = "( '".$studentMarkDetail->assessmentId."', ".$studentMarkDetail->studentId." )";
                            }
                            else{
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $studentMarkDetail->studentId;
                                $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                                $markEntryObj->attendanceStatus = "PRESENT";
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markproperties = "";
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                                $insertionMarkTableArray[] = $markEntryObj;
                                $delete_third_val_students[] = "( am_assessment_id = '$studentMarkDetail->assessmentId' AND studentID = '$studentMarkDetail->studentId' )" ;
                            }
                        }
                        elseif($currentValuationCount == 2 && $courseType->courseTypeMethod != "UG"){
                            $markEntryObj = new \stdClass();
                            $markEntryObj->studentId = $studentMarkDetail->studentId;
                            $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                            $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                            $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                            $markEntryObj->attendanceStatus = "PRESENT";
                            $markEntryObj->valuationCount = '2';
                            $markproperties = "";
                            $markEntryObj->properties  = $markproperties;
                            $markEntryObj->valuationType = null;
                            $insertionMarkTableArray[] = $markEntryObj;
                            $updateMarkValuatedStaff = new \Stdclass();
                            $updateMarkValuatedStaff->assessmentId = $studentMarkDetail->assessmentId;
                            $updateMarkValuatedStaff->studentId = $studentMarkDetail->studentId;
                            $updateMarkValuatedStaff->valuationProperties = $studentMarkDetail->valuationDetails;
                            $updateMarkValuatedStaff->valuationOrderDetails = $studentMarkDetail->valuationOrderDetails;
                            $updateMarkValuatedStaff->updatedBy = $currentStaffId ;
                            $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                            $updatedStudentCount ++;
                            $studentMarkDiff = abs ($studentMarkDetail->firsrValuationMark - $studentMarkDetail->currentMark);
                            $deleteMarkEntryObj = new ExamUserMarkRequest;
                            $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                            $deleteMarkEntryObj->studentId = $studentMarkDetail->studentId;
                            $deleteMarkEntryObj->valuationCount = 3;
                            $deleteMarkTableArray[] = $deleteMarkEntryObj;
                            if( $studentMarkDiff >= $markDiff){
                                // $deleteMarkEntryObj = new ExamUserMarkRequest;
                                // $deleteMarkEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                // $deleteMarkEntryObj->studentId = $studentMarkDetail->studentId;
                                // $deleteMarkEntryObj->valuationCount = 'FINALIZED';
                                // $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $studentMarkDetail->studentId;
                                $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                $markEntryObj->markObtained = null;
                                $markEntryObj->attendanceStatus = "PRESENT";
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markproperties = "";
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                                $insertionMarkTableArray[] = $markEntryObj;
                                $insert_third_val_students[] = "( '".$studentMarkDetail->assessmentId."', ".$studentMarkDetail->studentId." )";
                            }
                            else{
                                $studentMark =  ($studentMarkDetail->firsrValuationMark + $studentMarkDetail->currentMark)/2;
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $studentMarkDetail->studentId;
                                $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                $markEntryObj->markObtained = $studentMark;
                                $markEntryObj->attendanceStatus = "PRESENT";
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markproperties = "";
                                $markEntryObj->properties  = $markproperties;
                                $markEntryObj->valuationType = null;
                                $insertionMarkTableArray[] = $markEntryObj;
                                $delete_third_val_students[] = "( am_assessment_id = '$studentMarkDetail->assessmentId' AND studentID = '$studentMarkDetail->studentId' )" ;
                            }
                        }
                        elseif($currentValuationCount == 2 && $courseType->courseTypeMethod == "UG"){
                            if($studentMarkDetail->thirdValReq == 1){
                                if($studentMarkDetail->firsrValuationMark != null || $studentMarkDetail->secondValuationMark != null){
                                    $markEntryObj = new \stdClass();
                                    $markEntryObj->studentId = $studentMarkDetail->studentId;
                                    $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                    $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                    $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                                    $markEntryObj->attendanceStatus = "PRESENT";
                                    $markEntryObj->valuationCount = '3';
                                    $markproperties = "";
                                    $markEntryObj->properties  = $markproperties;
                                    $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
                                    $updateMarkValuatedStaff = new \Stdclass();
                                    $updateMarkValuatedStaff->assessmentId = $studentMarkDetail->assessmentId;
                                    $updateMarkValuatedStaff->studentId = $studentMarkDetail->studentId;
                                    $updateMarkValuatedStaff->valuationProperties = $studentMarkDetail->valuationDetails;
                                    $updateMarkValuatedStaff->valuationOrderDetails = $studentMarkDetail->valuationOrderDetails;
                                    $updateMarkValuatedStaff->updatedBy = $currentStaffId ;
                                    $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                                    $updatedStudentCount ++;
                                    $studentMark = array($studentMarkDetail->firsrValuationMark,$studentMarkDetail->secondValuationMark,$studentMarkDetail->currentMark);
                                    sort($studentMark);
                                    $diff_01 = abs ( $studentMark[0] - $studentMark[1] );
                                    $diff_12 = abs ( $studentMark[1] - $studentMark[2] );
                                    if ( $diff_01 < $diff_12 ) {
                                        $nearestTwo = array_slice($studentMark, 0, 2);
                                    } else {
                                        $nearestTwo = array_slice($studentMark, 1, 2);
                                    }
                                    $avgMark = array_sum($nearestTwo) / 2;
                                    $markEntryObj = new \stdClass();
                                    $markEntryObj->studentId = $studentMarkDetail->studentId;
                                    $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                    $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                    $markEntryObj->markObtained = $avgMark;
                                    $markEntryObj->attendanceStatus = "PRESENT";
                                    $markEntryObj->valuationCount = 'FINALIZED';
                                    $markproperties = "";
                                    $markEntryObj->properties  = $markproperties;
                                    $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
                                }
                                elseif($studentMarkDetail->firsrValuationMark == null){
                                    $firstValuationNotCompletedStudents[] = $studentDetail->registerNumber;
                                    $error = 1;
                                }
                                elseif($studentMarkDetail->chiefFirstValuationMark == null){
                                    $secondValuationNotCompletedStudents[] = $studentDetail->registerNumber;
                                    $error = 1;
                                }
                            }
                            else{
                                $notEligibleThirdValuation[] = $studentDetail->registerNumber;
                                $error = 1;
                            }
                        }
                        elseif($currentValuationCount == 3){
                            if($studentMarkDetail->thirdValReq == 1){
                                if($studentMarkDetail->firsrValuationMark != null || $studentMarkDetail->secondValuationMark != null) {
                                    $markEntryObj = new \stdClass();
                                    $markEntryObj->studentId = $studentMarkDetail->studentId;
                                    $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                    $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                    $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                                    $markEntryObj->attendanceStatus = "PRESENT";
                                    $markEntryObj->valuationCount = '3';
                                    $markproperties = "";
                                    $markEntryObj->properties  = $markproperties;
                                    $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
                                    $updateMarkValuatedStaff = new \Stdclass();
                                    // $insertionMarkTableArray[] = " ('".$studentMarkDetail->studentId."', '".$studentMarkDetail->currentMark."', 'PRESENT','".$studentMarkDetail->assessmentId."',$markProperties,'".$currentStaffId."', utc_timestamp(), '".$currentStaffId."', utc_timestamp() ) ";
                                    $updateMarkValuatedStaff->assessmentId = $studentMarkDetail->assessmentId;
                                    $updateMarkValuatedStaff->studentId = $studentMarkDetail->studentId;
                                    $updateMarkValuatedStaff->valuationProperties = $studentMarkDetail->valuationDetails;
                                    $updateMarkValuatedStaff->valuationOrderDetails = $studentMarkDetail->valuationOrderDetails;
                                    $updateMarkValuatedStaff->updatedBy = $currentStaffId ;
                                    $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                                    $updatedStudentCount ++;
                                    $studentMark = array($studentMarkDetail->firsrValuationMark,$studentMarkDetail->secondValuationMark,$studentMarkDetail->currentMark);
                                    sort($studentMark);
                                    $diff_01 = abs ( $studentMark[0] - $studentMark[1] );
                                    $diff_12 = abs ( $studentMark[1] - $studentMark[2] );
                                    if ( $diff_01 < $diff_12 ) {
                                        $nearestTwo = array_slice($studentMark, 0, 2);
                                    } else {
                                        $nearestTwo = array_slice($studentMark, 1, 2);
                                    }
                                    $avgMark = array_sum($nearestTwo) / 2;
                                    $markEntryObj = new \stdClass();
                                    $markEntryObj->studentId = $studentMarkDetail->studentId;
                                    $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                    $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                    $markEntryObj->markObtained = $avgMark;
                                    $markEntryObj->attendanceStatus = "PRESENT";
                                    $markEntryObj->valuationCount = 'FINALIZED';
                                    $markproperties = "";
                                    $markEntryObj->properties  = $markproperties;
                                    $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
                                }
                                elseif($studentMarkDetail->firsrValuationMark == null){
                                    $firstValuationNotCompletedStudents[] = $studentDetail->registerNumber;
                                    $error = 1;
                                }
                                elseif($studentMarkDetail->secondValuationMark == null){
                                    $secondValuationNotCompletedStudents[] = $studentDetail->registerNumber;
                                    $error = 1;
                                }
                            }
                            else {
                                $notEligibleThirdValuation[] = $studentDetail->registerNumber;
                                $error = 1;
                            }
                        }
                    }
                    else{   
                        if($currentValuationCount == 1 && $examValuation->isChiefExaminer && $courseType->courseTypeMethod == "UG") {
                            $markEntryObj = new \stdClass();
                            $markEntryObj->studentId = $studentMarkDetail->studentId;
                            $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                            $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                            $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                            $markEntryObj->attendanceStatus = "PRESENT";
                            $markEntryObj->valuationCount = '2';
                            $markproperties =  new \stdClass();
                            $markproperties->staffRevaluatedType = $studentMarkDetail->staffRevaluatedType;
                            $markEntryObj->properties  = $markproperties;
                            $markEntryObj->valuationType = null;
                            $insertionMarkTableArray[] = $markEntryObj;
                        }   
                        else{
                            $markEntryObj = new \stdClass();
                            $markEntryObj->studentId = $studentMarkDetail->studentId;
                            $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                            $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                            $markEntryObj->markObtained = $studentMarkDetail->currentMark;
                            $markEntryObj->attendanceStatus = "PRESENT";
                            $markEntryObj->valuationCount = $currentValuationCount == '2' && $courseType->courseTypeMethod == "UG" ? '3' : $currentValuationCount;
                            $markproperties =  new \stdClass();
                            $markEntryObj->properties  = $markproperties;
                            $markEntryObj->valuationType = null;
                            $insertionMarkTableArray[] = $markEntryObj;
                        }             
                        $updateMarkValuatedStaff = new \Stdclass();
                        $updateMarkValuatedStaff->assessmentId = $studentMarkDetail->assessmentId;
                        $updateMarkValuatedStaff->studentId = $studentMarkDetail->studentId;
                        $updateMarkValuatedStaff->valuationProperties = $studentMarkDetail->valuationDetails;
                        $updateMarkValuatedStaff->valuationOrderDetails = $studentMarkDetail->valuationOrderDetails;
                        $updateMarkValuatedStaff->updatedBy = $currentStaffId ;
                        $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                        $updatedStudentCount ++;
                    }
                }
            }
            if($currentValuationCount == 1 && $examValuation->isChiefExaminer && $courseType->courseTypeMethod == "UG"){
                $totalCount = count($insertionMarkTableWithOutFinalizeArray);
                $thirdValCount = count($insert_third_val_students);
                $thirdValCountPercent = round($thirdValCount / $totalCount * 100);
                if($thirdValCountPercent >= 30){
                    $insertionMarkTableArray = $insertionMarkTableWithOutFinalizeArray;
                    $insert_third_val_students = $insert_all_third_val_students;
                    $deleteMarkTableArray = $deleteAllFinalizeMarkTableArray;
                    $delete_third_val_students = [];
                }
            }
            if(! empty($insertionMarkTableArray)){
                ExamUserMarkService::getInstance()->saveExamUserTotalMark($insertionMarkTableArray);
            }
            if(! empty($updateValuatedStaffValues)){
                $this->updateValuatedStaffToStudentRegistration($updateValuatedStaffValues);
            }
            if(! empty($deleteMarkTableArray)){
                foreach($deleteMarkTableArray as $deleteObj){
                    ExamUserMarkService::getInstance()->deleteExamUserTotalMark($deleteObj);
                }
            }
            if(! empty($insert_third_val_students)){
                $this->insertThirdValStudentRegistration($insert_third_val_students);
            }
            if(! empty($delete_third_val_students)){
                $this->deleteThirdValStudentRegistration($delete_third_val_students);
            }
            $response->error = $error;
            $response->updatedStudentCount = $updatedStudentCount;
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    
    public function saveExtrenalMarkStatusByStaffSideWithPacketNo($request){
        $searchRequest = $this->realEscapeObject($request);
        try {
            $updateValuatedStaffValues = [];
            $request = new \stdClass;
            $request->paperSubjectId = $searchRequest->academicPaperSubjectId;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $request->packetNo = $searchRequest->packetNo;
            $request->valuationStaffType = $searchRequest->valuationStaffType;
            $valuatedStaffs =  new \stdClass;
            $valuationProperties =  new \stdClass;
            $valuatedStaffs->staffId = $GLOBALS['userId'];
            $valuatedStaffs->markEntryStatus = $searchRequest->markEntryStatus;
            $valuatedStaffs->count = $request->currentValuationCount;
            $valuatedStaffs->packetNo = $request->packetNo;
            $valuatedStaffs->valuationStaffType = $request->valuationStaffType;
            $valuatedStaffs->valuatedAnsweSheetCount = 0;
            $valuationProperties->valuatedStaffs = $valuatedStaffs;
            $subjects = ExamRegistrationSubjectService::getInstance()->getAllSubjectForCurrentStaff($request);
            foreach($subjects as $subject){
                $facultyUpdated = false;
                if(is_null($subject->valuationDetails)){
                    $subject->valuationDetails = $valuationProperties;
                }
                else{
                    $subject->valuationDetails = json_decode($subject->valuationDetails);
                    if(is_null($subject->valuationDetails->valuatedStaffs)){
                        $subject->valuationDetails->valuatedStaffs[] = $valuatedStaffs;
                    }
                    else{
                        foreach($subject->valuationDetails->valuatedStaffs as $valuatedStaff){
                            if($valuatedStaff->count == $request->currentValuationCount && $valuatedStaff->packetNo == $request->packetNo && $valuatedStaff->valuationStaffType == $request->valuationStaffType){
                                $valuatedStaff->staffId = $GLOBALS['userId'];
                                $valuatedStaff->markEntryStatus = $searchRequest->markEntryStatus;
                                $valuatedStaff->valuatedAnsweSheetCount = 0;
                                $facultyUpdated = true;
                            }
                        }
                        if(!$facultyUpdated){
                            $subject->valuationDetails->valuatedStaffs[] = $valuatedStaffs;
                        }
                    }
                }
                $updateSubjectValuationDetals = new \stdClass;
                $updateSubjectValuationDetals->assessmentId = $subject->assessmentId;
                $updateSubjectValuationDetals->valuationDetails = $subject->valuationDetails;
                $updateValuatedStaffValues[]=$updateSubjectValuationDetals;
            }
            if(!empty($updateValuatedStaffValues)){
                $this->updateValuatedStaffToExamRegistraionSubject($updateValuatedStaffValues);
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    
    
    public function printStudentStaffDetailsWithOrderForStaffSideMarkEntry($searchRequest)
    {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try
        {
            $response = new \stdClass;
            $request = new \stdClass;
            $currentStaffId = $GLOBALS['userId'];
            // $request->paperSubjectId = $searchRequest->paperSubjectId;
            $request->academicPaperSubjectIds = $searchRequest->paperSubjectId;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $request->packetNo = $searchRequest->packetNo;
            $response = $this->getAllStudentStaffDetailsWithOrderForStaffSideMarkEntry($request);
            $response->packetNo = $request->packetNo;
            $response->valuatedStudentsCount = count($response->valuatedStudents);
            $response->invaildAnswerScriptCount = $response->maxStudentsCount - $response->valuatedStudentsCount;
            $facultyIdArray[$currentStaffId] =$currentStaffId;
            $facultyIds = "sa.staffID = " .implode(" OR sa.staffID = ",$facultyIdArray);
            $faculties =  $this->getFacultiesByFacultyIds($facultyIds);
            foreach($faculties as $faculty)
            {
                $facultyNames[] =  $faculty->staffName;
            }
            $currentfacultyName = implode(" , ",$facultyNames);
            if(empty($response->valuatedStudents))
            {
                throw new ExamControllerException(ExamControllerException::NO_STUDENT_VALUATED_IN_THIS_PACKET,"No Students Valuated In This Packet");
            }
            else
            {
                if($response->subject->isChiefExaminer)
                {
                    $response->chiefExamaminer = $currentfacultyName;
                    if(!empty($response->subject->addiitonalExamniners))
                    {
                        $additionalFacultyIds = "sa.staffID = " .implode(" OR sa.staffID = ",$response->subject->addiitonalExamniners);
                        $additionalFaculties =  $this->getFacultiesByFacultyIds($additionalFacultyIds);
                        foreach($additionalFaculties as $faculty)
                        {
                            $additionalFacultyNames[] =  $faculty->staffName;
                        }
                        $response->additionalExaminer = implode(" , ",$additionalFacultyNames);
                    }
                }
                else
                {
                    $response->additionalExaminer = $currentfacultyName;
                }
                $additionalInfo = new \stdClass;
                $additionalInfo->collegeData = CommonExamService::getInstance()->getCollegeDetails();
                $templateName = "PrintValuatedStudentDetailsForEngineering";
                $responseHtml = TwigRenderer::renderTemplateFileToHtml(realpath(DOCUMENT_ROOT."../examcontroller-api/src/com/linways/web/templates/printTwigs/$templateName.twig"), [ 'response'=>$response , 'additionalInfo'=>$additionalInfo]);
                $prtContent = NULL;
                    $prtContent .= '<html><head>';
                    $prtContent .= "<style>
                        </style>";
                    $prtContent .= '</head><title>Student Mark Entry Report</title><body>';
                    $prtContent .= $responseHtml;
                    $prtContent .= '</body></html>';
                    $totalWidth = 210;
                    $totalHeight = 297;
                    $options = array(
                        'page-width'     => $totalWidth."mm",
                        'page-height'    => $totalHeight."mm",
                        'dpi'            => 96,
                        'margin-top' => "9mm",
                        'margin-left' => "1mm",
                        'margin-right' => "5mm",
                        'margin-bottom' => "9mm",
                        // 'binary' => "/usr/local/bin/wkhtmltopdf", // For Mac
                        'user-style-sheet' => realpath(DOCUMENT_ROOT . "/libcommon/bootstrap/css/bootstrap.min.css")
                    );
                $programResult = new \stdClass;
                $programResult->displayData = $responseHtml;
                $programResult->pdf = PdfUtil::renderPdf($prtContent, $options);
                return  $programResult;
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    /**
     * get All absent Students For Special Exam
     * @param $searchRequest 
     * @return $response 
     */
    public function getAllAbsentStudentDetailsForSpecialExam($searchRequest) {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $response = new \stdClass;
            $request = new \stdClass;
            $absentStudentDetails = [];
            $absentStudentDetailsArray = [];
            $request->regularExamGroupId = $searchRequest->regularExamGroupId;
            $request->regularExamRegstrationId = $searchRequest->regularExamRegstrationId;
            $request->regularExamAcademicTermId = $searchRequest->regularExamAcademicTermId;
            $request->SpecialExamRegstrationId = $searchRequest->SpecialExamRegstrationId;
            $studentsDetails = $this->getAllAbsentStudentDetails($request);
            if(empty($studentsDetails)){
                throw new ExamControllerException(ExamControllerException::NO_STUDENTS_ABSENT_IN_THIS_EXAM_REGISTRATION,"No Students Absent In Exam Registration");
            }
            else{
                foreach($studentsDetails as $student){
                    $absentStudentDetails[$student->studentId]->studentId = $student->studentId;
                    $absentStudentDetails[$student->studentId]->groupName = $student->groupName;
                    $absentStudentDetails[$student->studentId]->academicTerm = $student->academicTerm;
                    $absentStudentDetails[$student->studentId]->studentName = $student->studentName;
                    $absentStudentDetails[$student->studentId]->regNo = $student->regNo;
                    $absentStudentDetails[$student->studentId]->studentImage = $student->studentImage;
                    $absentStudentDetails[$student->studentId]->absentSubjects[$student->academicPaperSubjectId]->academicPaperSubjectId = $student->academicPaperSubjectId;
                    $absentStudentDetails[$student->studentId]->absentSubjects[$student->academicPaperSubjectId]->subjectCode = $student->subjectCode;
                    $absentStudentDetails[$student->studentId]->absentSubjects[$student->academicPaperSubjectId]->subjectName = $student->subjectName;
                    $absentStudentDetails[$student->studentId]->absentSubjects[$student->academicPaperSubjectId]->regularExamAssessmentId = $student->regularExamAssessmentId;
                    $absentStudentDetails[$student->studentId]->absentSubjects[$student->academicPaperSubjectId]->specialExamType = $student->specialExamType;
                    $absentStudentDetails[$student->studentId]->absentSubjects[$student->academicPaperSubjectId]->specialExamAssessmentId = $student->specialExamAssessmentId;
                    $absentStudentDetails[$student->studentId]->absentSubjects[$student->academicPaperSubjectId]->specialExamRegistrationId = $student->specialExamRegistrationId;
                    $absentStudentDetails[$student->studentId]->absentSubjects[$student->academicPaperSubjectId]->regularExamRegistrationId = $student->regularExamRegistrationId;
                    $absentStudentDetails[$student->studentId]->absentSubjects[$student->academicPaperSubjectId]->isAlreadyAssign = $student->isAlreadyAssign ? 1 : 0;
                }
                foreach($absentStudentDetails as $absentStudent){
                    $absentStudent->subjects=[];
                    foreach($absentStudent->absentSubjects as $subject){
                        $absentStudent->subjects[] = $subject;
                    }
                    $absentStudentDetailsArray[]=$absentStudent;
                }
            }
            $response->absentStudents = $absentStudentDetailsArray;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    /**
     * get All absent Students 
     * @param $searchRequest 
     * @return $response 
     */
    public function getAllAbsentStudentDetails($searchRequest) {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try
        {
            $query = "SELECT DISTINCT
                        sa.studentID as studentId,
                        sa.studentName,
                        spa.properties->>'$.registerNumber' as regNo,
                        sa.myImage as studentImage,
                        g.name as groupName,
                        act.name as academicTerm,
                        eerse.type as specialExamType,
                        eers.am_assessment_id as regularExamAssessmentId,
                        eersse.am_assessment_id as specialExamAssessmentId,
                        eerbse.ec_exam_registration_id as specialExamRegistrationId,
                        eerb.ec_exam_registration_id as regularExamRegistrationId,
                        eers.cm_academic_paper_subjects_id as academicPaperSubjectId,
                        s.code as subjectCode,
                        s.name as subjectName,
                        esarse.id AS isAlreadyAssign
                    FROM
                        ec_exam_registration_batch eerb
                    INNER JOIN ec_exam_registration_subject eers ON
                        eers.ec_exam_registration_batch_id = eerb.id
                    INNER JOIN oe_student_total_mark ostm ON
                        ostm.am_assessment_id = eers.am_assessment_id AND ostm.attendance_status = 'ABSENT'
                    INNER JOIN studentaccount sa ON 
                        sa.studentID = ostm.student_id
                    INNER JOIN  cm_academic_paper_subjects aps ON 
                        eers.cm_academic_paper_subjects_id = aps.id
                    INNER JOIN  v4_ams_subject s ON 
                        aps.ams_subject_id = s.id
                    INNER JOIN  `groups` g ON 
                        g.id = eerb.groups_id
                    INNER JOIN program p ON 
                        p.id = g.properties->>'$.programId'
                    INNER JOIN student_program_account spa ON 
                        spa.student_id  = sa.studentID AND
                        spa.current_program_id = p.id 
                    INNER JOIN  academic_term act ON 
                        act.id = CAST(eerb.properties ->> '$.academicTermId'AS CHAR)
                    INNER JOIN ec_exam_registration eerse ON
                        eerse.id = '$searchRequest->SpecialExamRegstrationId'
                    INNER JOIN ec_exam_registration_batch eerbse ON
                        eerbse.groups_id = '$searchRequest->regularExamGroupId' AND eerbse.ec_exam_registration_id = '$searchRequest->SpecialExamRegstrationId' AND CAST(eerb.properties ->> '$.academicTermId'AS CHAR) = '$searchRequest->regularExamAcademicTermId'
                    INNER JOIN ec_exam_registration_subject eersse ON
                        eersse.ec_exam_registration_batch_id = eerbse.id AND eersse.cm_academic_paper_subjects_id = eers.cm_academic_paper_subjects_id
                    LEFT JOIN ec_student_assessment_registration esarse ON
                        esarse.student_id = ostm.student_id AND esarse.am_assessment_id = eersse.am_assessment_id
                    WHERE
                        eerb.groups_id = '$searchRequest->regularExamGroupId' AND eerb.ec_exam_registration_id = '$searchRequest->regularExamRegstrationId' AND CAST(eerb.properties ->> '$.academicTermId'AS CHAR) = '$searchRequest->regularExamAcademicTermId";
            $absentStudentsDetails = $this->executeQueryForList($query);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $absentStudentsDetails;
    }
     /**
     * Assign Students For Special Exam
     * @param $searchRequest 
     * @return $response 
     */
    public function assignStudentsToSpecialExam($searchRequest) {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $response = new \stdClass;
            $properties = new \Stdclass();
            $properties->registrationStatus = "NOT_REGISTERED";
            $properties->isSpecialExamAssigned = "1";
            $properties = !empty($properties) ? "'" . json_encode($properties) . "'" : "NULL";
            $adminId = $GLOBALS['userId'];
            $students =json_decode(json_encode($searchRequest->students));
            $insertStudentAssessmentTableArray = [];
            $insertExamRegistrationMappingArray = [];
            if(!empty($students)){
                foreach($students as $student){
                    foreach($student->subjects as $subject){
                        if($subject->specialExamAssessmentId && $subject->specialExamRegistrationId && $subject->regularExamRegistrationId ){
                            if($subject->isInsert){
                                $studentAssessmentTableObj = new \stdClass;
                                $studentAssessmentTableObj->assessmentId = $subject->specialExamAssessmentId;
                                $studentAssessmentTableObj->examRegistrationType = $subject->specialExamType;
                                $studentAssessmentTableObj->studentId = $student->studentId;
                                $studentAssessmentTableObj->properties = $properties;
                                $insertStudentAssessmentTableArray[] = $studentAssessmentTableObj;
                                $insertExamRegistrationMappingArray[] = " ( '$subject->specialExamRegistrationId','$subject->regularExamRegistrationId','".$adminId."', utc_timestamp(), '".$adminId."', utc_timestamp() ) ";
                            }
                        }
                    }
                }
                if( !empty ( $insertStudentAssessmentTableArray ) )
                {
                    $this->insertStudentAssessmentResistrationDetails($insertStudentAssessmentTableArray);
                }
                if( !empty ( $insertExamRegistrationMappingArray ) )
                {
                    $this->insertExamRegistrationRetestMappingDetails($insertExamRegistrationMappingArray);
                }
            }
            
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
     /**
     * Remove Students For Special Exam
     * @param $searchRequest 
     * @return $response 
     */
    public function removeStudentsToSpecialExam($searchRequest) {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $response = new \stdClass;
            $students =json_decode(json_encode($searchRequest->students));
            $deleteStudentAssessmentTableArray = [];
            if(!empty($students)){
                foreach($students as $student){
                    foreach($student->subjects as $subject){
                        if($subject->specialExamAssessmentId && $subject->specialExamRegistrationId && $subject->regularExamRegistrationId ){
                            if($subject->isRemove){
                                $deleteStudentAssessmentTableArray[] = "( am_assessment_id = '$subject->specialExamAssessmentId' AND student_id = '$student->studentId') ";
                            }
                        }
                    }
                }
                if( !empty ( $deleteStudentAssessmentTableArray ) )
                {
                    $this->deleteStudentAssessmentResistrationDetails($deleteStudentAssessmentTableArray);
                }
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
     /**
     * insert Student Assessment Registration Details
     * @param  $insertionValues
     */
    public function insertStudentAssessmentResistrationDetails($insertionValues){
        try{
            $adminId = $GLOBALS['userId'];
            foreach($insertionValues as $insertionObj){
                $id = SecurityUtils::getRandomString();
                $insert_query = "INSERT INTO ec_student_assessment_registration
                                    (id,am_assessment_id,student_id,ec_exam_registration_type,properties,created_by,created_date,updated_by,updated_date)
                                    VALUES ('$id','$insertionObj->assessmentId','$insertionObj->studentId','$insertionObj->examRegistrationType',$insertionObj->properties,'$adminId',now(),'$adminId',now()) ON DUPLICATE KEY UPDATE updated_by = VALUES(created_by)";
                $this->executeQuery($insert_query);
            }
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * insert Exam Registration Mapping
     * @param  $insertionValues
     */
    public function insertExamRegistrationRetestMappingDetails($insertionValues){
        try {
            $insert_query = "INSERT INTO ec_exam_registration_retest_mapping
                                (ec_exam_registration_id,retest_exam_registration_id,created_by,created_date,updated_by,updated_date)
                                VALUES " . implode ( ",", $insertionValues ) . " ON DUPLICATE KEY UPDATE updated_by = VALUES(created_by)" ;
            $this->executeQuery($insert_query);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * Delete Student Assessment Registration Details
     * @param  $deleteThirdValStudent
     */
    public function deleteStudentAssessmentResistrationDetails($deleteStudentAssessmentTableArray){
        try{
            $sql_delete_query = "DELETE FROM 
                                    ec_student_assessment_registration
                                 WHERE " . implode ( " OR ", $deleteStudentAssessmentTableArray);
            $this->executeQuery($sql_delete_query);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    
    public function getAllStudentStaffDetailsWithOrderForStaffSideRevaluationMarkEntry($searchRequest)
    {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try
        {
            $response = new \stdClass;
            $request = new \stdClass;
            $request->paperSubjectId = $searchRequest->paperSubjectId;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $currentValuationCount = (int)$request->currentValuationCount ;
            $today = date("Y-m-d H:i");
            $isChiefExaminer = 0;
            $studentMarkDetails = [];
            $thirdValuatedStudentMarkDetails = [];
            $valuatedStudents = [];
            $isAdditonalExamniner = 0;
            $currentStaffId = $GLOBALS['userId'];
            $currentSubject = ExamRegistrationSubjectService::getInstance()->getcurrentExamSubjectForCurrentStaff($request);
            if($currentSubject){
                $currentSubject->isConfiremed = "";
                $currentSubject->isPrint = 1;
                $currentSubject->assessmentProperties = json_decode($currentSubject->assessmentProperties);
                $currentSubject->valuationDetails = json_decode($currentSubject->valuationDetails);
                $currentSubject->examDate = $currentSubject->assessmentProperties->assessmentDate;
                $currentSubject->errorMessage = null;
                $currentSubject->isConfiremed = "";
                $currentSubject->externalMaxMark = (int)$currentSubject->externalMaxMark;
                $currentSubject->valuationCount = $searchRequest->currentValuationCount;
                $markDetailsRequest = new ExamUserMarkRequest();
                $markDetailsRequest->assessmentId = $currentSubject->assessmentId;
                $markDetailsRequest->valuationCount = $currentSubject->valuationCount;
                $markDetailsRequest->valuationType = $searchRequest->valuationType;
                foreach($currentSubject->valuationDetails->valuationDates as $valuationDate)
                {
                    if($valuationDate->count == $searchRequest->currentValuationCount){
                        $currentSubject->valuationStartDate = $valuationDate->startDate;
                        $currentSubject->valuationEndDate = $valuationDate->endDate;
                        if(strtotime($today) < strtotime($currentSubject->valuationStartDate)){
                            $currentSubject->errorMessage = "Valuation Not Started";
                        }
                        else if((strtotime($today) > strtotime($currentSubject->valuationEndDate))){
                            $currentSubject->errorMessage = "Valuation Date Expired";
                        }
                        else{
                            foreach($currentSubject->valuationDetails->valuationStaffs as $valuationStaffs){
                                if($valuationStaffs->count == $request->currentValuationCount ){
                                    foreach($valuationStaffs->chiefExaminer as $chiefExaminer){
                                        if($chiefExaminer == $GLOBALS['userId']){
                                            $studentMarkDetails = ExamUserMarkService::getInstance()->getExamUserTotalMark($markDetailsRequest);
                                            break;
                                        }
                                    }
                                    foreach($valuationStaffs->addiitonalExamniners as $addiitonalExamniners){
                                        $currentSubject->addiitonalExamniners[] = $addiitonalExamniners;
                                        if($addiitonalExamniners == $GLOBALS['userId']){
                                            $studentMarkDetails = ExamUserMarkService::getInstance()->getExamUserTotalMark($markDetailsRequest);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        break;
                    }
                }
            }
            else {
                $currentSubject->errorMessage = "Permission Denied";
            }
            $response->studentsCount = count($studentMarkDetails);
            $response->subject = $currentSubject;
            $response->studentMarkDetails = $studentMarkDetails;
            $response->currentValuationCount = $searchRequest->currentValuationCount;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
     /**
     * get All Avilabele Student Details
     * @param $searchRequest 
     * @return $response 
     */
    public function getAllAvailableStudentDetails($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        $getAllFacultiesRequest = new GetAllFacultiesRequest;
        try{
            $searchRuleRequest = new SearchRuleRequest;
            $searchRuleRequest->name = "EXAM_VALUATION_PROCEDURE_RULE";
            $examValuationProcedureRule = reset(RuleService::getInstance()->searchRule($searchRuleRequest))->rule;
            $response = new \stdClass;
            $getAllFacultiesRequest->id = $searchRequest->staffId;
            $currentSubjectDetails =  new \stdClass;
            $searchRequest->fetchThirdValuationStudentsOnly = $searchRequest->valuationCount == '3' ? true : false;
            $currentStaffDetails = reset(StaffService::getInstance()->getAllFacultiesForApi($getAllFacultiesRequest));
            if($searchRequest->examType == "REVALUATION"){
                $searchRequest->fetchThirdValuationStudentsOnly = $searchRequest->valuationCount == '2' ? true : false;
                $studentDetails = StudentExamRegistrationService::getInstance()->getRevaluationRegisteredStudentsValuationDetails($searchRequest);
            }
            else{
                $studentDetails = StudentExamRegistrationService::getInstance()->getRegisteredStudentsValuationDetails($searchRequest);
            }
            if(empty($studentDetails) && !$searchRequest->notCheckEmpty){
                throw new ExamControllerException(ExamControllerException::NO_STUDENTS_REGISTEDED_OR_PAID,"No Students Found");
            }
            $currentSubjectDetails->code = reset($studentDetails)->subjectCode;
            $currentSubjectDetails->name = reset($studentDetails)->subjectName;
            foreach($studentDetails as $student){
                $student->isAlreadyAssigned = false;
                $student->isSelected = false;
                $student->valuationDetails = empty($student->valuationDetails) ? null : json_decode($student->valuationDetails);
                if($student->valuationDetails){
                    $currentValuationStaffDetails = reset(array_filter($student->valuationDetails->assignedValuationStaffs,function($value)use($searchRequest){
                        return $value->count == $searchRequest->valuationCount;
                    }));
                    if(!empty($currentValuationStaffDetails->addiitonalExamniners)){
                        if(!in_array($searchRequest->staffId,$currentValuationStaffDetails->addiitonalExamniners)){
                            $student->isAlreadyAssigned = true;
                            $student->isSelected = false;
                        }
                        else{
                            $student->isAlreadyAssigned = false;
                            $student->isSelected = true;
                        }
                       
                    }
                    //if chief examiner choosed a valuer ,filter out that valuer students from the list
                    if($searchRequest->additionalExaminer && !$student->isAlreadyAssigned){
                        $additionalExaminerDetails = reset(array_filter($student->valuationDetails->assignedValuationStaffs,function($value)use($searchRequest){
                            return $value->count == 1;
                        }));
                        if(!empty($additionalExaminerDetails->addiitonalExamniners)){
                            if(in_array($searchRequest->additionalExaminer,$additionalExaminerDetails->addiitonalExamniners)){
                                //only selectedAdditionalExaminerStudent will be filtererd in
                                $student->selectedAdditionalExaminerStudent = true;
                            }
                        }
                    }
                }
            }
            $studentDetails = array_values($studentDetails);
            $selectedStudents = array_filter($studentDetails,function($value){
                return  $value->isSelected == true;
            });
            $response->isAllSelected = count($studentDetails) == count($selectedStudents) ? true : false;
            $availableStudents = array_filter($studentDetails,function($value){
                return $value->isAlreadyAssigned == false;
            });
            $selectedStudents = array_filter($studentDetails,function($value){
                return $value->isSelected == true;
            });
            //filter available students further
            if($searchRequest->additionalExaminer){
                $availableStudents = array_filter($availableStudents,function($value){
                    return $value->selectedAdditionalExaminerStudent == true;
                });
            }
            if($examValuationProcedureRule->showOnlyFalseNumberInAssignStudents){
                $availableStudents = array_filter($availableStudents,function($value){
                    return $value->falseNo;
                });
            }
            $availableStudents = $availableStudents ? array_values($availableStudents) : [];
             //sorting student list befor adding slno
            if($searchRequest->studentListOrderBy){
                usort($availableStudents, function($a, $b) use ($searchRequest) {
                    return ($a->{$searchRequest->studentListOrderBy} > $b->{$searchRequest->studentListOrderBy}); 
                });
            }
            //adding a slNo to students as a final step
            $response->students = $this->assignSlNo($availableStudents);
            $response->countOfAssignedStudents = count($selectedStudents);
            $response->subject = $currentSubjectDetails;
            $response->staff = $currentStaffDetails;
            
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    //assign slNo to students
    public function assignSlNo($studentList)
    {
        $counter = 1;
        foreach ($studentList as $obj) {
            $obj->slNo = $counter++;
        }
        return $studentList;
    }
    
     /**
     * get all defined valuation rules
     * @throws ProfessionalException
     */
    public function getAllValuationRule()
    {
        try {
            $sql = "SELECT
                        evr.id,
                        evr.name,
                        evr.code,
                        evr.properties ->> '$.valuationCount' as valuationCount,
                        evr.properties as properties
                    FROM
                        `ec_valuation_rules` evr
                    WHERE 1=1";
            $result = $this->executeQueryForList($sql);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getMessage(), $e->getCode());
        }
        return $result;
    }
    public function getFinalizedMarkFromValuationRule($studentMark, $valuationCode,$isExcatFinalizeMark = false,$examValuationProcedureRule = null){
        switch ($valuationCode) {
            case 'AVERAGE_MARK':
                $finalizedMark = $isExcatFinalizeMark ? array_sum($studentMark) / count($studentMark) : round(array_sum($studentMark) / count($studentMark));
                break;
            case 'HIGHEST_MARK':
                $finalizedMark = max( $studentMark );
                break;
            case 'NEAREST_OF_TWO':
                $diff_01 = abs ( $studentMark[0] - $studentMark[1] );
                $diff_12 = abs ( $studentMark[1] - $studentMark[2] );
                $diff_02 = abs ( $studentMark[0] - $studentMark[2] );
                $lowestVal = min( $diff_01, $diff_12, $diff_02);
                if( $diff_01 == $lowestVal ){
                    $finalizedMark = ($studentMark[0]+ $studentMark[1])/2;
                }
                else if( $diff_12 == $lowestVal ){
                    $finalizedMark = ($studentMark[1] + $studentMark[2])/2;
                }
                else {
                    $finalizedMark = ($studentMark[0]+ $studentMark[2])/2;
                }
                $finalizedMark = $isExcatFinalizeMark ? $finalizedMark : round( $finalizedMark );
                break;
            case 'BEST_OF_TWO':
                $arrayForSort = [$studentMark[0], $studentMark[1], $studentMark[2]];
                rsort($arrayForSort);
                $averageOfTwo = array_slice($arrayForSort, 0, 2);
                $finalizedMark = $isExcatFinalizeMark ? array_sum($averageOfTwo) / 2 : round(array_sum($averageOfTwo) / 2);
                break;
            case 'CHEIF_VALUER_MARK':
                $finalizedMark = $isExcatFinalizeMark ? $studentMark[1] : $studentMark[1];
                // can be written at the end if needed as of now it will work for case 'CHEIF_VALUER_MARK'
                switch ($examValuationProcedureRule->finalizedMarkRoundOffType) {
                    case 'CEIL':
                        $finalizedMark = ceil($finalizedMark);
                        break;
                    default:
                        $finalizedMark = $isExcatFinalizeMark ? round($finalizedMark): $finalizedMark;
                        break;
                }
                break;
            case 'SINGLE_EVALUATION':
                $finalizedMark = $isExcatFinalizeMark ? $studentMark[0] : round($studentMark[0]);
                break;
        }
        return $finalizedMark;
    }
    /**
     * Get mark difference threshold value by courseTypeId
     * @param Integer $courseTypeId
     * @return Integer $markDiff
     * @throws ExamControllerException
     */
    public function getExternalValuationMarkDifference($courseTypeId)
    {
        $courseTypeId = $this->realEscapeString($courseTypeId);
        $markDiff = null;
        try {
            $sql = "SELECT 
                        courseTypeID, 
                        markdiff AS markDiff,
                        properties ->> '$.scheme' as scheme
                    FROM 
                        externalexam_thirdvalmarkdiff 
                    WHERE
                        courseTypeID = '$courseTypeId";
            $markDiff = $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
        return $markDiff;
    }
    /**
     * count Of Evaluated Students By Online Exam
     * @param Object $request
     * @return Integer $countOfEvaluatedStudents
     * @throws ExamControllerException
     */
    public function countOfEvaluatedStudentsByOnlineExam($request){
        try {
            $request = $this->realEscapeObject($request);
            $whereQuery = "";
            if(!empty($request->onlineExamId)) {
                $onlineExamIdString = is_array($request->onlineExamId) ? "'" . implode("','",$request->onlineExamId) . "'" : "'".$request->onlineExamId."'";
                $whereQuery .= " AND oeum.oe_exams_id IN ( $onlineExamIdString )";
            }
            // if(!empty($request->staffId)){
            //     $whereQuery .= " AND oeum.created_by = '$request->staffId' ";
            // }
            if(!empty($request->valuationCount)){
                $whereQuery .= " AND JSON_EXTRACT(oeum.valuation_marks,'$."   .'"'.$request->valuationCount.'"'."') IS NOT NULL ";
            }
            if(!empty($request->studentId)){
                $whereQuery .= " AND oeum.user_id = '$request->studentId";
            }
            $sql = "SELECT 
                        DISTINCT oeum.user_id as studentId,
                        oeum.valuation_marks as valuationDetails
                    FROM 
                        oe_exam_user_mark oeum 
                    WHERE
                        oeum.user_type = 'STUDENT' ";
            $studentDetails = $this->executeQueryForList($sql.$whereQuery);
            $evaluvatedStudents = [];
            foreach($studentDetails as $student){
                $student->valuationDetails = (array)json_decode($student->valuationDetails);
                if($student->valuationDetails[$request->valuationCount]->staffId == $request->staffId){
                    $evaluvatedStudents[$student->studentId] = $student->studentId;
                }
                
            }
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
        return count($evaluvatedStudents);
    }
    /**
     * check If Mark Confirm For Digital Valuation
     * @param Object $request
     * @return Object $markConfirm
     * @throws ExamControllerException
     */
    public function checkIfMarkConfirmForDigitalValuation($request){
        try {
            $request = $this->realEscapeObject($request);
            $whereQuery = "";
            if(!empty($request->onlineExamId)) {
                $onlineExamIdString = is_array($request->onlineExamId) ? "'" . implode("','",$request->onlineExamId) . "'" : "'".$request->onlineExamId."'";
                $whereQuery .= " AND oemc.oe_exams_id IN ( $onlineExamIdString )";
            }
            if(!empty($request->valuationCount)){
                $whereQuery .= " AND oemc.valuation_count = '$request->valuationCount";
            }
            if(!empty($request->isReviewer)){
                $whereQuery .= " AND oemc.review_id IS NOT NULL ";
            }
            else{
                $whereQuery .= " AND oemc.review_id IS NULL ";
            }
            if(!empty($request->studentId)){
                $whereQuery .= " AND oemc.oe_users_id = '$request->studentId";
            }
            if(!empty($request->revaluationType)){
                $whereQuery .= " AND oemc.revaluation_id = '$request->revaluationType";
            }
            
            $sql = "SELECT 
                        oemc.id,oemc.is_confirmed as markConfirm,oemc.exam_mark as mark
                    FROM 
                        oe_exam_marks_confirm oemc 
                    WHERE
                        1=1 AND oemc.is_confirmed = '1' ";
            $markConfirm = $this->executeQueryForObject($sql.$whereQuery);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
        return $markConfirm;
    }
     /**
     * get Subjects For Staff Side Mark Entry Revaluation
     * @return staffDetails details
     */
    public function getSubjectsForStaffSideMarkEntryRevaluation($searchRequest)
    {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try
        {
           // $isCentralizedSession is false for now becaue of college requirement (SJU )
            $isCentralizedSession =  false; 
            $staffSideMarkEntryUItype = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::STAFF_SIDE_MARK_ENTRY_UI_FORMAT);
            $response = new \stdClass;
            $request = new \stdClass;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $request->currentRevaluationType = $searchRequest->currentRevaluationType;
            $isQPCodeDisplayInStaffSideMarkEntry = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::IS_DISPALY_QP_CODE_IN_STAFF_SIDE_MARK_ENTRY);
            // $request->batchOrSubjectWise = "BATCH_WISE";
            $request->batchOrSubjectWise = "SUBJECT_WISE";
            $today = date("Y-m-d H:i");
            $assignedSubjects = ExamRegistrationSubjectService::getInstance()->getSubjectForCurrentStaffsRevaluation($request);
            if($request->batchOrSubjectWise == "SUBJECT_WISE"){
                foreach($assignedSubjects as $subject){
                    $subject->isExpand = false;
                    $subject->valuationDetails = json_decode($subject->valuationDetails);
                    $subject->errorMessage = null;
                    $subject->errorMessageInfo = null;
                    if($isCentralizedSession){
                        $subject->errorMessage = "Permission denied";
                        $subject->errorMessageInfo = "You can't view mark entry using centralized session.";
                    }
                    else{
                        $valuationDate = reset(array_filter($subject->valuationDetails->reValuationDates,function($value)use($searchRequest){
                            return $value->count == $searchRequest->currentValuationCount && $value->revaluationType == $searchRequest->currentRevaluationType;
                        }));
                        if(!empty($valuationDate)){
                            $subject->valuationStartDate = $valuationDate->startDate;
                            $subject->valuationEndDate = $valuationDate->endDate;
                            if(strtotime($today) < strtotime($subject->valuationStartDate)){
                                $subject->errorMessage = "Valuation Start On ".date("d-m-Y h:i A", strtotime($valuationDate->startDate));
                            }
                            else if(strtotime($today) > strtotime($subject->valuationEndDate)){
                                $subject->errorMessage = "Valuation Date Expired";
                            }
                            else if($staffSideMarkEntryUItype == 'DIGITAL_VALUATION' && $subject->isValidatedDetails){
                                foreach($subject->isValidatedDetails as $isValidated){
                                    if($isValidated == '0' || $isValidated == 0){
                                        $subject->errorMessage = "Exam Not Validated";
                                        $subject->errorMessageInfo = " Valuation blocked. Contact Exam Administration Team to get the exam validated and continue";
                                    }
                                }
                            }
                        }
                        else{
                            $subject->errorMessage = "Valuation not configured";
                        }
                    }
                    if ( $staffSideMarkEntryUItype == "NO_PREFETCH_STUDENTS" || $staffSideMarkEntryUItype == "STUDENT_WITH_PACKET" || $staffSideMarkEntryUItype == 'DIGITAL_VALUATION'){
                        if( $subjectArray[$subject->subjectId]){
                            $subjectArray[$subject->subjectId]->subjectIdArr[] = $subject->academicPaperSubjectId;
                        }
                        else{
                            $subject->subjectIdArr[] = $subject->academicPaperSubjectId;
                            $subjectArray[$subject->subjectId] = $subject;
                        }
                    }
                    $requestForPapersEvaluated = new \stdClass;
                    $requestForPapersEvaluated->onlineExamId = $subject->onlineExamId;
                    $requestForPapersEvaluated->valuationCount = $searchRequest->currentValuationCount;
                    $requestForPapersEvaluated->revaluationType = $searchRequest->currentRevaluationType;
                    $requestForPapersEvaluated->staffId = $GLOBALS['userId'];
                    // $subject->papersEvaluvated = $this->countOfEvaluatedStudentsByOnlineExam($requestForPapersEvaluated);
                    $subject->papersEvaluvated = '-';
                }
            }
            $response->staffSideMarkEntryUItype = $staffSideMarkEntryUItype;
            if ( $staffSideMarkEntryUItype == "NO_PREFETCH_STUDENTS"  || $staffSideMarkEntryUItype == "STUDENT_WITH_PACKET" || $staffSideMarkEntryUItype == 'DIGITAL_VALUATION'){
                $response->subjects = array_values($subjectArray);
            }
            else{
                $response->subjects = $assignedSubjects;
            }
            // $response->subjects = $assignedSubjects;
            $response->batchOrSubjectWise = $request->batchOrSubjectWise;
            $response->currentValuationCount = $searchRequest->currentValuationCount;
            $response->isQPCodeDisplay = $isQPCodeDisplayInStaffSideMarkEntry;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
     
        return $response;
    }
     /**
     * get Subjects For Staff Side Mark Entry Digital Valuation Revaluation
     * @return staffDetails details
     */
    public function getSubjectDetailsForStaffSideMarkEntryDigitalValuationRevaluation($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $showStudentsByFalseNumber = (int)CommonService::getInstance()->getSettings(SettingsConstents::EXAM_CONTROLLER, SettingsConstents::SHOW_STUDENTS_FOR_VALUATION_BY_FALSE_NUMBER);
            $registeredStudents = [];
            $enableValuatedCountCheck = NULL;
            $response = new \stdClass;
            $request = new \stdClass;
            $searchRequest->paperSubjectId = (array) $searchRequest->paperSubjectIdArr ? $searchRequest->paperSubjectIdArr : $searchRequest->paperSubjectId;
            $request->paperSubjectId = $searchRequest->paperSubjectId;
            $request->paperSubjectId = $searchRequest->paperSubjectId;
            $request->academicPaperSubjectIds = $searchRequest->paperSubjectId;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $request->currentRevaluationType = $searchRequest->currentRevaluationType;
            $request->revaluationType = $searchRequest->currentRevaluationType;
            $request->valuationCount = $searchRequest->currentValuationCount;
            $today = date("Y-m-d H:i");
            $assignedSubjects = ExamRegistrationSubjectService::getInstance()->getSubjectForCurrentStaffsRevaluation($request);
            $currentSubject = reset(array_filter($assignedSubjects,function($value)use($request){
                return in_array($value->academicPaperSubjectId,$request->paperSubjectId);
            }));
            // $currentSubject = ExamRegistrationSubjectService::getInstance()->getcurrentExamSubjectForCurrentStaffRevaluation($request);
            $studentIdentifier = $showStudentsByFalseNumber ? "falseNumber" : "registerNo";
            $studentIdentifierForPath = $showStudentsByFalseNumber ? "flNo" : "rgNo";
            if($currentSubject){
                $currentSubject->assessmentProperties = json_decode($currentSubject->assessmentProperties);
                $currentSubject->valuationDetails = json_decode($currentSubject->valuationDetails);
                $currentSubject->examDate = $currentSubject->assessmentProperties->assessmentDate;
                $currentSubject->errorMessage = null;
                $currentSubject->isConfiremed = "";
                $currentSubject->externalMaxMark = (int)$currentSubject->externalMaxMark;
                $currentSubject->valuationCount = $searchRequest->currentValuationCount;
                $currentValuationDateDetails = reset(array_filter($currentSubject->valuationDetails->reValuationDates,function($value)use($searchRequest){
                    return $value->count == $searchRequest->currentValuationCount;
                }));
                if(!empty($currentValuationDateDetails)){
                    $currentSubject->valuationStartDate = $currentValuationDateDetails->startDate;
                    $currentSubject->valuationEndDate = $currentValuationDateDetails->endDate;
                    if(strtotime($today) < strtotime($currentSubject->valuationStartDate)){
                        $currentSubject->errorMessage = "Valuation Not Started";
                    }
                    else if((strtotime($today) > strtotime($currentSubject->valuationEndDate))){
                        $currentSubject->errorMessage = "Valuation Date Expired";
                    }
                }
            }
            if(empty($currentSubject) || $currentSubject->errorMessage != null) {
                $registeredStudents = [];
            }
            else{
                if($showStudentsByFalseNumber){
                    $request->falseNoRegNoStatus = "falseNumber";
                }
                else{
                    $request->falseNoRegNoStatus = "registerNo";
                }
                $studentDetails = StudentExamRegistrationService::getInstance()->getRevaluationRegisteredStudentsValuationDetails($request);
                foreach($studentDetails as $student){
                    $requestForMarkConfirm = new \stdClass;
                    $requestForMarkConfirm->onlineExamId = $currentSubject->onlineExamId;
                    $requestForMarkConfirm->valuationCount = $searchRequest->currentValuationCount;
                    $requestForMarkConfirm->revaluationType = $searchRequest->currentRevaluationType;
                    $requestForMarkConfirm->studentId = $student->studentId;
                    $requestForMarkConfirm->staffId = $GLOBALS['userId'];
                    $student->markConfirmObj = $this->checkIfMarkConfirmForDigitalValuation($requestForMarkConfirm);
                    $student->isMarkConfirm = !empty($student->markConfirmObj) ? '1' : '0';
                    if($student->isMarkConfirm != '1'){
                        $requestForPapersEvaluated = new \stdClass;
                        $requestForPapersEvaluated->onlineExamId = $currentSubject->onlineExamId;
                        $requestForPapersEvaluated->valuationCount = $searchRequest->currentValuationCount;
                        $requestForPapersEvaluated->studentId = $student->studentId;
                        $requestForPapersEvaluated->staffId = $GLOBALS['userId'];
                        $student->papersEvaluvated = (int)$this->countOfEvaluatedStudentsByOnlineExam($requestForPapersEvaluated);
                        $student->markEntryStarted = $student->papersEvaluvated > 0 ? 1 : 0;
                    }
                    $student->filePath = "examId=".$student->assessmentId. "&vlc=". $request->valuationCount."&". $studentIdentifierForPath."=". $student->$studentIdentifier."&rvlId=". $request->currentRevaluationType;
                    $student->valuationDetails = empty($student->valuationDetails) ? null : json_decode($student->valuationDetails);
                    if($student->valuationDetails){
                        $currentValuationStaffDetails = reset(array_filter($student->valuationDetails->assignedValuationStaffs,function($value)use($searchRequest){
                            return $value->count == $searchRequest->currentValuationCount;
                        }));
                        if(!empty($currentValuationStaffDetails->addiitonalExamniners)){
                            if(in_array($searchRequest->staffId,$currentValuationStaffDetails->addiitonalExamniners)){
                                $registeredStudents[] = $student;
                            }
                            
                        
                        }
                    }
                }
            }
            $response->subject = $currentSubject;
            $response->students = $registeredStudents;
            $response->showStudentsByFalseNumber = $showStudentsByFalseNumber;
            $response->currentValuationCount = $searchRequest->currentValuationCount;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
        /**
     * get Mark Log Report
     * @param $searchRequest 
     * @return $response 
     */
    public function getMarkLogReport($searchRequest) {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $markLogRequest = new \stdClass;
            $markLogRequest->startDate = $searchRequest->startDate;
            $markLogRequest->endDate = $searchRequest->endDate;
            $markLogs = $this->getExternalMarkLogReport($markLogRequest);
            if(empty($markLogs)){
                throw new ExamControllerException(ExamControllerException::NO_REPORTS_DETAILS_FOUND,"No Mark log found.");
            }
            $markLogsArray = [];
            $getAllFacultiesRequest = new GetAllFacultiesRequest;
            $staffs = StaffService::getInstance()->getAllFacultiesForApi($getAllFacultiesRequest);
            $allStaffs = [];
            foreach($staffs as $staff){
                $allStaffs[$staff->id] = $staff;
            }
            foreach($markLogs as $markLog){
                if($markLog->externalMarkLogs){
                    $logs = $markLog->externalMarkLogs;
                    usort($logs, function ($a, $b) {
                        return strtotime($a->actionTakenTime) < strtotime($b->actionTakenTime);
                    });
                    $markLog->logs = $logs;
                    foreach($logs as $log){
                        $log->actionDate = date("Y-m-d", (strtotime($log->actionTakenTime)));
                        $log->actionTakenDateTime = date("Y-m-d H:i", (strtotime($log->actionTakenTime)));
                        if(($log->actionDate >= $markLogRequest->startDate) && ($log->actionDate <= $markLogRequest->endDate)) {
                            $log->updatedStaffName =  $allStaffs[$log->updatedStaffId]->name;
                            // $markLog->log = $log;
                            $markLogDetails = new \stdClass;
                            $markLogDetails->studentId = $markLog->studentId;
                            $markLogDetails->studentName = $markLog->studentName;
                            $markLogDetails->studentRegisterNo = $markLog->studentRegisterNo;
                            $markLogDetails->subjectCode = $markLog->subjectCode;
                            $markLogDetails->subjectName = $markLog->subjectName;
                            $markLogDetails->log = $log;
                            $markLogsArray[] = $markLogDetails;
                        }
                    }
                }
            }
            $templateName = "external_mark_log_report_template_1";
            $responseHtml = TwigRenderer::renderTemplateFileToHtml(realpath(DOCUMENT_ROOT."../examcontroller-api/src/com/linways/web/templates/markLogReport/$templateName.twig"), [ 'markLog'=>$markLogsArray ]);
            $prtContent = NULL;
                $prtContent .= '<html><head>';
                $prtContent .= "";
                $prtContent .= '</head><title>Extrenal mark log report</title><body>';
                $prtContent .= $responseHtml;
                $prtContent .= '</body></html>';
                $totalWidth = 210;
                $totalHeight = 297;
                $options = array(
                    'page-width'     => $totalHeight."mm",
                    'page-height'    => $totalWidth."mm",
                    'dpi'            => 96,
                    'margin-top' => "9mm",
                    'margin-left' => "1mm",
                    'margin-right' => "1mm",
                    'margin-bottom' => "9mm",
                    // 'binary' => "/usr/local/bin/wkhtmltopdf", // For Mac
                    'user-style-sheet' => realpath(DOCUMENT_ROOT . "/libcommon/bootstrap/css/bootstrap.min.css")
                );
            $programResult = new \stdClass;
            $programResult->dispalyHtmlData = $responseHtml;
            $programResult->studentsData = $markLogs;
            $programResult->printData = PdfUtil::renderPdf($prtContent, $options);
            
            
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return  $programResult;
    }
    /**
     * get External Mark Log Report
     * @param $searchRequest  
     * @author Krishnajith
     */
    public function getExternalMarkLogReport($searchRequest) {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $orderBy = " ORDER BY esmel.updated_date DESC";
            $whereQuery = "";
            if(!empty($searchRequest->startDate)) {
                $whereQuery .= " AND (DATE_FORMAT(esmel.created_date,'%Y-%m-%d') >= '$searchRequest->startDate' OR DATE_FORMAT(esmel.updated_date,'%Y-%m-%d') >= '$searchRequest->startDate') ";
            }
            if(!empty($searchRequest->endDate)) {
                $whereQuery .= " AND DATE_FORMAT(esmel.updated_date,'%Y-%m-%d') <= '$searchRequest->endDate'";
            }
            $query = "SELECT
                    DISTINCT sa.studentID as id,
                    sa.studentID as studentId, 
                    sa.studentName,
                    spa.properties->>'$.registerNumber' AS studentRegisterNo,
                    g.id AS groupId,
                    g.name AS groupName,
                    s.code as subjectCode,
                    s.name as subjectName,
                    esmel.log AS externalMarkLogs,
                    esar.am_assessment_id as assessmentId,
                    esar.properties ->> '$.isRevalued' as isRevalued,
                    esar.properties ->> '$.falseNo' as falseNo,
                    aps.properties ->> '$.isExternal' as isExternal,
                    aps.properties ->> '$.externalMaxMark' as maximumSubjectMark
                FROM
                    ec_student_assessment_registration esar
                INNER JOIN studentaccount sa ON 
                    sa.studentID = esar.student_id
                INNER JOIN ec_exam_registration_subject eers ON 
                    eers.am_assessment_id = esar.am_assessment_id
                INNER JOIN  cm_academic_paper_subjects aps ON 
                    aps.id = eers.cm_academic_paper_subjects_id
                INNER JOIN v4_ams_subject s ON 
                    s.id = aps.ams_subject_id
                INNER JOIN oe_exams oe ON
                        oe.assessment_id = eers.am_assessment_id AND oe.is_deleted = 0
                INNER JOIN ec_exam_registration_batch eerb ON
                    eerb.id = eers.ec_exam_registration_batch_id
                INNER JOIN ec_exam_registration eer ON
                    eer.id = eerb.ec_exam_registration_id
                INNER JOIN `groups` g ON
                        g.id = eerb.groups_id
                INNER JOIN program p ON 
                    p.id = g.properties->>'$.programId'
                INNER JOIN student_program_account spa ON 
                    spa.student_id  = esar.student_id  AND
                    spa.current_program_id = p.id 
                INNER JOIN ec_student_mark_edit_log esmel ON
                    esmel.student_id = sa.studentID AND
                    esmel.am_assessment_id = esar.am_assessment_id
                WHERE
                     CAST(esar.properties ->> '$.registrationStatus' AS CHAR) = 'REGISTERED' AND CAST(esar.properties ->> '$.feeStatus' AS CHAR) = 'PAID' AND esar.ec_exam_registration_type = eer.type";
            $externalMarkLogs = $this->executeQueryForList($query.$whereQuery.$orderBy);
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        array_walk($externalMarkLogs, function($externalMarkLog){
            $externalMarkLog->externalMarkLogs =  json_decode($externalMarkLog->externalMarkLogs);
        });
        return $externalMarkLogs;
    }
    /**
     * get All Student Valuation Mark For Digital Valuation
     * @param request $request
     * @return $studentsMarkDetails
     */
    public function getAllStudentValuationMarkForDigitalValuation($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        $whereQuery = "";
        try 
        {
            if(!empty($searchRequest->examRegistrationId)) {
                $examRegistrationIdString = is_array($searchRequest->examRegistrationId) ? "'" . implode("','",$searchRequest->examRegistrationId) . "'" : "'".$searchRequest->examRegistrationId."'";
                $whereQuery .= " AND eerb.ec_exam_registration_id IN ( $examRegistrationIdString )";
            }
            if(!empty($searchRequest->academicPaperSubjectId)) {
                $academicPaperSubjectIdString = is_array($searchRequest->academicPaperSubjectId) ? "'" . implode("','",$searchRequest->academicPaperSubjectId) . "'" : "'".$searchRequest->academicPaperSubjectId."'";
                $whereQuery .= " AND eers.cm_academic_paper_subjects_id IN ( $academicPaperSubjectIdString )";
            }
            $orderBy = " ORDER BY spa.properties->>'$.registerNumber' ASC ";
            $query = "SELECT
                        DISTINCT sa.studentID as id,
                        sa.studentID as studentId,
                        sa.studentName,
                        spa.properties->>'$.registerNumber' AS regNo,
                        esar.am_assessment_id as assessmentId,
                        esar.properties ->> '$.falseNo' as falseNo,
                        eerb.properties ->> '$.valuationRule' as valuationRule,
                        g.id as groupId,
                        g.name as groupName,
                        s.code as subjectCode,
                        s.name as subjectName,
                        eer.type as examRegistrationType,
                        oe.id as oeExamId,
                        oec1.is_confirmed as firstValuationConfirm,
                        oec1.exam_mark as firstValuationMark,
                        oec2.is_confirmed as secondValuationConfirm,
                        oec2.exam_mark as secondValuationMark,
                        oec3.is_confirmed as thirdValuationConfirm,
                        oec3.exam_mark as thirdValuationMark,
                        ostmf.mark_obtained as finalizedMark,
                        IF(ostmf.properties ->> '$.isNotConfirm' = true,0,1) as finalizedValuationConfirm,
                        ostmf.attendance_status as isAbsent,
                        caps.properties ->> '$.externalMaxMark' as externalMaxMark
                    FROM
                        ec_student_assessment_registration esar
                    INNER JOIN studentaccount sa ON 
                        sa.studentID = esar.student_id
                    INNER JOIN ec_exam_registration_subject eers ON 
                        eers.am_assessment_id = esar.am_assessment_id
                    INNER JOIN ec_exam_registration_batch eerb ON
                        eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer
                        ON eer.id = eerb.ec_exam_registration_id 
                    INNER JOIN cm_academic_paper_subjects caps ON
                        caps.id = eers.cm_academic_paper_subjects_id
                    INNER JOIN v4_ams_subject s ON 
                        s.id = caps.ams_subject_id
                    INNER JOIN `groups` g ON
                        g.id = eerb.groups_id
                        AND g.`type` = 'BATCH'
                    INNER JOIN program p ON 
                        p.id = g.properties->>'$.programId'
                    INNER JOIN student_program_account spa ON 
                        spa.current_program_id = p.id AND 
                        spa.student_id = esar.student_id 
                    INNER JOIN oe_exams oe ON 
                        JSON_UNQUOTE(JSON_EXTRACT(oe.identifying_context, '$.assessmentId')) = esar.am_assessment_id
                    LEFT JOIN oe_exam_marks_confirm oec1 ON oec1.oe_exams_id = oe.id AND oec1.oe_users_id = sa.studentID AND oec1.valuation_count = 1 AND (oec1.revaluation_id IS NULL OR oec1.revaluation_id = '') AND oec1.is_confirmed = '1'
                    LEFT JOIN oe_exam_marks_confirm oec2 ON oec2.oe_exams_id = oe.id AND oec2.oe_users_id = sa.studentID AND oec2.valuation_count = 2 AND (oec2.revaluation_id IS NULL OR oec2.revaluation_id = '') AND oec2.is_confirmed = '1'
                    LEFT JOIN oe_exam_marks_confirm oec3 ON oec3.oe_exams_id = oe.id AND oec3.oe_users_id = sa.studentID AND oec3.valuation_count = 3 AND (oec3.revaluation_id IS NULL OR oec3.revaluation_id = '') AND oec3.is_confirmed = '1'
                    LEFT JOIN oe_student_total_mark ostmf ON 
                        ostmf.student_id = sa.studentID AND ostmf.am_assessment_id = esar.am_assessment_id AND ostmf.valuation_count = 'FINALIZED' AND (ostmf.valuation_type IS NULL OR ostmf.valuation_type = '') 
                    WHERE
                        esar.ec_exam_registration_type = eer.type AND
                        esar.properties ->>'$.feeStatus' = 'PAID' AND 
                        esar.properties ->>'$.registrationStatus' = 'REGISTERED' 
                        AND (CAST(esar.properties ->> '$.syllabusSubType' AS CHAR) != 'MOOC' OR esar.properties ->> '$.syllabusSubType' IS NULL) ";
            $studentsMarkDetails = $this->executeQueryForList($query.$whereQuery.$orderBy);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $studentsMarkDetails;
    }
         /**
     * get Subjects For Remove Mark Entry Confirmed State
     * @return staffDetails details
     */
    public function getSubjectsForRemoveMarkEntryConfirmedState($searchRequest)
    {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try
        {
            $response = new \stdClass;
            $request = new \stdClass;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $request->subjectRequest = 1;
            $assignedSubjects = $this->getStudentsForRemoveConfirmedState($request);
            $subjectArray = [];
            foreach($assignedSubjects as $student){
                $subjectArray[$student->subjectCode]->subjectCode = $student->subjectCode;
                $subjectArray[$student->subjectCode]->subjectName = $student->subjectName;
                $subjectArray[$student->subjectCode]->assessmentId[$student->assessmentId] = $student->assessmentId;
            }
            $response->subjects = array_values($subjectArray);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    public function getStudentsForRemoveMarkEntryConfirmedState($searchRequest)
    {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try
        {
            $response = new \stdClass;
            $request = new \stdClass;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $request->assessmentId = (array) $searchRequest->subject->assessmentId;
            $request->falseNoRequired = 1;
            $students = $this->getStudentsForRemoveConfirmedState($request);
            $response->students = array_values($students);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    public function removeStudentsFromConfirmedState($searchRequest)
    {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try
        {
            if($searchRequest->currentValuationCount == '2'){
                $examConfirmRequest = new ExamConfirmRequest;
                $examConfirmRequest->examId = $searchRequest->student->onlineExamId;;
                $examConfirmRequest->userId = $searchRequest->student->studentId;
                $examConfirmRequest->reviewId = null;
                $examConfirmRequest->valuationCount = $searchRequest->currentValuationCount;
                ExamUserService::getInstance()->unConfirmUserMark($examConfirmRequest);
                $examConfirmRequest = new ExamConfirmRequest;
                $examConfirmRequest->examId = $searchRequest->student->onlineExamId;;
                $examConfirmRequest->userId = $searchRequest->student->studentId;
                $examConfirmRequest->userId = $searchRequest->student->studentId;
                $examConfirmRequest->reviewId = '1';
                $examConfirmRequest->valuationCount = '1';
                ExamUserService::getInstance()->unConfirmUserMark($examConfirmRequest);
            }
            else{
                $examConfirmRequest = new ExamConfirmRequest;
                $examConfirmRequest->examId = $searchRequest->student->onlineExamId;;
                $examConfirmRequest->userId = $searchRequest->student->studentId;
                $examConfirmRequest->valuationCount = $searchRequest->currentValuationCount;
                $examConfirmRequest->reviewId = null;
                ExamUserService::getInstance()->unConfirmUserMark($examConfirmRequest);
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    /**
     * get All Subject Details By Request
     * @param  $request
     * @return $students
     */
    public function getStudentsForRemoveConfirmedState($request)
    {
        $request = $this->realEscapeObject($request);
        $query = "";
        $currentUerId = $GLOBALS['userId'];
        $conditions = "";
        if( $request->examRegistrationId ){
            $conditions .= " AND eerb.ec_exam_registration_id = '$request->examRegistrationId'";
        }
        if( $request->currentValuationCount ){
            if($request->currentValuationCount == '2'){
                $conditions .= " AND ( oemc.valuation_count = '1' AND oemc.review_id IS NOT NULL OR oemc.valuation_count = '2' AND oemc.review_id IS NULL )";
            }
            else{
                $conditions .= " AND oemc.valuation_count = '$request->currentValuationCount' AND oemc.review_id IS NULL ";
            }
        }
        if( $request->assessmentId ){
            $assessmentIds = is_array($request->assessmentId) ? "'" . implode("','",$request->assessmentId) . "'" : "'".$request->assessmentId."'";
            $conditions .= " AND aa.id IN ( $assessmentIds )";
        }
        if( $request->falseNoRequired ){
            $conditions .= " AND esar.properties ->> '$.falseNo' IS NOT NULL";
        }
        $groupBy = "";
        if( $request->subjectRequest ){
            $groupBy = " GROUP BY aa.id";
        }
        else{
            $groupBy = " GROUP BY oe.id, oemc.oe_users_id";
        }
        try 
        { 
            $query = "SELECT
                    aps.id as academicPaperSubjectId,
                    s.code as subjectCode,
                    s.name as subjectName,
                    oe.id as onlineExamId,
                    eers.am_assessment_id as assessmentId,
                    sa.studentID AS studentId,
                    sa.myImage AS studentImage,
                    sa.studentName,
                    spa.properties->>'$.registerNumber' AS regNo,
                    esar.properties ->> '$.falseNo'  AS falseNo,
                    sa.rollNo,
                    sa.admissionNo,
                    aps.properties ->> '$.syllabusName' AS syllabusName,
                    IF(aps.properties ->> '$.classType' = 'THEORY',1,0) AS isTheory,
                    eers.valuation_details as valuationDetails,
                    eerb.ec_exam_registration_id as examRegistrationId
                FROM
                    ec_exam_registration_subject eers
                INNER JOIN ec_exam_registration_batch eerb ON
                    eerb.id = eers.ec_exam_registration_batch_id
                INNER JOIN  cm_academic_paper_subjects aps ON 
                    aps.id = eers.cm_academic_paper_subjects_id
                INNER JOIN am_assessment aa ON
                    aa.id = eers.am_assessment_id
                INNER JOIN oe_exams oe ON
                    oe.assessment_id = eers.am_assessment_id AND oe.is_deleted = 0
                INNER JOIN  v4_ams_subject s ON 
                    s.id = aps.ams_subject_id
                INNER JOIN oe_exam_marks_confirm oemc ON
                    oemc.oe_exams_id = oe.id
                INNER JOIN studentaccount sa ON 
                    sa.studentID = oemc.oe_users_id
                INNER JOIN ec_student_assessment_registration esar ON
                    esar.am_assessment_id = aa.id
                    AND esar.student_id = sa.studentID
                INNER JOIN `groups` g ON
                    g.id = eerb.groups_id
                INNER JOIN program p ON 
                    p.id = g.properties->>'$.programId'
                INNER JOIN student_program_account spa ON 
                    spa.student_id  = esar.student_id  AND
                    spa.current_program_id = p.id 
                WHERE
                    oemc.is_confirmed = 1 AND oemc.revaluation_id IS NULL";
            
            $students = $this->executeQueryForList($query.$conditions.$groupBy);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $students;
    }
      /**
     * Save exam registration additional mark
     * @param ObjectArray $examMarks
     * @return Boolean true
     */
    public function saveExamRegistrationAdditionalMark ($examMarks) {
        $examMarks = $this->realEscapeArray($examMarks);
        $values = [];
        if ( empty ( $examMarks ) ) {
            throw new ExamControllerException (ExamControllerException::EMPTY_PARAMETERS, "Empty Parameters! Please specify marks to save");
        }
        foreach ( $examMarks as $mark ) {
            $mark->properties = $mark->properties ? json_encode($mark->properties) : "{}";
            $values[] = "(
                '$mark->studentId',
                '$mark->examRegistrationId',
                '$mark->type',
                '$mark->groupId',
                '$mark->markObtained',
                '$mark->properties',
                '$mark->createdBy'
            )";
            $staffId = $mark->createdBy;
        }
        try {
            $sql = "INSERT INTO `ec_exam_registration_additional_mark` (
                        `student_id`, 
                        `ec_exam_registration_id`, 
                        `type`, 
                        `groups_id`, 
                        `mark_obtained`, 
                        `properties`, 
                        `created_by`
                    ) VALUES  " . implode(', ', $values). " ON DUPLICATE KEY UPDATE 
                        `mark_obtained` = VALUES(mark_obtained),
                        `properties` = VALUES(properties),
                        `updated_by` = VALUES(created_by)";
            $this->executeQuery($sql);
            AMSLogger::log_info($this->logger,Events::EC_SAVE_EXAM_REGISTRATION_ADDITIONAL_MARK, [
                "staff" => new Staff(["id" => $staffId]),
                "request" => $examMarks,
                "status" => StatusConstants::SUCCESS
            ]);
        } catch (\Exception $e) {
            AMSLogger::log_error($this->logger,Events::EC_SAVE_EXAM_REGISTRATION_ADDITIONAL_MARK, [
                "staff" => new Staff(["id" => $staffId]),
                "request" => $examMarks,
                "errorCode" => $e->getCode(),
                "errorMessage" => $e->getMessage(),
                "status" => StatusConstants::FAILED
            ]);
            throw new ExamControllerException ($e->getCode(), $e->getMessage());
        }
        return true;
    }
    /**
     * get All Registered Students additional marks
     * @param $searchRequest 
     */
    public function getExamRegistrationAdditionalMark($searchRequest) {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try
        {
            $orderBy = " ORDER BY spa.properties->>'$.registerNumber' ASC ";
            $whereQuery = "";
            if(!empty($searchRequest->groupId)) {
                $groupIdString = is_array($searchRequest->groupId) ? "'" . implode("','",$searchRequest->groupId) . "'" : "'".$searchRequest->groupId."'";
                $whereQuery .= " AND g.id IN ( $groupIdString )";
            }
            if(!empty($searchRequest->type)) {
                $whereQuery .= " AND  eeram.`type` = '$searchRequest->type'";
            }
            if(!empty($searchRequest->examRegistrationId)) {
                $examRegistrationIdString = is_array($searchRequest->examRegistrationId) ? "'" . implode("','",$searchRequest->examRegistrationId) . "'" : "'".$searchRequest->examRegistrationId."'";
                $whereQuery .= " AND eeram.ec_exam_registration_id  IN ( $examRegistrationIdString )";
            }
            if(!empty($searchRequest->studentId)) {
                $studentIdString = is_array($searchRequest->studentId) ? "'" . implode("','",$searchRequest->studentId) . "'" : "'".$searchRequest->studentId."'";
                $whereQuery .= " AND sa.studentID IN ( $studentIdString )";
            }
            if(!empty($searchRequest->requiredStudentHavingMark)) {
                $whereQuery .= " AND eeram.mark_obtained > 0";
            }
            
            $query = "    SELECT 
                    sa.studentID AS id,
                    sa.studentID AS studentId,
                    sa.studentName AS name,
                    spa.properties->>'$.rollNumber' AS rollNo,
                    spa.properties->>'$.registerNumber' AS registerNo,
                    spa.properties->>'$.universityRegisterNumber' AS universityRegNo,
                    sa.admissionNo,
                    sa.myImage,
                    sa.studentGender,
                    g.id AS groupId,
                    g.name AS groupName,
                    g.properties ->> '$.optionName' AS batchOptionName,
                    eeram.properties ->> '$.hashTotalGraceMark' AS hashTotalGraceMark,
                    eeram.mark_obtained AS gradeUpgradedMark
                FROM 
                    ec_exam_registration_additional_mark eeram
                INNER JOIN  `groups` g ON
                    g.id = eeram.groups_id 
                INNER JOIN program p ON
                    p.id = g.properties ->> '$.programId'
                INNER JOIN student_program_account spa ON 
                    spa.current_program_id = p.id AND 
                    spa.student_id = eeram.student_id 
                INNER JOIN studentaccount sa ON 
                    sa.studentID = eeram.student_id
                WHERE 
                    1 = 1";
            $studentMarkDetails = $this->executeQueryForList($query.$whereQuery.$orderBy);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $studentMarkDetails;
    }
       /**
     * Save exam registration additional mark
     * @param ObjectArray $examMarks
     * @return Boolean true
     */
    public function saveStudentAssessmentAdditionalMark ($examMarks) {
        $examMarks = $this->realEscapeArray($examMarks);
        $values = [];
        if ( empty ( $examMarks ) ) {
            throw new ExamControllerException (ExamControllerException::EMPTY_PARAMETERS, "Empty Parameters! Please specify marks to save");
        }
        foreach ( $examMarks as $mark ) {
            $mark->properties = $mark->properties ? json_encode($mark->properties) : "{}";
            $values[] = "(
                '$mark->studentId',
                '$mark->assessmentId',
                '$mark->type',
                '$mark->markObtained',
                '$mark->properties',
                '$mark->createdBy'
            )";
            $staffId = $mark->createdBy;
        }
        try {
            $sql = "INSERT INTO `ec_student_assessment_additional_mark` (
                        `student_id`, 
                        `am_assessment_id`, 
                        `type`,
                        `mark_obtained`, 
                        `properties`, 
                        `created_by`
                    ) VALUES  " . implode(', ', $values). " ON DUPLICATE KEY UPDATE 
                        `mark_obtained` = VALUES(mark_obtained),
                        `properties` = VALUES(properties),
                        `updated_by` = VALUES(created_by)";
            $this->executeQuery($sql);
            AMSLogger::log_info($this->logger,Events::EC_SAVE_STUDENT_ASSESSMENT_ADDITIONAL_MARK, [
                "staff" => new Staff(["id" => $staffId]),
                "request" => $examMarks,
                "status" => StatusConstants::SUCCESS
            ]);
        } catch (\Exception $e) {
            AMSLogger::log_error($this->logger,Events::EC_SAVE_STUDENT_ASSESSMENT_ADDITIONAL_MARK, [
                "staff" => new Staff(["id" => $staffId]),
                "request" => $examMarks,
                "errorCode" => $e->getCode(),
                "errorMessage" => $e->getMessage(),
                "status" => StatusConstants::FAILED
            ]);
            throw new ExamControllerException ($e->getCode(), $e->getMessage());
        }
        return true;
    }
     /**
     * delete exam assessment additional mark
     * @param  $studentMark
     */
    public function deleteStudentAssessmentAdditionalMark($studentMark){
        try {
            $studentMark = $this->realEscapeArray($studentMark);
            foreach ( $studentMark as $mark ) {
                $sql_delete = "DELETE FROM  ec_student_assessment_additional_mark WHERE student_id = '$mark->studentId' AND am_assessment_id = '$mark->assessmentId' AND `type` = '$mark->requestType'";
                $this->executeQuery($sql_delete);
                $staffId = $mark->createdBy;
            }
            AMSLogger::log_info($this->logger,Events::EC_DELETE_STUDENT_ASSESSMENT_ADDITIONAL_MARK, [
                "staff" => new Staff(["id" => $staffId]),
                "request" => $studentMark,
                "status" => StatusConstants::SUCCESS
            ]);
        }
        catch (\Exception $e){
            AMSLogger::log_error($this->logger,Events::EC_DELETE_STUDENT_ASSESSMENT_ADDITIONAL_MARK, [
                "staff" => new Staff(["id" => $staffId]),
                "request" => $studentMark,
                "errorCode" => $e->getCode(),
                "errorMessage" => $e->getMessage(),
                "status" => StatusConstants::FAILED
            ]);
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * get All Student details for sgpa direct entry
     * @param $request
     * @return studentDetails
     */
    public function getStudentDetailsForSgpaDirectEntry($request){
        $request = $this->realEscapeObject($request);
        try{
            $sortBy = " ORDER BY spa.properties->>'$.rollNumber' ASC ";
            $joinQueary = "";
            $whereQuery = "";
            $joinQueary = " LEFT JOIN ec_semester_additional_mark_details esamd ON
                esamd.student_id = sa.studentID AND  esamd.program_id = p.id AND esamd.type = 'SGPA_DIRECT_ENTRY'";
            if(!empty($request->studentWithSgpa)){
                $joinQueary = " INNER JOIN ec_semester_additional_mark_details esamd ON
                esamd.student_id = sa.studentID AND  esamd.program_id = p.id AND esamd.type = 'SGPA_DIRECT_ENTRY'";
            }
            // else{
            //     $whereQuery .= " AND spa.properties->>'$.academicStatus' IN ('ACTIVE','COMPLETED')";
            // }
            if(!empty($request->academicTermId)){
                $joinQueary .= " AND esamd.academic_term_id = $request->academicTermId";
            }
            if(!empty($request->sgpaStudentId)){
                $sgpaStudentIdString = is_array($request->sgpaStudentId) ? "'" . implode("','",$request->sgpaStudentId) . "'" : "'".$request->sgpaStudentId."'";
                $whereQuery .= "AND spa.student_id  IN ( $sgpaStudentIdString )";
            }
            
            if(!empty($request->groupId)){
                $groupIdString = is_array($request->groupId) ? "'" . implode("','",$request->groupId) . "'" : "'".$request->groupId."'";
                $whereQuery .= " AND g.id IN ( $groupIdString )";
            }
           
            $query = "SELECT DISTINCT
                sa.studentID as studentId,
                sa.studentName as name,
                sa.studentEmail as email,
                sa.studentPhone as phone,
                spa.properties->>'$.registerNumber' AS registerNo,
                spa.properties->>'$.rollNumber' AS rollNumber,
                esamd.academic_term_id AS academicTermId,
                p.id AS programId,
                g.id AS groupId,
                g.name AS groupName,
                esamd.properties->>'$.totalCredit' AS totalCredit,
                esamd.properties->>'$.totalCredit' AS totalCreditOld,
                esamd.properties->>'$.earnedCredit' AS earnedCredit,
                esamd.properties->>'$.earnedCredit' AS earnedCreditOld,
                CAST(esamd.mark_obtained AS DECIMAL(18, 2)) AS sgpa,
                CAST(esamd.mark_obtained AS DECIMAL(18, 2)) AS sgpaOld
            FROM
                `groups` g 
            INNER JOIN group_members gm ON
                gm.groups_id = g.id
            INNER JOIN program p ON 
                p.id = g.properties->>'$.programId'
            INNER JOIN student_program_account spa ON 
               spa.id = gm.members->>'$.studentId' AND
               spa.current_program_id = p.id AND 
               spa.current_batch_id = g.id 
            INNER JOIN studentaccount sa ON
                sa.studentID = spa.student_id
            $joinQueary 
            WHERE
                g.`type` = 'BATCH' ";
            $studentDetails = $this->executeQueryForList($query.$whereQuery.$sortBy);
        }
        catch(\Exception $e) {
            throw new ExamControllerException ($e->getCode(),$e->getMessage());
        }
        return $studentDetails;
    }
    /**
     * Save semester wise sgpa entered
     * @param ObjectArray $examMarks
     * @return Boolean true
     */
    public function saveStudentDetailsForSgpaDirectEntry ($examMarks) {
        $examMarks = $this->realEscapeArray($examMarks);
        $values = [];
        if ( empty ( $examMarks ) ) {
            throw new ExamControllerException (ExamControllerException::EMPTY_PARAMETERS, "Empty Parameters! Please specify marks to save");
        }
        foreach ( $examMarks as $mark ) {
            $mark->properties = $mark->properties ? json_encode($mark->properties) : "{}";
            $values[] = "(
                '$mark->studentId',
                '$mark->programId',
                '$mark->academicTermId',
                '$mark->type',
                '$mark->markObtained',
                '$mark->properties',
                '$mark->createdBy'
            )";
            $staffId = $mark->createdBy;
        }
        try {
            $sql = "INSERT INTO `ec_semester_additional_mark_details` (
                        `student_id`, 
                        `program_id`, 
                        `academic_term_id`, 
                        `type`, 
                        `mark_obtained`, 
                        `properties`, 
                        `created_by`
                    ) VALUES  " . implode(', ', $values). " ON DUPLICATE KEY UPDATE 
                        `mark_obtained` = VALUES(mark_obtained),
                        `properties` = VALUES(properties),
                        `updated_by` = VALUES(created_by)";
            $this->executeQuery($sql);
            AMSLogger::log_info($this->logger,Events::EC_SAVE_SEMESTER_ADDITIONAL_MARK, [
                "staff" => new Staff(["id" => $staffId]),
                "request" => $examMarks,
                "status" => StatusConstants::SUCCESS
            ]);
        } catch (\Exception $e) {
            AMSLogger::log_error($this->logger,Events::EC_SAVE_SEMESTER_ADDITIONAL_MARK, [
                "staff" => new Staff(["id" => $staffId]),
                "request" => $examMarks,
                "errorCode" => $e->getCode(),
                "errorMessage" => $e->getMessage(),
                "status" => StatusConstants::FAILED
            ]);
            throw new ExamControllerException ($e->getCode(), $e->getMessage());
        }
        return true;
    }
      /**
     * get Subjects For Viva valuation Staff
     * @return staffDetails details
     */
    public function getSubjectsForVivaValuationStaff($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $isCentralizedSession = $GLOBALS['isCentralizedSession'] == true ? true : false; 
            $response = new \stdClass;
            $request = new \stdClass;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $today = date("Y-m-d H:i");
            $assignedSubjects = ExamRegistrationSubjectService::getInstance()->getSubjectForCurrentVivaValuationStaffs($request);
            $subjectArray = [];
            foreach($assignedSubjects as $subject){
                $subject->isExpand = false;
                $subject->valuationDetails = json_decode($subject->valuationDetails);
                $subject->errorMessage = null;
                $subject->errorMessageInfo = null;
                if($isCentralizedSession){
                    $subject->errorMessage = "Permission denied";
                    $subject->errorMessageInfo = "You can't view mark entry using centralized session.";
                }
                else{
                    $valuationDate = reset(array_filter($subject->valuationDetails->valuationDates,function($value)use($searchRequest){
                        return $value->count == '1';
                    }));
                    if(!empty($valuationDate)){
                        $subject->valuationStartDate = $valuationDate->startDate;
                        $subject->valuationEndDate = $valuationDate->endDate;
                        if(strtotime($today) < strtotime($subject->valuationStartDate)){
                            $subject->errorMessage = "Valuation Start On ".date("d-m-Y h:i A", strtotime($valuationDate->startDate));
                        }
                        else if(strtotime($today) > strtotime($subject->valuationEndDate)){
                            $subject->errorMessage = "Valuation Date Expired";
                        }
                    }
                    else{
                        $subject->errorMessage = "Valuation not configured";
                    }
                }
                if( $subjectArray[$subject->subjectId]){
                    $subjectArray[$subject->subjectId]->subjectIdArr[] = $subject->academicPaperSubjectId;
                }
                else{
                    $subject->subjectIdArr[] = $subject->academicPaperSubjectId;
                    $subjectArray[$subject->subjectId] = $subject;
                }
            }
            $response->subjects = array_values($subjectArray);
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
     /**
     * get student details for viva valuation staff
     * @return staffDetails details
     */
    public function getStudentDetailsForVivaValuationStaff($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $registeredStudents = [];
            $subjectArray = [];
            $enableValuatedCountCheck = NULL;
            $response = new \stdClass;
            $request = new \stdClass;
            $request->paperSubjectId = $searchRequest->paperSubjectId;
            $request->academicPaperSubjectId = $searchRequest->paperSubjectId;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $today = date("Y-m-d H:i");
            $assignedSubjects = ExamRegistrationSubjectService::getInstance()->getSubjectForCurrentVivaValuationStaffs($request);
            foreach($assignedSubjects as $subject){
                
                if( $subjectArray[$subject->subjectId]){
                    $subjectArray[$subject->subjectId]->subjectIdArr[] = $subject->academicPaperSubjectId;
                }
                else{
                    $subject->subjectIdArr[] = $subject->academicPaperSubjectId;
                    $subjectArray[$subject->subjectId] = $subject;
                }
            }
            $currentSubject = reset($subjectArray);
            if($currentSubject){
                $currentSubject->assessmentProperties = json_decode($currentSubject->assessmentProperties);
                $currentSubject->valuationDetails = json_decode($currentSubject->valuationDetails);
                $currentSubject->examDate = $currentSubject->assessmentProperties->assessmentDate;
                $currentSubject->errorMessage = null;
                $currentSubject->externalMaxMark = (int)$currentSubject->externalMaxMark;
                $currentValuationDateDetails = reset(array_filter($currentSubject->valuationDetails->valuationDates,function($value)use($searchRequest){
                    return $value->count == '1';
                }));
                $currentValuatedStaff = reset(array_filter($currentSubject->valuationDetails->valuatedStaffs,function($value)use($searchRequest){
                    return $value->count == '1' && $value->staffId == $GLOBALS['userId'];
                }));
                if(!empty($currentValuationDateDetails)){
                    $currentSubject->valuationStartDate = $currentValuationDateDetails->startDate;
                    $currentSubject->valuationEndDate = $currentValuationDateDetails->endDate;
                    if(strtotime($today) < strtotime($currentSubject->valuationStartDate)){
                        $currentSubject->errorMessage = "Valuation Not Started";
                    }
                    else if((strtotime($today) > strtotime($currentSubject->valuationEndDate))){
                        $currentSubject->errorMessage = "Valuation Date Expired";
                    }
                }
                if($currentValuatedStaff){
                    if($currentValuatedStaff->markEntryStatus){
                        $currentSubject->markEntryStatus = $currentValuatedStaff->markEntryStatus;
                    }
                }
            }
            if(empty($currentSubject) || $currentSubject->errorMessage != null) {
                $registeredStudents = [];
            }
            else{
                $registeredStudents = $this->getRegisteredStudentsForVivaValuationStaff($request);
                foreach($registeredStudents as $student){
                    $student->errorMessage = "";
                    if ( $student->isAbsent == "ABSENT" ) {
                        $student->mark  = "AB";
                    } 
                    else if ($student->isAbsent == "MALPRACTICE") {
                        $student->mark  = "MAL";
                    }
                    else if ($student->isAbsent == "WITHHELD") {
                        $student->mark  = "WH";
                    }
                    else{
                        $student->mark = $student->finalizedMark ? number_format((float)$student->finalizedMark, 2, '.', '') : null;
                    }
                }
            }
            $response->subject = $currentSubject;
            $response->students = $registeredStudents;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    /**
     * Get Registered Student for viva valuation staff
     * @param $request
     * @return $students
     */
    public function getRegisteredStudentsForVivaValuationStaff($request){
        try{
            $request = $this->realEscapeObject($request);
            $joinQuery = "";
            $whereQuery = "";
            $orderBy = "";
            $currentUerId = $GLOBALS['userId'];
            if(!empty($request->examRegistrationId)) {
                $whereQuery .= " AND eerb.ec_exam_registration_id = '$request->examRegistrationId'";
            }
            if(!empty($request->academicPaperSubjectId)) {
                $academicPaperSubjectIdsString = is_array($request->academicPaperSubjectId) ? "'" . implode("','",$request->academicPaperSubjectId) . "'" : "'".$request->academicPaperSubjectId."'";
                $whereQuery .= " AND eers.cm_academic_paper_subjects_id IN ( $academicPaperSubjectIdsString )";
            }
            $orderBy = " ORDER BY spa.properties->>'$.registerNumber' ASC";
            $query = "SELECT DISTINCT
                esar.id,
                sa.studentID as studentId,
                aa.id AS assessmentId,
                esar.falseNo AS falseNumber,
                IF (esar.valuation_details IS NULL, JSON_OBJECT(), esar.valuation_details) AS valuationDetails,
                sa.studentName,
                spa.properties->>'$.registerNumber' AS registerNo,
                spa.properties->>'$.rollNumber' AS rollNo,
                sub.code AS subjectCode,
                sub.name AS subjectName,
                caps.id AS academicPaperSubjectId,
                oe.id AS onlineExamId,
                ostmf.mark_obtained as finalizedMark,
                ostmf.properties as finalizedMarkProperties,
                ostmf.attendance_status as isAbsent,
                ostmf.id as assessmentStudentTotalMarkId
            FROM
                ec_student_assessment_registration esar
            INNER JOIN studentaccount sa ON
                sa.studentID = esar.student_id
            INNER JOIN am_assessment aa ON
                aa.id = esar.am_assessment_id
            INNER JOIN oe_exams oe ON
                oe.assessment_id = aa.id AND oe.is_deleted = 0
            INNER JOIN ec_exam_registration_subject eers ON
                eers.am_assessment_id = aa.id
            INNER JOIN ec_exam_registration_batch eerb ON
                eerb.id = eers.ec_exam_registration_batch_id
            INNER JOIN ec_exam_registration eer ON
                eer.id = eerb.ec_exam_registration_id AND
                eer.trashed IS NULL
            INNER JOIN `groups` g ON 
                g.id = eerb.groups_id
            INNER JOIN program p ON 
                p.id = g.properties->>'$.programId'
            INNER JOIN ec_student_additional_details esad ON
                esad.student_id = esar.student_id AND esad.program_id = p.id AND esad.type = 'PROJECT_THESIS'
            INNER JOIN student_program_account spa ON 
                spa.student_id  = esar.student_id  AND
                spa.current_program_id = p.id
            INNER JOIN cm_academic_paper_subjects caps ON
                caps.id = eers.cm_academic_paper_subjects_id
            INNER JOIN v4_ams_subject sub ON
                sub.id = caps.ams_subject_id
            LEFT JOIN oe_student_total_mark ostmf ON 
                ostmf.student_id = sa.studentID AND ostmf.am_assessment_id = esar.am_assessment_id AND ostmf.valuation_count = 'FINALIZED' AND (ostmf.valuation_type IS NULL OR ostmf.valuation_type = '') 
            WHERE
                esar.trashed IS NULL AND esar.properties ->> '$.registrationStatus' IN ('REGISTERED') AND eer.type = esar.ec_exam_registration_type AND JSON_CONTAINS(esad.properties,JSON_OBJECT('vivaFacultyId', '$currentUerId'))";
            $registeredStudent = $this->executeQueryForList($query.$whereQuery.$orderBy);
            return $registeredStudent;
        }
        catch(\Exception $e) {
            throw new ExamControllerException ($e->getCode(),$e->getMessage());
        }
    }
     /**
     * Save Student Mark Entry  For Viva valuation Staff
     * @param  $request
     * @return $response
     */
    public function saveAllExternalMarkDetailsForVivaValuationStaff($request){
        $request = $this->realEscapeObject($request);
        try {
            $response = new \stdClass;
            $registredStudentsArray = [];
            $registeredStudentDetails = [];
            $studentMarkArray=$request->studentMarkArray;
            $insertionMarkTableArray = [];
            $searchRequest = new \stdClass;
            $searchRequest->academicPaperSubjectId = $request->academicPaperSubjectId;
            $searchRequest->examRegistrationId = $request->examRegistrationId;
            $academicPaperSubjectId = implode("','",$request->academicPaperSubjectId);
            $registeredStudents = $this->getRegisteredStudentsForVivaValuationStaff($searchRequest);
            $maxmarkOfSubject = ExamRegistrationSubjectService::getInstance()->getMaxSubjectMarkByAcademicPaperSubjectId(($academicPaperSubjectId));
            foreach($registeredStudents as $registeredStudent){
                $registredStudentsArray[$registeredStudent->studentId] = $registeredStudent->studentId;
                $registeredStudentDetails[$registeredStudent->studentId] = [
                    "studentId" => $registeredStudent->studentId,
                    "assessmentId" => $registeredStudent->assessmentId,
                    "registerNo" => $registeredStudent->registerNo,
                    "onlineExamId" => $registeredStudent->onlineExamId,
                    "finalizedMarkProperties" => $registeredStudent->finalizedMarkProperties,
                ];
            }
            if(!empty($studentMarkArray)){
                foreach($studentMarkArray as $student){
                    $studentId = strtoupper($student['studentId']);
                    if ( in_array ( $studentId, $registredStudentsArray ) ) {
                        if($student['mark'] == "AB" || $student['mark'] == "MAL" || $student['mark'] == "WH" ){
                            $markEntryObj = new \stdClass();
                            $markEntryObj->studentId = $studentId;
                            $markEntryObj->assessmentId = $registeredStudentDetails[$studentId]['assessmentId'];
                            $markEntryObj->oeExamsId = $registeredStudentDetails[$studentId]['onlineExamId'];
                            $markEntryObj->markObtained = NULL;
                            $markEntryObj->attendanceStatus = $student['mark'] = "AB" ? "ABSENT" : $student['mark'] = "MAL" ? "MALPRACTICE" : "WITHHELD" ;
                            $markEntryObj->valuationCount = 'FINALIZED';
                            $markproperties = "";
                            $finalizedMarkProperties = new \Stdclass(); 
                            $finalizedMarkProperties = json_decode($registeredStudentDetails[$studentId]['finalizedMarkProperties']);
                            if($finalizedMarkProperties){
                                $markproperties = (object)$finalizedMarkProperties;
                            }
                            $markEntryObj->properties  = $markproperties;
                            $markEntryObj->valuationType = null;
                            $insertionMarkTableArray[] = $markEntryObj;
                        }
                        else if ( $student['mark'] > $maxmarkOfSubject ){
                            $markExceedsTotalMark[] = $student['registerNo'];
                            $errorFlag = 1;
                        }
                        else{
                            $markEntryObj = new \stdClass();
                            $markEntryObj->studentId = $studentId;
                            $markEntryObj->assessmentId = $registeredStudentDetails[$studentId]['assessmentId'];
                            $markEntryObj->oeExamsId = $registeredStudentDetails[$studentId]['onlineExamId'];
                            $markEntryObj->markObtained = $student['mark'];
                            $markEntryObj->attendanceStatus = "PRESENT" ;
                            $markEntryObj->valuationCount = 'FINALIZED';
                            $markproperties = "";
                            $finalizedMarkProperties = new \Stdclass(); 
                            $finalizedMarkProperties = json_decode($registeredStudentDetails[$studentId]['finalizedMarkProperties']);
                            if($finalizedMarkProperties){
                                $markproperties = (object)$finalizedMarkProperties;
                            }
                            $markEntryObj->properties  = $markproperties;
                            $markEntryObj->valuationType = null;
                            $insertionMarkTableArray[] = $markEntryObj;
                        }
                    }
                    else{
                        $unregisteredStudents[] = $student['registerNo'];
                        $errorFlag = 1;
                    }
                }
                if(! empty($insertionMarkTableArray)){
                    ExamUserMarkService::getInstance()->saveExamUserTotalMark($insertionMarkTableArray);
                }
                if($request->savingType){
                    $searchRequest = new \Stdclass();
                    $searchRequest->examRegistrationId = $request->examRegistrationId;
                    $searchRequest->academicPaperSubjectId =  $request->academicPaperSubjectId;
                    $searchRequest->currentValuationCount =  '1';
                    $valuatedStaffs =  new \stdClass;
                    $valuationProperties =  new \stdClass;
                    $valuatedStaffs->staffId = $GLOBALS['userId'];
                    $valuatedStaffs->markEntryStatus = $request->savingType == 'CONFIRM_MARK' ? 'CONFIRMED': 'SAVED';
                    $valuatedStaffs->count = "1";
                    $valuatedStaffs->valuationStaffType = 'VIVA_FACULTY';
                    $valuationProperties->valuatedStaffs = $valuatedStaffs;                    
                    $assignedSubjects = ExamRegistrationSubjectService::getInstance()->getSubjectForCurrentVivaValuationStaffs($request);
                    foreach($assignedSubjects as $subject){
                        $updateSubjectValuationDetals = new \stdClass;
                        $facultyUpdated = false;
                        if(is_null($subject->valuationDetails)){
                            $subject->valuationDetails = $valuationProperties;
                        }
                        else{
                            $subject->valuationDetails = json_decode($subject->valuationDetails);
                            if(is_null($subject->valuationDetails->valuatedStaffs)){
                                $subject->valuationDetails->valuatedStaffs[] = $valuatedStaffs;
                            }
                            else{
                                foreach($subject->valuationDetails->valuatedStaffs as $valuatedStaff){
                                    if($valuatedStaff->count == '1' && $valuatedStaff->staffId == $GLOBALS['userId']){
                                        $valuatedStaff->staffId = $GLOBALS['userId'];
                                        $valuatedStaff->markEntryStatus = $request->savingType == 'CONFIRM_MARK' ? 'CONFIRMED': 'SAVED';
                                        $facultyUpdated = true;
                                    }
                                }
                                if(!$facultyUpdated){
                                    $subject->valuationDetails->valuatedStaffs[] = $valuatedStaffs;
                                }
                            }
                        }
                        $updateSubjectValuationDetals->assessmentId = $subject->assessmentId;
                        $updateSubjectValuationDetals->valuationDetails = $subject->valuationDetails;
                        $updateSubjectValuationDetals->examRegSubjectId = $subject->examRegistrationSubjectId;
                        $updateValuatedStaffValues[]=$updateSubjectValuationDetals;
                    }
                    if(!empty($updateValuatedStaffValues)){
                        $this->updateValuatedStaffToExamRegistraionSubject($updateValuatedStaffValues);
                        AMSLogger::log_info($this->logger,Events::EC_CONFIRM_STAFF_SIDE_MARK_ENTRY, [
                            "staff" => new Staff(["id" => $valuatedStaffs->staffId]),
                            "request" => $updateValuatedStaffValues,
                            "status" => StatusConstants::SUCCESS
                        ]);
                    }
                
                }
                if ( $errorFlag || $response->error) {
                    $errors["unregisteredStudent"] = $errors["markExceedsTotalMark"] =$errors["error"] = $errors["success"] = "";
                    if ( !empty ( $unregisteredStudents ) ) {
                        $errors["unregisteredStudent"] = "The student with register number ". implode(", ", $unregisteredStudents)." is/are not registered for exam";
                    }
                    if ( !empty ( $markExceedsTotalMark ) ) {
                        $errors["markExceedsTotalMark"] = "The marks entered for the student(s) with register number ". implode(", ", $markExceedsTotalMark)." exceeds the total mark of exam";
                    }
                    if($response->updatedStudentCount){
                        $errors["success"] = "Marks saved successfully for $response->updatedStudentCount student(s)";
                    }
                }
                else{
                    $success["success"] = "";
                    if($response->updatedStudentCount){
                        $success["success"] = "Marks saved successfully for $response->updatedStudentCount student(s)";
                    }
                }
            }
            else{
                $errors["unregisteredStudent"] = $errors["markExceedsTotalMark"] =$errors["error"] = $errors["success"] = "";
                $errors["error"] = "No Student Mark Entered";
            }
            $response->errors = $errors;
            $response->success = $success;
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
      /**
     * getCourseTypeIdByExamRevaluationIdAndPaperSubjectId 
     * @param ExamRegistrationId $examRegistrationId
     * @param SubjectId $academicPaperSbjectId
     * @return $subject->isTheory
     */
    public function getCourseTypeIdByExamRevaluationIdAndPaperSubjectId($examRegistrationId,$academicPaperSbjectId)
    {
        $examRegistrationId = $this->realEscapeString($examRegistrationId);
        if(is_array($academicPaperSbjectId)){
            $academicPaperSbjectId = $this->realEscapeArray($academicPaperSbjectId);
            $academicPaperSbjectId = implode("','",$academicPaperSbjectId);
        }
        else{
            $academicPaperSbjectId = $this->realEscapeString($academicPaperSbjectId);
        }
        try
        {
            $query = "SELECT
                        p.course_type_id as courseTypeId
                    FROM
                        ec_exam_registration_subject eers
                    INNER JOIN ec_exam_registration_batch eerb ON
                            eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eerp ON
                        eerp.id = eerb.ec_exam_registration_id AND
                        eerp.trashed IS NULL
                    INNER JOIN ec_exam_registration eer ON
                        eer.properties->>'$.parentExamRegistrationId' = eerp.id AND 
                        eer.trashed IS NULL
                    INNER JOIN  `groups` g ON 
                            g.id = eerb.groups_id
                    INNER JOIN program p ON 
                        p.id = g.properties->>'$.programId'
                    WHERE
                        eer.id='$examRegistrationId' AND
                        eers.cm_academic_paper_subjects_id IN ('$academicPaperSbjectId')";
            $courseType = $this->executeQueryForObject($query);
            
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $courseType->courseTypeId;
    }
    
    
    /**
     * count Of Evaluated Students By Online Exam - confirmed
     * @param Object $request
     * @return Integer $countOfEvaluatedStudents
     * @throws ExamControllerException
     */
    public function countOfEvaluatedStudentsConfimeredByOnlineExam($request){
        try {
            $request = $this->realEscapeObject($request);
            $whereQuery = "";
            if(!empty($request->onlineExamId)) {
                $onlineExamIdString = is_array($request->onlineExamId) ? "'" . implode("','",$request->onlineExamId) . "'" : "'".$request->onlineExamId."'";
                $whereQuery .= " AND oeum.oe_exams_id IN ( $onlineExamIdString )";
            }
            if(!empty($request->staffId)){
                $whereQuery .= " AND oeum.created_by = '$request->staffId";
            }
            if(!empty($request->isReviewer)){
                $whereQuery .= " AND review_id IS NOT NULL";
            }
            else{
                $whereQuery .= " AND review_id IS NULL ";
            }
            if(!empty($request->valuationCount)){
                $whereQuery .= " AND valuation_count = $request->valuationCount";
            }
            if(!empty($request->studentId)){
                $whereQuery .= " AND oeum.oe_users_id = '$request->studentId";
            }
            $sql = "SELECT 
                        DISTINCT oeum.oe_users_id as studentId
                    FROM 
                        oe_exam_marks_confirm oeum 
                    WHERE
                        oeum.is_confirmed = '1' ";
            $studentDetails = $this->executeQueryForList($sql.$whereQuery);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
        return count($studentDetails);
    }
    /**
     * copy student questionwise digital valuation marks from 1 valuation to another
     * @param $request
     */
    public function copyStudentPreviousDigitalValuationMarks($request){
        $request = $this->realEscapeObject($request);
        $sql = "UPDATE oe_exam_user_mark
                SET valuation_marks = JSON_SET(valuation_marks, 
                    '$.\"$request->valuationTo\"', 
                    CASE
                        WHEN valuation_marks->'$.\"$request->valuationFrom\".grade' IS NOT NULL
                        THEN JSON_OBJECT(
                            \"mark\", valuation_marks->'$.\"$request->valuationFrom\".mark',
                            \"staffId\", '$request->staffId',
                            \"grade\", JSON_UNQUOTE(valuation_marks->'$.\"$request->valuationFrom\".grade')
                        )
                        ELSE JSON_OBJECT(
                            \"mark\", valuation_marks->'$.\"$request->valuationFrom\".mark',
                            \"staffId\", '$request->staffId'
                        )
                    END
                )
                WHERE oe_exams_id = '$request->oeExamId' AND user_id = '$request->user_id' AND user_type = '$request->userType' AND valuation_marks->>'$.\"$request->valuationTo\".staffId' IS NULL";
        try {
            $this->executeQueryForObject($sql);
            AMSLogger::log_info($this->logger,Events::COPY_STUDENT_DIGITAL_VALUATION_MARKS, [
                "staff" => new Staff(["id" => $request->staffId]),
                "request" => $request,
                "status" => StatusConstants::SUCCESS
            ]);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
        return true;
    }
    
    /**
     * get Subjects For Valuer Revierer Mark Entry Digital Valuation
     * @return staffDetails details
     */
    public function getSubjectDetailsForValuerReviewerMarkEntryDigitalValuation($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $firstValuationStaffs = [];
            $searchRuleRequest = new SearchRuleRequest;
            $searchRuleRequest->name = "EXAM_VALUATION_PROCEDURE_RULE";
            $examValuationProcedureRule = reset(RuleService::getInstance()->searchRule($searchRuleRequest))->rule;
            $templateName = $examValuationProcedureRule->templateName ;
            $digitalValuationProperties = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_CONTROLLER, SettingsConstents::DIGITAL_VALUATION_PROPERTIES);
            $digitalValuationProperties = $digitalValuationProperties ? json_decode($digitalValuationProperties) : "";
            if($templateName == 'TEMPLATE_WITH_DIGITAL_VALUATION'){
                $showStudentsByFalseNumber = (int)CommonService::getInstance()->getSettings(SettingsConstents::EXAM_CONTROLLER, SettingsConstents::SHOW_STUDENTS_FOR_VALUATION_BY_FALSE_NUMBER);
                $registeredStudents = [];
                $absentStudents = [];
                $enableValuatedCountCheck = NULL;
                $response = new \stdClass;
                $request = new \stdClass;
                $searchRequest->paperSubjectId = (array) $searchRequest->paperSubjectIdArr ? $searchRequest->paperSubjectIdArr : $searchRequest->paperSubjectId;
                $userId = $GLOBALS['userId'];
                $request->paperSubjectId = $searchRequest->paperSubjectId;
                $request->academicPaperSubjectId = $searchRequest->paperSubjectId;
                $request->examRegistrationId = $searchRequest->examRegistrationId;
                $request->currentValuationCount = $searchRequest->currentValuationCount;
                $request->valuationCount = $searchRequest->currentValuationCount;
                // $request->assessmentId = $searchRequest->assessmentId;
                $today = date("Y-m-d H:i");
                $currentSubject = ExamRegistrationSubjectService::getInstance()->getcurrentExamSubjectForCurrentStaff($request);
                $subject = ExamRegistrationSubjectService::getInstance()->getAllExamSubjectForCurrentStaffDigitalValuation($request);
                $studentIdentifier = $showStudentsByFalseNumber ? "falseNumber" : "registerNo";
                $studentIdentifierForPath = $showStudentsByFalseNumber ? "flNo" : "rgNo";
                if($currentSubject){
                    $isPg = 0;
                    if($currentSubject->courseType == 'PG'){
                        $isPg = 1;
                    }
                    else{
                        $request->valuationCount = $request->valuationCount == '2' ? '1' : $request->valuationCount;
                    }
                    $pgPara = (int)$isPg ? "&pg=1" : "";
                    $rvwIdPath = ($searchRequest->currentValuationCount == '2' && !(int)$isPg) ? "&rvwId=1" : "";
                    $currentSubject->assessmentProperties = json_decode($currentSubject->assessmentProperties);
                    $currentSubject->valuationDetails = json_decode($currentSubject->valuationDetails);
                    $currentSubject->examDate = $currentSubject->assessmentProperties->assessmentDate;
                    $currentSubject->errorMessage = null;
                    $currentSubject->isConfiremed = "";
                    $currentSubject->externalMaxMark = (int)$currentSubject->externalMaxMark;
                    $currentSubject->valuationCount = $searchRequest->currentValuationCount;
                    if($searchRequest->currentValuationCount == '2'){
                        $firstValuationStaffsDetails = array_filter($currentSubject->valuationDetails->valuationStaffs,function($value){
                            return $value->count == '1';
                        });
                        $secondValuationStaffsDetails = array_filter($currentSubject->valuationDetails->valuationStaffs,function($value){
                            return $value->count == '2';
                        });
                        if($currentSubject->courseType == 'PG' || count(reset($secondValuationStaffsDetails)->addiitonalExamniners) < 2){
                            $viewerIds = [];
                            usort($currentSubject->valuationDetails->valuationDates, function($a, $b) {
                                return strtotime($b->endDate) - strtotime($a->endDate);
                            });
                            foreach($firstValuationStaffsDetails as $firstValuationStaff){
                                foreach($firstValuationStaff->addiitonalExamniners as $staff){
                                    $viewerIds[] = $staff;
                                }
                            }
                            $firstValuationStaffs = empty($viewerIds) ?  [] : StaffService::getInstance()->getStaffByIds($viewerIds);
                            $currentValuationDateDetails = reset(array_filter($currentSubject->valuationDetails->valuationDates,function($value)use($viewerIds,$userId){
                                return $value->count == '1' && in_array($value->staffId,$viewerIds);
                            }));
                        }
                        else{
                            $currentValuationDate = reset(array_filter($currentSubject->valuationDetails->valuationDates,function($value)use($searchRequest,$userId){
                                return $value->count == $searchRequest->currentValuationCount && $value->staffId == $userId;
                            }));
                            $viewerIds = $currentValuationDate->viewerIds;
                            $firstValuationStaffs = empty($viewerIds) ?  [] : StaffService::getInstance()->getStaffByIds($viewerIds);
                            $currentValuationDateDetails = reset(array_filter($currentSubject->valuationDetails->valuationDates,function($value)use($viewerIds,$userId){
                                return $value->count == '1' && in_array($value->staffId,$viewerIds);
                            }));
                        }
                        if($currentSubject->courseType == 'UG'){
                            if(!empty($digitalValuationProperties->noOfDaysInBufferForReviewer)){
                                $addOndaysForReviewer = (($digitalValuationProperties->noOfDaysInBufferForReviewer ?? 0) - $digitalValuationProperties->noOfDaysInBufferForValuer);
                                if($addOndaysForReviewer > 0){
                                    $currentValuationDateDetails->endDate = date("Y-m-d H:i", strtotime($currentValuationDateDetails->endDate . " +$addOndaysForReviewer days"));
                                }
                            }
                        }
                    }
                    else{
                        $currentValuationDateDetails = reset(array_filter($currentSubject->valuationDetails->valuationDates,function($value)use($searchRequest,$userId){
                            return $value->count == $searchRequest->currentValuationCount && $value->staffId == $userId;
                        }));
                    }
                    if(!empty($currentValuationDateDetails)){
                        $currentSubject->valuationStartDate = $currentValuationDateDetails->startDate;
                        $currentSubject->valuationEndDate = $currentValuationDateDetails->endDate;
                        if(strtotime($today) < strtotime($currentSubject->valuationStartDate)){
                            $currentSubject->errorMessage = "Valuation Not Started";
                        }
                        else if((strtotime($today) > strtotime($currentSubject->valuationEndDate))){
                            $currentSubject->errorMessage = "Valuation Date Expired";
                        }
                    }
                }
                if(empty($subject) || $currentSubject->errorMessage != null) {
                    $registeredStudents = [];
                }
                else{
                    if(!empty($searchRequest->firstValuationStaffId) || $searchRequest->currentValuationCount != '2'){ 
                        if($showStudentsByFalseNumber){
                            $request->falseNoRegNoStatus = "falseNumber";
                        }
                        else{
                            $request->falseNoRegNoStatus = "registerNo";
                        }
                        $s3FileRequest = new \stdClass;
                        $s3FileRequest->folderPath = $GLOBALS['COLLEGE_CODE'] . "/Digital Evaluation" . "/" . $currentSubject->examRegistrationName . "/" . $currentSubject->subjectCode;
                        $s3DocStudentKeyList = ExamValuationRuleService::getInstance()->getS3FileDetails($s3FileRequest);
                        $studentDetails = StudentExamRegistrationService::getInstance()->getRegisteredStudentsValuationDetails($request);
                        foreach($studentDetails as $student){
                            $requestForMarkConfirm = new \stdClass;
                            $requestForMarkConfirm->onlineExamId = $student->onlineExamId;
                            $requestForMarkConfirm->valuationCount = $searchRequest->currentValuationCount;
                            if($currentSubject->courseType != 'PG' && $searchRequest->currentValuationCount == '2'){
                                $requestForMarkConfirm->valuationCount = '1';
                                $requestForMarkConfirm->isReviewer = true;
                            }
                            $requestForMarkConfirm->studentId = $student->studentId;
                            $requestForMarkConfirm->staffId = $GLOBALS['userId'];
                            $student->markConfirmObj = $this->checkIfMarkConfirmForDigitalValuation($requestForMarkConfirm);
                            $student->isMarkConfirm = !empty($student->markConfirmObj) ? '1' : '0';
                            if($searchRequest->currentValuationCount == '2'){
                                $requestForMarkConfirm = new \stdClass;
                                $requestForMarkConfirm->onlineExamId = $student->onlineExamId;
                                $requestForMarkConfirm->valuationCount = '1';
                                $requestForMarkConfirm->studentId = $student->studentId;
                                $requestForMarkConfirm->staffId = $searchRequest->firstValuationStaffId;
                                $student->mark1ConfirmObj = $this->checkIfMarkConfirmForDigitalValuation($requestForMarkConfirm);
                                $student->isMark1Confirm = !empty($student->mark1ConfirmObj) ? '1' : '0';
                            }
                            if($student->isMarkConfirm != '1'){
                                $requestForPapersEvaluated = new \stdClass;
                                $requestForPapersEvaluated->onlineExamId = $student->onlineExamId;
                                $requestForPapersEvaluated->valuationCount = $searchRequest->currentValuationCount;
                                if($currentSubject->courseType != 'PG' && $searchRequest->currentValuationCount == '2'){
                                    $requestForPapersEvaluated->valuationCount = 'review_1';
                                }
                                $requestForPapersEvaluated->studentId = $student->studentId;
                                $requestForPapersEvaluated->staffId = $GLOBALS['userId'];
                                $student->papersEvaluvated = (int)$this->countOfEvaluatedStudentsByOnlineExam($requestForPapersEvaluated);
                                $student->markEntryStarted = $student->papersEvaluvated > 0 ? 1 : 0;
                            }
                            $student->filePath = "examId=".$student->assessmentId. "&vlc=". $request->valuationCount."&". $studentIdentifierForPath."=". $student->$studentIdentifier . $rvwIdPath . $pgPara;
                            $student->valuationDetails = empty($student->valuationDetails) ? null : json_decode($student->valuationDetails);
                            $student->path = $GLOBALS['COLLEGE_CODE'] . "/Digital Evaluation" . "/" . $currentSubject->examRegistrationName . "/" . $currentSubject->subjectCode . "/" . $student->$studentIdentifier . ".PDF";
                            if($student->valuationDetails){
                                if($searchRequest->currentValuationCount == '2'){
                                    $currentValuationStaffDetails = reset(array_filter($student->valuationDetails->assignedValuationStaffs,function($value){
                                        return $value->count == '1';
                                    }));
                                    if(!empty($currentValuationStaffDetails->addiitonalExamniners)){
                                        if(in_array($searchRequest->firstValuationStaffId,$currentValuationStaffDetails->addiitonalExamniners)){
                                            if (in_array($student->path, $s3DocStudentKeyList)) {
                                                $registeredStudents[] = $student;
                                            }
                                            // else {
                                            //     $student->blockValuationReason = "Student is absent";
                                            //     $absentStudents[] = $student;
                                            // }
                                            
                                        }
                                    }
                                }
                                else{
                                    $currentValuationStaffDetails = reset(array_filter($student->valuationDetails->assignedValuationStaffs,function($value)use($searchRequest){
                                        return $value->count == $searchRequest->currentValuationCount;
                                    }));
                                    if(!empty($currentValuationStaffDetails->addiitonalExamniners)){
                                        if(in_array($searchRequest->staffId,$currentValuationStaffDetails->addiitonalExamniners)){
                                            if (in_array($student->path, $s3DocStudentKeyList)) {
                                                $registeredStudents[] = $student;
                                            }
                                            else {
                                                $student->blockValuationReason = "Student is absent";
                                                $absentStudents[] = $student;
                                            }
                                            // $registeredStudents[] = $student;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                $studentList = [];
                $studentListSet = [];
                if($currentSubject->courseType == 'PG'){
                    $studentList = $registeredStudents;
                }
                else{
                    $studentListSetArray  = array_chunk($registeredStudents, $digitalValuationProperties->noOfValScriptsInset);
                    foreach ($studentListSetArray as $setKey => $set) {
                        $studentListSet[$setKey]->students = $set;
                        $studentListSet[$setKey]->totalStudent = count($set);
                        $studentListSet[$setKey]->markConfirmStudentCount = count(array_filter($set,function($value){
                            return $value->isMarkConfirm == '1';
                        }));
                        $studentListSet[$setKey]->markConfirmStudentPercentage =($studentListSet[$setKey]->markConfirmStudentCount / $studentListSet[$setKey]->totalStudent) * 100;
                        $studentListSet[$setKey]->minValScriptsPercentForReviewer = 100;
                        if($currentSubject->courseType != 'PG' && $searchRequest->currentValuationCount == '2'){
                            $studentListSet[$setKey]->minValScriptsPercentForReviewer = (int)$digitalValuationProperties->minValScriptsPercentForReviewer;
                        }
                        $studentListSet[$setKey]->minValScripts = ceil($studentListSet[$setKey]->totalStudent *  $studentListSet[$setKey]->minValScriptsPercentForReviewer) / 100;
                        if($studentListSet[$setKey]->minValScripts <= $studentListSet[$setKey]->markConfirmStudentCount){
                            $studentListSet[$setKey]->badgeMsg = "Completed minimum scripts";
                            $studentListSet[$setKey]->badgeMsgClass = "text-success";
                        }
                        else{
                            $studentListSet[$setKey]->badgeMsg = "Pending minimum scripts";
                            $studentListSet[$setKey]->badgeMsgClass = "text-danger";
                        }
                        if($searchRequest->currentValuationCount == '2'){
                            foreach ($set as $student) {
                                if (!$student->isMark1Confirm) {
                                    unset($studentListSet[$setKey]);
                                    break;
                                }
                            }
                        }
                    }
                }
                $studentListSet = array_values($studentListSet);
                $response->subject = $currentSubject;
                $response->firstValuationStaffs = $firstValuationStaffs;
                $response->students = $studentListSet;
                $response->studentList = $studentList;
                $response->isCheckValuerReviewer = $currentSubject->courseType == 'PG' ? '0' : '1';
                $response->absentStudents = $absentStudents;
                $response->showStudentsByFalseNumber = $showStudentsByFalseNumber;
                $response->currentValuationCount = $searchRequest->currentValuationCount;
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    /**
     * Finalize Digital Valuation Marks With out third valuation
     * 
     */
    public function finalizeDigitalValuationMarksWithOutThirdValuation($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $showStudentsByFalseNumber = (int)CommonService::getInstance()->getSettings(SettingsConstents::EXAM_CONTROLLER, SettingsConstents::SHOW_STUDENTS_FOR_VALUATION_BY_FALSE_NUMBER);
            $studentIdentifier = $showStudentsByFalseNumber ? "falseNumber" : "registerNo";
            $studentIdentifierForPath = $showStudentsByFalseNumber ? "flNo" : "rgNo";
            $digitalValuationProperties = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_CONTROLLER, SettingsConstents::DIGITAL_VALUATION_PROPERTIES);
            $digitalValuationProperties = $digitalValuationProperties ? json_decode($digitalValuationProperties) : "";
            $searchRequest->academicPaperSubjectIdArray = explode(",",$searchRequest->academicPaperSubjectId);
            $request = new \stdClass;
            $request->academicPaperSubjectId = $searchRequest->academicPaperSubjectIdArray;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->id = $searchRequest->examRegistrationId;
            $request->falseNoRegNoStatus = $studentIdentifier;
            $subject = ExamRegistrationSubjectService::getInstance()->getCurrentSubjectDetailsByExamRegistrationIdAndPaperSubjectId($request);
            $request->academicPaperSubjectId = $searchRequest->academicPaperSubjectIdArray;
            $request->isValuerReviewerCriteria = $subject->courseType == 'UG' ? true : false;
            $examRegistration = reset(ExamRegistrationService::getInstance()->searchExamRegistrationByOtherDetails($request));
            if($examRegistration->type == "REVALUATION"){
                $studentDetails = $this->getAllStudentByRevaluationRegistrationSubjectForDigitalValuation($request);
            }
            else{
                $studentDetails = $this->getAllStudentByExamRegistrationSubjectForDigitalValuation($request);
                foreach($studentDetails as $student){
                    $firstValuationStaffId = "";
                    $student->valuationDetails = json_decode($student->valuationDetails);
                    $valuationStaff = reset(array_filter($student->valuationDetails->assignedValuationStaffs ,function($value)use($searchRequest){
                        return $value->count == '1' && !empty($value->addiitonalExamniners);
                    }));
                    $firstValuationStaffId = !empty($valuationStaff->addiitonalExamniners) ? reset($valuationStaff->addiitonalExamniners) : "NOT_ASSIGNED";
                    $studentsByStaffDetails[$firstValuationStaffId]->students[] = $student;
                }
            }
            $requestForSubjectDetails = new \stdClass;
            $requestForSubjectDetails->academicPaperSubjectIds = $searchRequest->academicPaperSubjectIdArray;
            $requestForSubjectDetails->examRegistrationId = $searchRequest->examRegistrationId;
            $currentSubject = ExamRegistrationSubjectService::getInstance()->getExamregistrationSubjectDetails($requestForSubjectDetails); 
            $registeredStudents = [];
            $absentStudents = [];
            $s3FileRequest = new \stdClass;
            $s3FileRequest->folderPath = $GLOBALS['COLLEGE_CODE'] . "/Digital Evaluation" . "/" . $currentSubject->examRegistrationName . "/" . $currentSubject->subjectCode;
            $s3DocStudentKeyList = ExamValuationRuleService::getInstance()->getS3FileDetails($s3FileRequest);
            if($examRegistration->type == "REVALUATION"){
                foreach($studentDetails as $student){
                    $markEntryObj = new ExamUserMarkRequest();
                    $markEntryObj->studentId = $student->studentId;
                    $markEntryObj->assessmentId = $student->assessmentId;
                    $markEntryObj->oeExamsId = $student->oeExamId;
                    $markEntryObj->attendanceStatus = "PRESENT";
                    $markEntryObj->valuationCount = 'FINALIZED';
                    $markEntryObj->valuationType = 'REVALUATION';
                    $markEntryObj->staffId = $GLOBALS['userId'];
                    $student->hasMark1 = 0;
                    if (is_numeric($student->mark1) && $student->mark1Confirm) {
                        $student->hasMark1 = 1;
                    }
                    $student->hasMark2 = 0;
                    if (is_numeric($student->mark2) && $student->mark2Confirm) {
                        $student->hasMark2 = 1;
                    }
                    if ($student->hasMark1 && $student->hasMark2) {
                        $student->externalMark = round((round($student->mark2, 2) + round($student->mark1, 2)) / 2,2);
                        $markEntryObj->markObtained = ceil($student->externalMark);
                        $examMarkEntryArray[] = $markEntryObj;
                    } else {
                        continue;
                    }
                }
            }
            else{
                foreach($studentsByStaffDetails as $staffId => $studentMarkDetails){
                    foreach($studentMarkDetails->students as $student){
                        $student->path = $GLOBALS['COLLEGE_CODE'] . "/Digital Evaluation" . "/" . $currentSubject->examRegistrationName . "/" . $currentSubject->subjectCode . "/" . $student->$studentIdentifier . ".PDF";
                        if (in_array($student->path, $s3DocStudentKeyList)) {
                            if($subject->courseType == 'PG'){
                                $registeredStudents[] = $student;
                            }
                            else{
                                $registeredStaffStudents[$staffId]->students[] = $student;
                            }
                        }
                        else {
                            $absentStudents[] = $student;
                        }
                    }
                }
                if($currentSubject->courseType == 'PG'){
                    $studentListSet[0]->students = $registeredStudents;
                    $studentListSet[0]->allowFinalizeSet = '1';
                }
                else{
                    $setKey = 0;
                    foreach($registeredStaffStudents as $registeredStaff){
                        $studentListSetArray  = array_chunk($registeredStaff->students, $digitalValuationProperties->noOfValScriptsInset);
                        foreach ($studentListSetArray as $set) {
                            $studentListSet[$setKey]->students = $set;
                            $studentListSet[$setKey]->allowFinalizeSet = 1;
                            $studentListSet[$setKey]->totalStudent = count($set);
                            $studentListSet[$setKey]->mark1ConfirmStudentCount = count(array_filter($set,function($value){
                                return $value->mark1Confirm == '1';
                            }));
                            $studentListSet[$setKey]->mark2ConfirmStudentCount = count(array_filter($set,function($value){
                                return $value->mark2Confirm == '1';
                            }));
                            $studentListSet[$setKey]->minVal1Scripts = $studentListSet[$setKey]->totalStudent;
                            $studentListSet[$setKey]->minVal2Scripts = ceil($studentListSet[$setKey]->totalStudent *  (int)$digitalValuationProperties->minValScriptsPercentForReviewer) / 100;
                            if($studentListSet[$setKey]->minVal1Scripts > $studentListSet[$setKey]->mark1ConfirmStudentCount){
                                $studentListSet[$setKey]->allowFinalizeSet = 0;
                            }
                            else if($studentListSet[$setKey]->minVal2Scripts > $studentListSet[$setKey]->mark2ConfirmStudentCount){
                                $studentListSet[$setKey]->allowFinalizeSet = 0;
                            }
                            $setKey++;
                        }
                    }
                }
                foreach($studentListSet as $set){
                    if($set->allowFinalizeSet){
                        foreach($set->students as $student){
                            $markEntryObj = new ExamUserMarkRequest();
                            $markEntryObj->studentId = $student->studentId;
                            $markEntryObj->assessmentId = $student->assessmentId;
                            $markEntryObj->oeExamsId = $student->oeExamId;
                            $markEntryObj->attendanceStatus = "PRESENT";
                            $markEntryObj->valuationCount = 'FINALIZED';
                            $markEntryObj->staffId = $GLOBALS['userId'];
                            $student->hasMark1 = 0;
                            if (is_numeric($student->mark1) && $student->mark1Confirm) {
                                $student->hasMark1 = 1;
                            }
                            $student->hasMark2 = 0;
                            if (is_numeric($student->mark2) && $student->mark2Confirm) {
                                $student->hasMark2 = 1;
                            }
                            if($currentSubject->courseType == 'PG'){
                                if ($student->hasMark1 && $student->hasMark2) {
                                    $student->externalMark = round((round($student->mark2, 2) + round($student->mark1, 2)) / 2,2);
                                    $markEntryObj->markObtained = ceil($student->externalMark);
                                    $examMarkEntryArray[] = $markEntryObj;
                                } else {
                                    continue;
                                }
                            }else{
                                if ($student->hasMark1) {
                                    $student->externalMark = $student->mark2Confirm ? round($student->mark2, 2) : round($student->mark1, 2);
                                    $markEntryObj->markObtained = ceil($student->externalMark);
                                    $examMarkEntryArray[] = $markEntryObj;
                                } else {
                                    continue;
                                }
                            }
                        }
                    }
    
                }
            }
            if( !empty ( $examMarkEntryArray ) ){
                ExamUserMarkService::getInstance()->saveExamUserTotalMark($examMarkEntryArray);
            }
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * get packet issued details
     * @param $searchRequest
     */
     public function getSubjectPacketIssuedDetails($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try {
            $condition = "";
            if($searchRequest->examRegistrationId){
                $examRegistrationIdString = is_array($searchRequest->examRegistrationId) ? "'" . implode("','",$searchRequest->examRegistrationId) . "'" : "'".$searchRequest->examRegistrationId."'";
                $condition .=" AND asg.ec_exam_registration_id IN ($examRegistrationIdString)";
            }
            if($searchRequest->academicPaperSubjectIds){
                $academicPaperSubjectIdString = is_array($searchRequest->academicPaperSubjectIds) ? "'" . implode("','",$searchRequest->academicPaperSubjectIds) . "'" : "'".$searchRequest->academicPaperSubjectIds."'";
                $condition .=" AND asg.cm_academic_paper_subjects_id IN ($academicPaperSubjectIdString)";
            }
            $groupBy = " group by s.id";
            $orderBy = " ORDER BY asg.id";
            $query = "SELECT
                    s.code as subjectCode,
                    s.name as subjectName,
                    aa.properties_value ->>'$.assessmentDate' AS assessmentDate,
                    aa.properties_value ->>'$.startTime' AS assessmentStartTime,
                    aa.properties_value ->>'$.endTime' AS assessmentEndTime,
                    asgc.studentsPerAnswerSheetGroupCount AS totalPacketCount,
                    asg.packet_start_no AS packetStartNo ,
                    asg.packet_end_no AS packetEndNo,
                    asg.cm_academic_paper_subjects_id,
                    asg.ec_exam_registration_id,
                    asg.id AS exam_examReg_subject_answerSheet_group_id
                FROM
                    exam_examReg_subject_answerSheet_group asg
                INNER JOIN exam_examReg_subject_answerSheet_group_config asgc ON
                    asgc.id = asg.examReg_subject_answerSheet_group_config_id
                INNER JOIN ec_exam_registration_batch eerb ON
                    eerb.ec_exam_registration_id = asg.ec_exam_registration_id
                INNER JOIN ec_exam_registration_subject eers ON
                    eers.ec_exam_registration_batch_id = eerb.id
                    AND eers.cm_academic_paper_subjects_id = asg.cm_academic_paper_subjects_id
                INNER JOIN am_assessment aa ON
                    aa.id = eers.am_assessment_id
                INNER JOIN cm_academic_paper_subjects aps ON
                    aps.id = eers.cm_academic_paper_subjects_id
                INNER JOIN v4_ams_subject s ON
                    s.id = aps.ams_subject_id
                WHERE 1=1 ";
            return $this->executeQueryForList($query.$condition.$groupBy.$orderBy);
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
        /**
     * get issued packet details
     * @param $searchRequest
     */
    public function getIssuedPacketDetails($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try {
            $condition = "";
            if($searchRequest->examRegSubjectAnswerSheetGroupId){
                $examRegSubjectAnswerSheetGroupIdString = is_array($searchRequest->examRegSubjectAnswerSheetGroupId) ? "" . implode(",",$searchRequest->examRegSubjectAnswerSheetGroupId) . "" : "".$searchRequest->examRegSubjectAnswerSheetGroupId."";
                $condition .=" AND epr.exam_examReg_subject_answerSheet_group_id IN ($examRegSubjectAnswerSheetGroupIdString)";
            }
            $query = "SELECT
                        epr.id,
                        epr.packet_no AS packetNo,
                        sa.staffName,
                        epr.exam_examReg_subject_valuation_staff_id as assignedStaff,
                        epr.issue_date AS issueDate,
                        epr.return_date AS returnDate,
                        epr.exam_examReg_subject_answerSheet_group_id AS examRegSubjectAnswerSheetGroupId
                    FROM
                        ec_packet_issue_register epr
                    INNER JOIN staffaccounts sa ON sa.staffID = epr.exam_examReg_subject_valuation_staff_id
                        WHERE 1=1 ";
            return $this->executeQueryForList($query.$condition);
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * issue packets to staff
     * @param Array PacketIssueRegister $packetIssueRegisterArray []
     */
    public function issuePacketToStaffForValuation ($packetIssueRegister) {
        $packetIssueRegister = $this->realEscapeObject ($packetIssueRegister);
        $sql = null;
        $sqlInsertValues = null;
        $sqlInsertValueString = null;
        $userId = $packetIssueRegister->userId;
        foreach ($packetIssueRegister->packets as $packet) {
            $staffId = $packet['staffId'];
            $packetNum = $packet['packetNum'];
            $issueDate = date('Y-m-d G:i',strtotime($packet['issueDate']));
            if ($staffId && $packetNum && $issueDate) {
                $sqlInsertValues[] = "(".$packetIssueRegister->examRegSubjectAnswerSheetGroupId."$staffId$packetNum$userId, '$issueDate', $userId)";
                $staffId = "";
                $packetNum = "";
                $issueDate = "";
            }
        }
        try {
            $sqlInsertValueString = implode(',',$sqlInsertValues);
            $sql = "INSERT IGNORE INTO ec_packet_issue_register 
            (exam_examReg_subject_answerSheet_group_id,
            exam_examReg_subject_valuation_staff_id,
            packet_no,
            issued_by,
            issue_date,
            created_by)
            VALUES $sqlInsertValueString";
            $id = $this->executeQuery($sql,true);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $id;
    }
     /**
     * update return date for packet issused
     */
    public function updatePacketIssuedReturnDate ($id,$date,$userId) {
        $id = $this->realEscapeString ($id);
        $date = $this->realEscapeString ($date);
        $sql = null;
        $userId = $userId;
        try {
                $returnDate = date('Y-m-d G:i',strtotime($date));
                $sql = "UPDATE ec_packet_issue_register 
                SET return_date = '$returnDate', updated_by = $userId, return_to = $userId
                WHERE
                    id = $id";
           $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $id;
    }
    
    /**
     * get all Packets For Staff Side Mark Entry Revaluation 
     * @return staffDetails details
     */
    public function getAllStudentStaffDetailsWithOrderForStaffSideMarkEntryRevaluation($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $response = new \stdClass;
            $request = new \stdClass;
            $request->paperSubjectId = $searchRequest->paperSubjectId;
            $request->academicPaperSubjectIds = $searchRequest->academicPaperSubjectIds;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $request->packetNo = $searchRequest->packetNo;
            $request->currentRevaluationType = $searchRequest->currentRevaluationType;
            $currentValuationCount = (int)$request->currentValuationCount ;
            $today = date("Y-m-d H:i");
            $studentMarkDetails = [];
            $thirdValuatedStudentMarkDetails = [];
            $valuatedStudents = [];
            $currentStaffId = $GLOBALS['userId'];
            $currentSubject = reset(ExamRegistrationSubjectService::getInstance()->getSubjectForCurrentStaffsRevaluation($request));
            if($currentSubject){
                $currentSubject->isConfiremed = "";
                $currentSubject->isPrint = 1;
                $currentSubject->assessmentProperties = json_decode($currentSubject->assessmentProperties);
                $currentSubject->valuationDetails = json_decode($currentSubject->valuationDetails);
                $currentSubject->examDate = $currentSubject->assessmentProperties->assessmentDate;
                $currentSubject->errorMessage = null;
                $currentSubject->isConfiremed = "";
                $currentSubject->externalMaxMark = (int)$currentSubject->externalMaxMark;
                $currentSubject->valuationCount = $searchRequest->currentValuationCount;
                // $currentSubject->courseType = $courseType->courseTypeMethod;
                foreach($currentSubject->valuationDetails->reValuationDates as $valuationDate){
                    if($valuationDate->count == $searchRequest->currentValuationCount){
                        $currentSubject->valuationStartDate = $valuationDate->startDate;
                        $currentSubject->valuationEndDate = $valuationDate->endDate;
                        if(strtotime($today) < strtotime($currentSubject->valuationStartDate)){
                            $currentSubject->errorMessage = "Valuation Not Started";
                        }
                        else if((strtotime($today) > strtotime($currentSubject->valuationEndDate))){
                            $currentSubject->errorMessage = "Valuation Date Expired";
                        }
                        else{
                            if($currentValuationCount == 1){
                                $previousValuationStatus = 'NO_PREVIOUS_VALUATIONS';
                            }
                            foreach($currentSubject->valuationDetails->reValuatedStaffs as $valuatedStaff){
                                if($valuatedStaff->count == $request->currentValuationCount  && $valuatedStaff->packetNo == $request->packetNo && $valuatedStaff->staffId == $currentStaffId){
                                    if($valuatedStaff->markEntryStatus){
                                        $currentSubject->isConfiremed = $valuatedStaff->markEntryStatus;
                                    }
                                }
                                if($currentValuationCount > 1){    
                                    if($valuatedStaff->count == $currentValuationCount-1  && $valuatedStaff->packetNo == $request->packetNo ){
                                        if($valuatedStaff->markEntryStatus){
                                            $previousValuationStatus = $valuatedStaff->markEntryStatus;
                                              }
                                    }
                                }
                            }
                            if($previousValuationStatus == 'CONFIRMED' || $previousValuationStatus == 'NO_PREVIOUS_VALUATIONS'){
                                $studentMarkDetails = $this->getAllStudentsMarksWithFalseNumberOrderForRevaluation($request);
                            }
                            else{
                                $currentSubject->errorMessage = "Previous Valuation Pending ";
                                $currentSubject->students = [];
                            }
                            
                        }
                    }
                }
            }
            if($currentValuationCount == 2){
                $requestForThirdValuation = new \stdClass;
                $requestForThirdValuation = $request;
                $requestForThirdValuation->currentValuationCount = 2;
                $thirdValuatedStudentMarkDetails = $this->getAllStudentsMarksWithFalseNumberOrderForRevaluation($requestForThirdValuation);
            }
            foreach($studentMarkDetails as $student){
                $student->staffRevaluatedType = $student->secondValuationStaffRevaluatedType;
                $student->alphaNumericCode = $student->alphaNumericCode;
                if($currentValuationCount == 1){
                    if($student->secondValuationMark){
                        $valuatedStudents[] = $student;
                    }
                    $student->mark = $student->secondValuationMark;
                    $student->markDifference = abs($student->firstValuationMark - $student->secondValuationMark);
                }
                else if($currentValuationCount == 2 ){
                    if($student->thirdValuationMark){
                        $valuatedStudents[] = $student;
                    }
                    $student->mark = $student->thirdValuationMark ;
                }
            }
            $response->maxStudentsCount = count($studentMarkDetails);
            $response->subject = $currentSubject;
            $response->allStudentMarkDetails = $studentMarkDetails;
            $response->valuatedStudents = $valuatedStudents;
            $response->currentValuationCount = $searchRequest->currentValuationCount;
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
         return $response;
    }
     /**
     * get AllStudent By ExamRegistrationSubject For Digital Valuation
     * @param request $request
     */
    public function getAllStudentsMarksWithFalseNumberOrderForRevaluation($request,$conditions= [])
    {
        $request = $this->realEscapeObject($request);
        try {
            $joinQuery = null;
            $orderBy = null;
            $whereQuery = null;
            if($request->currentValuationCount == 2 ){
                $joinQuery .= "INNER JOIN ec_revaluation_mark erm2 ON 
                erm2.student_id = sa.studentID AND erm2.am_assessment_id = esar.am_assessment_id AND erm2.revaluation_type = CAST(esar.identifying_context->>'$.revaluationType'AS CHAR) AND erm2.valuation_count = '2' AND erm2.properties ->> '$.hasEligibleThirdValuation' = '1'";
            }
            else{
                $joinQuery .= "LEFT JOIN ec_revaluation_mark erm2 ON 
                erm2.student_id = sa.studentID AND erm2.am_assessment_id = esar.am_assessment_id AND erm2.revaluation_type = CAST(esar.identifying_context->>'$.revaluationType'AS CHAR) AND erm2.valuation_count = '2'";
            }
            if(!empty($searchRequest->currentRevaluationType)) {
                $whereQuery .= " AND esar.identifying_context->>'$.revaluationType' IN ( '$searchRequest->currentRevaluationType' )";
            }
            if(!empty($request->academicPaperSubjectIds)) {
                $academicPaperSubjectIdsString = is_array($request->academicPaperSubjectIds) ? "'" . implode("','",$request->academicPaperSubjectIds) . "'" : "'".$request->academicPaperSubjectIds."'";
                $whereQuery .= " AND eers.cm_academic_paper_subjects_id IN ( $academicPaperSubjectIdsString )";
            }
            if(!empty($conditions) && is_array($conditions)) {
                $whereQuery = null;
                $whereQuery .= implode(" OR ", $conditions);
                $query = "SELECT
                            DISTINCT sa.studentID as id,
                            sa.studentID ,
                            sa.studentID as studentId,
                            sa.studentName,
                            sa.regNo,
                            oe.id as onlineExamId,
                            esar.am_assessment_id as assessmentId,
                            esarParent.properties ->> '$.falseNo' as falseNo,
                            esarParent.properties ->> '$.alphaNumericCode' as alphaNumericCode,
                            esar.valuation_details as valuationDetails,
                            erm.mark_obtained  AS revaluationMark,
                            ostmf.attendance_status AS isAbsent,
                            ostmf.mark_obtained AS oldRevaluationMark,
                            ostmf.properties AS finalizedMarkProperties,
                            esmdsubcon.mark_details ->>'$.externalMark' AS firstValuationMark,
                            erm2.id as secondValuationId,
                            erm2.mark_obtained as secondValuationMark,
                            erm3.id as thirdValuationId,
                            erm3.mark_obtained as thirdValuationMark,
                            erm2.properties ->> '$.hasEligibleThirdValuation' as thirdValReq,
                            @path_to_count := JSON_UNQUOTE(JSON_SEARCH(esar.valuation_order_details ->>'$.valuationOrder', 'one', '$request->currentValuationCount', NULL, '$[*].count')) AS path_to_count,
                            @path_to_parent := trim(TRAILING '.count' from @path_to_count) AS path_to_parent,
                            @current_object := JSON_EXTRACT(esar.valuation_order_details ->>'$.valuationOrder', @path_to_parent ) as current_object,
                            CAST(json_extract(@current_object, '$.falseNoOrder')AS UNSIGNED) as falseNoOrder
                        FROM
                            ec_student_assessment_registration esar
                        INNER JOIN studentaccount sa ON
                            sa.studentID = esar.student_id
                        INNER JOIN am_assessment aa ON
                            aa.id = esar.am_assessment_id
                        INNER JOIN oe_exams oe ON
                            oe.identifying_context ->> '$.assessmentId' = aa.id AND oe.is_deleted = 0
                        INNER JOIN ec_exam_registration_subject eers ON
                            eers.am_assessment_id = aa.id
                        INNER JOIN ec_exam_registration_batch eerb ON
                            eerb.id = eers.ec_exam_registration_batch_id
                        INNER JOIN ec_exam_registration eerp ON
                            eerp.id = eerb.ec_exam_registration_id AND
                            eerp.trashed IS NULL
                        INNER JOIN ec_exam_registration eer ON
                            eer.properties->>'$.parentExamRegistrationId' = eerp.id AND 
                            eer.trashed IS NULL
                        INNER JOIN `groups` g ON 
                            g.id = eerb.groups_id
                        INNER JOIN program p ON 
                            p.id = g.properties->>'$.programId'
                        INNER JOIN student_program_account spa ON 
                            spa.student_id  = esar.student_id  AND
                            spa.current_program_id = p.id 
                        INNER JOIN cm_academic_paper_subjects caps ON
                            caps.id = eers.cm_academic_paper_subjects_id
                        INNER JOIN v4_ams_subject s ON
                            s.id = caps.ams_subject_id
                        LEFT JOIN ec_student_assessment_registration esarParent ON
                            esar.student_id = esarParent.student_id AND 
                            esar.am_assessment_id = esarParent.am_assessment_id AND
                            eerp.type = esarParent.ec_exam_registration_type
                        LEFT JOIN ec_revaluation_mark erm ON 
                            erm.student_id = sa.studentID AND erm.am_assessment_id = esar.am_assessment_id AND erm.revaluation_type = CAST(esar.identifying_context->>'$.revaluationType'AS CHAR) AND erm.valuation_count = 'FINALIZED'
                        LEFT JOIN oe_student_total_mark ostmf ON 
                            ostmf.student_id = sa.studentID AND ostmf.am_assessment_id = esar.am_assessment_id AND ostmf.valuation_count = 'FINALIZED' AND (ostmf.valuation_type = 'REVALUATION') 
                        LEFT JOIN ec_revaluation_mark erm3 ON 
                            erm3.student_id = sa.studentID AND erm3.am_assessment_id = esar.am_assessment_id AND erm3.revaluation_type = CAST(esar.identifying_context->>'$.revaluationType'AS CHAR) AND erm3.valuation_count = '3'
                        INNER JOIN ec_consolidated_subject_mark_details esmdsubcon ON
                            esmdsubcon.groups_id = eerb.groups_id AND esmdsubcon.cm_academic_paper_subjects_id = eers.cm_academic_paper_subjects_id AND esmdsubcon.student_id = sa.studentID 
                        $joinQuery
                        WHERE
                            $whereQuery  
                        ORDER BY CAST(json_extract(@current_object, '$.falseNoOrder') AS UNSIGNED)";
                }
                else{
                    $query = "SELECT
                            DISTINCT sa.studentID as id,
                            sa.studentID ,
                            sa.studentName,
                            spa.properties->>'$.registerNumber' AS regNo,
                            oe.id as onlineExamId,
                            esar.am_assessment_id as assessmentId,
                            esarParent.properties ->> '$.falseNo' as falseNo,
                            esarParent.properties ->> '$.alphaNumericCode' as alphaNumericCode,
                            esar.valuation_details as valuationDetails,
                            erm.id  AS finalizedValuationId,
                            erm.mark_obtained  AS revaluationMark,
                            ostmf.attendance_status AS isAbsent,
                            ostmf.mark_obtained AS oldRevaluationMark,
                            ostmf.properties AS finalizedMarkProperties,
                            esmdsubcon.mark_details ->>'$.externalMark' AS firstValuationMark,
                            erm2.mark_obtained as secondValuationMark,
                            erm3.mark_obtained as thirdValuationMark,
                            erm2.properties ->> '$.hasEligibleThirdValuation' as thirdValReq,
                            @path_to_count := JSON_UNQUOTE(JSON_SEARCH(esar.valuation_order_details ->>'$.reValuationOrder', 'one', '$request->currentValuationCount', NULL, '$[*].count')) AS path_to_count,
                            @path_to_parent := trim(TRAILING '.count' from @path_to_count) AS path_to_parent,
                            @current_object := JSON_EXTRACT(esar.valuation_order_details ->>'$.reValuationOrder', @path_to_parent ) as current_object,
                            CAST(json_extract(@current_object, '$.falseNoOrder')AS UNSIGNED) as falseNoOrder
                        FROM
                            ec_student_assessment_registration esar
                        INNER JOIN studentaccount sa ON
                            sa.studentID = esar.student_id
                        INNER JOIN am_assessment aa ON
                            aa.id = esar.am_assessment_id
                        INNER JOIN oe_exams oe ON
                            oe.identifying_context ->> '$.assessmentId' = aa.id AND oe.is_deleted = 0
                        INNER JOIN ec_exam_registration_subject eers ON
                            eers.am_assessment_id = aa.id
                        INNER JOIN ec_exam_registration_batch eerb ON
                            eerb.id = eers.ec_exam_registration_batch_id
                        INNER JOIN ec_exam_registration eerp ON
                            eerp.id = eerb.ec_exam_registration_id AND
                            eerp.trashed IS NULL
                        INNER JOIN ec_exam_registration eer ON
                            eer.properties->>'$.parentExamRegistrationId' = eerp.id AND 
                            eer.trashed IS NULL
                        INNER JOIN `groups` g ON 
                            g.id = eerb.groups_id
                        INNER JOIN program p ON 
                            p.id = g.properties->>'$.programId'
                        INNER JOIN student_program_account spa ON 
                            spa.student_id  = esar.student_id  AND
                            spa.current_program_id = p.id 
                        INNER JOIN cm_academic_paper_subjects caps ON
                            caps.id = eers.cm_academic_paper_subjects_id
                        INNER JOIN v4_ams_subject s ON
                            s.id = caps.ams_subject_id
                        LEFT JOIN ec_student_assessment_registration esarParent ON
                            esar.student_id = esarParent.student_id AND 
                            esar.am_assessment_id = esarParent.am_assessment_id AND
                            eerp.type = esarParent.ec_exam_registration_type
                        LEFT JOIN ec_revaluation_mark erm ON 
                            erm.student_id = sa.studentID AND erm.am_assessment_id = esar.am_assessment_id AND erm.revaluation_type = CAST(esar.identifying_context->>'$.revaluationType'AS CHAR) AND erm.valuation_count = 'FINALIZED'
                        LEFT JOIN oe_student_total_mark ostmf ON 
                            ostmf.student_id = sa.studentID AND ostmf.am_assessment_id = esar.am_assessment_id AND ostmf.valuation_count = 'FINALIZED' AND (ostmf.valuation_type  = 'REVALUATION') 
                        LEFT JOIN ec_revaluation_mark erm3 ON 
                            erm3.student_id = sa.studentID AND erm3.am_assessment_id = esar.am_assessment_id AND erm3.revaluation_type = CAST(esar.identifying_context->>'$.revaluationType'AS CHAR) AND erm3.valuation_count = '3'
                        INNER JOIN ec_consolidated_subject_mark_details esmdsubcon ON
                            esmdsubcon.groups_id = eerb.groups_id AND esmdsubcon.cm_academic_paper_subjects_id = eers.cm_academic_paper_subjects_id AND esmdsubcon.student_id = sa.studentID 
                        $joinQuery
                        WHERE
                            esar.ec_exam_registration_type = eer.type AND
                            CAST(esar.properties ->> '$.registrationStatus' AS CHAR) = 'REGISTERED' AND 
                            CAST(esar.properties ->> '$.feeStatus' AS CHAR) = 'PAID' AND
                            eer.id = '$request->examRegistrationId' AND 
                            esar.valuation_details ->> '$.packetNo' = '$request->packetNo'
                            $whereQuery  
                        ORDER BY CAST(json_extract(@current_object, '$.falseNoOrder') AS UNSIGNED)";
                }
            $studentsMarkDetails = $this->executeQueryForList($query);
             }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $studentsMarkDetails;
    }
    /**
     * get all Packets For Staff Side Mark Entry
     * @return staffDetails details
     */
    public function saveStudentMarksDetailsWithOrderForStaffSideMarkEntryRevaluation($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $response = new \stdClass;
            $request = new \stdClass;
            $regStudentCount = 0;
            // $request->paperSubjectId = $searchRequest->paperSubjectId;
            $request->academicPaperSubjectIds = $searchRequest->paperSubjectId;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $request->currentRevaluationType = $searchRequest->currentRevaluationType;
            $request->examType = $searchRequest->examType;
            $request->packetNo = $searchRequest->packetNo;
            $request->markSaveType = $searchRequest->markSaveType;
            $studentMarkArray = $searchRequest->studentsMarkDetails;
            $maxmarkOfSubject = 0;
            $maximumStudentsInPacket = 0;
            $registredStudentsFalseNoArray = [];
            $registeredStudentDetailsByFalseNo =[];
            $examValuation = new \Stdclass();
            $examValuation->academicPaperSubjectId = $request->academicPaperSubjectIds;
            $examValuation->packetNo = $request->packetNo;
            $examValuation->examRegistrationId = $request->examRegistrationId;
            $examValuation->currentRevaluationType = $request->currentRevaluationType;
            $examValuation->currentValuationCount =$request->currentValuationCount  ? $request->currentValuationCount  : 1;
           
            $currentSubject = reset(ExamRegistrationSubjectService::getInstance()->getSubjectForCurrentStaffsRevaluation($request));
            if($currentSubject){
                $currentSubject->isConfiremed = "";
                $currentSubject->assessmentProperties = json_decode($currentSubject->assessmentProperties);
                $currentSubject->valuationDetails = json_decode($currentSubject->valuationDetails);
                $maxmarkOfSubject = (int)$currentSubject->externalMaxMark;
                $allStudentMarkDetails = $this->getAllStudentsMarksWithFalseNumberOrderForRevaluation($request);
               
            }
            $maximumStudentsInPacket = count($allStudentMarkDetails);
            foreach($allStudentMarkDetails as $registeredStudent){
                $registeredStudent->falseNo = strtoupper($registeredStudent->falseNo);
                $registredStudentsFalseNoArray[$registeredStudent->falseNo] = $registeredStudent->falseNo;
                $registeredStudentDetailsByFalseNo[$registeredStudent->falseNo] = [
                    "studentId" => $registeredStudent->studentID,
                    "assessmentId" => $registeredStudent->assessmentId,
                    "registerNo" => $registeredStudent->regNo,
                    "falseNo" => $registeredStudent->falseNo
                       ];
            }
            if(!empty($studentMarkArray)){
                foreach($studentMarkArray as $student){
                    $valuationStudents = new \Stdclass();
                    $falseNo = strtoupper($student['falseNo']);
                    if ( in_array ( $falseNo, $registredStudentsFalseNoArray ) ) {
                        if($student['mark']){
                            if ( $student['mark'] > $maxmarkOfSubject ){
                                $markExceedsTotalMark[] = $student['falseNo'];
                                $errorFlag = 1;
                            }
                            else{
                                $valuationStudents->falseNumber = $student['falseNo'];
                                $valuationStudents->studentId = $registeredStudentDetailsByFalseNo[$falseNo]["studentId"];
                                $valuationStudents->mark = $student['mark'];
                                $valuationStudents->falseNoOrder =  $student['falseNoOrder'];
                                $valuationStudents->staffRevaluatedType =  $student['staffRevaluatedType'];
                                $valuationStudents->assessmentId = $registeredStudentDetailsByFalseNo[$falseNo]["assessmentId"];
                                $valuationStudents->registerNumber = $registeredStudentDetailsByFalseNo[$falseNo]["registerNo"];
                                $examValuation->examValuationStudentMarkDetails[] = $valuationStudents;
                                $regStudentCount++;
                            }
                        }
                    }
                    else{
                        $unregisteredStudents[] = $student['falseNo'];
                        $errorFlag = 1;
                    }
                }
                if($request->markSaveType == "CONFIRM"){
                    if($regStudentCount != $maximumStudentsInPacket){
                        throw new ExamControllerException(ExamControllerException::NOT_ENTERED_ALL_MARKS,"Please Enter All The Marks!");
                    }
                    else{
                        $examValuation->markSaveType = $request->markSaveType;
                        $response = $this->saveExamValuationStudentmarksWithOrderForStaffSideMarkEntryRevaluation ( $examValuation );
                        $searchRequest = new \Stdclass();
                        $searchRequest->examRegistrationId = $request->examRegistrationId;
                        $searchRequest->academicPaperSubjectIds = $request->academicPaperSubjectIds;
                        $searchRequest->currentValuationCount = $request->currentValuationCount;
                        $searchRequest->currentRevaluationType = $request->currentRevaluationType;
                        $searchRequest->packetNo =  $request->packetNo;
                        $searchRequest->markEntryStatus = "CONFIRMED";
                        $searchRequest->valuationStaffType = 'ADDITIONAL_EVALUVATOR';
                        $this->saveExtrenalMarkStatusByStaffSideWithPacketNoRevaluation( $searchRequest );
                    }
                }
                elseif($regStudentCount) {
                    $examValuation->markSaveType = $request->markSaveType;
                    $response = $this->saveExamValuationStudentmarksWithOrderForStaffSideMarkEntryRevaluation ( $examValuation );
                    $searchRequest = new \Stdclass();
                    $searchRequest->examRegistrationId = $request->examRegistrationId;
                    $searchRequest->academicPaperSubjectIds = $request->academicPaperSubjectIds;
                    $searchRequest->currentValuationCount = $request->currentValuationCount;
                    $searchRequest->currentRevaluationType = $request->currentRevaluationType;
                    $searchRequest->packetNo =  $request->packetNo;
                    $searchRequest->markEntryStatus = "SAVED";
                    $searchRequest->valuationStaffType = 'ADDITIONAL_EVALUVATOR';
                    $this->saveExtrenalMarkStatusByStaffSideWithPacketNoRevaluation( $searchRequest );
                }
            }
            else{
                $errors["unregisteredStudent"] = $errors["markExceedsTotalMark"] =$errors["error"] = $errors["success"] = $errors["notEligibleThirdValuation"] = $errors["secondValuationNotCompletedStudents"] = $errors["firstValuationNotCompletedStudents"] = $errors["otherPacketStudents"] ="";
                $errors["error"] = "No Student Mark Entered";
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    public function saveExtrenalMarkStatusByStaffSideWithPacketNoRevaluation($request){
        $searchRequest = $this->realEscapeObject($request);
        try {
            $updateValuatedStaffValues = [];
            $request = new \stdClass;
            $request->academicPaperSubjectIds = $searchRequest->academicPaperSubjectIds;
            $request->examRegistrationId = $searchRequest->examRegistrationId;
            $request->currentValuationCount = $searchRequest->currentValuationCount;
            $request->currentRevaluationType = $searchRequest->currentRevaluationType;
            $request->packetNo = $searchRequest->packetNo;
            $request->valuationStaffType = $searchRequest->valuationStaffType;
            $valuatedStaffs =  new \stdClass;
            $valuationProperties =  new \stdClass;
            $valuatedStaffs->staffId = $GLOBALS['userId'];
            $valuatedStaffs->markEntryStatus = $searchRequest->markEntryStatus;
            $valuatedStaffs->count = $request->currentValuationCount;
            $valuatedStaffs->packetNo = $request->packetNo;
            $valuatedStaffs->revaluationType = $searchRequest->currentRevaluationType;
            $valuatedStaffs->valuationStaffType = $request->valuationStaffType;
            $valuatedStaffs->valuatedAnsweSheetCount = 0;
            $valuationProperties->reValuatedStaffs = $valuatedStaffs;
            $subjects = ExamRegistrationSubjectService::getInstance()->getSubjectForCurrentStaffsRevaluation($request);
            foreach($subjects as $subject){
                $facultyUpdated = false;
                if(is_null($subject->valuationDetails)){
                    $subject->valuationDetails = $valuationProperties;
                }
                else{
                    $subject->valuationDetails = json_decode($subject->valuationDetails);
                    if(is_null($subject->valuationDetails->reValuatedStaffs)){
                        $subject->valuationDetails->reValuatedStaffs[] = $valuatedStaffs;
                    }
                    else{
                        foreach($subject->valuationDetails->reValuatedStaffs as $valuatedStaff){
                            if($valuatedStaff->count == $request->currentValuationCount && $valuatedStaff->packetNo == $request->packetNo && $valuatedStaff->valuationStaffType == $request->valuationStaffType){
                                $valuatedStaff->staffId = $GLOBALS['userId'];
                                $valuatedStaff->markEntryStatus = $searchRequest->markEntryStatus;
                                $valuatedStaff->valuatedAnsweSheetCount = 0;
                                $facultyUpdated = true;
                            }
                        }
                        if(!$facultyUpdated){
                            $subject->valuationDetails->reValuatedStaffs[] = $valuatedStaffs;
                        }
                    }
                }
                $updateSubjectValuationDetals = new \stdClass;
                $updateSubjectValuationDetals->assessmentId = $subject->assessmentId;
                $updateSubjectValuationDetals->valuationDetails = $subject->valuationDetails;
                $updateValuatedStaffValues[]=$updateSubjectValuationDetals;
            }
            if(!empty($updateValuatedStaffValues)){
                $this->updateValuatedStaffToExamRegistraionSubject($updateValuatedStaffValues);
            }
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * save Exam Valuation Studentmarks For Staff Side Mark Entry Revaluation
     * @param $examValuation
     * @return $response
     */
    public function saveExamValuationStudentmarksWithOrderForStaffSideMarkEntryRevaluation($examValuation){
        $examValuation = $this->realEscapeObject($examValuation);
        try {
            $examRegistrationId = $examValuation->examRegistrationId;
            $academicPaperSubjectId = $examValuation->academicPaperSubjectId;
            $currentValuationCount = $examValuation->currentValuationCount;
            $studentMarkDetailsArray = $examValuation->examValuationStudentMarkDetails;
            $studentMarkDetailsArray = $examValuation->examValuationStudentMarkDetails;
            $currentRevaluationType = $examValuation->currentRevaluationType;
            $markSaveType = $examValuation->markSaveType;
            $registeredStudentsArray = [];
            $registeredStudentsCurrentMarks = [];
            $registeredStudentsFalseNumberOrder = [];
            $registeredStudentRevaluvatedType = [];
            $error = 0;
            $currentStaffId = $GLOBALS['userId'];
            $updatedStudentCount = 0;
            $insertionMarkTableArray = [];
            $studentMarkDetails = [];
            $valuationProperties = new \Stdclass();
            $markProperties = new \Stdclass();
            $response = new \Stdclass();
            $valuatedStaffObject = new \Stdclass();
            $valuatedStaffObject->staffIds = $currentStaffId;
            $valuatedStaffObject->count = $examValuation->currentValuationCount;
            $valuatedStaffObject->revaluationType = $examValuation->currentRevaluationType;
            $valuationProperties->reValuatedStaffs[]=$valuatedStaffObject;
            $courseTypeId = $this->getCourseTypeIdByExamRevaluationIdAndPaperSubjectId($examRegistrationId,$academicPaperSubjectId);
            $maxmarkOfSubject = (int)ExamRegistrationSubjectService::getInstance()->getMaxSubjectMarkByAcademicPaperSubjectId($academicPaperSubjectId);
            $markDiff = CommonExamService::getInstance()->getExternalValuationMarkDiff($courseTypeId,$maxmarkOfSubject);
            $valuationProperties->packetNo = $examValuation->packetNo;
            foreach($studentMarkDetailsArray as $student){
                if(($student->registerNumber) && ($student->mark != "")){
                    $conditions[] = " (sa.regNo = '".$student->registerNumber."' AND  esar.am_assessment_id = '".$student->assessmentId."'  AND eer.id = '".$examRegistrationId."' AND esar.identifying_context->>'$.revaluationType' = '".$currentRevaluationType."') ";
                }
            }
            $request = new \stdClass;
            $request->academicPaperSubjectIds = $examValuation->academicPaperSubjectId;
            $request->examRegistrationId = $examValuation->examRegistrationId;
            $request->currentValuationCount = $examValuation->currentValuationCount;
            $request->currentRevaluationType = $examValuation->currentRevaluationType;
            $request->packetNo = $examValuation->packetNo;
            $subject = reset(ExamRegistrationSubjectService::getInstance()->getSubjectForCurrentStaffsRevaluation($request));
            $valuationRules =  (array) $this->getAllValuationRule();
            $definedValuationRule = json_decode($subject->valuationRule);
            $selectedSecondValuationRule = reset(array_filter($definedValuationRule, function ($rule) {
                return $rule->count == 2;
            }));
            $selectedThirdValuationRule = reset(array_filter($definedValuationRule, function ($rule) {
                return $rule->count == 3;
            }));
            $secondValuationRuleKey =  array_search($selectedSecondValuationRule->ruleId, array_column( $valuationRules, "id"));
            $thirdValuationRuleKey =  array_search($selectedThirdValuationRule->ruleId, array_column( $valuationRules, "id"));
            if($secondValuationRuleKey !== false){
                $secondValuationRule = $valuationRules[$secondValuationRuleKey];
            }
            if($thirdValuationRuleKey !== false){
                $thirdValuationRule = $valuationRules[$thirdValuationRuleKey];
            }
            if(empty($definedValuationRule)){
                throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS,"Please define valuation rule!");
            }
            if(! empty($conditions)){
                $searchStudentRequest = new \Stdclass();
                $studentDetails = $this->getAllStudentsMarksWithFalseNumberOrderForRevaluation($searchStudentRequest,$conditions);
                foreach($studentMarkDetailsArray as $student){
                    $registeredStudentsArray[$student->studentId] = $student->studentId;
                    $registeredStudentsCurrentMarks[$student->studentId] = $student->mark;
                    $registeredStudentsFalseNumberOrder[$student->studentId] = $student->falseNoOrder;
                    $registeredStudentRevaluvatedType[$student->studentId] = $currentRevaluationType;
                }
                foreach($studentDetails as $studentDetail){
                    if ( in_array ( $studentDetail->studentId, $registeredStudentsArray ) ) {
                        $singleStudentDetail = new \Stdclass();
                        $facultyUpdated = false;
                        $orderUpdated = false;
                        $singleStudentDetail->studentId = $studentDetail->studentId;
                        $singleStudentDetail->registerNumber = $studentDetail->regNo;
                        $singleStudentDetail->assessmentId = $studentDetail->assessmentId;
                        $singleStudentDetail->revaluationId = $examRegistrationId;
                        $singleStudentDetail->oeExamId = $studentDetail->onlineExamId;
                        $singleStudentDetail->currentMark = $registeredStudentsCurrentMarks[$studentDetail->studentId];
                        $singleStudentDetail->falseNoOrder = $registeredStudentsFalseNumberOrder[$studentDetail->studentId];
                        $singleStudentDetail->revaluationType = $registeredStudentRevaluvatedType[$studentDetail->studentId];
                        $singleStudentDetail->finalizedMarkProperties = $studentDetail->finalizedMarkProperties ? json_decode($studentDetail->finalizedMarkProperties) : null;
                        $singleStudentDetail->firsrValuationMark = $studentDetail->firstValuationMark;
                        $singleStudentDetail->oldRevaluationMark = $studentDetail->oldRevaluationMark;
                        $singleStudentDetail->secondValuationId = $studentDetail->secondValuationId;
                        $singleStudentDetail->secondValuationMark = $studentDetail->secondValuationMark;
                        $singleStudentDetail->thirdValuationId = $studentDetail->thirdValuationId;
                        $singleStudentDetail->thirdValuationMark = $studentDetail->thirdValuationMark;
                        $singleStudentDetail->finalizedValuationId = $studentDetail->finalizedValuationId;   
                        $singleStudentDetail->finalizedMark = $studentDetail->revaluationMark;
                        $singleStudentDetail->thirdValReq = $studentDetail->thirdValReq;
                        $valuatedOrderObject = new \Stdclass();
                        $valuationOrderProperties = new \Stdclass();
                        $valuatedOrderObject->count = $currentValuationCount;
                        $valuatedOrderObject->revaluationType = $currentRevaluationType;
                        $valuatedOrderObject->falseNoOrder = (int)$singleStudentDetail->falseNoOrder;
                        $valuationOrderProperties->reValuationOrder[]= $valuatedOrderObject;
                        $valuationDetails =  json_decode($studentDetail->valuationDetails);
                        $singleStudentDetail->valuationDetails = $valuationDetails;
                        if(is_null($studentDetail->reValuationOrders)){
                            $singleStudentDetail->valuationOrderDetails = $valuationOrderProperties;
                        }
                        else if($studentDetail->valuationOrders){
                            $valuationOrders = json_decode($studentDetail->valuationOrders);
                            foreach($valuationOrders as $valuationOrder){
                                if($valuationOrder->count == $currentValuationCount){
                                    $valuationOrder->falseNoOrder = (int)$singleStudentDetail->falseNoOrder;
                                    $orderUpdated = true;
                                }
                            }
                            if(!$orderUpdated){
                                $valuationOrders[] = $valuatedOrderObject;
                            }
                            $singleStudentDetail->valuationOrderDetails->reValuationOrder = $valuationOrders;
                        }
                        if( $singleStudentDetail->studentId){
                            $studentMarkDetails[] = $singleStudentDetail;
                        }
                    }
                }
                foreach($studentMarkDetails as $studentMarkDetail){
                    if($currentValuationCount == '1' ){
                        if( empty($secondValuationRule->code) ){
                            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS,"Please define second valuation rule!");
                        }
                        $revaluationObj = new ExamUserMarkRequest();
                        $revaluationObj->id = $studentMarkDetail->secondValuationId ?? NULL;
                        $revaluationObj->studentId = $studentMarkDetail->studentId;
                        $revaluationObj->assessmentId = $studentMarkDetail->assessmentId;
                        $revaluationObj->oeExamsId = $studentMarkDetail->oeExamId;
                        $revaluationObj->valuationType = "REVALUATION";
                        $revaluationObj->revaluationType = $studentMarkDetail->revaluationType;
                        $revaluationObj->revaluationId = $studentMarkDetail->revaluationId;
                        $revaluationObj->markObtained = $studentMarkDetail->currentMark;
                        $revaluationObj->createdBy = $GLOBALS['userId'];
                        $revaluationObj->valuationCount = '2';
                        $properties = new \stdClass();
                        // $properties->finalizedMark = $finalized;
                        if($markSaveType == "CONFIRM"){
                            $studentMarkDiff = abs ($studentMarkDetail->firsrValuationMark - $studentMarkDetail->currentMark);
                            if( $studentMarkDiff >= $markDiff){
                                $properties->hasEligibleThirdValuation= true;
                            }
                            else{
                                $revaluationObj->id = $studentMarkDetail->secondValuationId ?? NULL;
                                $revaluationObj = new ExamUserMarkRequest();
                                $revaluationObj->id = $studentMarkDetail->finalizedValuationId;
                                $revaluationObj->studentId = $studentMarkDetail->studentId;
                                $revaluationObj->assessmentId = $studentMarkDetail->assessmentId;
                                $revaluationObj->oeExamsId = $studentMarkDetail->oeExamId;
                                $revaluationObj->valuationType = "REVALUATION";
                                $revaluationObj->revaluationType = $studentMarkDetail->revaluationType;
                                $revaluationObj->revaluationId = $studentMarkDetail->revaluationId;
                                $revaluationObj->markObtained = $studentMarkDetail->currentMark;
                                $revaluationObj->createdBy = $GLOBALS['userId'];
                                $revaluationObj->valuationCount = 'FINALIZED';
                                $properties = new \stdClass();
                                // $properties->finalizedMark = $finalized;
                                $revaluationMarkEntryObj = clone $revaluationObj;              
                                $revaluationMarkEntryObj->properties = $properties;              
                                $studentRevaluationMark[] = $revaluationMarkEntryObj;
                                $studentMark = [];
                                $studentMark[0] = $studentMarkDetail->oldRevaluationMark ;
                                $studentMark[1] = $studentMarkDetail->currentMark;
                                $finalizeMark =  $this->getFinalizedMarkFromValuationRule($studentMark, $secondValuationRule->code);
                                $markEntryObj = new \stdClass();
                                $markEntryObj->studentId = $studentMarkDetail->studentId;
                                $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                                $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                                $markEntryObj->valuationType = 'REVALUATION';
                                $markEntryObj->markObtained = $finalizeMark;
                                $markEntryObj->attendanceStatus = "PRESENT";
                                $markEntryObj->valuationCount = 'FINALIZED';
                                $markproperties = "";
                                if($studentMarkDetail->finalizedMarkProperties){
                                    $markproperties = (object)$studentMarkDetail->finalizedMarkProperties;
                                }
                                $markEntryObj->properties  = $markproperties;
                                $insertionMarkTableArray[] = $markEntryObj;
                            }
                        }
                        $revaluationMarkEntryObj = clone $revaluationObj;              
                        $revaluationMarkEntryObj->properties = $properties;              
                        $studentRevaluationMark[] = $revaluationMarkEntryObj;
                        $updateMarkValuatedStaff = new \Stdclass();
                        $updateMarkValuatedStaff->assessmentId = $studentMarkDetail->assessmentId;
                        $updateMarkValuatedStaff->studentId = $studentMarkDetail->studentId;
                        $updateMarkValuatedStaff->revaluationType = $currentRevaluationType;
                        $updateMarkValuatedStaff->valuationProperties = $studentMarkDetail->valuationDetails;
                        $updateMarkValuatedStaff->valuationOrderDetails = $studentMarkDetail->valuationOrderDetails;
                        $updateMarkValuatedStaff->updatedBy = $currentStaffId ;
                        $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                        $updatedStudentCount ++;
                    }
                    elseif($currentValuationCount == 2 ){
                        if( empty($thirdValuationRule->code) ){
                            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS,"Please define third valuation rule!");
                        }
                        $revaluationObj = new ExamUserMarkRequest();
                        $revaluationObj->studentId = $studentMarkDetail->studentId;
                        $revaluationObj->assessmentId = $studentMarkDetail->assessmentId;
                        $revaluationObj->oeExamsId = $studentMarkDetail->oeExamId;
                        $revaluationObj->valuationType = "REVALUATION";
                        $revaluationObj->revaluationType = $studentMarkDetail->revaluationType;
                        $revaluationObj->revaluationId = $studentMarkDetail->revaluationId;
                        $revaluationObj->markObtained = $studentMarkDetail->currentMark;
                        $revaluationObj->createdBy = $GLOBALS['userId'];
                        $revaluationObj->valuationCount = '3';
                        $properties = new \stdClass();
                        // $properties->finalizedMark = $finalized;
                        $revaluationMarkEntryObj = clone $revaluationObj;              
                        $revaluationMarkEntryObj->properties = $properties;              
                        $studentRevaluationMark[] = $revaluationMarkEntryObj;
                        if($markSaveType == "CONFIRM"){
                            $studentMark = array($studentMarkDetail->firsrValuationMark,$studentMarkDetail->secondValuationMark,$studentMarkDetail->currentMark);
                            $studentMark = [];
                            $studentMark[0] = $studentMarkDetail->firsrValuationMark ;
                            $studentMark[1] = $studentMarkDetail->secondValuationMark;
                            $studentMark[2] = $studentMarkDetail->currentMark;
                            $finalizedMark =  $this->getFinalizedMarkFromValuationRule($studentMark, $thirdValuationRule->code);
                            $revaluationObj = new ExamUserMarkRequest();
                            $revaluationObj->studentId = $studentMarkDetail->studentId;
                            $revaluationObj->assessmentId = $studentMarkDetail->assessmentId;
                            $revaluationObj->oeExamsId = $studentMarkDetail->oeExamId;
                            $revaluationObj->valuationType = "REVALUATION";
                            $revaluationObj->revaluationType = $studentMarkDetail->revaluationType;
                            $revaluationObj->revaluationId = $studentMarkDetail->revaluationId;
                            $revaluationObj->markObtained = $finalizedMark;
                            $revaluationObj->createdBy = $GLOBALS['userId'];
                            $revaluationObj->valuationCount = 'FINALIZED';
                            $properties = new \stdClass();
                            // $properties->finalizedMark = $finalized;
                            $revaluationMarkEntryObj = clone $revaluationObj;              
                            $revaluationMarkEntryObj->properties = $properties;              
                            $studentRevaluationMark[] = $revaluationMarkEntryObj;
                           
                            $markEntryObj = new \stdClass();
                            $markEntryObj->studentId = $studentMarkDetail->studentId;
                            $markEntryObj->assessmentId = $studentMarkDetail->assessmentId;
                            $markEntryObj->oeExamsId = $studentMarkDetail->oeExamId;
                            $markEntryObj->valuationType = 'REVALUATION';
                            $markEntryObj->markObtained = $finalizedMark;
                            $markEntryObj->attendanceStatus = "PRESENT";
                            $markEntryObj->valuationCount = 'FINALIZED';
                            $markproperties = "";
                            if($studentMarkDetail->finalizedMarkProperties){
                                $markproperties = (object)$studentMarkDetail->finalizedMarkProperties;
                            }
                            $markEntryObj->properties  = $markproperties;
                            $insertionMarkTableArray[] = $markEntryObj;
                        }
                        $updateMarkValuatedStaff = new \Stdclass();
                        $updateMarkValuatedStaff->assessmentId = $studentMarkDetail->assessmentId;
                        $updateMarkValuatedStaff->studentId = $studentMarkDetail->studentId;
                        $updateMarkValuatedStaff->revaluationType = $currentRevaluationType;
                        $updateMarkValuatedStaff->valuationProperties = $studentMarkDetail->valuationDetails;
                        $updateMarkValuatedStaff->valuationOrderDetails = $studentMarkDetail->valuationOrderDetails;
                        $updateMarkValuatedStaff->updatedBy = $currentStaffId ;
                        $updateValuatedStaffValues[] = $updateMarkValuatedStaff;
                        $updatedStudentCount ++;
                    }
                }
            }
            if(!empty($updateValuatedStaffValues)){
                $this->updateValuatedStaffToStudentRegistration($updateValuatedStaffValues);
            }
            if(! empty($studentRevaluationMark)){
                ExamRevaluationService::getInstance()->saveStudentRevaluationMarks($studentRevaluationMark);
            }
            if(! empty($insertionMarkTableArray)){
                ExamUserMarkService::getInstance()->saveExamUserTotalMark($insertionMarkTableArray);
            }
            $response->error = $error;
            $response->updatedStudentCount = $updatedStudentCount;
             }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    /**
     * print packet issue register
     */
    public function printPacketIssueRegister($subjects,$request){
        try{
            $result = null;
            if(empty($subjects)){
                throw new ExamControllerException(ExamControllerException::PACKETS_NOT_GENERATED,"Packets Are Not Generated,Please Assign Subject Packets");
            }
            else{
                $searchRequest = new SearchExamRegistrationRequest();
                $searchRequest->id = current($subjects)->ec_exam_registration_id;
                $examRegDetails = current(ExamRegistrationService::getInstance()->searchExamRegistration($searchRequest)); 
                $templateName = "examPacketListRegisterTemplate";
                $data = new \stdClass();
                $data->subjects = $subjects;
                $data->examRegDetails->name = $examRegDetails->name;
                $courseTypeId = PacketService::getInstance()->getCourseTypeIdByExamRegistrationId($searchRequest->id,$request->examType);
                $courseType = CourseTypeService::getInstance()->getCourseTypesById ($courseTypeId);
                $pageNumberPrefix = "UG [page]";
                if($courseType->extValRequired == "1"){
                    $data->examRegDetails->isPg = true;
                    $pageNumberPrefix = "PG [page]";
                }
                $data->examRegDetails->studentPerPacket =  CommonService::getInstance()->getSettings("EXAM_VALUATION", "ANSWERSHEETS_PER_PACKET");
                $collegeDetails = CommonExamService::getInstance()->getCollegeDetails();
                if($request->reportType == 'packet-issue'){
                    $templateName = "issuedPacketListTemplate";
                }else if ($request->reportType == 'exam-register'){
                    $templateName = "examPacketListRegisterTemplate";
                }
                $responseHtml = TwigRenderer::renderTemplateFileToHtml(realpath(DOCUMENT_ROOT."../examcontroller-api/src/com/linways/web/templates/printTwigs/$templateName.twig"), [ 'data'=>$data,'college',$collegeDetails]);
                $prtContent = NULL;
                    $prtContent .= '<html><head>';
                    $prtContent .= "<style>
                        
                        </style>";
                    $prtContent .= '</head><title>Subject Assigned Staff Report </title><body>';
                    $prtContent .= $responseHtml;
                    $prtContent .= '</body></html>';
                    $totalWidth = 210;
                    $totalHeight = 297;
                    $options = array(
                        'page-width'     => $totalWidth."mm",
                        'page-height'    => $totalHeight."mm",
                        'dpi'         => 96,
                        'margin-bottom' => "10mm",
                        'margin-top' => "10mm",
                        'footer-right' => $pageNumberPrefix,
                        // 'binary' => "/usr/local/bin/wkhtmltopdf", // For Mac
                        'user-style-sheet' => realpath(DOCUMENT_ROOT . "/libcommon/bootstrap/css/bootstrap.min.css")
                    );
                $result = new \stdClass;
                $result->displayData = $responseHtml;
                $result->pdf = PdfUtil::renderPdf($prtContent, $options);
            }
            return  $result;
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        
    }
        /**
     * get All Students Marks Details For ExamRegistration Subject
     * @param $searchRequest
     * @return $response
     */
    public function getAllFalseNoStudentsMarksDetailsForExamRegistrationSubject($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try {
            $response = new \stdClass;
            $registeredStudentMarkDetails = [];
            $isnotPG = false;
            $currentValuationCount = null;
            $academicPaperId = stripslashes($searchRequest->academicPaperId);
            $markEntryEditSettings = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::EXAM_VALUATION_MARK_EDIT);
            $isFalseNumber = CommonService::getInstance()->getSettings(SettingsConstents::EXAM_VALUATION, SettingsConstents::IS_FALSE_NUMBER_IN_EXTERNAL_MARK_ENTRY_DIRECT);
            $editEnabled = CommonUtil::isEditEnabledInExamValuation ( $markEntryEditSettings, ExamType::EXTERNAL );
            $subjectDetails = $this->getSubjectDetailsByAcademicPaperSubjectId($academicPaperId);
            $maxmarkOfSubject = ExamRegistrationSubjectService::getInstance()->getMaxSubjectMarkByAcademicPaperSubjectId($academicPaperId);
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ($searchRequest->courseType);
            if(! $subjectDetails->isExternal){
                throw new ExamControllerException(ExamControllerException::INTERNAL_ONLY_SUBJECT,"Internal Only Subject");
            }
            elseif(! $subjectDetails->maximumSubjectMark){
                throw new ExamControllerException(ExamControllerException::MAX_MARK_NOT_CONFIGURED,"Subject not configured");
            }
            $searchRequest->academicPaperSubjectId =  $academicPaperId;
            $valuationDetails = ExamRegistrationSubjectService::getInstance()->getExamregistrationSubjectDetails($searchRequest)->valuationDetails;
            $valuationDetails = $valuationDetails ? json_decode($valuationDetails)->valuationDates:"";
            $inDateRange = 0;
            $today = date("Y-m-d H:i");
            foreach($valuationDetails as $valuationDate){
                if( $valuationDate->count == $searchRequest->currentValuationCount && (strtotime($today) >= strtotime($valuationDate->startDate)) && (strtotime($today) <= strtotime($valuationDate->endDate))){
                    $inDateRange = 1;
                }
            }
            if(!$inDateRange){
                throw new ExamControllerException(ExamControllerException::DATE_NOT_IN_RANGE,"Valuation Date is not in range");
            }
            if($courseType->extValRequired == '1'){
                $currentValuationCount = $searchRequest->currentValuationCount;
                $isnotPG = false;
            }
            else{
                $currentValuationCount = $searchRequest->currentValuationCount;
                $isnotPG = true;
            }
            if($editEnabled){
                if($isnotPG){
                    $request = new \stdClass;
                    $request->examRegistrationId = $searchRequest->examRegistrationId;
                    $request->academicPaperSubjectId = $academicPaperId;
                    $request->groupId = $searchRequest->groupId;
                    $request->showFinalizedMarkOnly = $searchRequest->showFinalizedMarkOnly;
                    $registeredStudentMarkDetails = $this->getAllStudentEditExternalMarksByExamRegistrationSubject($request);
                    foreach($registeredStudentMarkDetails as $student){
                        $student->isWithHeld  = false;
                        if ( $student->isExempted == 1 ) {
                            $student->mark = "EX";
                            $student->oldMark  = 'Exempted';
                        }
                        else if ( $student->isAbsent == "ABSENT" ) {
                            $student->mark  = "AB";
                            $student->oldMark  = 'Absent';
                        } 
                        else if ( $student->isAbsent == "MALPRACTICE" ) {
                            $student->mark  = "MAL";
                            $student->oldMark  = 'Mal-Practice';
                        } 
                        else if ($student->isAbsent == "WITHHELD") {
                            $student->mark  = $student->finalizedMark;
                            $student->isWithHeld  = true;
                            $student->oldMark  = 'with held';
                        }
                        else{
                            $student->mark  = $student->finalizedMark;
                            $student->oldMark  = $student->finalizedMark;
                        }
                        // to disable valuation markentry if its confirmed
                        if($student->finalizedValuationConfirm == "1"){
                            $student->isCurrentValuationFinalized = 1;
                        }
                    }
                }
                else{
                    if($currentValuationCount == 1){
                        $request = new \stdClass;
                        $request->examRegistrationId = $searchRequest->examRegistrationId;
                        $request->academicPaperSubjectId = $academicPaperId;
                        $request->groupId = $searchRequest->groupId;
                        $request->isFirstValuatedAndAbsentMarkedStudents = $searchRequest->isFirstValuatedStudentOnly;
                        $registeredStudentMarkDetails = $this->getAllStudentEditExternalMarksByExamRegistrationSubject($request);
                        foreach($registeredStudentMarkDetails as $student){
                            $student->isWithHeld  = false;
                            if ( $student->isExempted == 1 ) {
                                $student->mark = "EX";
                                $student->oldMark  = 'Exempted';
                            }
                            else if ( $student->isAbsent == "ABSENT" ) {
                                $student->mark  = "AB";
                                $student->oldMark  = 'Absent';
                                $student->isCurrentValuationFinalized = 1;
                            } 
                            else if ( $student->isAbsent == "MALPRACTICE" ) {
                                $student->mark  = "MAL";
                                $student->oldMark  = 'Mal-Practice';
                            } 
                            else if ($student->isAbsent == "WITHHELD") {
                                $student->mark  = $student->firstValuationMark;
                                $student->isWithHeld  = true;
                                $student->oldMark  = 'with held';
                            }
                            else{
                                $student->mark  = $student->firstValuationMark;
                            }
                            if($student->finalizedValuationConfirm == "1"){
                                $student->isCurrentValuationFinalized = 1;
                            }
                            // to disable valuation markentry if its confirmed
                            if($student->firstValuationConfirm == "1"){
                                $student->isCurrentValuationFinalized = 1;
                            }
                        }
                    }
                    else if($currentValuationCount == 2){
                        $markDiff = CommonExamService::getInstance()->getExternalValuationMarkDiff($searchRequest->courseType,$maxmarkOfSubject);
                        $request = new \stdClass;
                        $request->examRegistrationId = $searchRequest->examRegistrationId;
                        $request->academicPaperSubjectId = $academicPaperId;
                        $request->groupId = $searchRequest->groupId;
                        $request->isFirstValuatedStudentOnly = true;
                        $registeredStudentMarkDetails = $this->getAllStudentEditExternalMarksByExamRegistrationSubject($request);
                        foreach($registeredStudentMarkDetails as $student){
                            $student->isWithHeld  = false;
                            if ( $student->isExempted == 1 ) {
                                $student->mark = "EX";
                            }
                            else if ( $student->isAbsent == "ABSENT" ) {
                                $student->mark  = "AB";
                            } 
                            else if ( $student->isAbsent == "MALPRACTICE" ) {
                                $student->mark  = "MAL";
                            } 
                            else if ($student->isAbsent == "WITHHELD") {
                                $student->mark  = $student->secondValuationMark." (With Held)";
                                $student->isWithHeld  = true;
                            }
                            else{
                                $student->mark  = $student->secondValuationMark;
                            }
                            // to disable valuation markentry if its confirmed
                            if($student->secondValuationConfirm == "1"){
                                $student->isCurrentValuationFinalized = 1;
                            }
                            if($student->secondValuationMark != null){
                                $studentMarkDiff = abs ($student->firstValuationMark - $student->secondValuationMark);
                                if($studentMarkDiff >= $markDiff){
                                    $student->thirdValRequiredFlag = 1;
                                }
                                else{
                                    $student->thirdValRequiredFlag = 0;
                                }
                            }
                            else{
                                $student->thirdValRequiredFlag = 0;
                            }
                        }
                    }
                    else if($currentValuationCount == 3){
                        $request = new \stdClass;
                        $request->examRegistrationId = $searchRequest->examRegistrationId;
                        $request->academicPaperSubjectId = $academicPaperId;
                        $request->groupId = $searchRequest->groupId;
                        $request->isFirstValuatedStudentOnly = true;
                        $request->isSecondValuatedStudentOnly = true;
                        $request->isThirdValuationStudentOnly = true;
                        $registeredStudentMarkDetails = $this->getAllStudentEditExternalMarksByExamRegistrationSubject($request);
                        foreach($registeredStudentMarkDetails as $student){
                            $student->isWithHeld  = false;
                            if ( $student->isExempted == 1 ) {
                                $student->mark = "EX";
                            }
                            else if ( $student->isAbsent == "ABSENT" ) {
                                $student->mark  = "AB";
                            } 
                            else if ( $student->isAbsent == "MALPRACTICE" ) {
                                $student->mark  = "MAL";
                            } 
                            else if ($student->isAbsent == "WITHHELD") {
                                $student->mark  = $student->thirdValuationMark." (With Held)" ;
                                $student->isWithHeld  = true;
                            }
                            else{
                                $student->mark  = $student->thirdValuationMark;
                            }
                            // to disable valuation markentry if its confirmed
                            if($student->thirdValuationConfirm == "1"){
                                $student->isCurrentValuationFinalized = 1;
                            }
                        }
                    } 
                }
            }
            if($isnotPG){
                $searchRequest->currentValuationCount=1;
            }
            if(empty($registeredStudentMarkDetails) && $currentValuationCount > 1){
                throw new ExamControllerException(ExamControllerException::NO_REGISTERED_STUDENTS_IN_SUBJECTS,"No student details found");
            }
            else if(!empty($registeredStudentMarkDetails)){
                $isFalseNumberGenerated = $this->checkFalseNumberGenerated($registeredStudentMarkDetails);
                if(!$isFalseNumberGenerated){
                    throw new ExamControllerException(ExamControllerException::FALSE_NUMBER_NOT_GENERATED,"False Number Not Generated");
                }
            }
            $response->MakEntryDetails = $registeredStudentMarkDetails;
            $response->currentValuationCount = (int)$currentValuationCount;
            $response->IsFalseNumberSettings = $isFalseNumber;
            $response->maxMarkOfSubject = (int)$maxmarkOfSubject;
            $response->markDiff = (float)$markDiff;
            $response->subject = $subjectDetails;
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $response;
    }
    private function checkFalseNumberGenerated($registeredStudentMarkDetails){
        $isFalseNumberGenerated = false;
        foreach($registeredStudentMarkDetails as $student){
            if($student->falseNo){
                $isFalseNumberGenerated =  true;
                break;
            }
        }
        return $isFalseNumberGenerated;
    }
    /**
     * save All External Marks examcontroller
     * @param $studentMarkDetailsArray
     * @param $searchRequest
     * @return $subjectDetails
     */
    public function saveAllExternalMarks($studentMarkDetailsArray,$searchRequest){
        $searchRequest = $this->realEscapeArray($searchRequest);
        $studentMarkDetailsArray = $this->realEscapeArray($studentMarkDetailsArray);
        try{
            $adminId =  $GLOBALS['userId'];
            $staffName = $this->getStaffNameByStaffId($adminId);
            $registeredStudentsArray = [];
            $registeredStudentsCurrentMark = [];
            $registeredStudentsAssessmentIds = [];
            $notRegisteredStudents = [];
            $delete_third_val_students = [];
            $editHistoryLog = [];
            $insertionExtrnalMarkLogTableArray = [];
            $examRegistrationId = $searchRequest['examRegistrationId'];
            $academicPaperId = stripslashes($searchRequest['academicPaperId']);
            $currentValuationCount =  1;
            $courseType = CourseTypeService::getInstance()->getCourseTypesById ( $searchRequest['courseType'] );
            $isTheory = $this->getIsTheoryOrNotByExamRegistrationIdAndPaperSubjectId( $examRegistrationId,$academicPaperId);
            $maxmarkOfSubject = ExamRegistrationSubjectService::getInstance()->getMaxSubjectMarkByAcademicPaperSubjectId($academicPaperId);
            $markDiff = CommonExamService::getInstance()->getExternalValuationMarkDiff($searchRequest['courseType'],$maxmarkOfSubject );
            if(($courseType->extValRequired != "1")){
                $currentValuationCount = "FINALIZED";
            }
            else if($courseType->extValRequired == "1"){
                $currentValuationCount =  $searchRequest['currentValuationCount'];
                if(($currentValuationCount == 1) && ($isTheory == "0")){
                    $currentValuationCount = "FINALIZED";
                }
            }
            $markProperties = !empty($markProperties) ? "'" . json_encode($markProperties) . "'" : "NULL";
            //remove current valuation confirmed students from the list
            $studentMarkDetailsArray = $this->filterOutCurrentValuationConfirmedMarkStudents($studentMarkDetailsArray,$searchRequest,$courseType->courseTypeMethod);
            if(empty($studentMarkDetailsArray)){
                throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS,"No marks entered to update!");
            }
            $searchRuleRequest = new SearchRuleRequest;
            $searchRuleRequest->name = "EXAM_VALUATION_PROCEDURE_RULE";
            $examValuationProcedureRule = reset(RuleService::getInstance()->searchRule($searchRuleRequest))->rule;
            $examValuationProcedureRule->isExcatFinalizeMark = $examValuationProcedureRule->isExcatFinalizeMark ? $examValuationProcedureRule->isExcatFinalizeMark : false;
            $examValuationProcedureRule->roundOffDigits = $examValuationProcedureRule->roundOffDigits ? $examValuationProcedureRule->roundOffDigits : 0;
            if( $currentValuationCount == 1 || $currentValuationCount == "FINALIZED"){
                $request = new \stdClass;
                $request->examRegistrationId = $searchRequest['examRegistrationId'];
                $request->academicPaperSubjectId = stripslashes($searchRequest['academicPaperId']);
                $request->groupId = $searchRequest['groupId'];
                $registeredStudentMarkDetails = $this->getAllStudentEditExternalMarksByExamRegistrationSubject($request);
                foreach($registeredStudentMarkDetails as $student){
                    $registeredStudentsArray[$student->id] = $student->id;
                    $registeredStudentsAssessmentIds[$student->id] = $student->assessmentId;
                }
                $registeredStudentMarkDetailsFalseNo = [];
                foreach($registeredStudentMarkDetails as $registeredStudent){
                    $registeredStudentMarkDetailsFalseNo[$registeredStudent->falseNo] = $registeredStudent;
                }
                foreach($studentMarkDetailsArray as $studKey => $studentEntry){
                    if(!$studentEntry['id']){
                        $studentEntry = (array)$registeredStudentMarkDetailsFalseNo[$studentEntry['falseNo']];
                        $studentEntry['mark'] = $studentMarkDetailsArray[$studKey]['mark'];
                        $studentMarkDetailsArray[$studKey] = $studentEntry;
                    }
                    if( in_array ( $studentEntry['id'], $registeredStudentsArray ) ) {
                        if($studentEntry['isWithHeld'] != true){
                            if($studentEntry['mark'] != null){
                                $assessmentId = $registeredStudentsAssessmentIds[$studentEntry['id']];
                                $assessmentId = $registeredStudentsAssessmentIds[$studentEntry['id']];
                                $oeExamId = $studentEntry['oeExamId'];
                                $studentId = $studentEntry['id'];
    
                                // for high lighting edit changes in import mark
                                $editRequest = new \stdClass();
                                $editRequest->groupId = $studentEntry['groupId'];
                                $editRequest->studentId = $studentEntry['id'];
                                $editRequest->isDirty = 1;
                                $editRequest->staffId = $GLOBALS['userId'];
                                $editHistoryLog[] = $editRequest;
                                
                                if($studentEntry['mark'] == "AB"){
                                        $markEntryObj = new \stdClass();
                                        $markEntryObj->studentId = $studentEntry['id'];
                                        $markEntryObj->assessmentId = $assessmentId;
                                        $markEntryObj->oeExamsId = $oeExamId;
                                        $markEntryObj->markObtained = null;
                                        $markEntryObj->attendanceStatus = "ABSENT";
                                        $markEntryObj->valuationCount = 'FINALIZED';
                                        $markproperties = "";
                                        if($studentEntry['finalizedMarkProperties']){
                                            $markproperties = json_decode($studentEntry['finalizedMarkProperties']);
                                            $markproperties->isNotConfirm = 0;
                                        }else{
                                            $markproperties = new \stdClass();
                                            $markproperties->isNotConfirm = 0;
                                        } 
                                        $markEntryObj->properties  = $markproperties;
                                        $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
                                        $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 1;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                        $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 2;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                        $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 3;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                    $deleteExempted[] = " ( am_assessment_id = '".$assessmentId."' AND studentaccount_id =  '".$studentEntry['id']."' ) ";
                                    $delete_third_val_students[] = "( am_assessment_id = '$assessmentId' AND studentID = '".$studentEntry['id']."' )" ;
                                }
                                else if($studentEntry['mark'] == "MAL"){
                                        $markEntryObj = new \stdClass();
                                        $markEntryObj->studentId = $studentEntry['id'];
                                        $markEntryObj->assessmentId = $assessmentId;
                                        $markEntryObj->oeExamsId = $oeExamId;
                                        $markEntryObj->markObtained = null;
                                        $markEntryObj->attendanceStatus = "MALPRACTICE";
                                        $markEntryObj->valuationCount = 'FINALIZED';
                                        $markproperties = "";
                                        if($studentEntry['finalizedMarkProperties']){
                                            $markproperties = json_decode($studentEntry['finalizedMarkProperties']);
                                            $markproperties->isNotConfirm = 0;
                                        }
                                        else{
                                            $markproperties = new \stdClass();
                                            $markproperties->isNotConfirm = 0;
                                        } 
                                        $markEntryObj->properties  = $markproperties;
                                        $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
                                        $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 1;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                        $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 2;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                        $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 3;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                    $deleteExempted[] = " ( am_assessment_id = '".$assessmentId."' AND studentaccount_id =  '".$studentEntry['id']."' ) ";
                                    $delete_third_val_students[] = "( am_assessment_id = '$assessmentId' AND studentID = '".$studentEntry['id']."' )" ;
                                }
                                else if($studentEntry['mark'] == "WH"){
                                        $markEntryObj = new \stdClass();
                                        $markEntryObj->studentId = $studentEntry['id'];
                                        $markEntryObj->assessmentId = $assessmentId;
                                        $markEntryObj->oeExamsId = $oeExamId;
                                        $markEntryObj->markObtained = $studentEntry['finalizedMark'];
                                        $markEntryObj->attendanceStatus = "WITHHELD";
                                        $markEntryObj->valuationCount = 'FINALIZED';
                                        $markproperties = "";
                                        if($studentEntry['finalizedMarkProperties']){
                                            $markproperties = json_decode($studentEntry['finalizedMarkProperties']);
                                            $markproperties->isNotConfirm = 0;
                                        }
                                        else{
                                            $markproperties = new \stdClass();
                                            $markproperties->isNotConfirm = 0;
                                        } 
                                        $markEntryObj->properties  = $markproperties;
                                        $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
                                    $deleteExempted[] = " ( am_assessment_id = '".$assessmentId."' AND studentaccount_id =  '".$studentEntry['id']."' ) ";
                                }
                                else if($studentEntry['mark'] == "EX"){
                                        $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 1;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                    $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 2;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                    $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 3;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                    $deleteMarkEntryObj = new ExamUserMarkRequest;
                                        $deleteMarkEntryObj->assessmentId = $assessmentId;
                                        $deleteMarkEntryObj->studentId =  $studentEntry['id'];
                                        $deleteMarkEntryObj->valuationCount = 'FINALIZED';
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                    $deleteExempted[] = " ( am_assessment_id = '".$assessmentId."' AND studentaccount_id =  '".$studentEntry['id']."' ) ";
                                    $insertExempted[] = " ( '".$studentEntry['id']."', '".$assessmentId."' ,'".$adminId."', utc_timestamp(), '".$adminId."', utc_timestamp() ) ";
                                    $delete_third_val_students[] = "( am_assessment_id = '$assessmentId' AND studentID = '".$studentEntry['id']."' )" ;
                                }
                                else{
                                    if(is_numeric($studentEntry['mark']) && $studentEntry['mark'] <= $maxmarkOfSubject){
                                            $markEntryObj = new \stdClass();
                                            $markEntryObj->studentId = $studentEntry['id'];
                                            $markEntryObj->assessmentId = $assessmentId;
                                            $markEntryObj->oeExamsId = $oeExamId;
                                            $markEntryObj->markObtained =  $studentEntry['mark'];
                                            $markEntryObj->attendanceStatus = "PRESENT";
                                            $markEntryObj->valuationCount =  $currentValuationCount == 1 ? 1 : 'FINALIZED';
                                            $markproperties ="";
                                            if($currentValuationCount == 1){
                                                if($studentEntry['firstValuationMarkProperties']){
                                                    $markproperties = json_decode($studentEntry['firstValuationMarkProperties']);
                                                    $markproperties->isNotConfirm = 0;
                                                }else{
                                                    $markproperties = new \stdClass();
                                                    $markproperties->isNotConfirm = 0;
                                                } 
                                            }
                                            else{
                                                if($studentEntry['finalizedMarkProperties']){
                                                    $markproperties = json_decode($studentEntry['finalizedMarkProperties']);
                                                    if($currentValuationCount == "FINALIZED"){
                                                        $markproperties->isNotConfirm = 0;
                                                    }
                                                }else{
                                                    $markproperties = new \stdClass();
                                                    $markproperties->isNotConfirm = 0;
                                                } 
                                            }
                                            $markEntryObj->properties  = $markproperties;
                                            $markEntryObj->valuationType = null;
                                        $insertionMarkTableArray[] = $markEntryObj;
                                        $deleteExempted[] = " ( am_assessment_id = '".$assessmentId."' AND studentaccount_id =  '".$studentEntry['id']."' ) ";
                                    }
                                }
                                if($studentEntry['oldMark'] != $studentEntry['mark']) {
                                    $log = new StudentMarkEditLog();
                                    $log->oldMark = $studentEntry['oldMark'];
                                    $log->newMark = $studentEntry['mark'];
                                    $log->remarks = "Mark changed by edit external mark";
                                    $log->markType = "EXTERNAL_MARK";
                                    $log->actionTakenTime = date("d-m-Y h:i A");
                                    $log->updatedStaffId = $adminId;
                                    $log->updatedStaffName = $staffName;
                                    $log->updatedStaffType = "EXAM_CONTROLLER";
                                    $logRequest = new \stdClass();
                                    $logRequest->studentId =  $studentEntry['id'];
                                    $logRequest->assessmentId = $assessmentId;
                                    $logRequest->staffId = $adminId;
                                    $logRequest->log = $log;
                                    $insertionExtrnalMarkLogTableArray[] = $logRequest;
                                }
                               
                            }
                        }
                    }
                    else{
                        $notRegisteredStudents[] = $studentEntry['regNo'];
                        $error = 1;
                    }
                }
            }
            else if( $currentValuationCount == 2){
                $markDiff = CommonExamService::getInstance()->getExternalValuationMarkDiff($searchRequest['courseType'],$maxmarkOfSubject );
                $request = new \stdClass;
                $request->examRegistrationId = $searchRequest['examRegistrationId'];
                $request->academicPaperSubjectId = stripslashes($searchRequest['academicPaperId']);
                $request->groupId = $searchRequest['groupId'];
                $request->isFirstValuatedStudentOnly = true;
                $registeredStudentMarkDetails = $this->getAllStudentEditExternalMarksByExamRegistrationSubject($request);
                foreach($studentMarkDetailsArray as $student){
                    if($student['isWithHeld'] != true){
                        $registeredStudentsArray[$student['studentId']] = $student['studentId'];
                        $registeredStudentsCurrentMark[$student['studentId']] = $student['mark'];
                        $registeredStudentsOldMark[$student['studentId']] = $student['oldMark'];
                    }
                }
                foreach($registeredStudentMarkDetails as $studentEntry){
                    if($studentEntry->isAbsent != "WITHHELD"){
                        if( in_array ( $studentEntry->studentId, $registeredStudentsArray ) ) {
                            $currentMark = $registeredStudentsCurrentMark[$studentEntry->studentId];
                            if($currentMark != null){
                                if((is_numeric($currentMark)) && ($currentMark <= $maxmarkOfSubject)){
                                        // for high lighting edit changes in import mark
                                        $editRequest = new \stdClass();
                                        $editRequest->groupId = $studentEntry->groupId;
                                        $editRequest->studentId = $studentEntry->studentId;
                                        $editRequest->isDirty = 1;
                                        $editRequest->staffId = $GLOBALS['userId'];
                                        $editHistoryLog[] = $editRequest;
                                        
                                        $markEntryObj = new \stdClass();
                                        $markEntryObj->studentId = $studentEntry->studentId;
                                        $markEntryObj->assessmentId = $studentEntry->assessmentId;
                                        $markEntryObj->oeExamsId = $studentEntry->oeExamId;
                                        $markEntryObj->markObtained = $currentMark;
                                        $markEntryObj->attendanceStatus = "PRESENT";
                                        $markEntryObj->valuationCount = 2;
                                        $markproperties = "";
                                        if($studentEntry->secondValuationMarkProperties){
                                            $markproperties = json_decode($studentEntry->secondValuationMarkProperties);
                                            $markproperties->isNotConfirm = 0;
                                        }else{
                                            $markproperties = new \stdClass();
                                            $markproperties->isNotConfirm = 0;
                                        } 
                                        $markEntryObj->properties  = $markproperties;
                                        $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
        
                                    $studentMarkDiff = abs ($studentEntry->firstValuationMark - $currentMark);
                                    $deleteMarkEntryObj = new ExamUserMarkRequest;
                                    $deleteMarkEntryObj->assessmentId = $studentEntry->assessmentId;
                                    $deleteMarkEntryObj->studentId = $studentEntry->studentId;
                                    $deleteMarkEntryObj->valuationCount = 3;
                                    $deleteMarkTableArray[] = $deleteMarkEntryObj;
                                    if( $studentMarkDiff >= $markDiff){
                                        $markEntryObj = new \stdClass();
                                        $markEntryObj->studentId = $studentEntry->studentId;
                                        $markEntryObj->assessmentId = $studentEntry->assessmentId;
                                        $markEntryObj->oeExamsId = $studentEntry->oeExamId;
                                        $markEntryObj->markObtained = null;
                                        $markEntryObj->attendanceStatus = "PRESENT";
                                        $markEntryObj->valuationCount = 'FINALIZED';
                                        $markproperties = "";
                                        if($studentEntry->secondValuationMarkProperties){
                                            $markproperties = json_decode($studentEntry->secondValuationMarkProperties);
                                            $markproperties->isNotConfirm = 0;
                                        }else{
                                            $markproperties = new \stdClass();
                                            $markproperties->isNotConfirm = 0;
                                        } 
                                        $markEntryObj->properties  = $markproperties;
                                        $markEntryObj->valuationType = null;
                                        $insertionMarkTableArray[] = $markEntryObj;
                                        $insert_third_val_students[] = "( '".$studentEntry->assessmentId."', ".$studentEntry->studentId." )";
                                    }
                                    else{
                                        $studentMark =  ($studentEntry->firstValuationMark + $currentMark)/2;
                                        if($examValuationProcedureRule->roundOffDigits){
                                            $studentMark = round($studentMark,$examValuationProcedureRule->roundOffDigits);
                                        }
                                        $markEntryObj = new \stdClass();
                                        $markEntryObj->studentId = $studentEntry->studentId;
                                        $markEntryObj->assessmentId = $studentEntry->assessmentId;
                                        $markEntryObj->oeExamsId = $studentEntry->oeExamId;
                                        $markEntryObj->markObtained = $studentMark;
                                        $markEntryObj->attendanceStatus = "PRESENT";
                                        $markEntryObj->valuationCount = 'FINALIZED';
                                        $markproperties = "";
                                        if($studentEntry->secondValuationMarkProperties){
                                            $markproperties = json_decode($studentEntry->secondValuationMarkProperties);
                                            $markproperties->isNotConfirm = 0;
                                        }else{
                                            $markproperties = new \stdClass();
                                            $markproperties->isNotConfirm = 0;
                                        } 
                                        $markEntryObj->properties  = $markproperties;
                                        $markEntryObj->valuationType = null;
                                        $insertionMarkTableArray[] = $markEntryObj;
                                        $delete_third_val_students[] = "( am_assessment_id = '$studentEntry->assessmentId' AND studentID = '$studentEntry->studentId' )" ;
                                        if( $registeredStudentsOldMark[$studentEntry->studentId] != $studentMark){
                                            $log = new StudentMarkEditLog();
                                            $log->oldMark = $registeredStudentsOldMark[$studentEntry->studentId];
                                            $log->newMark = $studentMark;
                                            $log->remarks = "Mark changed by edit external mark";
                                            $log->markType = "EXTERNAL_MARK";
                                            $log->actionTakenTime = date("d-m-Y h:i A");
                                            $log->updatedStaffId = $adminId;
                                            $log->updatedStaffName = $staffName;
                                            $log->updatedStaffType = "EXAM_CONTROLLER";
                                            $logRequest = new \stdClass();
                                            $logRequest->studentId =  $studentEntry->id;
                                            $logRequest->assessmentId = $studentEntry->assessmentId;
                                            $logRequest->staffId = $adminId;
                                            $logRequest->log = $log;
                                            $insertionExtrnalMarkLogTableArray[] = $logRequest;
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            $notRegisteredStudents[] = $studentEntry->regNo;
                            $error = 1;
                        }
                    }
                }
            }
            else if($currentValuationCount == 3){
                $markDiff = CommonExamService::getInstance()->getExternalValuationMarkDiff($searchRequest['courseType'],$maxmarkOfSubject );
                $request = new \stdClass;
                $request->examRegistrationId = $searchRequest['examRegistrationId'];
                $request->academicPaperSubjectId = stripslashes($searchRequest['academicPaperId']);
                $request->groupId = $searchRequest['groupId'];
                $request->isFirstValuatedStudentOnly = true;
                $request->isSecondValuatedStudentOnly = true;
                $registeredStudentMarkDetails = $this->getAllStudentEditExternalMarksByExamRegistrationSubject($request);
                foreach($studentMarkDetailsArray as $student)
                {
                    if($student['isWithHeld'] != true)
                    {
                        $registeredStudentsArray[$student['studentId']] = $student['studentId'];
                        $registeredStudentsCurrentMark[$student['studentId']] = $student['mark'];
                        $registeredStudentsOldMark[$student['studentId']] = $student['oldMark'];
                    }
                }
                $valuationRules =  (array) $this->getAllValuationRule();
                $definedValuationRule = json_decode(reset($registeredStudentMarkDetails)->batchProperties)->valuationRule;
                $selectedThirdValuationRule = reset(array_filter($definedValuationRule, function ($rule) {
                    return $rule->count == 3;
                }));
                $thirdValuationRuleKey =  array_search($selectedThirdValuationRule->ruleId, array_column( $valuationRules, "id"));
                if($thirdValuationRuleKey !== false){
                    $thirdValuationRule = $valuationRules[$thirdValuationRuleKey];
                }
                if(empty($thirdValuationRule)){
                    throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS,"Please define valuation rule!");
                }
                foreach($registeredStudentMarkDetails as $studentEntry)
                {
                    if($studentEntry->isAbsent != "WITHHELD")
                    {
                        if( in_array ( $studentEntry->studentId, $registeredStudentsArray ) ) 
                        {
                            $currentMark = $registeredStudentsCurrentMark[$studentEntry->studentId];
                            if($currentMark != null){
                                if((is_numeric($currentMark)) && ($currentMark <= $maxmarkOfSubject)){
                                    // for high lighting edit changes in import mark
                                    $editRequest = new \stdClass();
                                    $editRequest->groupId = $studentEntry->groupId;
                                    $editRequest->studentId = $studentEntry->studentId;
                                    $editRequest->isDirty = 1;
                                    $editRequest->staffId = $GLOBALS['userId'];
                                    $editHistoryLog[] = $editRequest;
                                      
                                    $markEntryObj = new \stdClass();
                                    $markEntryObj->studentId = $studentEntry->studentId;
                                    $markEntryObj->assessmentId = $studentEntry->assessmentId;
                                    $markEntryObj->oeExamsId = $studentEntry->oeExamId;
                                    $markEntryObj->markObtained = $currentMark;
                                    $markEntryObj->valuationCount = 3;
                                    $markEntryObj->attendanceStatus = "PRESENT";
                                    $markproperties = "";
                                    if($studentEntry->thirdValuationMarkProperties){
                                        $markproperties = json_decode($studentEntry->thirdValuationMarkProperties);
                                        $markproperties->isNotConfirm = 0;
                                    }else{
                                        $markproperties = new \stdClass();
                                        $markproperties->isNotConfirm = 0;
                                    } 
                                    $markEntryObj->properties  = $markproperties;
                                    $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
                                    $studentMarks[0] = $studentEntry->firstValuationMark;
                                    $studentMarks[1] = $studentEntry->secondValuationMark;
                                    $studentMarks[2] = $currentMark;
                                    $externalMark = $this->getFinalizedMarkFromValuationRule($studentMarks, $thirdValuationRule->code,$examValuationProcedureRule->isExcatFinalizeMark);
                                    if($examValuationProcedureRule->roundOffDigits){
                                        $externalMark = round($externalMark,$examValuationProcedureRule->roundOffDigits);
                                    }else{
                                        $externalMark = round($externalMark);
                                    }
                                    $markEntryObj = new \stdClass();
                                    $markEntryObj->studentId = $studentEntry->studentId;
                                    $markEntryObj->assessmentId = $studentEntry->assessmentId;
                                    $markEntryObj->oeExamsId = $studentEntry->oeExamId;
                                    $markEntryObj->markObtained = $externalMark;
                                    $markEntryObj->valuationCount = 'FINALIZED';
                                    $markEntryObj->attendanceStatus = "PRESENT";
                                    $markproperties = "";
                                    if($studentEntry->finalizedMarkProperties){
                                        $markproperties = json_decode($studentEntry->finalizedMarkProperties);
                                        $markproperties->isNotConfirm = 0;
                                    }else{
                                        $markproperties = new \stdClass();
                                        $markproperties->isNotConfirm = 0;
                                    } 
                                    $markEntryObj->properties  = $markproperties;
                                    $markEntryObj->valuationType = null;
                                    $insertionMarkTableArray[] = $markEntryObj;
                                    if( $registeredStudentsOldMark[$studentEntry->studentId] != $externalMark){
                                        $log = new StudentMarkEditLog();
                                        $log->oldMark = $registeredStudentsOldMark[$studentEntry->studentId];
                                        $log->newMark = $externalMark;
                                        $log->remarks = "Mark changed by edit external mark";
                                        $log->markType = "EXTERNAL_MARK";
                                        $log->actionTakenTime = date("d-m-Y h:i A");
                                        $log->updatedStaffId = $adminId;
                                        $log->updatedStaffName = $staffName;
                                        $log->updatedStaffType = "EXAM_CONTROLLER";
                                        $logRequest = new \stdClass();
                                        $logRequest->studentId =  $studentEntry->id;
                                        $logRequest->assessmentId = $studentEntry->assessmentId;
                                        $logRequest->staffId = $adminId;
                                        $logRequest->log = $log;
                                        $insertionExtrnalMarkLogTableArray[] = $logRequest;
                                    }
                                }
                            }
                        }
                        else
                        {
                            $notRegisteredStudents[] = $studentEntry->regNo;
                            $error = 1;
                        }
                    }
                }
            }
            if(! empty($insertionMarkTableArray)){
                ExamUserMarkService::getInstance()->saveExamUserTotalMark($insertionMarkTableArray);
            }
            if(! empty($deleteMarkTableArray)){
                foreach($deleteMarkTableArray as $deleteObj){
                    ExamUserMarkService::getInstance()->deleteExamUserTotalMark($deleteObj);
                }
            }
            if(! empty($insertionExtrnalMarkLogTableArray)){
                foreach($insertionExtrnalMarkLogTableArray as $logRequest){
                    $this->saveExamEditLog($logRequest);
                }
            }
            if(! empty($insert_third_val_students)){
                $this->insertThirdValStudentRegistration($insert_third_val_students);
            }
            if(! empty($delete_third_val_students)){
                $this->deleteThirdValStudentRegistration($delete_third_val_students);
            }
            if( !empty ( $deleteExempted ) ){
                $this->deleteExemptedStudents($deleteExempted);
            }
            if( !empty ( $insertExempted ) ){
                $this->insertExemptedStudents($insertExempted);
            }
            if(! empty($editHistoryLog)){
                StudentsOverAllMarkReportService::getInstance()->insertStudentEditStatus($editHistoryLog);
            }
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    private function filterOutCurrentValuationConfirmedMarkStudents($studentMarkDetailsArray,$searchRequest,$courseType){
        foreach($studentMarkDetailsArray as $key => $studentMarkDetail){
            if($searchRequest['currentValuationCount'] == 1 && $studentMarkDetail['firstValuationConfirm'] == "1"){
                unset($studentMarkDetailsArray[$key]);
            }
            if($searchRequest['currentValuationCount'] == 2 && $studentMarkDetail['secondValuationConfirm'] == "1"){
                unset($studentMarkDetailsArray[$key]);
            }
            if($searchRequest['currentValuationCount'] == 3 && $studentMarkDetail['thirdValuationConfirm']){
                unset($studentMarkDetailsArray[$key]);
            }
            //for ug
            if($courseType == "UG" && $studentMarkDetail['finalizedValuationConfirm']){
                unset($studentMarkDetailsArray[$key]);
            }
            if($studentMarkDetail['finalizedValuationConfirm'] && ($studentMarkDetail['isAbsent'] == "ABSENT" || $studentMarkDetail['isAbsent'] == "MALPRACTICE" || $studentMarkDetail['isAbsent'] == "WITHHELD")){
                unset($studentMarkDetailsArray[$key]);
            }
        }
        return array_values($studentMarkDetailsArray);
    }
        /**
     * get AllStudent External Marks By ExamRegistrationSubject
     * @param searchRequest $searchRequest
     * @return $studentsMarkDetails
     */
    public function getAllStudentEditExternalMarksByExamRegistrationSubject($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        $searchRequest->academicPaperSubjectId = is_array($searchRequest->academicPaperSubjectId) ? $searchRequest->academicPaperSubjectId : stripslashes($searchRequest->academicPaperSubjectId);
        $joinQuery = "";
        try {
            $orderBy = " ORDER BY spa.properties->>'$.registerNumber' ASC , s.code ASC";
            $whereQuery = "";
            $groupBy = "";
            if ( $searchRequest->isOrderByRollNo ){
                $orderBy = " ORDER BY spa.properties->>'$.rollNumber' ASC , s.code ASC";
            }
            if(!empty($searchRequest->groupId)) {
                $groupIdString = is_array($searchRequest->groupId) ? "'" . implode("','",$searchRequest->groupId) . "'" : "'".$searchRequest->groupId."'";
                $whereQuery .= " AND eerb.groups_id IN ( $groupIdString )";
            }
            if(!empty($searchRequest->isThirdValuationStudentOnly)) {
                $whereQuery .= " AND ets.thirdvalstudentID IS NOT NULL ";
            }
            if(!empty($searchRequest->examRegistrationId)) {
                $examRegistrationIdString = is_array($searchRequest->examRegistrationId) ? "'" . implode("','",$searchRequest->examRegistrationId) . "'" : "'".$searchRequest->examRegistrationId."'";
                $whereQuery .= " AND eerb.ec_exam_registration_id IN ( $examRegistrationIdString )";
            }
            if(!empty($searchRequest->academicPaperSubjectId)) {
                $academicPaperSubjectIdString = is_array($searchRequest->academicPaperSubjectId) ? "'" . implode("','",$searchRequest->academicPaperSubjectId) . "'" : "'".$searchRequest->academicPaperSubjectId."'";
                $whereQuery .= " AND eers.cm_academic_paper_subjects_id IN ( $academicPaperSubjectIdString )";
            }
            if(!empty($searchRequest->examRegistrationBatchId)) {
                $examRegistrationBatchIdString = is_array($searchRequest->examRegistrationBatchId) ? "'" . implode("','",$searchRequest->examRegistrationBatchId) . "'" : "'".$searchRequest->examRegistrationBatchId."'";
                $whereQuery .= " AND eerb.id IN ( $examRegistrationBatchIdString )";
            }
            if(!empty($searchRequest->studentRegisterNo)) {
                $studentRegisterNoString = is_array($searchRequest->studentRegisterNo) ? "'" . implode("','",$searchRequest->studentRegisterNo) . "'" : "'".$searchRequest->studentRegisterNo."'";
                $whereQuery .= " AND spa.properties->>'$.registerNumber' IN ( $studentRegisterNoString )";
            }
            if(!empty($searchRequest->studentRollNo)) {
                $studentRollNoString = is_array($searchRequest->studentRollNo) ? "'" . implode("','",$searchRequest->studentRollNo) . "'" : "'".$searchRequest->studentRollNo."'";
                $whereQuery .= " AND spa.properties->>'$.rollNumber' IN ( $studentRollNoString )";
            }
            if(!empty($searchRequest->studentFalseNo)) {
                $studentFalseNoString = is_array($searchRequest->studentFalseNo) ? "'" . implode("','",$searchRequest->studentFalseNo) . "'" : "'".$searchRequest->studentFalseNo."'";
                $whereQuery .= " AND esar.properties->>'$.falseNo' IN ( $studentFalseNoString )";
            }
            if(!empty($searchRequest->assessmentId)) {
                $assessmentIdString = is_array($searchRequest->assessmentId) ? "'" . implode("','",$searchRequest->assessmentId) . "'" : "'".$searchRequest->assessmentId."'";
                $whereQuery .= " AND eers.am_assessment_id IN ( $assessmentIdString )";
            }
            if(!empty($searchRequest->isRequiredFalseNo)) {
                $whereQuery .= " AND esar.properties ->> '$.falseNo'  IS NOT NULL ";
                $groupBy = " GROUP BY esar.student_id ";
            }
            $finalizedMarkJoin = 'LEFT';
            $joinConditionMarkFinalized = "";
            if(!empty($searchRequest->showFinalizedMarkOnly)) {
                $joinConditionMarkFinalized .= "  AND  ostmf.properties->>'$.isNotConfirm' = '0'";
                $finalizedMarkJoin = "INNER";
            }
            if(!empty($searchRequest->isFirstValuatedStudentOnly)) {
                $joinQuery .= " INNER JOIN oe_student_total_mark ostm1 ON 
                                    ostm1.student_id = sa.studentID AND 
                                    ostm1.am_assessment_id = esar.am_assessment_id AND 
                                    (ostm1.valuation_type IS NULL OR ostm1.valuation_type = '' ) AND
                                    ostm1.valuation_count = '1'";
            }
            else{
                $joinQuery .= " LEFT JOIN oe_student_total_mark ostm1 ON 
                                    ostm1.student_id = sa.studentID AND 
                                    ostm1.am_assessment_id = esar.am_assessment_id AND 
                                    (ostm1.valuation_type IS NULL OR ostm1.valuation_type = '') AND
                                    ostm1.valuation_count = '1'";
            }
            if(!empty($searchRequest->isSecondValuatedStudentOnly)) {
                $joinQuery .= " INNER JOIN oe_student_total_mark ostm2 ON 
                                    ostm2.student_id = sa.studentID AND 
                                    ostm2.am_assessment_id = esar.am_assessment_id AND 
                                    (ostm2.valuation_type IS NULL OR ostm2.valuation_type = '') AND
                                    ostm2.valuation_count = '2'";
            }
            else{
                $joinQuery .= " LEFT JOIN oe_student_total_mark ostm2 ON 
                                    ostm2.student_id = sa.studentID AND 
                                    ostm2.am_assessment_id = esar.am_assessment_id AND 
                                    (ostm2.valuation_type IS NULL OR ostm2.valuation_type = '') AND
                                    ostm2.valuation_count = '2'";
            }
            //will fetch first valuation students and absent marked students
            if($searchRequest->isFirstValuatedAndAbsentMarkedStudents){
                $whereQuery .="  AND (IF(ostm1.properties ->> '$.isNotConfirm' = '0', 1, 0) = 1 OR ostmf.attendance_status = 'ABSENT' OR ostmf.attendance_status = 'MALPRACTICE' OR ostmf.attendance_status = 'WITHHELD')";
            }
              
            $query = "SELECT
                        DISTINCT sa.studentID as id,
                        sa.studentID as studentId, 
                        sa.studentName,
                        aa.properties_value ->>'$.assessmentDate' AS assessmentDate,
                        spa.properties->>'$.registerNumber' as regNo,
                        spa.properties->>'$.rollNumber' as rollNo,
                        sa.myImage as studentImage,
                        g.id AS groupId,
                        g.name AS groupName,
                        eer.type AS examRegType,
                        eerb.properties as batchProperties,
                        s.id as subjectId,
                        s.code as subjectCode,
                        s.name as subjectName,
                        IF(aps.properties ->> '$.classType' = 'THEORY',1,0) AS isTheory,
                        esmel.log,
                        im.internal_mark as internalMark,
                        ostmf.mark_obtained as externalMark,
                        ostmf.id as assessmentStudentTotalMarkId,
                        oe.id AS oeExamId,
                        ostmf.mark_obtained,
                        ostmf.mark_obtained as finalizedMark,
                        ostmf.properties as finalizedMarkProperties,
                        ostmf.exam_additional_marks->>'$.mark1' AS vivaMark,
                        IF(ostmf.properties ->> '$.isNotConfirm' = '0', 1, 0) AS finalizedValuationConfirm,
                        ostm1.mark_obtained as firstValuationMark,
                        ostm1.properties as firstValuationMarkProperties,
                        IF(ostm1.properties ->> '$.isNotConfirm' = '0', 1, 0) as firstValuationConfirm,
                        ostm2.mark_obtained as secondValuationMark,
                        ostm2.properties as secondValuationMarkProperties,
                        IF(ostm2.properties ->> '$.isNotConfirm' = '0', 1, 0) as secondValuationConfirm,
                        ostm3.mark_obtained as thirdValuationMark,
                        ostm3.properties as thirdValuationMarkProperties,
                        IF(ostm3.properties ->> '$.isNotConfirm' = '0', 1, 0) as thirdValuationConfirm,
                        ostmf.attendance_status as isAbsent,
                        esar.am_assessment_id as assessmentId,
                        IF(ees.id,1,0) AS isExempted,
                        esar.properties ->> '$.isRevalued' as isRevalued,
                        esar.properties ->> '$.falseNo' as falseNo,
                        esar.properties ->> '$.alphaNumericCode' as alphaNumericCode,
                        esar.valuation_details ->> '$.packetNo' as packetNo,
                        IF(ets.thirdvalstudentID, 1, 0) AS thirdValReq,
                        aps.properties ->> '$.isExternal' as isExternal,
                        aps.properties ->> '$.externalMaxMark' as maximumSubjectMark,
                        aps.properties ->> '$.internalMaxMark' as internalMaxMark,
                        eers.valuation_details,
                        esar.valuation_details as studentValuationDetails
                    FROM
                        ec_student_assessment_registration esar
                    INNER JOIN studentaccount sa ON 
                        sa.studentID = esar.student_id
                    INNER JOIN ec_exam_registration_subject eers ON 
                        eers.am_assessment_id = esar.am_assessment_id
                    INNER JOIN am_assessment aa ON
                        aa.id = eers.am_assessment_id
                    INNER JOIN  cm_academic_paper_subjects aps ON 
                        aps.id = eers.cm_academic_paper_subjects_id
                    INNER JOIN v4_ams_subject s ON 
                        s.id = aps.ams_subject_id
                    INNER JOIN oe_exams oe ON
                            oe.assessment_id = eers.am_assessment_id AND oe.is_deleted = 0
                    INNER JOIN ec_exam_registration_batch eerb ON
                        eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer ON
                        eer.id = eerb.ec_exam_registration_id
                    INNER JOIN `groups` g ON
                        g.id = eerb.groups_id
                    INNER JOIN program p ON 
                        p.id = g.properties->>'$.programId'
                    INNER JOIN `student_program_account` spa ON 
                        spa.current_program_id = p.id AND 
                        spa.student_id = esar.student_id 
                    LEFT JOIN ec_student_mark_edit_log esmel ON
                        esmel.student_id = sa.studentID AND
                        esmel.am_assessment_id = esar.am_assessment_id
                    LEFT JOIN ec_internal_marks im ON
                        im.groups_id = eerb.groups_id AND 
                        im.academic_paper_subjects_id = aps.id AND  im.student_id = sa.studentID
                    LEFT JOIN exam_exempted_students ees ON
                        ees.am_assessment_id  = esar.am_assessment_id AND
                        ees.studentaccount_id =  sa.studentID
                    LEFT JOIN externalexam_thirdvalstudents ets ON 
                            ets.studentID = sa.studentID AND ets.am_assessment_id = eers.am_assessment_id
                    $finalizedMarkJoin JOIN oe_student_total_mark ostmf ON 
                        ostmf.student_id = sa.studentID AND ostmf.am_assessment_id = esar.am_assessment_id AND ostmf.valuation_count = 'FINALIZED' AND (ostmf.valuation_type IS NULL OR ostmf.valuation_type = '') $joinConditionMarkFinalized
                    ".$joinQuery."
                    LEFT JOIN oe_student_total_mark ostm3 ON 
                        ostm3.student_id = sa.studentID AND ostm3.am_assessment_id = esar.am_assessment_id AND (ostm3.valuation_type IS NULL OR ostm3.valuation_type = '') AND ostm3.valuation_count = '3'
                    WHERE
                        1=1  AND CAST(esar.properties ->> '$.registrationStatus' AS CHAR) = 'REGISTERED' AND CAST(esar.properties ->> '$.feeStatus' AS CHAR) = 'PAID' AND esar.ec_exam_registration_type = eer.type
                        AND (CAST(esar.properties ->> '$.syllabusSubType' AS CHAR) != 'MOOC' OR esar.properties ->> '$.syllabusSubType' IS NULL) ";
            $studentsMarkDetails = $this->executeQueryForList($query.$whereQuery.$groupBy.$orderBy);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $studentsMarkDetails;
    }
        /**
     * get AllStudent marks By ExamRegistrationSubject For Digital Valuation
     * @param searchRequest $searchRequest
     * @return $studentsMarkDetails
     */
    public function getStudentDigitalValuationMarks($request){
        $registeredStudentMarkDetails = $this->getAllStudentByExamRegistrationSubjectForDigitalValuation($request);
        $result = new \stdClass();
        if($request->getValuatedStaffDetails && !empty($registeredStudentMarkDetails)){
            $result = $this->getValuatedStaffsFiltered($registeredStudentMarkDetails);
        }
        else{
            $result->students = $registeredStudentMarkDetails;
        }
        return $result;
    }
    private function getValuatedStaffsFiltered($studentMarkDetails){
        $additionalStaffs = [];
        $chiefValuerstaffs = [];
        foreach($studentMarkDetails as $key => $student){
            if($student->valuationDetails){
                $valuationDetails = json_decode($student->valuationDetails)->assignedValuationStaffs;
                $additionalStaffs = array_merge($additionalStaffs, $this->filterStaffsByValuationCount($valuationDetails,1));
                $chiefValuerstaffs = array_merge($chiefValuerstaffs, $this->filterStaffsByValuationCount($valuationDetails,2));
            }
            if($student->mark1Confirm){
                $student->rvStatus = "No";
            }
            if($student->valuation2Details){
                if(json_decode($student->valuation2Details)->chiefEvaluatorValuationStatus == 1){
                    $student->rvStatus = "Yes";
                }
                
            }
        }
        $additionalStaffs = implode(",",array_unique($additionalStaffs));
        $chiefValuerstaffs = implode(",",array_unique($chiefValuerstaffs));
        $result = new \stdClass();
        $result->valuatedStaffDetails->additionalExaminerName = StaffService::getInstance()->getStaffByStaffIds($additionalStaffs);
        $result->valuatedStaffDetails->chiefValuerStaffName = StaffService::getInstance()->getStaffByStaffIds($chiefValuerstaffs);
        $result->students = $studentMarkDetails;
        return $result;
    }
    private function filterStaffsByValuationCount($valuationDetails, $count){
        $staffs = array_map(
            function($valuerDetails) {
            return !empty($valuerDetails->addiitonalExamniners) ? current($valuerDetails->addiitonalExamniners) : null;
            },
            array_filter($valuationDetails, function($valuerDetails) use ($count) {
            return $valuerDetails->count == $count;
            })
        );
        return array_filter($staffs);
    }
    public function getOeMarksStudentList($request){
        $request = $this->realEscapeObject($request);
        $studentList = [];
        $whereQuery = "";
        $orderBy = " ORDER BY spa.properties->>'$.registerNumber' ASC";
        if($request->assessmentId){
            $assessmentIdString = is_array($request->assessmentId) ? "'" . implode("','",$request->assessmentId) . "'" : "'".stripslashes($request->assessmentId)."'";
            $whereQuery = " AND oe.assessment_id IN($assessmentIdString)";
        }
        try 
        {
            $query = "SELECT DISTINCT oemc.oe_users_id AS studentId,oemc.oe_exams_id AS oeExamId,sa.studentName,spa.properties->>'$.registerNumber' AS regNo,esar.falseNo,esar.properties->>'$.alphaNumericCode' AS alphaNumericCode FROM oe_exam_marks_confirm oemc
                        INNER JOIN oe_exams oe ON oe.id = oemc.oe_exams_id
                        INNER JOIN studentaccount sa ON sa.studentID = oemc.oe_users_id 
                        INNER JOIN student_program_account spa ON spa.student_id = sa.studentID 
                        INNER JOIN ec_student_assessment_registration esar ON esar.student_id = sa.studentID AND esar.am_assessment_id = oe.assessment_id
                        WHERE 1=1 ";
            $studentList  = $this->executeQueryForList($query.$whereQuery.$orderBy);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $studentList;
    }
    /**
     * @author Sibin
     * get third val students by exam
     */
    public function submitRemunerationBill($request)
    {
        $properties = $request->properties ? addslashes(json_encode($request->properties, JSON_INVALID_UTF8_IGNORE | JSON_PARTIAL_OUTPUT_ON_ERROR | JSON_ERROR_INVALID_PROPERTY_NAME)) : "";
        $request = $this->realEscapeObject($request);
        $identifier = $request->identifier;
        $subjectId = $request->subjectId; // Assuming subjectId is available in $request object
        $userId = $request->userId; // Assuming userId is available in $request object
        $entryType = $request->entryType;
        $userType = $request->userType;
        $identifierType = $request->identifierType;
        $sql = "INSERT INTO subjectWiseSubmissions (identifier, subjectId, userId, properties, entryType, userType, identifierType, created_by, created_date) VALUES  ('$identifier', '$subjectId', '$userId', '$properties', '$entryType', '$userType', '$identifierType', '$userId', NOW())";
        try {
           return $this->executeQuery($sql);
           AMSLogger::log_info($this->logger,Events::FACULTY_REMUNERATION_BILL_SUBMISSION, [
            "staff" => new Staff(["id" => $userId]),
            "request" => $request,
            "status" => StatusConstants::SUCCESS
        ]);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getMessage(), $e->getCode());
        }
    }
    /**
     * Retrieves the finalized status of a student's mark based on the provided request.
     *
     * @param object $request The request object containing the necessary parameters.
     * @return array The list of student mark details.
     * @throws ExamControllerException If an error occurs during the query execution.
     */
    private function getFinalizedStatusOfStudentMark($request)
    {
        $request = $this->realEscapeObject($request);
        $request->academicPaperSubjectId = is_array($request->academicPaperSubjectId) ? "'" . implode("','",$request->academicPaperSubjectId) . "'" : "'".$request->academicPaperSubjectId."'";
        try 
        {
            $query = "SELECT
                        DISTINCT sa.studentID as id,
                        sa.studentID as studentId,
                        sa.studentName,
                        spa.properties->>'$.registerNumber' AS regNo
                    FROM
                        ec_student_assessment_registration esar
                    INNER JOIN studentaccount sa ON 
                        sa.studentID = esar.student_id
                    INNER JOIN ec_exam_registration_subject eers ON 
                        eers.am_assessment_id = esar.am_assessment_id
                    INNER JOIN ec_exam_registration_batch eerb ON
                        eerb.id = eers.ec_exam_registration_batch_id
                    INNER JOIN ec_exam_registration eer
                        ON eer.id = eerb.ec_exam_registration_id 
                    INNER JOIN cm_academic_paper_subjects caps ON
                        caps.id = eers.cm_academic_paper_subjects_id
                    INNER JOIN `groups` g ON
                        g.id = eerb.groups_id
                        AND g.`type` = 'BATCH'
                    INNER JOIN program p ON 
                        p.id = g.properties->>'$.programId'
                    INNER JOIN student_program_account spa ON 
                        spa.current_program_id = p.id AND 
                        spa.student_id = esar.student_id 
                    INNER JOIN oe_exams oe ON 
                        oe.assessment_id = esar.am_assessment_id
                    INNER JOIN oe_student_total_mark ostmf ON 
                        ostmf.student_id = sa.studentID AND ostmf.am_assessment_id = esar.am_assessment_id AND ostmf.valuation_count = 'FINALIZED' AND (ostmf.valuation_type IS NULL OR ostmf.valuation_type = '')
                    WHERE
                        esar.ec_exam_registration_type = eer.type AND
                        esar.properties ->>'$.feeStatus' = 'PAID' AND 
                        esar.properties ->>'$.registrationStatus' = 'REGISTERED' AND 
                        eerb.ec_exam_registration_id='$request->examRegistrationId' AND 
                        ostmf.mark_obtained IS NOT NULL AND
                        eers.cm_academic_paper_subjects_id IN ( $request->academicPaperSubjectId ) LIMIT 1";
            $studentsMarkDetails = $this->executeQueryForList($query);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $studentsMarkDetails;
    }
}