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 / 26
CRAP
0.00% covered (danger)
0.00%
0 / 1040
ExamRegistrationBatchService
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 26
33306.00
0.00% covered (danger)
0.00%
0 / 1040
 __construct
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 3
 saveExamRegistrationBatch
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 38
 validateSaveExamRegistrationBatch
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 6
 insertExamRegistrationBatch
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 17
 updateExamRegistrationBatch
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 21
 deleteExamRegistrationBatch
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 30
 searchExamRegistrationBatch
0.00% covered (danger)
0.00%
0 / 1
462.00
0.00% covered (danger)
0.00%
0 / 110
 getAssignedSubjectByBatchOrExamReg
0.00% covered (danger)
0.00%
0 / 1
272.00
0.00% covered (danger)
0.00%
0 / 75
 getAllSubjectsByExamRegistrationBatch
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 30
 getBatchWithExamMonthAndYears
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 46
 getExamregistrationBatchesByCurrentStaff
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 27
 getNotAssignedBatchesForRevaluation
0.00% covered (danger)
0.00%
0 / 1
132.00
0.00% covered (danger)
0.00%
0 / 62
 getAllAssignedBatchGroupsForRevaluation
0.00% covered (danger)
0.00%
0 / 1
182.00
0.00% covered (danger)
0.00%
0 / 81
 getAllRevaluationBatchGroups
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 33
 getAllBatchesAndSubjectDetailsByExamRegistration
0.00% covered (danger)
0.00%
0 / 1
182.00
0.00% covered (danger)
0.00%
0 / 69
 searchExamRegistrationBatchesWithSubjects
0.00% covered (danger)
0.00%
0 / 1
90.00
0.00% covered (danger)
0.00%
0 / 63
 searchBatchWithOutAcademicTerm
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 42
 saveExamResultPublishDetails
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 27
 getAllBatchesAndAssignedValuationRule
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 35
 saveBatchValuationRule
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 18
 searchExamRegistrationBatchDetails
0.00% covered (danger)
0.00%
0 / 1
132.00
0.00% covered (danger)
0.00%
0 / 61
 saveBatchExamRegistrationRequiredStatus
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 14
 saveBatchGradeUpgradationRule
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 15
 updateExamRegistrationBatchCustomFeilds
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 14
 saveConsolidatedFooterDetails
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 15
 getRegularExamAssignedSubjects
0.00% covered (danger)
0.00%
0 / 1
342.00
0.00% covered (danger)
0.00%
0 / 88
<?php
namespace com\linways\ec\core\service;
use com\linways\ec\core\dto\ExamRegistrationBatch;
use com\linways\base\util\MakeSingletonTrait;
use com\linways\base\util\SecurityUtils;
use com\linways\ec\core\constant\StatusConstants;
use com\linways\ec\core\exception\ExamControllerException;
use com\linways\ec\core\mapper\ExamRegistrationBatchServiceMapper;
use com\linways\ec\core\request\SearchExamRegistrationBatchRequest;
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\service\CommonExamService;
use com\linways\ec\core\service\GroupService as ECGroupService;
use com\linways\ec\core\service\ExamRevaluationService;
use com\linways\core\ams\professional\request\academic\SearchGroupRequest;
use com\linways\ec\core\constant\SyllabusTypeConstants;
use com\linways\core\ams\professional\service\CommonService;
use com\linways\core\ams\professional\constant\SettingsConstants;
class ExamRegistrationBatchService extends BaseService
{
    use MakeSingletonTrait;
    private function __construct() {
        $this->logger = AMSLogger::getLogger('exam-controller-log');
        $this->mapper = ExamRegistrationBatchServiceMapper::getInstance()->getMapper();
    }
    /**
     * Save ExamRegistrationBatch
     * @param ExamRegistrationBatch $examRegistrationBatch
     * @return $id
     */
    public function saveExamRegistrationBatch (ExamRegistrationBatch $examRegistrationBatch)
    {
        $examRegistrationBatch = $this->realEscapeObject($examRegistrationBatch);
        $examRegistrationBatch->createdBy = $GLOBALS['userId'] ?? $examRegistrationBatch->createdBy;
        $examRegistrationBatch->updatedBy = $GLOBALS['userId'] ?? $examRegistrationBatch->updatedBy;
        $staffId = $GLOBALS['userId'];
        try{
            $this->validateSaveExamRegistrationBatch($examRegistrationBatch);
            if(!empty($examRegistrationBatch->id))
            {
                $examRegistrationBatch->id = $this->updateExamRegistrationBatch($examRegistrationBatch);
            }
            else
            {
                $examRegistrationBatch->id = $this->insertExamRegistrationBatch($examRegistrationBatch);
            }
            AMSLogger::log_info($this->logger,Events::EC_SAVE_EXAM_REGISTRATION_BATCH,[
                "staff" => new Staff(["id" => $staffId]),
                "request" => $examRegistrationBatch,
                "status" => StatusConstants::SUCCESS
            ]);
        }catch(\Exception $e) {
            AMSLogger::log_error($this->logger,Events::EC_SAVE_EXAM_REGISTRATION_BATCH, [
                "staff" => new Staff(["id" => $staffId]),
                "request" => $examRegistrationBatch,
                "errorCode" => $e->getCode(),
                "errorMessage" => $e->getMessage(),
                "status" => StatusConstants::FAILED
            ]);
            if($e->getCode() !== ExamControllerException::INVALID_PARAMETERS_EXAM_REGISTRATION_BATCH && $e->getCode() !== ExamControllerException::EMPTY_PARAMETERS_EXAM_REGISTRATION_BATCH_BATCH && $e->getCode() !== ExamControllerException::DUPLICATE_ENTRY) {
                throw new ExamControllerException($e->getCode(),"Failed to assign Exam Registration to Batch! Please try again");
            } else if ($e->getCode() === ExamControllerException::DUPLICATE_ENTRY) {
                throw new ExamControllerException (ExamControllerException::DUPLICATE_ENTRY_EXAM_REGISTRATION_BATCH,"Cannot assign Exam Registration to Batch .This Exam is already Assigned!");
            } else {
                throw new ExamControllerException ($e->getCode(),$e->getMessage());
            }
        }
        return $examRegistrationBatch->id;
    }
    /**
     * Validate examRegistration Request Before Saving
     * @param ExamRegistrationBatch $examRegistrationBatch
     * @return NULL
     */
    private function validateSaveExamRegistrationBatch(ExamRegistrationBatch $examRegistrationBatch)
    {
        if(empty($examRegistrationBatch->groupId))
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS_EXAM_REGISTRATION_BATCH_BATCH," Batch  is  empty! Please choose any Batch");
        if(empty($examRegistrationBatch->examRegistrationId))
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS_EXAM_REGISTRATION_BATCH_BATCH," Exam Registration is  empty! Please choose any Exam Registration for Assigning Batch ");
    }
    
    /**
     * Insert ExamRegistrationBatch
     * @param ExamRegistrationBatch $examRegistrationBatch
     * @return  $id
     */
    private function insertExamRegistrationBatch(ExamRegistrationBatch $examRegistrationBatch)
    {
        $properties = !empty($examRegistrationBatch->properties) ? "'" . json_encode($examRegistrationBatch->properties) . "'" : "NULL";
        $feeProperties = !empty($examRegistrationBatch->feeProperties) ? "'" . json_encode($examRegistrationBatch->feeProperties) . "'" : "NULL";
        
        $id = SecurityUtils::getRandomString();
        $query = "INSERT INTO ec_exam_registration_batch
                  (id,groups_id,ec_exam_registration_id,properties,fees_properties,created_by,updated_by)
                  VALUES
                  ('$id','$examRegistrationBatch->groupId','$examRegistrationBatch->examRegistrationId',$properties,$feeProperties,'$examRegistrationBatch->createdBy','$examRegistrationBatch->updatedBy')";
        try {
           $this->executeQuery($query);
           $examRegistrationBatch->id = $id;
           return $examRegistrationBatch->id;
        } catch (\Exception $e) {
             throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $id;
    }
    /**
     * Update ExamRegistrationBatch
     * @param ExamRegistrationBatch $examRegistrationBatch
     * @return String $examRegistrationBatch->id
     */
    private function updateExamRegistrationBatch(ExamRegistrationBatch $examRegistrationBatch)
    {
        $properties = !empty($examRegistrationBatch->properties) ? "'".json_encode($examRegistrationBatch->properties)."'" : "NULL";
        $feeProperties = !empty($examRegistrationBatch->feeProperties) ? "'".json_encode($examRegistrationBatch->feeProperties)."'" : "NULL";
        $identifyingContext = !empty($examRegistrationBatch->identifyingContext) ? "'" . json_encode($examRegistrationBatch->identifyingContext) . "'" : "NULL";
        $query = "UPDATE
                    ec_exam_registration_batch
                SET
                    ec_exam_registration_id = '$examRegistrationBatch->examRegistrationId',
                    groups_id = '$examRegistrationBatch->groupId',
                    properties = $properties,
                    fees_properties = $feeProperties,
                    updated_by = '$examRegistrationBatch->updatedBy'
                WHERE
                    id = '$examRegistrationBatch->id'";
        try {
            $this->executeQuery($query);
            return $examRegistrationBatch->id;
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * Delete examRegistration (Soft Delete)
     * @param String $id
     * @return NULL
     */
    public function deleteExamRegistrationBatch($id)
    {
        $staffId = $GLOBALS['userId'];
        $id = $this->realEscapeString($id);
        $searchRequest = new SearchExamRegistrationBatchRequest();
        $searchRequest->id = $id;
        $examRegistrationBatch = reset($this->searchExamRegistrationBatch($searchRequest));
        if(empty($id) || empty($examRegistrationBatch))
            throw new ExamControllerException(ExamControllerException::EMPTY_PARAMETERS_EXAM_REGISTRATION_BATCH,"Exam Registration Batch is invalid! Please enter a valid Exam Registration Batch");
        $query = "DELETE FROM
                    ec_exam_registration_batch
                WHERE
                    id = '$id'";
        try {
            $this->executeQuery($query);
            AMSLogger::log_info($this->logger,Events::EC_DELETE_EXAM_REGISTRATION_BATCH,[
                "staff" => new Staff(["id" => $staffId]),
                "request" => $examRegistrationBatch,
                "status" => StatusConstants::SUCCESS
            ]);
        } catch (\Exception $e) {
            AMSLogger::log_error($this->logger,Events::EC_DELETE_EXAM_REGISTRATION_BATCH, [
                "staff" => new Staff(["id" => $staffId]),
                "request" => $examRegistrationBatch,
                "errorCode" => $e->getCode(),
                "errorMessage" => $e->getMessage(),
                "status" => StatusConstants::FAILED
            ]);
            throw new ExamControllerException(ExamControllerException::ERROR_DELETING_EXAM_REGISTRATION_BATCH,"Error deleting Exam Registration Batch! Please try again");
        }
    }
    
    /**
     * Search examRegistration
     * @param SearchExamRegistrationBatchRequest $request
     * @return examRegistration
     */
    public function searchExamRegistrationBatch(SearchExamRegistrationBatchRequest $request){
        $request = $this->realEscapeObject($request);
        $whereQuery = "";
        $limitQuery = "";
        if(!empty($request->id)) {
            $whereQuery .= " AND eerb.id='$request->id";
        }
        if(!empty($request->academicTermId)) {
            $academicTermIdStr = is_array($request->academicTermId) ? "'" . implode("','",$request->academicTermId) . "'" : "'".$request->academicTermId."'";
            $whereQuery .= " AND eerb.properties ->> '$.academicTermId' IN ($academicTermIdStr)";
        }
        if(!empty($request->examRegistrationBatchId)) {
            $examRegistrationBatchIdStr = is_array($request->examRegistrationBatchId) ? "'" . implode("','",$request->examRegistrationBatchId) . "'" : "'".$request->examRegistrationBatchId."'";
            $whereQuery .= " AND eerb.id IN ($examRegistrationBatchIdStr)";
        }
        if(!empty($request->groupId)) {
            $groupIdStr = is_array($request->groupId) ? "'" . implode("','",$request->groupId) . "'" : "'".$request->groupId."'";
            $whereQuery .= " AND eerb.groups_id IN ($groupIdStr)";
        }
        if(!empty($request->degreeId)) {
            $degreeIdStr = is_array($request->degreeId) ? "'" . implode("','",$request->degreeId) . "'" : "'".$request->degreeId."'";
            $whereQuery .= " AND deg.id IN ($degreeIdStr)";
        }
        if(!empty($request->deptId)) {
            $deptIdStr = is_array($request->deptId) ? "'" . implode("','",$request->deptId) . "'" : "'".$request->deptId."'";
            $whereQuery .= " AND dept.deptID IN ($deptIdStr)";
        }
        if(!empty($request->programId)) {
            $programIdStr = is_array($request->programId) ? "'" . implode("','",$request->programId) . "'" : "'".$request->programId."'";
            $whereQuery .= " AND p.id IN ($programIdStr)";
        }
        if(!empty($request->examRegistrationId)) {
            $examRegistrationIdStr = is_array($request->examRegistrationId) ? "'" . implode("','",$request->examRegistrationId) . "'" : "'".$request->examRegistrationId."'";
            $whereQuery .= " AND eerb.ec_exam_registration_id IN ($examRegistrationIdStr)";
        }
        if(!empty($request->startYear)) {
            $whereQuery .= " AND g.properties->>'$.startYear'='$request->startYear";
        }
        if($request->resultPublishedRegistrationOnly) {
            $whereQuery .= " AND  eerb.properties ->>'$.isResultPublished' = 1 ";
        }
        if($request->startIndex !== "" && $request->endIndex !== ""){
            $limitQuery .= " LIMIT $request->startIndex,$request->endIndex";
        }
        $query = "SELECT DISTINCT
            eerb.id,
            eerb.groups_id,
            eerb.ec_exam_registration_id,        
            eerb.properties,
            eerb.fees_properties as batchFeeProperty,
            eerb.created_by,
            eerb.created_date,
            eerb.updated_by,
            eerb.updated_date,
            act.id as academicTermId,
            act.name as academicTermName,
            g.name AS groupName,
            g.type AS groupType,
            dept.deptID,
            deg.name as degreeName,
            dept.deptName,
            dept.departmentDesc as deptDescription,
            ct.courseTypeID,
            ct.typeName as courseTypeName,
            g.identifying_context AS groupIdentifyingContext,
            g.properties AS groupProperties,
            eer.identifying_context AS examRegistrationIdentifyingContext,        
            eer.name AS examRegistrationName,
            eer.type AS examRegistrationType,
            eer.properties AS examRegistrationProperties,
            aps.id AS academicPaperSubjectId,
            aps.properties->>'$.classType' as subjectPropertyType,
            eers.fees_properties as feesProperties,
            eers.properties as ecSubjectProperties,
            eers.id as examRegistrationSubjectId,
            eers.am_assessment_id as assessmentId,
            s.code AS subjectCode,
            s.name AS subjectName,
            IF(aps.properties ->> '$.classType' = 'THEORY',1,0) AS isTheory,
            eers.fm_head_id as subjectFeeHeadId
        FROM
            ec_exam_registration_batch eerb
        INNER JOIN `groups` g ON
            g.id = eerb.groups_id
        INNER JOIN program p ON
            p.id = CONVERT(g.properties ->> '$.programId',CHAR)
        INNER JOIN degree deg ON
            deg.id = p.degree_id
        INNER JOIN `academic_term` act ON
            act.id = CONVERT(eerb.properties ->> '$.academicTermId',CHAR)
        INNER JOIN `department` dept ON
            dept.deptID = CONVERT(g.properties ->> '$.departmentId',CHAR)
        INNER JOIN `course_type` ct ON
            ct.courseTypeID = p.course_type_id
        INNER JOIN ec_exam_registration eer ON
            eer.id = eerb.ec_exam_registration_id
        LEFT JOIN ec_exam_registration_subject eers ON
            eers.ec_exam_registration_batch_id = eerb.id
        LEFT JOIN  cm_academic_paper_subjects aps ON 
            eers.cm_academic_paper_subjects_id = aps.id
        LEFT JOIN  v4_ams_subject s ON 
            aps.ams_subject_id = s.id
        WHERE
            1 = 1";
        try {
            $examRegistrationBatch = $this->executeQueryForList($query.$whereQuery.$limitQuery, $this->mapper[ExamRegistrationBatchServiceMapper::SEARCH_EXAM_REGISTRATION_BATCH]);
        } catch (\Exception $e) {
            throw new ExamControllerException(ExamControllerException::ERROR_FETCHING_EXAM_REGISTRATION_BATCH,"Cannot fetch Exam Registration Batch details! Please try again.");
        }
        return $examRegistrationBatch;
    }
    /**
     * Get Exam Registration Subject 
     * @param GroupID @groupId
     * *@param ExamRegisrationId @examRegisrationId
     * @return Subjects
     */
    public function getAssignedSubjectByBatchOrExamReg($searchRequest)
    {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try {
            $whereQuery = "";
            if($searchRequest->isAvoidPracticalSub){
                $whereQuery .= " AND JSON_CONTAINS(aps.properties, '{\"isPractical\":\"false\"}') ";
            }
            if(!empty($searchRequest->groupId)) {
                $groupIdString = is_array($searchRequest->groupId) ? "'" . implode("','",$searchRequest->groupId) . "'" : "'".$searchRequest->groupId."'";
                $whereQuery .= " AND eerb.groups_id IN ( $groupIdString )";
            }
            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->examDate)) {
                $examDateString = is_array($searchRequest->examDate) ? "'" . implode("','",$searchRequest->examDate) . "'" : "'".$searchRequest->examDate."'";
                $whereQuery .= " AND aa.properties_value ->> '$.assessmentDate' IN ( $examDateString )";
            }
            if(!empty($searchRequest->examStartTime)) {
                $examStartTimeString = is_array($searchRequest->examStartTime) ? "'" . implode("','",$searchRequest->examStartTime) . "'" : "'".$searchRequest->examStartTime."'";
                $examStartTime .= " AND aa.properties_value ->> '$.startTime' IN ( $examStartTimeString )";
            }
            if(!empty($searchRequest->examEndTime)) {
                $examEndTimeString = is_array($searchRequest->examEndTime) ? "'" . implode("','",$searchRequest->examEndTime) . "'" : "'".$searchRequest->examEndTime."'";
                $examEndTime .= " AND aa.properties_value ->> '$.endTime' IN ( $examEndTimeString )";
            }
            
            if(!empty($searchRequest->academicTermId)) {
                $academicTermIdString = is_array($searchRequest->academicTermId) ? "'" . implode("','",$searchRequest->academicTermId) . "'" : "'".$searchRequest->academicTermId."'";
                $whereQuery .= " AND eerb.academicTermId IN ( $academicTermIdString )";
            }
            if($searchRequest->groupByAcademicPaperSubject){
                $groupBy = " GROUP BY eers.cm_academic_paper_subjects_id ";
            }
            $orderBy = " ORDER BY s.code,s.name,eers.cm_academic_paper_subjects_id ";
            $query = "SELECT DISTINCT
                            eers.cm_academic_paper_subjects_id as id,
                            eers.cm_academic_paper_subjects_id as academicPaperSubjectId,
                            eers.am_assessment_id as assessmentId,
                            eers.id AS examSubjectRelationId,
                            eers.properties AS subjectProperties,
                            s.id AS subjectId,
                            s.name as name,
                            s.code AS code,
                            eers.fm_head_id,
                            g.name as groupName,
                            g.id as groupId,
                            cclo.name as slot,
                            IF(aps.properties ->> '$.classType' = 'THEORY',1,0) AS isTheory,
                            CONCAT(s.name, ' (', s.code, ')') as text
                        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 am_assessment aa ON
                            aa.id = eers.am_assessment_id
                        INNER JOIN cm_academic_paper ap ON 
                            ap.id = aps.cm_academic_paper_id
                        INNER JOIN  v4_ams_subject s ON 
                            aps.ams_subject_id = s.id
                        INNER JOIN  `groups` g ON 
                            eerb.groups_id = g.id
                        LEFT JOIN cm_common_list_object cclo ON
                            ap.slot_id = cclo.id AND cclo.type = 'SLOT'
                        WHERE
                            1=1 ";
            $assignedSubjects = $this->executeQueryForList($query.$whereQuery.$groupBy.$orderBy );
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $assignedSubjects;
        
    }
    /**
     * Get Exam Registration Subject By Registration Batch
     * @param GroupID @groupId
     * *@param ExamRegisrationId @examRegisrationId
     * @return Subjects
     */
    public function getAllSubjectsByExamRegistrationBatch($examRegistrationId,$examBatch,$isAvoidPracticalSub = false)
    {
       
        $query = "SELECT
                        DISTINCT eers.cm_academic_paper_subjects_id as id,
                        s.code as code,
                        s.name as name,
                        IF(aps.properties ->> '$.classType' = 'THEORY',1,0) AS isTheory,
                        eers.id as examRegistrationSubjectId
                    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.ec_exam_registration_batch_id = '$examBatch'
                    ORDER BY eers.created_date ASC ";
        
        try 
        {
            $assignedSubjects = $this->executeQueryForList($query);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $assignedSubjects;
        
    }
    public function getBatchWithExamMonthAndYears($request) {
        $request = $this->realEscapeObject($request);
        $whereQuery = "";
        if(!empty($request->batchStartYear))  {
            $whereQuery .= " AND g.properties->>'$.startYear' = '$request->batchStartYear";
        }
        if(!empty($request->courseTypeId))  {
            $whereQuery .= "AND g.properties->>'$.courseTypeId' = '$request->courseTypeId";
        }
        $query = "SELECT DISTINCT
            g.id AS groupId,
            g.name AS batchName,
            eer.properties->>'$.examYear' AS examYear,
            eer.properties->>'$.examMonth' AS examMonth,
            CONCAT(eer.properties->>'$.examYear','-',eer.properties->>'$.examMonth','-1') AS monthYear
        FROM
            ec_exam_registration_batch eerb
        INNER JOIN `groups` g ON
            g.id = eerb.groups_id
            AND g.properties->>'$.finalTermId' = CAST(eerb.properties ->> '$.academicTermId'AS CHAR)
        INNER JOIN ec_exam_registration eer ON
            eer.id = eerb.ec_exam_registration_id
        WHERE
            eer.`type` = 'REGULAR'
            $whereQuery";
        
        try {
            $examMonthAndYears = $this->executeQueryForList($query);
        }
        catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        $batches = [];
        foreach ($examMonthAndYears as $monthYear) {
            $examMonthYear = new \stdClass();
            $batches[$monthYear->groupId]->id = $monthYear->groupId;
            $batches[$monthYear->groupId]->name = $monthYear->batchName;
            $batches[$monthYear->groupId]->monthYears[$monthYear->monthYear]->year = $monthYear->examYear;
            $batches[$monthYear->groupId]->monthYears[$monthYear->monthYear]->month = $monthYear->examMonth;
            $batches[$monthYear->groupId]->monthYears[$monthYear->monthYear]->monthYearText = date("F-Y",strtotime($monthYear->monthYear));
            $batches[$monthYear->groupId]->monthYears[$monthYear->monthYear]->monthYear = $monthYear->monthYear;
            $batches[$monthYear->groupId]->selectedMonthYear = "";
        }
        foreach ($batches as $batch) {
            $batch->monthYears = array_values($batch->monthYears);
        }
        return $batches;
        
    }
   
    
     /**
     * Search examRegistration Batch
     * @param  $request
     * @return examRegistrationBatch
     */
    public function getExamregistrationBatchesByCurrentStaff( $request)
    {
        $request = $this->realEscapeObject($request);
        $currentUerId = $GLOBALS['userId'];
        $whereQuery = "";
        $limitQuery = "";
        
        $query = "SELECT
                        DISTINCT(g.id) as groupId,
                        g.name as groupName,
                        eerb.id as id
                    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
                    WHERE
                        eerb.ec_exam_registration_id='$request->examRegistrationId' AND
                        eers.cm_academic_paper_subjects_id='$request->academicPaperSubjectId' AND
                        JSON_CONTAINS(JSON_EXTRACT(eers.valuation_details ,'$.valuationStaffs'),JSON_OBJECT('addiitonalExamniners', '$currentUerId')) AND
                        JSON_CONTAINS(JSON_EXTRACT(eers.valuation_details ,'$.valuationStaffs'),JSON_OBJECT('count', '$request->currentValuationCount')) ";
        try {
            $examRegistration = $this->executeQueryForList($query.$whereQuery.$limitQuery);
        } catch (\Exception $e) {
            throw new ExamControllerException(ExamControllerException::ERROR_FETCHING_EXAM_REGISTRATION_BATCH,"Cannot fetch Exam Registration Batch details! Please try again.");
        }
        return $examRegistration;
    }
     /**
     * get Not Assigned Batches For Revaluation
     * @param $searchRequest 
     * @return $response 
     */
    public function getNotAssignedBatchesForRevaluation($searchRequest) {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $batches = [];
            $request = new \stdClass;
            $request->revaluationId = $searchRequest->revaluationId;
            $request->examRegistrationId = $searchRequest->parentExamRegistrationId;
            $assignedGroupIds = [];
            $revaluationBatchGroups = $this->getAllRevaluationBatchGroups($request); 
            foreach($revaluationBatchGroups as $batchGroup){
                $batchGroup->groupIds = json_decode($batchGroup->groupIds);
                foreach($batchGroup->groupIds->groupIds as $groupId){
                    $assignedGroupIds[$groupId] = $groupId;
                }
            }
            $request->id = $searchRequest->revaluationId;
            $examRevaluationDetails = ExamRegistrationService::getInstance()->getCurrentExamRevaluationDetails($request);
            $currentRevaluationTypes = $examRevaluationDetails->properties->revaluationFeeTypeIds;
            $allRevaluationExceptCurrent = ExamRevaluationService::getInstance()->getAllRevaluationsByParentRegistrations($request);
            foreach($allRevaluationExceptCurrent as $revaluation){
                $oldRevalrequest = new \stdClass;
                $oldRevalrequest->revaluationId = $revaluation->id;
                $revaluationBatchGroups = $this->getAllRevaluationBatchGroups($oldRevalrequest); 
                foreach($revaluationBatchGroups as $batchGroup){
                    foreach($currentRevaluationTypes as $revaluationType){
                        $batchGroup->groupIds = json_decode($batchGroup->groupIds);
                        $batchGroup->properties = json_decode($batchGroup->properties);
                        if(in_array($revaluationType, $batchGroup->properties->revaluationFeeTypeIds)){
                            foreach($batchGroup->groupIds->groupIds as $groupId){
                                $assignedGroupIds[$groupId] = $groupId;
                            }
                        }
                    }
                }
            }
            // $alreadyAssignedGroups = ExamRegistrationService::getInstance()->getAllALreadyAssignedBatchesForRevaluation($request);
            $request->notAssignedGroupIds = $assignedGroupIds;
            $groups = $this->getAllBatchesAndSubjectDetailsByExamRegistration($request); 
            foreach($groups as $group){
                $batches[$group->groupId]->groupId = $group->groupId;
                $batches[$group->groupId]->id = $group->groupId;
                $batches[$group->groupId]->groupName = $group->groupName;
                $batches[$group->groupId]->name = $group->groupName;
                $batches[$group->groupId]->examRegistrationId = $group->examRegistrationId;
                $batches[$group->groupId]->examRegistrationName = $group->examRegistrationName;
                $batches[$group->groupId]->examRegistrationBatchId = $group->examRegistrationBatchId;
                $batches[$group->groupId]->subjects[$group->academicPaperSubjectsId]->id = $group->academicPaperSubjectsId;
                $batches[$group->groupId]->subjects[$group->academicPaperSubjectsId]->academicPaperSubjectsId = $group->academicPaperSubjectsId;
                $batches[$group->groupId]->subjects[$group->academicPaperSubjectsId]->assessmentId = $group->assessmentId;
            }
            $batches = array_values($batches);
            foreach($batches as $batch){
                $batch->subjects = array_values($batch->subjects);
            }
            $response = new \stdClass;
            $response->revaluationBatchGroups = $revaluationBatchGroups;
            $response->notAssignedBatches = $batches;
            return  $response;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * get Not Assigned Batches For Revaluation
     * @param $searchRequest 
     * @return $response 
     */
    public function getAllAssignedBatchGroupsForRevaluation($searchRequest) {
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $request = new \stdClass;
            $request->revaluationId = $searchRequest->revaluationId;
            $request->examRegistrationId = $searchRequest->revaluationId;
            $request->id = $searchRequest->revaluationId;
            $request->batchGroupId = $searchRequest->batchGroupId;
            $examRevaluationDetails = ExamRegistrationService::getInstance()->getCurrentExamRevaluationDetails($request);
            $searchRequest->sortByCommonFee = 1;
            $feesTypeArray = CommonExamService::getInstance()->getAllFeesTypes($searchRequest);
            $feesTypes = new \stdClass();
            $commonFee = [];
            $revaluationFee = [];
            foreach ($feesTypeArray as $feeType){
                if($feeType->isCommon){
                    $commonFee[] = $feeType;
                }
                else{
                    if(in_array($feeType->id, $examRevaluationDetails->properties->revaluationFeeTypeIds)){
                        $revaluationFee[] = $feeType;
                    }
                }
            }
            $feesTypes->commonFee = $commonFee;
            $feesTypes->revaluationFee = $revaluationFee;
            $revaluationBatchGroups = $this->getAllRevaluationBatchGroups($request); 
            foreach($revaluationBatchGroups as $batchGroup){
                $batches = [];
                $batchGroup->startDate = date("d-m-Y", strtotime($batchGroup->startDate));
                $batchGroup->endDate = date("d-m-Y", strtotime($batchGroup->endDate));
                $batchGroup->verificationDate = date("d-m-Y", strtotime($batchGroup->verificationDate));
                $batchGroup->subjectLimit = $batchGroup->subjectLimit == 0 ? "ALL" : "$batchGroup->subjectLimit";
                $assignedGroupIds = [];
                $batchGroup->groupIds = json_decode($batchGroup->groupIds);
                $batchGroup->feesTypes = json_decode(json_encode($feesTypes));
                $assignedFeetypes = json_decode($batchGroup->feeProperties);
                $assignedFeetypes->revaluationFee = (array) $assignedFeetypes->revaluationFee;
                $batchGroup->existingTemplateId = $assignedFeetypes->feeTemplateId;
                $batchGroup->paymentMethods = $assignedFeetypes->paymentMethods;
                foreach($batchGroup->feesTypes->commonFee as $feesType){
                    if( $assignedFeetypes->revaluationFee[$feesType->id]){
                        $feesType->value = $assignedFeetypes->revaluationFee[$feesType->id]->value;
                    }
                }
                foreach($batchGroup->feesTypes->revaluationFee as $feesType){
                    if( $assignedFeetypes->revaluationFee[$feesType->id]){
                        $feesType->value = $assignedFeetypes->revaluationFee[$feesType->id]->value;
                    }
                }
                foreach($batchGroup->groupIds->groupIds as $groupId){
                    $requestObj = new \stdClass();
                    $requestObj->examRegistrationId = $request->examRegistrationId ;
                    $requestObj->groupIds = $groupId;
                    $entryCheck = ExamRegistrationService::getInstance()->getRevaluationStudentAssignedDetails($request);
                    if($entryCheck){
                        $batches[$groupId]->hasStudentRegistered = 1;
                        $batchGroup->hasStudentRegistered = 1;
                    }
                    $batches[$groupId]->groupId = $groupId;
                    $batches[$groupId]->id = $groupId;
                    $searchGroupRequest = new SearchGroupRequest;
                    $searchGroupRequest->id = $groupId;
                    $searchGroupRequest->type = "BATCH";
                    $batch = ECGroupService::getInstance()->searchGroupByRequest($searchGroupRequest);
                    $batches[$groupId]->groupName = current($batch)->name;
                    $batches[$groupId]->name = current($batch)->name;
                    $assignedGroupIds[] = $groupId;
                }
                $request->assignedGroupIds = $assignedGroupIds;
                $batches = array_values($batches);
                $batchGroup->groups = $batches;
            }
            $response = new \stdClass;
            $response->revaluationBatchGroups = $revaluationBatchGroups;
            return  $response;
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    
     /**
     * get All Revaluation Batch Groups
     * @param $searchRequest 
     * @return $programResult 
     */
    public function getAllRevaluationBatchGroups($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
            $whereQuery = "";
            if(!empty($searchRequest->revaluationId)) {
                $whereQuery .= " AND erbg.ec_exam_revaluation_id = '$searchRequest->revaluationId'";
            }
            if(!empty($searchRequest->batchGroupId)) {
                $whereQuery .= " AND erbg.id = '$searchRequest->batchGroupId'";
            }
            $query = "SELECT DISTINCT
                            erbg.id as batchGroupId,
                            erbg.ec_exam_revaluation_id as examValuationId,
                            erbg.group_ids as groupIds,
                            erbg.startDate,
                            erbg.endDate,
                            erbg.subjectLimit,
                            erbg.verificationDate,
                            eer.properties,
                            erbg.fee_properties as feeProperties
                        FROM
                            `exam_revaluation_batch_groups` erbg
                        INNER JOIN 
                            ec_exam_registration eer ON
                            eer.id = erbg.ec_exam_revaluation_id
                        WHERE 1=1 ";
            $batchGroups = $this->executeQueryForList($query.$whereQuery);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $batchGroups;
    }
     /**
     * get All Revaluation Batch Groups
     * @param $searchRequest 
     * @return $programResult 
     */
    public function getAllBatchesAndSubjectDetailsByExamRegistration($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
          
            $orderBy = "ORDER BY g.created_date DESC";
            $whereQuery = "";
            $joinQuery = "";
            if($searchRequest->isEnableMinorHonorExamRegistration){
                $joinQuery .= " INNER JOIN  cm_academic_paper_subjects aps ON 
                            eers.cm_academic_paper_subjects_id = aps.id
                        INNER JOIN cm_academic_paper ap ON 
                            ap.id = aps.cm_academic_paper_id
                        INNER JOIN cm_syllabus_academic_term_settings csats ON
                            csats.id = ap.cm_syllabus_academic_term_settings_id 
                        INNER JOIN cm_syllabus cs ON
                            cs.id = csats.cm_syllabus_id ";
                if($searchRequest->syllabusType == SyllabusTypeConstants::MINOR){
                    $whereQuery .= " AND cs.type IN ('MINOR')";
                }
                elseif($searchRequest->syllabusType == SyllabusTypeConstants::HONOURS){
                    $whereQuery .= " AND cs.type IN ('HONOURS')";
                }
                else{
                    $whereQuery .= " AND cs.type NOT IN ('HONOURS','MINOR')";
                }
            }
            if(!empty($searchRequest->notAssignedGroupIds)) {
                $groupIdString = is_array($searchRequest->notAssignedGroupIds) ? "'" . implode("','",$searchRequest->notAssignedGroupIds) . "'" : "'".$searchRequest->notAssignedGroupIds."'";
                $whereQuery .= " AND g.id NOT IN ( $groupIdString )";
            }
            if(!empty($searchRequest->assignedGroupIds)) {
                $assignedGroupIdString = is_array($searchRequest->assignedGroupIds) ? "'" . implode("','",$searchRequest->assignedGroupIds) . "'" : "'".$searchRequest->assignedGroupIds."'";
                $whereQuery .= " AND g.id IN ( $assignedGroupIdString )";
            }
            if(!empty($searchRequest->assignedTermId)) {
                $assignedTermIdString = is_array($searchRequest->assignedTermId) ? "'" . implode("','",$searchRequest->assignedTermId) . "'" : "'".$searchRequest->assignedTermId."'";
                $whereQuery .= " AND eerb.properties ->> '$.academicTermId' IN ( $assignedTermIdString )";
            }
            if(!empty($searchRequest->examRegistrationId)) {
                $whereQuery .= " AND eerb.ec_exam_registration_id = '$searchRequest->examRegistrationId'";
            }
            if(!empty($searchRequest->examRegistrationType)) {
                $whereQuery .= " AND eer.type = '$searchRequest->examRegistrationType'";
            }
            $query = "SELECT DISTINCT
                            g.id,
                            g.id as groupId,
                            g.name as groupName,
                            eer.id as examRegistrationId,
                            eerb.id as examRegistrationBatchId,
                            eers.cm_academic_paper_subjects_id as academicPaperSubjectsId,
                            eers.am_assessment_id as assessmentId,
                            eer.name as examRegistrationName
                        FROM
                            `groups` g
                        INNER JOIN ec_exam_registration_batch eerb ON
                            eerb.groups_id = g.id
                        LEFT JOIN ec_exam_registration_subject eers ON
                            eers.ec_exam_registration_batch_id = eerb.id
                        INNER JOIN ec_exam_registration eer ON
                            eer.id = eerb.ec_exam_registration_id
                        $joinQuery
                        WHERE 1=1 AND eer.trashed IS NULL";
            $groups = $this->executeQueryForList($query.$whereQuery.$orderBy);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $groups;
    }
     /**
     * searchExamRegistrationBatchesWithSubjects
     * @param SearchExamRegistrationBatchRequest $request
     * @return examRegistrationBatches
     */
    public function searchExamRegistrationBatchesWithSubjects(SearchExamRegistrationBatchRequest $request){
        $request = $this->realEscapeObject($request);
        $whereQuery = "";
        $limitQuery = "";
        if(!empty($request->id)) {
            $whereQuery .= " AND eerb.id='$request->id";
        }
        if(!empty($request->examRegistrationBatchId)) {
            $examRegistrationBatchIdStr = is_array($request->examRegistrationBatchId) ? "'" . implode("','",$request->examRegistrationBatchId) . "'" : "'".$request->examRegistrationBatchId."'";
            $whereQuery .= " AND eerb.id IN ($examRegistrationBatchIdStr)";
        }
        if(!empty($request->groupId)) {
            $whereQuery .= " AND eerb.groups_id = '$request->groupId";
        }
        if(!empty($request->examRegistrationId)) {
            $whereQuery .= " AND eerb.ec_exam_registration_id='$request->examRegistrationId";
        }
        if($request->startIndex !== "" && $request->endIndex !== ""){
            $limitQuery .= " LIMIT $request->startIndex,$request->endIndex";
        }
        $query = "SELECT DISTINCT
            eerb.id,
            eerb.groups_id,
            eerb.ec_exam_registration_id,        
            eerb.properties,
            eerb.created_by,
            eerb.created_date,
            eerb.updated_by,
            eerb.updated_date,
            g.name AS groupName,
            g.type AS groupType,
            eer.name AS examRegistrationName,
            eer.type AS examRegistrationType,
            eers.id AS examRegistrationSubjectId,
            eers.cm_academic_paper_subjects_id,
            eers.am_assessment_id,
            s.code AS subjectCode,
            s.name as subjectName,
            IF(aps.properties ->> '$.classType' = 'THEORY',1,0) AS isTheory,
            eers.revaluation_properties ,
            eers.valuation_details ,
            eers.fees_properties ,
            eers.properties AS examRegistrationSubjectProperties
        FROM
            ec_exam_registration_batch eerb
        INNER JOIN `groups` g ON
            g.id = eerb.groups_id
        INNER JOIN ec_exam_registration eer ON
            eer.id = eerb.ec_exam_registration_id
        LEFT JOIN  ec_exam_registration_subject eers ON 
            eers.ec_exam_registration_batch_id = eerb.id
        LEFT JOIN  cm_academic_paper_subjects aps ON 
            eers.cm_academic_paper_subjects_id = aps.id
        LEFT JOIN  v4_ams_subject s ON 
            aps.ams_subject_id = s.id
        WHERE
            1 = 1";
        try {
            $examRegistrationBatches = $this->executeQueryForList($query.$whereQuery.$limitQuery, $this->mapper[ExamRegistrationBatchServiceMapper::SEARCH_EXAM_REGISTRATION_BATCHES_WITH_SUBJECTS]);
        } catch (\Exception $e) {
            throw new ExamControllerException(ExamControllerException::ERROR_FETCHING_EXAM_REGISTRATION_BATCH,"Cannot fetch Exam Registration Batch details! Please try again.");
        }
        return $examRegistrationBatches;
    }
    /**
     * Search Batch With Out Academic Term
     * @param  $request
     * @return examRegistration
     */
    public function searchBatchWithOutAcademicTerm($request){
        $request = $this->realEscapeObject($request);
        $whereQuery = "";
        if(!empty($request->groupId)) {
            $groupIdStr = is_array($request->groupId) ? "'" . implode("','",$request->groupId) . "'" : "'".$request->groupId."'";
            $whereQuery .= " AND eerb.groups_id IN ($groupIdStr)";
        }
        if(!empty($request->courseTypeId))  {
            $whereQuery .= "AND p.course_type_id = '$request->courseTypeId";
        }
        if(!empty($request->startYear)) {
            $whereQuery .= " AND g.properties->>'$.startYear'='$request->startYear";
        }
        
        $query = "SELECT DISTINCT
            g.id AS id,
            g.id AS groupId,
            g.name AS groupName,
            g.type AS groupType,
            dept.deptID,
            dept.deptName,
            deg.name as degreeName,
            dept.departmentDesc as deptDescription,
            ct.courseTypeID,
            ct.typeName as courseTypeName
        FROM
            `groups` g
        INNER JOIN program p ON
            p.id = CONVERT(g.properties ->> '$.programId',CHAR)
        INNER JOIN degree deg ON
            deg.id = p.degree_id
        INNER JOIN `department` dept ON
            dept.deptID = CONVERT(g.properties ->> '$.departmentId',CHAR)
        INNER JOIN `course_type` ct ON
            ct.courseTypeID = p.course_type_id
        WHERE
            g.type = 'BATCH'";
        try {
            $examRegistrationBatch = $this->executeQueryForList($query.$whereQuery);
        } catch (\Exception $e) {
            throw new ExamControllerException(ExamControllerException::ERROR_FETCHING_EXAM_REGISTRATION_BATCH,"Cannot fetch Exam Registration Batch details! Please try again.");
        }
        return $examRegistrationBatch;
    }
    /**
     * Save exam result publish details
     * @param $request
     */
    public function saveExamResultPublishDetails($request)
    {
        $columnVal = "";
       
        if(!$request->isAvoidFinalizeFlag){
            $isFinalize = $request->isFinalize ? 1 : 0;
            $columnVal .= "properties = JSON_SET(properties, '$.isResultFinalized',$isFinalize),";
        }
        if(!$request->isAvoidPublishFlag){
            if(!empty($request->publish)){
                $columnVal .= "properties = JSON_SET(properties, '$.publishingStartDate','$request->startDate'),
                properties = JSON_SET(properties, '$.publishingEndDate','$request->endDate'),";
            }
            $publish = $request->publish ? 1 : 0;
            $columnVal .= "properties = JSON_SET(properties, '$.isResultPublished',$publish),";
        }
       
        $query = "UPDATE
                    ec_exam_registration_batch
                SET
                    $columnVal 
                    updated_date = utc_timestamp()
                WHERE
                    id IN ('$request->examRegistrationBatchId')";
        try {
            $this->executeQuery($query);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
    }
    
  /**
     * get all batches and assigned valuation rule
     * @param $searchRequest 
     * @return $programResult 
     */
    public function getAllBatchesAndAssignedValuationRule($searchRequest){
        $searchRequest = $this->realEscapeObject($searchRequest);
        try{
          
            $orderBy = "ORDER BY g.created_date DESC";
            $whereQuery = "";
            if(!empty($searchRequest->assignedTermId)) {
                $assignedTermIdString = is_array($searchRequest->assignedTermId) ? "'" . implode("','",$searchRequest->assignedTermId) . "'" : "'".$searchRequest->assignedTermId."'";
                $whereQuery .= " AND eerb.properties ->> '$.academicTermId' IN ( $assignedTermIdString )";
            }
            if(!empty($searchRequest->examRegistrationId)) {
                $whereQuery .= " AND eerb.ec_exam_registration_id = '$searchRequest->examRegistrationId'";
            }
            $query = "SELECT DISTINCT
                            g.id,
                            g.id as groupId,
                            g.name as groupName,
                            eer.id as examRegistrationId,
                            eerb.id as examRegistrationBatchId,
                            eerb.properties ->> '$.valuationRule' as valuationRule,
                            eerb.properties as properties,
                            eer.name as examRegistrationName
                        FROM
                            `groups` g
                        INNER JOIN ec_exam_registration_batch eerb ON
                            eerb.groups_id = g.id
                        INNER JOIN ec_exam_registration eer ON
                            eer.id = eerb.ec_exam_registration_id
                        WHERE 1=1 AND eer.trashed IS NULL";
            $groups = $this->executeQueryForList($query.$whereQuery.$orderBy);
        }
        catch (\Exception $e)
        {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $groups;
    }
    
    /**
     * save batch valuation rule
     * @param $batch 
     */
    public function saveBatchValuationRule($batch)
    {
        // $batch = $this->realEscapeObject($batch);
        $properties = $batch->properties;
        if($properties->customFeilds){
            $properties->customFeilds = json_decode($properties->customFeilds);
        }
        $properties = json_encode($properties);
        $query = "UPDATE
                    ec_exam_registration_batch
                SET
                    properties = '$properties'
                WHERE
                    id IN ('$batch->examRegistrationBatchId')";
        try {
            $this->executeQuery($query);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Search examRegistration Batch Details
     * @param $request
     * @return $examRegistrationBatches
     */
    public function searchExamRegistrationBatchDetails( $request){
        $request = $this->realEscapeObject($request);
        $whereQuery = "";
        if(!empty($request->groupId)) {
            $groupIdStr = is_array($request->groupId) ? "'" . implode("','",$request->groupId) . "'" : "'".$request->groupId."'";
            $whereQuery .= " AND eerb.groups_id IN ($groupIdStr)";
        }
        if(!empty($request->degreeId)) {
            $degreeIdStr = is_array($request->degreeId) ? "'" . implode("','",$request->degreeId) . "'" : "'".$request->degreeId."'";
            $whereQuery .= " AND deg.id IN ($degreeIdStr)";
        }
        if(!empty($request->examRegistrationId)) {
            $examRegistrationIdString = is_array($request->examRegistrationId) ? "'" . implode("','",$request->examRegistrationId) . "'" : "'".$request->examRegistrationId."'";
            $whereQuery .= " AND eerb.ec_exam_registration_id IN ( $examRegistrationIdString )";
        }
        if(!empty($request->startYear)) {
            $startYearStr = is_array($request->startYear) ? "'" . implode("','",$request->startYear) . "'" : "'".$request->startYear."'";
            $whereQuery .= " AND g.properties->>'$.startYear' IN ($startYearStr)";
        }
        if(!empty($request->courseTypeId))  {
            $whereQuery .= "AND p.course_type_id = '$request->courseTypeId";
        }
        $query = "SELECT DISTINCT
            g.id AS id,
            g.id AS groupId,
            g.name AS groupName,
            g.type AS groupType,
            act.id as academicTermId,
            act.name as academicTermName,
            dept.deptID,
            dept.deptName,
            dept.departmentDesc as deptDescription,
            ct.courseTypeID,
            ct.typeName as courseTypeName,
            eer.id AS examRegistrationId,        
            eer.name AS examRegistrationName,
            eer.type AS examRegistrationType,
            eer.properties AS examRegistrationProperties,
            g.properties->>'$.startYear' AS startYear
        FROM
            ec_exam_registration_batch eerb
        INNER JOIN `groups` g ON
            g.id = eerb.groups_id
        INNER JOIN program p ON
            p.id = CONVERT(g.properties ->> '$.programId',CHAR)
        INNER JOIN `academic_term` act ON
            act.id = CONVERT(eerb.properties ->> '$.academicTermId',CHAR)
        INNER JOIN `department` dept ON
            dept.deptID = CONVERT(g.properties ->> '$.departmentId',CHAR)
        INNER JOIN `course_type` ct ON
            ct.courseTypeID = p.course_type_id
        INNER JOIN ec_exam_registration eer ON
            eer.id = eerb.ec_exam_registration_id
        WHERE
            1 = 1";
        try {
            $examRegistrationBatches = $this->executeQueryForList($query.$whereQuery);
        } catch (\Exception $e) {
            throw new ExamControllerException(ExamControllerException::ERROR_FETCHING_EXAM_REGISTRATION_BATCH,"Cannot fetch Exam Registration Batch details! Please try again.");
        }
        return $examRegistrationBatches;
    }
    /**
     * Save exam result publish details
     * @param $request
     */
    public function saveBatchExamRegistrationRequiredStatus($request)
    {
        $statusFlag = $request->statusFlag ? 1 : 0;
        $query = "UPDATE
                    ec_exam_registration_batch
                SET
                    properties = JSON_SET(properties, '$.isRequiredForImport',$statusFlag)
                WHERE
                    id IN ('$request->batchRelationId')";
        try {
            $this->executeQuery($query);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
    }
        /**
     * Save exam result publish details
     * @param $request
     */
    public function saveBatchGradeUpgradationRule($request)
    {
        $request = $this->realEscapeObject($request);
        $properties = json_encode($request->properties);
        $query = "UPDATE
                    ec_exam_registration_batch
                SET
                    properties = JSON_SET(properties, '$.gradeUpgradationRule','$properties')
                WHERE
                    id IN ('$request->id')";
        try {
            $this->executeQuery($query);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Update ExamRegistration Batch Custom Feilds
     * @param $examRegistrationBatch
     */
    public function updateExamRegistrationBatchCustomFeilds($examRegistrationBatch){
        $customFeilds = !empty($examRegistrationBatch->customFeilds) ? "'".json_encode($examRegistrationBatch->customFeilds)."'" : "NULL";
        $query = "UPDATE
                    ec_exam_registration_batch
                SET
                    properties = JSON_SET(properties, '$.customFeilds',$customFeilds),
                    updated_by = '$examRegistrationBatch->updatedBy'
                WHERE
                    id = '$examRegistrationBatch->id'";
        try {
            $this->executeQuery($query);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * Save consolidated Footer details
     * @param $request
     */
    public function saveConsolidatedFooterDetails($request){
        $footerData = !empty($request->footerData) ? "'" . json_encode($request->footerData) . "'" : "NULL";
        $userId = $GLOBALS['userId'];
        $query = "UPDATE
                    ec_exam_registration_batch
                SET
                    properties = JSON_SET(properties, '$.consolidatedMarkListFooterData',$footerData),
                    updated_by = '$userId'
                WHERE
                    groups_id IN ($request->groupsId) AND  ec_exam_registration_id  IN ('$request->examRegistrationId') ";
        try {
            $this->executeQuery($query);
        } catch (\Exception $e) {
            throw new ExamControllerException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * get Regular exam assigned subjects
     * @param $searchRequest 
     * @return $subjectDetails 
     * @author Krishnajith
     */
    public function getRegularExamAssignedSubjects($searchRequest) {
        $searchRequest = $this->realEscapeObject($searchRequest);
        $searchRequest->academicPaperSubjectIds = stripslashes($searchRequest->academicPaperSubjectIds);
        try{
            $subjectOrderBy = CommonService::getInstance()->getSettings(SettingsConstants::EXAM_CONTROLLER, SettingsConstants::SUBJECT_ORDER_TAKEN_BY);
            if($subjectOrderBy == "ORDER"){
                $orderBy = " ORDER BY CAST(aps.properties ->> '$.orderNo' AS UNSIGNED) ASC";
            }
            else{
                $orderBy = " ORDER BY CAST(aps.properties ->> '$.priority' AS UNSIGNED) DESC";
            }
            $whereQuery = "";
            if($searchRequest->isEnableMinorHonorExamRegistration){
                if($searchRequest->syllabusType == SyllabusTypeConstants::MINOR){
                    $whereQuery .= " AND cs.type IN ('MINOR')";
                }
                elseif($searchRequest->syllabusType == SyllabusTypeConstants::HONOURS){
                    $whereQuery .= " AND cs.type IN ('HONOURS')";
                }
                else{
                    $whereQuery .= " AND cs.type NOT IN ('HONOURS','MINOR')";
                }
            }
            if(!empty($searchRequest->courseTypeId)) {
                $courseTypeIdString = is_array($searchRequest->courseTypeId) ? "'" . implode("','",$searchRequest->courseTypeId) . "'" : "'".$searchRequest->courseTypeId."'";
                $whereQuery .= " AND p.course_type_id IN ( $courseTypeIdString )";
            }
            if(!empty($searchRequest->groupId)) {
                $groupIdString = is_array($searchRequest->groupId) ? "'" . implode("','",$searchRequest->groupId) . "'" : "'".$searchRequest->groupId."'";
                $whereQuery .= " AND g.id IN ( $groupIdString )";
            }
            if(!empty($searchRequest->startYear)) {
                $startYearStrng = is_array($searchRequest->startYear) ? "'" . implode("','",$searchRequest->startYear) . "'" : "'".$searchRequest->startYear."'";
                $whereQuery .= " AND g.properties ->> '$.startYear' IN ( $startYearStrng )";
            }
            if(!empty($searchRequest->academicTermId)) {
                $academicTermIdString = is_array($searchRequest->academicTermId) ? "'" . implode("','",$searchRequest->academicTermId) . "'" : "'".$searchRequest->academicTermId."'";
                $whereQuery .= " AND eerb.properties ->> '$.academicTermId' IN ( $academicTermIdString )";
            }
            if(!empty($searchRequest->academicPaperSubjectIds)) {
                $academicPaperSubjectIdsString = is_array($searchRequest->academicPaperSubjectIds) ? "'" . implode("','",$searchRequest->academicPaperSubjectIds) . "'" : $searchRequest->academicPaperSubjectIds;
                $whereQuery .= " AND aps.id IN ( $academicPaperSubjectIdsString )";
            }
            if(!empty($searchRequest->academicPaperSubjectId)) {
                $academicPaperSubjectIdString = is_array($searchRequest->academicPaperSubjectId) ? "'" . implode("','",$searchRequest->academicPaperSubjectId) . "'" : "'".$searchRequest->academicPaperSubjectId."'";
                $whereQuery .= " AND aps.id IN ( $academicPaperSubjectIdString )";
            }
            $query = "SELECT DISTINCT
                        aps.id AS id,
                        aps.id AS academicPaperSubjectId,
                        sub.id AS subjectId,
                        sub.code AS subjectCode,
                        sub.name AS subjectName,
                        sub.name AS name,
                        eerb.properties ->> '$.academicTermId' as academicTermId,
                        g.id AS groupId,
                        g.name AS groupName,
                        aps.properties->>'$.externalMaxMark' as externalMaxMark,
                        aps.properties ->> '$.isInternal' as isInternal,
                        aps.properties ->> '$.isExternal' as isExternal,
                        aps.properties ->> '$.internalMaxMark' as internalMaxMark,
                        aps.properties->>'$.classType' as subjectPropertyType
                    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 `program` p ON 
                        p.id = g.properties->>'$.programId'
                    INNER JOIN cm_academic_paper_subjects aps ON 
                        aps.id = eers.cm_academic_paper_subjects_id
                    INNER JOIN cm_academic_paper ap ON 
                        aps.cm_academic_paper_id = ap.id
                    INNER JOIN cm_syllabus_academic_term_settings csats ON
                        csats.id = ap.cm_syllabus_academic_term_settings_id 
                    INNER JOIN v4_ams_subject sub ON 
                        sub.id = aps.ams_subject_id
                    INNER JOIN cm_syllabus cs ON
                        cs.id = csats.cm_syllabus_id
                    WHERE 1=1 AND g.type = 'BATCH' AND eer.type = 'REGULAR' AND eer.trashed IS NULL";
            $subjectDetails = $this->executeQueryForList($query.$whereQuery.$orderBy);
            
        }
        catch (\Exception $e){
            throw new ExamControllerException($e->getCode(),$e->getMessage());
        }
        return $subjectDetails;
    }
    
}