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 / 56
CRAP
0.00% covered (danger)
0.00%
0 / 1254
CertificateService
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 56
45156.00
0.00% covered (danger)
0.00%
0 / 1254
 __construct
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 1
 __clone
0.00% covered (danger)
0.00%
0 / 1
2.00
0.00% covered (danger)
0.00%
0 / 1
 getInstance
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 5
 createCertificatePrefix
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 51
 updateCertificatePrefix
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 38
 searchCertificatePrefix
0.00% covered (danger)
0.00%
0 / 1
90.00
0.00% covered (danger)
0.00%
0 / 43
 getCertificatePrefixByYear
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 14
 getCertificatePrefixByDate
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 15
 checkCertificatePrefixByDate
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 24
 getCertificatePrefixById
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 deleteCertificatePrefix
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 createStudentTransferCertificate
0.00% covered (danger)
0.00%
0 / 1
506.00
0.00% covered (danger)
0.00%
0 / 100
 updateStudentTransferCertificate
0.00% covered (danger)
0.00%
0 / 1
420.00
0.00% covered (danger)
0.00%
0 / 94
 getFailedStudentTransferCertificateByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 getStudentTransferCertificateByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 65
 checkFailedStudentTransferCertificateByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 20
 checkStudentTransferCertificateByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 generateTcNo
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 18
 generateConductNo
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 21
 getConductSlNo
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 getAdmissionCertificate
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 addApplicationFormTypeCertificate
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 deleteApplicationFormTypeCertificateByFormTypeId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 getApplicationFormTypeCertificateByFormTypeId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 getStudentApplicationCertificateForAdmissionByFormTypeId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 14
 addStudentApplicationCertificate
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 deleteStudentApplicationCertificateByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 getStudentApplicationCertificateByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 getAdmissionCertificateByFormTypeId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 addStudentApplicationCertificateByList
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 20
 getStudentCharacters
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 getMediumOfInstruction
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 deleteStudentTransferCertificate
0.00% covered (danger)
0.00%
0 / 1
30.00
0.00% covered (danger)
0.00%
0 / 30
 getCertificatePrefixByCampusTypeId
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 20
 getMigrationCertNo
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 generateMigrationCertNo
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 34
 getCancelCertNo
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 generateCancelCertNo
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 23
 getCertificatesContent
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 12
 upsertCertificateContent
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 20
 deleteMigrationCert
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 deleteCancelCert
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 9
 checkIfStudentCertificateExistsForPerfix
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 25
 createStudentTransferCertificateBatchwise
0.00% covered (danger)
0.00%
0 / 1
182.00
0.00% covered (danger)
0.00%
0 / 147
 getCustomTemplateName
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 11
 getCustomTemplate
0.00% covered (danger)
0.00%
0 / 1
56.00
0.00% covered (danger)
0.00%
0 / 18
 getCustomTCform
0.00% covered (danger)
0.00%
0 / 1
20.00
0.00% covered (danger)
0.00%
0 / 22
 getCertificatePrefixByType
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 17
 getAllAcademicCertificates
0.00% covered (danger)
0.00%
0 / 1
12.00
0.00% covered (danger)
0.00%
0 / 17
 getConductSlNoByPrefixId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 13
 getUnknownTransferCertificate
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 getUnknownTransferCertificateById
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 deleteUnknownTransferCertificateById
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 getTransferCertificateDetailsByStudentId
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 11
 getStudentCategorys
0.00% covered (danger)
0.00%
0 / 1
6.00
0.00% covered (danger)
0.00%
0 / 10
 getDynamicTransferCertificateValues
0.00% covered (danger)
0.00%
0 / 1
42.00
0.00% covered (danger)
0.00%
0 / 30
<?php
namespace com\linways\core\ams\professional\service;
use com\linways\core\ams\professional\dto\CertificatePrefixes;
use com\linways\core\ams\professional\exception\ProfessionalException;
use com\linways\core\ams\professional\request\CertificatePrefixesRequest;
use com\linways\core\ams\professional\dto\StudentTransferCertificate;
use com\linways\core\ams\professional\dto\ApplicationFormTypeCertificate;
use com\linways\core\ams\professional\dto\StudentApplicationCertificate;
use com\linways\core\ams\professional\dto\SettingsConstents;
use com\linways\core\ams\professional\dto\StudentMigrationCertificate;
use com\linways\core\ams\professional\dto\StudentCancellationCertificate;
use com\linways\core\ams\professional\toggles\PermissionToggle;
use com\linways\core\ams\professional\toggles\PermissionToggles;
use com\linways\core\ams\professional\constant\SettingsConstants;
use com\linways\core\ams\professional\constant\FailedReason;
use com\linways\core\ams\professional\constant\StatusConstants;
use com\linways\core\ams\professional\request\academic\FailedStudentRequest;
use \stdClass;
class CertificateService extends BaseService
{
    // /Condition 1 - Presence of a static member variable
    private static $_instance = null;
    // /Condition 2 - Locked down the constructor
    private function __construct()
    {}
    // Prevent any oustide instantiation of this class
    // /Condition 3 - Prevent any object or instance of that class to be cloned
    private function __clone()
    {}
    // Prevent any copy of this object
    // /Condition 4 - Have a single globally accessible static method
    public static function getInstance()
    {
        if (! is_object(self::$_instance)) // or if( is_null(self::$_instance) ) or if( self::$_instance == null )
            self::$_instance = new self();
        return self::$_instance;
    }
    /**
     * add new prefix
     * @param CertificatePrefixes $certificatePrefix
     * @throws ProfessionalException
     * @return \com\linways\base\dto\MySqlResult
     */
    public function createCertificatePrefix($certificatePrefix)
    {
        $sql= "INSERT INTO certificatePrefixes
        (
        prefixName,
        prefix,
        courseTypeId,
        startYear,
        endYear,
        certificateType,
        campusTypeId, fromDate, toDate, prefixYear, yearWise,
        createdBy,
        createdDate,
        updatedBy,
        updatedDate
        )
        VALUES
        (
        '$certificatePrefix->prefixName',
        '$certificatePrefix->prefix',
        $certificatePrefix->courseTypeId,
        $certificatePrefix->startYear,
        $certificatePrefix->endYear,
        '$certificatePrefix->certificateType',
        $certificatePrefix->campusTypeId$certificatePrefix->fromDate$certificatePrefix->toDate, '$certificatePrefix->prefixYear', '$certificatePrefix->yearWise', $certificatePrefix->createdBy,
        utc_timestamp(),
        $certificatePrefix->updatedBy,
        utc_timestamp()
        )";
        try
        {
            if(!empty($certificatePrefix->campusTypeId))
            {
                $certificatePrefixRequest = new CertificatePrefixesRequest();
                $certificatePrefixRequest->campusTypeId = trim($certificatePrefix->campusTypeId, "'");
                $certificatePrefixRequest->certificateType = $certificatePrefix->certificateType;
                $certificatePrefixDetails = $this->searchCertificatePrefix($certificatePrefixRequest);
                foreach ($certificatePrefixDetails as $certificatePrefixDetail)
                {
                    if((strtotime(str_replace("'", "", $certificatePrefix->fromDate))<= strtotime($certificatePrefixDetail->toDate)) && (strtotime(str_replace("'", "", $certificatePrefix->toDate))>= strtotime($certificatePrefixDetail->fromDate)))
                    {
                        throw new ProfessionalException("PREFIX_FOR_GIVEN_DATES_EXISTS", "PREFIX_FOR_GIVEN_DATES_EXISTS");
                    }
                }
            }
            return $this->executeQuery($sql, TRUE);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * update prefix
     * @param CertificatePrefixes $certificatePrefix
     * @throws ProfessionalException
     * @return \com\linways\base\dto\MySqlResult
     */
    public function updateCertificatePrefix($certificatePrefix)
    {
        $sql = "UPDATE certificatePrefixes SET
        prefixName='$certificatePrefix->prefixName',
        prefix='$certificatePrefix->prefix',
        courseTypeId=$certificatePrefix->courseTypeId,
        startYear=$certificatePrefix->startYear,
        endYear=$certificatePrefix->endYear,
        certificateType='$certificatePrefix->certificateType',
        campusTypeId = $certificatePrefix->campusTypeId,
        fromDate = $certificatePrefix->fromDate
        toDate = $certificatePrefix->toDate,
        prefixYear = '$certificatePrefix->prefixYear',
        yearWise = '$certificatePrefix->yearWise',
        updatedBy=$certificatePrefix->updatedBy,
        updatedDate=utc_timestamp()
        WHERE
        id=$certificatePrefix->id";
        try
        {
            if(!empty($certificatePrefix->campusTypeId))
            {
                $sqlDate = "SELECT fromDate, toDate FROM certificatePrefixes WHERE id != $certificatePrefix->id AND campusTypeId=".$certificatePrefix->campusTypeId." and certificateType = '$certificatePrefix->certificateType'";
                $certificatePrefixDetails = $this->executeQueryForList($sqlDate);
                foreach ($certificatePrefixDetails as $certificatePrefixDetail)
                {
                    if((strtotime(str_replace("'", "", $certificatePrefix->fromDate))<= strtotime($certificatePrefixDetail->toDate)) && (strtotime(str_replace("'", "", $certificatePrefix->toDate))>= strtotime($certificatePrefixDetail->fromDate)))
                    {
                        throw new ProfessionalException("PREFIX_FOR_GIVEN_DATES_EXISTS", "PREFIX_FOR_GIVEN_DATES_EXISTS");
                    }
                }
            }
            return $this->executeQuery($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * get details of certificate prefix
     * @param CertificatePrefixesRequest $certificatePrefixRequest
     * @return $certificatePrefix
     */
    public function searchCertificatePrefix($certificatePrefixRequest)
    {
        $certificatePrefix=NULL;
        $sqlCond="";
        $sql = "SELECT cp.id, cp.prefixName,cp.prefix, cp.value, bct.type_name as typeName, cp.startYear, cp.endYear, cp.certificateType, cp.courseTypeId, cp.prefixYear, cp.campusTypeId, ct.name as campusTypeName, fromDate, toDate FROM certificatePrefixes cp left JOIN batch_course_type bct ON cp.courseTypeId=bct.id left join campus_type ct on ct.id = cp.campusTypeID WHERE cp.id >0 ";
        if($certificatePrefixRequest->courseTypeName)
        {
            $sqlCond .="AND bct.type_code='$certificatePrefixRequest->courseTypeName";
        }
        if($certificatePrefixRequest->startYear)
        {
            $sqlCond .="AND cp.startYear='$certificatePrefixRequest->startYear";
        }
        if($certificatePrefixRequest->endYear)
        {
            $sqlCond .="AND cp.endYear='$certificatePrefixRequest->endYear";
        }
        if($certificatePrefixRequest->campusTypeId)
        {
            $sqlCond .="AND cp.campusTypeId='$certificatePrefixRequest->campusTypeId";
        }
        if($certificatePrefixRequest->fromDate)
        {
            $sqlCond .="AND cp.fromDate='$certificatePrefixRequest->fromDate";
        }
        if($certificatePrefixRequest->toDate)
        {
            $sqlCond .="AND cp.toDate='$certificatePrefixRequest->toDate";
        }
        if($certificatePrefixRequest->certificateType)
        {
            $sqlCond .="AND cp.certificateType='$certificatePrefixRequest->certificateType";
        }
        $sql .=$sqlCond;
        try
        {
            $certificatePrefix = $this->executeQueryForList($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage()); 
        }
        return $certificatePrefix;
    }
    /**
     * get details of certificate prefix by year and coursetype name
     * @param CertificatePrefixesRequest $certificatePrefixRequest
     * @return $certificatePrefix
     */
    public function getCertificatePrefixByYear($startYear,$endYear,$courseTypeId, $certificateType)
    {
        $certificatePrefix=NULL;
        $sqlCond="";
        $sql = "SELECT cp.id, cp.prefixName,cp.prefix, cp.value, bct.type_name as typeName, cp.startYear, cp.endYear, cp.certificateType, cp.courseTypeId FROM certificatePrefixes cp INNER JOIN batch_course_type bct ON cp.courseTypeId=bct.id WHERE bct.id='$courseTypeId' AND cp.startYear='$startYear' AND cp.endYear='$endYear' AND cp.certificateType='$certificateType'";
        try
        {
            $certificatePrefix = $this->executeQueryForObject($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $certificatePrefix;
    }
    
    /**
     * get details of certificate prefix by year and coursetype name
     * @param CertificatePrefixesRequest $certificatePrefixRequest
     * @return $certificatePrefix
     */
    public function getCertificatePrefixByDate($date, $certificateType)
    {
        $certificatePrefix=NULL;
        $date = date('Y-m-d', strtotime($date));
        $sqlCond="";
        $sql = "SELECT cp.id, cp.prefixName,cp.prefix, cp.value, cp.startYear, cp.endYear, cp.certificateType, cp.courseTypeId FROM certificatePrefixes cp WHERE '$date' BETWEEN cp.fromDate AND cp.toDate AND cp.certificateType='$certificateType'";
        try
        {
            $certificatePrefix = $this->executeQueryForObject($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        
        return $certificatePrefix;
    }
    
    /**
     * check coexistance of date in certificate prefix
     * @return $certificatePrefix
     */
    public function checkCertificatePrefixByDate($startDate, $endDate, $certificateType, $excludeId=null)
    {
        $certificatePrefix=NULL;
        $startDate = date('Y-m-d', strtotime($startDate));
        $endDate = date('Y-m-d', strtotime($endDate));
        $sqlCond="";
        $sql = "SELECT cp.id, cp.prefixName,cp.prefix, cp.value, cp.startYear, cp.endYear, cp.certificateType, cp.courseTypeId FROM certificatePrefixes cp WHERE (cp.fromDate BETWEEN '$startDate' AND '$endDate'  OR cp.toDate BETWEEN '$startDate' AND '$endDate') AND cp.certificateType='$certificateType".($excludeId?"AND cp.id !='$excludeId'":"");
        try
        {
            $certificatePrefix = $this->executeQueryForList($sql);
            if(!empty($certificatePrefix))
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        
        return $certificatePrefix;
    }
    /**
     * get details of certificate prefix by id
     * @param int $id
     * @return $certificatePrefix
     */
    public function getCertificatePrefixById($id)
    {
        $certificatePrefix=NULL;
        $sql = "SELECT cp.id, cp.prefixName,cp.prefix, cp.value, bct.type_name as typeName, cp.startYear, cp.endYear, cp.certificateType, cp.courseTypeId, cp.prefixYear, cp.campusTypeId, ct.name as campusTypeName, fromDate, toDate, yearWise FROM certificatePrefixes cp left JOIN batch_course_type bct ON cp.courseTypeId=bct.id left join campus_type ct on ct.id = cp.campusTypeID WHERE cp.id=$id";
        try
        {
            $certificatePrefix = $this->executeQueryForObject($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $certificatePrefix;
    }
    /**
     * delete prefix
     * @param array $prefixIds
     * @throws ProfessionalException
     * @return \com\linways\base\dto\MySqlResult
     */
    public function deleteCertificatePrefix($prefixIds)
    {
        $sql = "DELETE FROM certificatePrefixes WHERE id IN(".implode(',', $prefixIds).")";
        try
        {
            return $this->executeQuery($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * create student transfer certificate
     * @param StudentTransferCertificate $studentTransferCertificate
     * @throws ProfessionalException
     * @return \com\linways\base\dto\MySqlResult
     */
    public function createStudentTransferCertificate($studentTransferCertificate)
    {
        $studentTransferCertificate = $this->realEscapeObject($studentTransferCertificate);
        $id=NULL;
        if($studentTransferCertificate->manualTcNo){
            $sqlTc = "select id, tcNo from studentTransferCertificate where tcPrefixId = $studentTransferCertificate->tcPrefixId and is_deleted = 1 and tcNo = '".$studentTransferCertificate->manualTcNo."'";
        }
        else{
            $sqlTc = "select id, min(tcNo) as tcNo from studentTransferCertificate where tcPrefixId = $studentTransferCertificate->tcPrefixId and is_deleted = 1";
        }
        try {
            $tcDetails = $this->executeQueryForObject($sqlTc);
            if(!empty($tcDetails->id))
            {
                $studentTransferCertificate->id = $tcDetails->id;
                $id = $this->updateStudentTransferCertificate($studentTransferCertificate);
            }
            else
            {
                if($studentTransferCertificate->manualTcNo){
                    $tcNo = $studentTransferCertificate->manualTcNo;
                }
                else{
                    $sqlNewTc = "SELECT MAX(cast(tcNo as unsigned))+1 AS tcNo FROM studentTransferCertificate WHERE tcPrefixId = $studentTransferCertificate->tcPrefixId";
                    $newTCNo = $this->executeQueryForObject($sqlNewTc);
                    $tcNo = empty((int)$newTCNo->tcNo) ? $studentTransferCertificate->value : $newTCNo->tcNo;
                }
                $studentTransferCertificate->tcNo = $tcNo;
                $sql= "INSERT INTO studentTransferCertificate 
                        (studentId, admitedSemId, lastSemId, applicationDate, issueDate, reasonForLeave, lastExamName, feesPaid,studentCharacter,tcNo, createdBy,createdDate, updatedBy,updatedDate,mediumOfInstruction,isqualifiedForPromotion,totalHours,attendedHours,examStatus,isScholarShipGranted,leavingMonth,leavingYear,leavingDate, monthOfExamination, yearOfExamination, isFeeConcessionReceived, tcPrefixId, admisson_courseID, admission_deptID,leaving_courseID, leaving_deptID,  studied_patterndeptID, studied_subsID, lst_exm_courseID, lst_exm_deptID, lst_exm_semID, has_appeared, remarks, is_deleted, is_alumini, studentPassedStatus, lst_exm_status,optional_subjects,conduct_of_student, classOfAdmission, classOfLeaving, subjectStudied, studentName, admissionNo, regNo, secondLangauge, studentJoindate, dateOfbirth, tcPrefix,tcBatchName,tcBatchAcademicYear,tcLastClassAttendedDate, studentCategory,tc_print_date,rollNo,bookNo,
                        isAppearedForExam,
                        passedParts,
                        isRaggingIncident,
                        programAndPeriod,
                        admissionProgramId,
                        leavingProgramId,
                        bookReturned,
                        failedParts)
                        VALUES
                        (".($studentTransferCertificate->studentId?"'$studentTransferCertificate->studentId'":'null').", ".($studentTransferCertificate->admitedSemId?"'$studentTransferCertificate->admitedSemId'":'null').", ".($studentTransferCertificate->lastSemId?"'$studentTransferCertificate->lastSemId'":'null').",'".(empty($studentTransferCertificate->applicationDate)?NULL:date('Y-m-d',strtotime($studentTransferCertificate->applicationDate)))."', '".(empty($studentTransferCertificate->issueDate)?NULL:date('Y-m-d',strtotime($studentTransferCertificate->issueDate)))."','$studentTransferCertificate->reasonForLeave', '$studentTransferCertificate->lastExamName', '$studentTransferCertificate->feesPaid','$studentTransferCertificate->studentCharacter', '$studentTransferCertificate->tcNo', $studentTransferCertificate->createdBy,  utc_timestamp(),$studentTransferCertificate->updatedBy,utc_timestamp(),'$studentTransferCertificate->mediumOfInstruction', '$studentTransferCertificate->isQualifiedForNextSem', '$studentTransferCertificate->totalHours','$studentTransferCertificate->attendedHours','$studentTransferCertificate->passedStatus','$studentTransferCertificate->studentScholarshipStatus','$studentTransferCertificate->leavingMonth','$studentTransferCertificate->leavingYear', '$studentTransferCertificate->leavingDate', '$studentTransferCertificate->monthOfExamination', '$studentTransferCertificate->yearOfExamination', '$studentTransferCertificate->isFeeConcessionReceived', '$studentTransferCertificate->tcPrefixId', '$studentTransferCertificate->admissonCourseId', '$studentTransferCertificate->admissionDeptId', '$studentTransferCertificate->leavingCourseId', '$studentTransferCertificate->leavingDeptId', '$studentTransferCertificate->studied_patterndeptId', '$studentTransferCertificate->studiedSubsId', '$studentTransferCertificate->lstExmCourseId', '$studentTransferCertificate->lstExmDeptId', '$studentTransferCertificate->lstExmSemId', '$studentTransferCertificate->hasAppeared', '$studentTransferCertificate->remarks', '$studentTransferCertificate->isDeleted', '$studentTransferCertificate->isAlumini', '$studentTransferCertificate->studentPassedStatus', '$studentTransferCertificate->lastExamStatus','".$studentTransferCertificate->optionalSubjects."','$studentTransferCertificate->conductOfStudent', '$studentTransferCertificate->classOfAdmission','$studentTransferCertificate->classOfLeaving','$studentTransferCertificate->subjectStudied', '$studentTransferCertificate->studentName', '$studentTransferCertificate->admissionNo', '$studentTransferCertificate->studentRegNo', '$studentTransferCertificate->secondLangauge', '$studentTransferCertificate->studentJoindate', '$studentTransferCertificate->dateOfbirth', '$studentTransferCertificate->tcPrefix','$studentTransferCertificate->tcBatchOptionName','$studentTransferCertificate->tcBatchAcademicYear','$studentTransferCertificate->tcLastClassAttendedDate',
                        '$studentTransferCertificate->studentCategory',
                        '$studentTransferCertificate->tcPrintDate','$studentTransferCertificate->rollNo','$studentTransferCertificate->bookNo',
                        '$studentTransferCertificate->isAppearedForExam',
                        '$studentTransferCertificate->passedParts',
                        '$studentTransferCertificate->isRaggingIncident',
                        '$studentTransferCertificate->programAndPeriod',
                        '$studentTransferCertificate->admissionProgramId',
                        '$studentTransferCertificate->leavingProgramId',
                        '$studentTransferCertificate->bookReturned',
                        '$studentTransferCertificate->failedParts')";
                $id = $this->executeQuery($sql,TRUE);
                if($studentTransferCertificate->studentId)
                {
                    $updateFields = [];
                    $updateFields[] = "tcIssued = 1";
                    
                    if (!empty($studentTransferCertificate->dateOfbirth)) {
                        $updateFields[] = "studentBirthday = '" . date('Y-m-d', strtotime($studentTransferCertificate->dateOfbirth)) . "'";
                    }
                    
                    if (!empty($studentTransferCertificate->nationalities)) {
                        $updateFields[] = "nationality_id = '" . $studentTransferCertificate->nationalities . "'";
                    }
                    
                    if (!empty($studentTransferCertificate->states)) {
                        $updateFields[] = "state_id = '" . $studentTransferCertificate->states . "'";
                    }
                    
                    if (!empty($studentTransferCertificate->religions)) {
                        $updateFields[] = "religionID = '" . $studentTransferCertificate->religions . "'";
                    }
                    
                    if (!empty($studentTransferCertificate->castes)) {
                        $updateFields[] = "casteID = '" . $studentTransferCertificate->castes . "'";
                    }
                    
                    $sqlUpdate = "UPDATE studentaccount SET " . implode(", ", $updateFields) . " WHERE studentID = $studentTransferCertificate->studentId";
                    
                        $this->executeQuery($sqlUpdate);
                }
                $this->generateTcNo($studentTransferCertificate->tcPrefixId);
            }
            if(CommonService::getInstance()->getSettings(SettingsConstents::CERTIFICATE, SettingsConstents::MOVE_STUDENTS_ISSUING_TC_BEFORE_BATCH_TC_ISSUED_DATE_TO_FAILED_LIST) && $studentTransferCertificate->batchId)
            {
                $batchDetials = BatchService::getInstance()->getBatchById($studentTransferCertificate->batchId);
                if((strtotime($batchDetials->tcIssueDate) > strtotime($studentTransferCertificate->issueDate)) && !empty($studentTransferCertificate->issueDate))
                {
                    // StudentService::getInstance()->moveStudentToFailedList($studentTransferCertificate->studentId,null,FailedReason::CERTIFICATE_GENERATED);
                    
                    // TAKEN V4 UPDATES
                    $failedStudentRequest = new FailedStudentRequest;
                    $failedStudentRequest->studentId = $studentTransferCertificate->studentId;
                    $failedStudentRequest->batchId = "";
                    $failedStudentRequest->reason = FailedReason::CERTIFICATE_GENERATED;
                    $failedStudentRequest->remarks = "";
                    $failedStudentRequest->academicSatus = StatusConstants::ACTIVE;
                    StudentService::getInstance()->createV4MoveStudentFailedRequest($failedStudentRequest);
                }
            }
        } catch (\Exception $e) {
            if($e->getCode() == "STUDENT_ALREADY_IN_FAILED_LIST")
            {
                return ;
            }
            else
            {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        }
        return $id;
    }
    /**
     * update strudent transfer certificate
     * @param StudentTransferCertificate $studentTransferCertificate
     * @throws ProfessionalException
     * @return \com\linways\base\dto\MySqlResult
     */
    public function updateStudentTransferCertificate($studentTransferCertificate,$isTcBatchwise = false)
    {
        $tcNoUpdate = $studentTransferCertificate->manualTcNo?",tcNo = '".$studentTransferCertificate->manualTcNo."' ":"";
        $sql = "UPDATE studentTransferCertificate SET
        studentId = ".($studentTransferCertificate->studentId?"'$studentTransferCertificate->studentId'":'null').",
        admitedSemId=".($studentTransferCertificate->admitedSemId?"'$studentTransferCertificate->admitedSemId'":'null').",
        lastSemId=".($studentTransferCertificate->lastSemId?"'$studentTransferCertificate->lastSemId'":'null').",
        applicationDate='".(empty($studentTransferCertificate->applicationDate)?NULL:date('Y-m-d',strtotime($studentTransferCertificate->applicationDate)))."',
                    issueDate='".(empty($studentTransferCertificate->issueDate)?NULL:date('Y-m-d',strtotime($studentTransferCertificate->issueDate)))."',
                    reasonForLeave='$studentTransferCertificate->reasonForLeave',
                    lastExamName='$studentTransferCertificate->lastExamName',
                    feesPaid='$studentTransferCertificate->feesPaid',
                    studentCharacter='$studentTransferCertificate->studentCharacter',
                    updatedBy=$studentTransferCertificate->updatedBy,
                    mediumOfInstruction='$studentTransferCertificate->mediumOfInstruction',
                    isqualifiedForPromotion='$studentTransferCertificate->isQualifiedForNextSem',
                    totalHours='$studentTransferCertificate->totalHours',
                    attendedHours='$studentTransferCertificate->attendedHours',
                    examStatus='$studentTransferCertificate->passedStatus',
                    isScholarShipGranted='$studentTransferCertificate->studentScholarshipStatus',
                    leavingMonth='$studentTransferCertificate->leavingMonth',
                    leavingYear='$studentTransferCertificate->leavingYear',
                    leavingDate='$studentTransferCertificate->leavingDate',
                    monthOfExamination='$studentTransferCertificate->monthOfExamination',
                    yearOfExamination='$studentTransferCertificate->yearOfExamination',
                    isFeeConcessionReceived='$studentTransferCertificate->isFeeConcessionReceived', admisson_courseID = '$studentTransferCertificate->admissonCourseId', admission_deptID = '$studentTransferCertificate->admissionDeptId',leaving_courseID = '$studentTransferCertificate->leavingCourseId', leaving_deptID = '$studentTransferCertificate->leavingDeptId',  studied_patterndeptID = '$studentTransferCertificate->studied_patterndeptId ', studied_subsID = '$studentTransferCertificate->studiedSubsId', lst_exm_courseID = '$studentTransferCertificate->lstExmCourseId', lst_exm_deptID = '$studentTransferCertificate->lstExmDeptId', lst_exm_semID = '$studentTransferCertificate->lstExmSemId', has_appeared = '$studentTransferCertificate->hasAppeared', remarks = '$studentTransferCertificate->remarks', is_deleted = '$studentTransferCertificate->isDeleted', is_alumini = '$studentTransferCertificate->isAlumini', studentPassedStatus = '$studentTransferCertificate->studentPassedStatus', lst_exm_status = '$studentTransferCertificate->lastExamStatus', isPrinted = 1, optional_subjects = '".$studentTransferCertificate->optionalSubjects."',conduct_of_student = '$studentTransferCertificate->conductOfStudent', classOfAdmission='$studentTransferCertificate->classOfAdmission', classOfLeaving='$studentTransferCertificate->classOfLeaving', subjectStudied='$studentTransferCertificate->subjectStudied', studentName='$studentTransferCertificate->studentName', admissionNo='$studentTransferCertificate->admissionNo', regNo='$studentTransferCertificate->regNo', secondLangauge='$studentTransferCertificate->secondLangauge', studentJoindate='$studentTransferCertificate->studentJoindate', dateOfbirth='$studentTransferCertificate->dateOfbirth',
                    tcBatchName='$studentTransferCertificate->tcBatchOptionName',
                    tcBatchAcademicYear='$studentTransferCertificate->tcBatchAcademicYear',
                    tcLastClassAttendedDate='$studentTransferCertificate->tcLastClassAttendedDate',
                    studentCategory = '$studentTransferCertificate->studentCategory',
                    tc_print_date = '$studentTransferCertificate->tcPrintDate',
                    bookNo='$studentTransferCertificate->bookNo',  
                    rollNo='$studentTransferCertificate->rollNo'".$tcNoUpdate.",
                    isAppearedForExam='$studentTransferCertificate->isAppearedForExam',
                    passedParts='$studentTransferCertificate->passedParts',
                    isRaggingIncident='$studentTransferCertificate->isRaggingIncident',
                    programAndPeriod='$studentTransferCertificate->programAndPeriod',
                    admissionProgramId='$studentTransferCertificate->admissionProgramId',
                    leavingProgramId='$studentTransferCertificate->leavingProgramId',
                    bookReturned='$studentTransferCertificate->bookReturned',
                    needDuplicate='$studentTransferCertificate->needDuplicate',
                    failedParts='$studentTransferCertificate->failedParts',
                    regNo='$studentTransferCertificate->studentRegNo'
                    WHERE id=$studentTransferCertificate->id";
        try
        {
            $id = $this->executeQuery($sql);
            if($studentTransferCertificate->studentId)
            {
                $updateFields = [];
                $updateFields[] = "tcIssued = 1";
                if (!empty($studentTransferCertificate->nationalities)) {
                    $updateFields[] = "nationality_id = '" . $studentTransferCertificate->nationalities . "'";
                }
                if (!empty($studentTransferCertificate->states)) {
                    $updateFields[] = "state_id = '" . $studentTransferCertificate->states . "'";
                }
                if (!empty($studentTransferCertificate->religions)) {
                    $updateFields[] = "religion = '" . $studentTransferCertificate->religions . "'";
                }
                if (!empty($studentTransferCertificate->castes)) {
                    $updateFields[] = "casteID = '" . $studentTransferCertificate->castes . "'";
                }
                if (!empty($studentTransferCertificate->dateOfbirth)) {
                    $studentBirthday = date('Y-m-d', strtotime($studentTransferCertificate->dateOfbirth));
                    $updateFields[] = "studentBirthday = '$studentBirthday'";
                }
                // Finally build the SQL
                $sqlUpdate = "UPDATE studentaccount SET " . implode(", ", $updateFields) . " WHERE studentID = $studentTransferCertificate->studentId";
                $this->executeQuery($sqlUpdate);
            }
            if(CommonService::getInstance()->getSettings(SettingsConstents::CERTIFICATE, SettingsConstents::MOVE_STUDENTS_ISSUING_TC_BEFORE_BATCH_TC_ISSUED_DATE_TO_FAILED_LIST) && $studentTransferCertificate->studentId && !$isTcBatchwise)
            {
                $isFailed = StudentService::getInstance()->isFailed($studentTransferCertificate->studentId);
                if(!$isFailed)
                {
                    $batchDetials = BatchService::getInstance()->getBatchById($studentTransferCertificate->batchId);
                    if((strtotime($batchDetials->tcIssueDate) > strtotime($studentTransferCertificate->issueDate)) && !empty($studentTransferCertificate->issueDate))
                    {
                        // StudentService::getInstance()->moveStudentToFailedList($studentTransferCertificate->studentId,null,FailedReason::CERTIFICATE_GENERATED);
                        
                        // TAKEN V4 UPDATES
                        $failedStudentRequest = new FailedStudentRequest;
                        $failedStudentRequest->studentId = $studentTransferCertificate->studentId;
                        $failedStudentRequest->batchId = "";
                        $failedStudentRequest->reason = FailedReason::CERTIFICATE_GENERATED;
                        $failedStudentRequest->remarks = "";
                        $failedStudentRequest->academicSatus = StatusConstants::ACTIVE;
                        StudentService::getInstance()->createV4MoveStudentFailedRequest($failedStudentRequest);
                    }
                }
            }
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $id;
    }
    /**
     * get details of a transfer certificate by id
     * @param int $id
     * @throws ProfessionalException
     * @return object|NULL|\com\linways\base\util\$objectList[]
     */
    public function getFailedStudentTransferCertificateByStudentId($id)
    {
        $studentTc=NULL;
        $sql ="SELECT stc.*,sa.studentName as name, sa.studentFather, sa.studentBirthday, r.religionName as religion, sc.casteName as community, sa.studentJoindate, sa.studentAccount, dept.departmentDesc, bct.type_name as typeName,bct.type_code as typeCode, sa.regNo, sa.rollNo, sa.admissionNo, sa.studentGender,uv.name as university,sa.category,sem.semName,CONCAT(batchStartYear,'-',batchEndYear) as periodOfStudy,bth.batchID,bth.semID, sl.secondLangaugeName, stc.optional_subjects,sa.exitType, sa.joiningSemId,stc.studentJoindate as certificateStudentJoindate,sa.previousSchool,sa.studentMother,stc.regNo as certificateRegNo,ssc.subcaste_name as subCasteName,sa.nationality_id,sa.state_id,sa.casteID,sa.religion as religionID FROM studentTransferCertificate stc INNER JOIN studentaccount sa ON sa.studentID=stc.studentID INNER JOIN failed_students fs ON fs.studentID=sa.studentID INNER JOIN batches bth ON bth.batchID=fs.previousBatch INNER JOIN semesters sem ON sem.semID = bth.semID LEFT JOIN batch_course_type bct ON bct.id=bth.patternID INNER JOIN department dept ON dept.deptID= sa.deptID LEFT JOIN university uv ON bth.universityId = uv.id LEFT JOIN religion r ON r.religionID=sa.religion LEFT JOIN student_caste sc ON sc.casteID=sa.casteID AND sc.religionID=sa.religion LEFT JOIN secondLangauge sl ON sa.secondlangaugeID = sl.secondlangaugeID LEFT JOIN student_subcaste ssc on sa.student_subcaste_id=ssc.id WHERE stc.studentId=$id and stc.is_deleted = 0";
        try
        {
            $studentTc=  $this->executeQueryForObject($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentTc;
    }
    /**
     * get details of a transfer certificate by id
     * @param int $id
     * @throws ProfessionalException
     * @return object|NULL|\com\linways\base\util\$objectList[]
     */
    
    public function getStudentTransferCertificateByStudentId($id)
    {
        $studentTc=NULL;
        $sql ="SELECT stc.*,
                        sa.studentName as name,
                         sa.studentFather,
                          sa.studentBirthday,
                           r.religionName as religion,
                           sa.religion as religionID,
                            sc.casteName as community,
                             sa.studentJoindate,
                              sa.studentAccount,
                               dept.departmentDesc,
                                bct.type_name as typeName,
                                bct.type_code as typeCode,
                                 sa.regNo,
                                  sa.rollNo,
                                   sa.admissionNo,
                                    sa.studentGender,
                                    uv.name as university,
                                    sa.category,
                                    sem.semName,
                                    CONCAT(batchStartYear,'-',batchEndYear) as periodOfStudy,
                                    bth.batchID,
                                    bth.semID,
                                     sl.secondLangaugeName,
                                      stc.optional_subjects,
                                      sa.exitType,
                                       sa.joiningSemId,
                                       stc.studentJoindate as certificateStudentJoindate,
                                       sa.previousSchool,
                                       sa.studentMother,
                                       stc.regNo as certificateRegNo,
                                       ssc.subcaste_name as subCasteName  
                                FROM studentTransferCertificate stc 
                                    INNER JOIN studentaccount sa 
                                        ON sa.studentID=stc.studentID 
                                    INNER JOIN batches bth 
                                        ON bth.batchID=sa.batchID 
                                    LEFT JOIN batch_course_type bct
                                         ON bct.id=bth.patternID 
                                    INNER JOIN semesters sem 
                                        ON sem.semID = bth.semID 
                                    INNER JOIN department dept 
                                        ON dept.deptID= sa.deptID 
                                    LEFT JOIN university uv 
                                        ON bth.universityId = uv.id 
                                    LEFT JOIN religion r 
                                        ON r.religionID=sa.religion 
                                    LEFT JOIN student_caste sc 
                                        ON sc.casteID=sa.casteID AND sc.religionID=sa.religion 
                                    LEFT JOIN secondLangauge sl 
                                        ON sa.secondlangaugeID = sl.secondlangaugeID 
                                    LEFT JOIN student_subcaste ssc 
                                        on sa.student_subcaste_id=ssc.id 
                                    WHERE stc.studentId=$id and stc.is_deleted = 0";
        try
        {
            $studentTc=  $this->executeQueryForObject($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $studentTc;
    }
    /**
     * check transfer certificate generated or not
     * @param int $id
     * @throws ProfessionalException
     * @return object|NULL|\com\linways\base\util\$objectList[]
     */
    public function checkFailedStudentTransferCertificateByStudentId($id)
    {
        $checkTc=0;
        $sql ="SELECT count(stc.studentId) as flag 
                    FROM studentTransferCertificate stc 
                    INNER JOIN studentaccount sa ON sa.studentID=stc.studentID 
                    INNER JOIN failed_students fs ON fs.studentID=sa.studentID 
                    INNER JOIN batches bth ON bth.batchID=fs.previousBatch 
                    LEFT JOIN batch_course_type bct ON bct.id=bth.patternID 
                    INNER JOIN department dept ON dept.deptID= sa.deptID 
                    WHERE stc.studentId=$id and is_deleted = 0";
        try
        {
            $checkTc=  $this->executeQueryForObject($sql)->flag;
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $checkTc;
    }
    /**
     * check transfer certificate generated or not
     * @param int $id
     * @throws ProfessionalException
     * @return object|NULL|\com\linways\base\util\$objectList[]
     */
    public function checkStudentTransferCertificateByStudentId($id)
    {
        $checkTc=0;
        $sql ="SELECT count(stc.studentId) as flag FROM studentTransferCertificate stc INNER JOIN studentaccount sa ON sa.studentID=stc.studentID WHERE stc.studentId=$id and is_deleted = 0";
        try
        {
            $checkTc=  $this->executeQueryForObject($sql)->flag;
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $checkTc;
    }
    /**
     * for generating tc Number
     * @param int $prefixId
     * @throws ProfessionalException
     * @return string
     */
    public function generateTcNo($prefixId)
    {
        $tcNo="";
        $sql="select cp.id, cp.prefix, cp.value from certificatePrefixes cp INNER JOIN batch_course_type bct ON bct.id=cp.courseTypeId WHERE cp.id=$prefixId";
        try
        {
            $tcPrefix =  $this->executeQueryForObject($sql);
            $value = $tcPrefix->value;
            $value++;
            $tcNo .=$tcPrefix->prefix.$tcPrefix->value;
            $sqlUpdate="UPDATE certificatePrefixes SET value=$value WHERE id=$prefixId";
            $this->executeQuery($sqlUpdate);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $tcNo;
    }
    /**
     * generate code for conduct and course certificate
     * @param int $prefixId
     * @param int $studentId
     * @throws ProfessionalException
     * @return string $slNo
     */
    public function generateConductNo($prefixId, $studentId, $certificateType , $adminID)
    {
        $slNo="";
        $sql="select cp.id, cp.prefix, cp.value, cp.prefixYear from certificatePrefixes cp WHERE cp.id=$prefixId";
        try
        {
            $prefix =  $this->executeQueryForObject($sql);
            $value = $prefix->value;
            $value++;
            $prefixYear = $prefix->prefixYear ? "/".$prefix->prefixYear : "" ;
            $slNo .=$prefix->prefix.$prefix->value.$prefixYear;
            $sqlCreate="INSERT INTO studentCourseConductCertificate(studentId, ccNo, prefixId, certificateType, createdBy, createdDate, updatedBy, updatedDate) VALUES($studentId,'$prefix->value', $prefixId, '$certificateType', $adminID, utc_timestamp(), $adminID, utc_timestamp());";
            $this->executeQuery($sqlCreate);
            $sqlUpdate="UPDATE certificatePrefixes SET value=$value WHERE id=$prefixId";
            $this->executeQuery($sqlUpdate);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $slNo;
    }
   
    /**
     * get generated prefix using studentId
     * @param int $studentId
     * @throws ProfessionalException
     * @return string $slNo
     */
    public function getConductSlNo($studentId, $certificateType)
    {
        $slNo=NULL;
        $sql ="SELECT ccNo FROM studentCourseConductCertificate WHERE studentId=$studentId and certificateType = '$certificateType'";
        try
        {
            $slNo =  $this->executeQueryForObject($sql)->ccNo;
            
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $slNo;
    }
    /**
     * get admission certificates
     * @throws ProfessionalException
     * @return object|array|\com\linways\base\util\$objectList[]
     */
    public function getAdmissionCertificate()
    {
        $sql ="SELECT * FROM admission_student_certificates";
        try
        {
            return $this->executeQueryForList($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * add application form type certificates
     * @param ApplicationFormTypeCertificate $applicationFormTypeCertificate
     * @throws ProfessionalException
     * @return object|NULL|\com\linways\base\util\$objectList[]
     */
    public function addApplicationFormTypeCertificate($applicationFormTypeCertificate)
    {
        $applicationFormTypeCertificate = $this->realEscapeObject($applicationFormTypeCertificate);
        $sql ="INSERT INTO applicationFormTypeCertificate (certificateTypeId, applicationFormTypeId, isRequired, createdBy, createdDate, updatedBy, updatedDate) VALUES ($applicationFormTypeCertificate->certificateTypeId$applicationFormTypeCertificate->applicationFormTypeId$applicationFormTypeCertificate->isRequired$applicationFormTypeCertificate->createdBy, utc_timestamp(), $applicationFormTypeCertificate->updatedBy, utc_timestamp())";
        try
        {
            return $this->executeQueryForObject($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * delete application form type certicates by form type id
     * @param int $formTypeId
     * @throws ProfessionalException
     * @return object|NULL|\com\linways\base\util\$objectList[]
     */
    public function deleteApplicationFormTypeCertificateByFormTypeId($formTypeId, $certificateId)
    {
        $formTypeId = $this->realEscapeString($formTypeId);
        $certificateId = $this->realEscapeString($certificateId);
        $sql ="DELETE FROM applicationFormTypeCertificate WHERE applicationFormTypeId=$formTypeId AND certificateTypeId=$certificateId";
        try
        {
            return $this->executeQueryForObject($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * get application form type certificate by formTypeId
     * @param int $formTypeId
     * @throws ProfessionalException
     * @return object|array|\com\linways\base\util\$objectList[]
     */
    public function getApplicationFormTypeCertificateByFormTypeId($formTypeId)
    {
        $formTypeId = $this->realEscapeString($formTypeId);
        $sql = "select adc.certificateID, adc.certificateName, afc.isRequired, afc.applicationFormTypeId from admission_student_certificates adc left join applicationFormTypeCertificate afc ON afc.certificateTypeId=adc.certificateID AND afc.applicationFormTypeId=$formTypeId";
        try
        {
            return $this->executeQueryForList($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @author Sanoop
     * get application form type certificate by formTypeId
     * @param int $formTypeId
     * @param int $courseTypeId
     * @param int $studentId
     * @throws ProfessionalException
     * @return object|array|\com\linways\base\util\$objectList[]
     */
    public function getStudentApplicationCertificateForAdmissionByFormTypeId($formTypeId, $courseTypeId, $studentId)
    {
        $formTypeId = $this->realEscapeString($formTypeId);
        $courseTypeId = $this->realEscapeString($courseTypeId);
        $studentId = $this->realEscapeString($studentId);
        $sql = "select adc.certificateID, adc.certificateName, afc.isRequired, afc.applicationFormTypeId, sac.path, sac.fileName from admission_student_certificates adc inner join applicationFormTypeCertificate afc ON afc.certificateTypeId=adc.certificateID left join studentApplicationCertificate sac ON sac.certificateTypeId=certificateID AND sac.courseTypeId=$courseTypeId AND sac.studentId=$studentId WHERE afc.applicationFormTypeId=$formTypeId";
        try
        {
            return $this->executeQueryForList($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * add student application certificate
     * @param StudentApplicationCertificate $studentApplicationCertificate
     * @throws ProfessionalException
     * @return object|NULL|\com\linways\base\util\$objectList[]
     */
    public function addStudentApplicationCertificate($studentApplicationCertificate)
    {
        $studentApplicationCertificate = $this->realEscapeObject($studentApplicationCertificate);
        $sql ="INSERT INTO studentApplicationCertificate (studentId, courseTypeId, certificateTypeId, fileName, path, createdBy, createdDate, updatedBy, updatedDate) VALUES ($studentApplicationCertificate->studentId$studentApplicationCertificate->courseTypeId$studentApplicationCertificate->certificateTypeId, '$studentApplicationCertificate->fileName', '$studentApplicationCertificate->path', $studentApplicationCertificate->createdBy, utc_timestamp(), $studentApplicationCertificate->updatedBy, utc_timestamp())";
        try
        {
            return $this->executeQueryForObject($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * delete student application certificate by student id
     * @param int $studentId
     * @param int $courseTypeId
     * @throws ProfessionalException
     * @return object|NULL|\com\linways\base\util\$objectList[]
     */
    public function deleteStudentApplicationCertificateByStudentId($studentId, $certificateId, $courseTypeId)
    {
        $studentId = $this->realEscapeString($studentId);
        $courseTypeId = $this->realEscapeString($courseTypeId);
        $sql ="DELETE FROM studentApplicationCertificate WHERE studentId=$studentId AND courseTypeId=$courseTypeId AND certificateTypeId=$certificateId";
        try
        {
            return $this->executeQueryForObject($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * delete student application certificate by student id
     * @param int $studentId
     * @param int $courseTypeId
     * @throws ProfessionalException
     * @return object|NULL|\com\linways\base\util\$objectList[]
     */
    public function getStudentApplicationCertificateByStudentId($studentId, $certificateId, $courseTypeId)
    {
        $studentId = $this->realEscapeString($studentId);
        $courseTypeId = $this->realEscapeString($courseTypeId);
        $sql ="select * from studentApplicationCertificate WHERE studentId=$studentId AND courseTypeId=$courseTypeId AND certificateTypeId=$certificateId";
        try
        {
            return $this->executeQueryForObject($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * @author Sanoop
     * get application form type certificate by formTypeId
     * @param int $formTypeId
     * @throws ProfessionalException
     * @return object|array|\com\linways\base\util\$objectList[]
     */
    public function getAdmissionCertificateByFormTypeId($formTypeId)
    {
        $formTypeId = $this->realEscapeString($formTypeId);
        $sql = "select adc.certificateID, adc.certificateName, afc.isRequired, afc.applicationFormTypeId from admission_student_certificates adc inner join applicationFormTypeCertificate afc ON afc.certificateTypeId=adc.certificateID WHERE afc.applicationFormTypeId=$formTypeId";
        try
        {
            return $this->executeQueryForList($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * add student application certificate by list
     * @param array $studentApplicationCertificate
     * @throws ProfessionalException
     * @return object|NULL|\com\linways\base\util\$objectList[]
     */
    public function addStudentApplicationCertificateByList($studentApplicationCertificateList)
    {
        $studentApplicationCertificateList = $this->realEscapeArray($studentApplicationCertificateList);
        $sql ="INSERT INTO studentApplicationCertificate (studentId, courseTypeId, certificateTypeId, fileName, path, createdBy, createdDate, updatedBy, updatedDate) VALUES ";
        if(!empty($studentApplicationCertificateList) && $studentApplicationCertificateList !=NULL)
        {
            foreach ($studentApplicationCertificateList as $studentApplicationCertificate)
            {
                $value[]= "($studentApplicationCertificate->studentId$studentApplicationCertificate->courseTypeId$studentApplicationCertificate->certificateTypeId, '$studentApplicationCertificate->fileName', '$studentApplicationCertificate->path', $studentApplicationCertificate->createdBy, utc_timestamp(), $studentApplicationCertificate->updatedBy, utc_timestamp())";
            }
        }
        try
        {
            $sql .= implode(', ', $value);
            return $this->executeQueryForObject($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /*
     * Get array of student characters for certicate
     */
    public function getStudentCharacters()
    {
        $characters = NULL;
        $arr = NULL;
        $arr = explode(';',CommonService::getInstance()->getSettings(SettingsConstents::CERTIFICATE, SettingsConstents::TC_STUDENT_CHARACTER));
        foreach ( $arr as $el )
        {
            $characters[$el] = $el;
        }
        return $characters;
    }
    /*
     * Get array of media of instruction
     */
    public function getMediumOfInstruction()
    {
        $media = NULL;
        $arr = NULL;
        $arr = explode(';',CommonService::getInstance()->getSettings(SettingsConstents::CERTIFICATE, SettingsConstents::TC_MEDIUM_OF_INSTRUCTION));
        foreach ( $arr as $el )
        {
            $media[$el] = $el;
        }
        return $media;
    }
    /**
     * Delete student tc details and update prefix value
     * @param int $studentId
     * @param int $prefixId
     * @throws ProfessionalException
     * @return boolean
     */
    public function deleteStudentTransferCertificate($studentId,$tcNo = NULL)
    {
        $studentId = $this->realEscapeString($studentId);
        $tcNo = $this->realEscapeString($tcNo);
        $tcCond = "";
        if(!empty($tcNo)){
            $tcCond .= " AND tcNo = $tcNo ";
        }
        $sql = "SELECT studentId,tcPrefix FROM studentTransferCertificate WHERE studentId = $studentId".$tcCond;
        $tcList = $this->executeQueryForList($sql);
        $tcCount = count($tcList);
        if($tcCount > 1){
            $tcCount--;
            $sql = "DELETE FROM studentTransferCertificate WHERE studentId = $studentId ".$tcCond."LIMIT $tcCount";
            $this->executeQuery($sql); 
        }
        $sql_updateTc = "UPDATE studentTransferCertificate SET is_deleted = 1 where studentId = $studentId".$tcCond;
        $sql_updateStudent = "UPDATE studentaccount SET tcissued = 0 where studentId = $studentId";
        try {
            $tcUpdated = $this->executeQuery($sql_updateTc);
            if($tcUpdated){
                $this->executeQuery($sql_updateStudent);
                return true;
            }
            else {
                return false;
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Get certificate prefix by campusTypeId
     * @param unknown $campusTypeId
     * @param unknown $date
     * @throws ProfessionalException
     * @return \com\linways\base\dto\MySqlResult
     */
    public function getCertificatePrefixByCampusTypeId($campusTypeId, $date, $certificateType)
    {
        $campusTypeId = $this->realEscapeString($campusTypeId);
        $date = $this->realEscapeString($date);
        if ($certificateType == "TC" || $certificateType == "MIGRATION" || $certificateType == "CANCELLATION")
        {
            $sql = "SELECT cp.id, cp.prefixName,cp.prefix, cp.value, bct.type_name as typeName, cp.startYear, cp.endYear, cp.certificateType, cp.courseTypeId, cp.prefixYear, cp.campusTypeId, ct.name as campusTypeName, fromDate, toDate FROM certificatePrefixes cp left JOIN batch_course_type bct ON cp.courseTypeId=bct.id left join campus_type ct on ct.id = cp.campusTypeID WHERE cp.campusTypeId = $campusTypeId and '$date' between fromDate and toDate and cp.certificateType = '$certificateType'";
        }
        else
        {
            $sql = "SELECT cp.id, cp.prefixName,cp.prefix, cp.value, bct.type_name as typeName, cp.startYear, cp.endYear, cp.certificateType, cp.courseTypeId, cp.prefixYear, cp.campusTypeId, ct.name as campusTypeName, fromDate, toDate FROM certificatePrefixes cp left JOIN batch_course_type bct ON cp.courseTypeId=bct.id left join campus_type ct on ct.id = cp.campusTypeID WHERE prefixYear = '".$date."' and cp.certificateType = '$certificateType'";
            if (!empty($campusTypeId)) {
                $sql .= " AND cp.campusTypeId = '$campusTypeId'";
            }
        }
        try {
            return $this->executeQueryForObject($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Get migration certificate No:
     * @param int $studentId
     * @throws ProfessionalException
     * @return unknown
     */
    public function getMigrationCertNo ($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        $sql = "select migrationCertificateNo from studentMigrationCertificate where studentId = $studentId and isDeleted= 0;";
        try {
            return $this->executeQueryForObject($sql)->migrationCertificateNo;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Generate migration certificate no
     * @param StudentMigrationCertificate $studentMigrationCertificate
     * @throws ProfessionalException
     * @return unknown
     */
    public function generateMigrationCertNo($prefixId,$studentId)
    {
        $prefixId = $this->realEscapeString($prefixId);
        $sql = "select id, min(migrationCertificateNo) as migrationCertificateNo from studentMigrationCertificate where isDeleted = 1 and prefixId = $prefixId and studentId = $studentId";
        try {
            $mcDetails =  $this->executeQueryForObject($sql);
            if(!empty($mcDetails->id))
            {
                $mcNo = $mcDetails->migrationCertificateNo;
                //$sqlUpdate = "UPDATE studentMigrationCertificate SET studentId = $studentMigrationCertificate->studentId, isDeleted = 0,  updatedBy = $studentMigrationCertificate->updatedBy , updatedDate =  UTC_TIMESTAMP() WHERE id = $mcDetails->id";
                //$this->executeQuery($sqlUpdate);
            }
            else
            {
                $sql = "select max(migrationCertificateNo) + 1 as migrationCertificateNo from studentMigrationCertificate where isDeleted = 0 and prefixId = $prefixId";
                $mcNo = $this->executeQueryForObject($sql)->migrationCertificateNo;
                if(empty((int)$mcNo))
                {
                    $mcNo = $this->getCertificatePrefixById($prefixId)->value;
                }
                
                
                $sqlAvoidDuplicate = "SELECT studentId from studentMigrationCertificate WHERE studentId = $studentId";
                $duplicateResult = $this->executeQueryForObject($sqlAvoidDuplicate);
                
                
                if(!$duplicateResult)
                {
                    if($studentId)
                    {
                        $createdBy = $updatedBy = $_SESSION['adminID'];
                        $sqlInsert = "INSERT INTO studentMigrationCertificate (studentId, migrationCertificateNo, prefixId, isDeleted, createdBy, createdDate, updatedBy, updatedDate) VALUES ($studentId$mcNo$prefixId, 0, $createdBy,  UTC_TIMESTAMP(), $updatedBy, UTC_TIMESTAMP())";
                        $id =  $this->executeQueryForObject($sqlInsert, true);
                    }
                }
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $mcNo;
    }
    /**
     * Get cancellation certificate No:
     * @param int $studentId
     * @throws ProfessionalException
     * @return unknown
     */
    public function getCancelCertNo ($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        $sql = "select cancellationCertificateNo from studentCancellationCertificate where studentId = $studentId and isDeleted= 0;";
        try {
            return $this->executeQueryForObject($sql)->cancellationCertificateNo;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /**
     * Generate cancel certificate no
     * @param StudentCancellationCertificate $studentCancelCertificate
     * @throws ProfessionalException
     * @return unknown
     */
    public function generateCancelCertNo($cancelPrefixId)
    {
        $cancelPrefixId = $this->realEscapeString($cancelPrefixId);
        $sql = "select id, min(cancellationCertificateNo) as cancellationCertificateNo from studentCancellationCertificate where isDeleted = 1 and prefixId = $cancelPrefixId";
        try {
            $ccDetails =  $this->executeQueryForObject($sql);
            if(!empty($ccDetails->id))
            {
                $ccNo = $ccDetails->cancellationCertificateNo;
                //$sqlUpdate = "UPDATE studentCancellationCertificate SET studentId = $studentCancelCertificate->studentId, isDeleted = 0,  updatedBy = $studentCancelCertificate->updatedBy , updatedDate =  UTC_TIMESTAMP() WHERE id = $ccDetails->id";
                //$this->executeQuery($sqlUpdate);
            }
            else
            {
                $sql = "select max(cancellationCertificateNo) + 1 as cancellationCertificateNo from studentCancellationCertificate where isDeleted = 0 and prefixId = $cancelPrefixId";
                $ccNo = $this->executeQueryForObject($sql)->cancellationCertificateNo;
                if(empty($ccNo))
                {
                    $ccNo = 1;
                }
                //$sqlInsert = "INSERT INTO studentCancellationCertificate (studentId, cancellationCertificateNo, prefixId, isDeleted, createdBy, createdDate, updatedBy, updatedDate) VALUES ($studentCancelCertificate->studentId, $ccNo, $studentCancelCertificate->prefixId, 0, $studentCancelCertificate->createdBy,  UTC_TIMESTAMP(), $studentCancelCertificate->updatedBy, UTC_TIMESTAMP())";
                //$id =  $this->executeQueryForObject($sqlInsert, true);
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $ccNo;
    }
    /**
     * Get certificate content
     * @param int $certificateType
     * @param int $courseTypeId
     * @throws ProfessionalException
     * @return object|NULL|\com\linways\base\util\$objectList[]
     */
    public function getCertificatesContent($certificateType,$courseTypeId)
    {
        $certificateType = $this->realEscapeString($certificateType);
        $courseTypeId = $this->realEscapeString($courseTypeId);
        $sql = "SELECT content FROM courseConductContent WHERE certificateType = $certificateType 
               AND courseTypeId = $courseTypeId";
        try{
            $courseConductContent = $this->executeQueryForObject($sql);
        }catch (\Exception $e){
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
        return $courseConductContent;
    }
    /**
     * Insert or update certificate content
     * @param string $content
     * @param int $certificateType
     * @param int $courseTypeId
     * @throws ProfessionalException
     * @return unknown
     */
    public function upsertCertificateContent($content,$certificateType,$courseTypeId)
    {
        $content = $this->realEscapeString($content);
        $certificateType = $this->realEscapeString($certificateType);
        $courseTypeId = $this->realEscapeString($courseTypeId);
        try {
            $savedContent = $this->getCertificatesContent($certificateType, $courseTypeId);
            if($savedContent->content)
            {
                $sql = "UPDATE courseConductContent SET content = '$content' WHERE certificateType = $certificateType AND courseTypeId = $courseTypeId";
                return $this->executeQuery($sql);
            }
            else
            {
                $sql = "INSERT INTO courseConductContent(certificateType,content,courseTypeId) VALUES ('$certificateType','$content',$courseTypeId)";
                return $this->executeQueryForObject($sql, true);
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * Delete migration certificate
     * @param int $studentId
     * @throws ProfessionalException
     * @return \com\linways\base\dto\MySqlResult
     */
    public function deleteMigrationCert($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        $sql = "UPDATE studentMigrationCertificate SET isDeleted = 1 WHERE studentId = $studentId";
        try {
            return $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * Delete cancellation certificate
     * @param int $studentId
     * @throws ProfessionalException
     * @return \com\linways\base\dto\MySqlResult
     */
    public function deleteCancelCert($studentId)
    {
        $studentId = $this->realEscapeString($studentId);
        $sql = "UPDATE studentCancellationCertificate SET isDeleted = 1 WHERE studentId = $studentId";
        try {
            return $this->executeQuery($sql);
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
    }
    /**
     * Checks if student certificate exists for given prefix
     * @param int $prefixId
     * @throws ProfessionalException
     * @return boolean
     */
    public function checkIfStudentCertificateExistsForPerfix($prefixId)
    {
        $prefixId = $this->realEscapeString($prefixId);
        try {
            $prefix = $this->getCertificatePrefixById($prefixId);
            switch ($prefix->certificateType)
            {
                case "TC": $sql = "SELECT id FROM studentTransferCertificate WHERE tcPrefixId = ".$prefixId." and is_deleted = 0";
                    break;
                case "MIGRATION":  $sql = "SELECT id FROM studentMigrationCertificate WHERE prefixId = ".$prefixId." AND isDeleted = 0";
                    break;
                case "CANCELLATION":    $sql = "SELECT id FROM studentCancellationCertificate WHERE prefixId = ".$prefixId." AND isDeleted = 0";
                    break;
                default:
                    $sql = "SELECT id FROM studentCourseConductCertificate  WHERE prefixId = ".$prefixId."";
                break;
            }
            if($this->executeQueryForObject($sql))
            {
                return true;
            }
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(),$e->getMessage());
        }
        return false;
    }
    /**
     * Create student's transfer certificate - batchwise
     * @param StudentTransferCertificate $studentTransferCertificate
     * @throws ProfessionalException
     * @return \com\linways\base\dto\MySqlResult
     * @author Vishnu M
     * WIP
     */
    public function createStudentTransferCertificateBatchwise ( $studentTransferCertificate ) {
        $studentTransferCertificate = $this->realEscapeObject($studentTransferCertificate);
        $selectedStudents = implode(",",$studentTransferCertificate->selectedStudentList);
        try {
            $batchId = $studentTransferCertificate->batchId;
            $students = StudentService::getInstance()->getStudentsByBatch($batchId);
            // Check if there are students for the batch and if any students are selected
            if ( !empty ( $students ) && !empty($studentTransferCertificate->selectedStudentList)) {
                $tcGeneratedStudents = [];
                foreach ( $studentTransferCertificate->selectedStudentList as $student ) {
                    // Check If the TC Exist for the Student ID
                    $isTcGenerated = $this->checkStudentTransferCertificateByStudentId($student);
                    if($isTcGenerated){
                        continue;
                    }
                    // Find the oldest TC no which is given to a deleted TC
                    $sql_deletedTc = "SELECT id, MIN(tcNo) AS tcNo FROM studentTransferCertificate WHERE tcPrefixId = $studentTransferCertificate->tcPrefixId AND is_deleted = 1";
                    $tcDetails = $this->executeQueryForObject($sql_deletedTc);
                    if(!empty($tcDetails->id)) {
                        $studentTransferCertificate->id = $tcDetails->id;
                        $studentTransferCertificate->studentId = $student;
                        // Update Old Deleted TC with Details of a New Student TC
                        $this->updateStudentTransferCertificate($studentTransferCertificate,true);
                        $tcGeneratedStudents[$student] = $student;
                    }
                    else{
                        break;
                    }
                }
                if ( count ( $studentTransferCertificate->selectedStudentList ) > count ( $tcGeneratedStudents ) ) {
                    // Obtained Latest TC no 
                    $sqlNewTc = "SELECT IF (tcNo, MAX(cast(tcNo as unsigned)), 0) AS tcNo FROM studentTransferCertificate WHERE tcPrefixId = $studentTransferCertificate->tcPrefixId";
                    $lastTcNo = $this->executeQueryForObject($sqlNewTc)->tcNo;
                    // Insert TC for the batch or selected students which don't have previously created TC that isn't deleted 
                    $sql= "INSERT INTO studentTransferCertificate (
                        studentId,
                        admitedSemId,
                        lastSemId,
                        applicationDate,
                        issueDate,
                        reasonForLeave,
                        lastExamName,
                        feesPaid,
                        studentCharacter,
                        tcNo, 
                        createdBy,
                        createdDate, 
                        updatedBy,
                        updatedDate,
                        mediumOfInstruction,
                        conduct_of_student,
                        isqualifiedForPromotion,
                        totalHours,
                        attendedHours,
                        examStatus,
                        isScholarShipGranted,
                        leavingMonth,
                        leavingYear,
                        leavingDate, 
                        monthOfExamination, 
                        yearOfExamination, 
                        isFeeConcessionReceived, 
                        tcPrefixId, 
                        admisson_courseID, 
                        admission_deptID,
                        leaving_courseID, 
                        leaving_deptID,  
                        studied_patterndeptID, 
                        studied_subsID, 
                        lst_exm_courseID, 
                        lst_exm_deptID, 
                        lst_exm_semID, 
                        has_appeared, 
                        remarks, 
                        is_deleted, 
                        is_alumini, 
                        studentPassedStatus, 
                        lst_exm_status,
                        classOfAdmission,
                        classOfLeaving,
                        subjectstudied,tc_print_date,bookNo )
                        
                        SELECT sa.studentID, 
                        '$studentTransferCertificate->admitedSemId',
                        $studentTransferCertificate->lastSemId,
                        '".(empty($studentTransferCertificate->applicationDate)?NULL:date('Y-m-d',strtotime($studentTransferCertificate->applicationDate)))."',
                        '".(empty($studentTransferCertificate->issueDate)?NULL:date('Y-m-d',strtotime($studentTransferCertificate->issueDate)))."',
                        '$studentTransferCertificate->reasonForLeave',
                        '$studentTransferCertificate->lastExamName',
                        '$studentTransferCertificate->feesPaid',
                        '$studentTransferCertificate->studentCharacter',
                        @tcNo:=@tcNo+1 tcNo,
                        $studentTransferCertificate->createdBy,
                        utc_timestamp(),
                        $studentTransferCertificate->updatedBy
                        utc_timestamp(),
                        '$studentTransferCertificate->mediumOfInstruction',
                        '$studentTransferCertificate->conductOfStudent',
                        '$studentTransferCertificate->isQualifiedForNextSem',
                        '$studentTransferCertificate->totalHours',
                        '$studentTransferCertificate->attendedHours',
                        '$studentTransferCertificate->passedStatus',
                        '$studentTransferCertificate->studentScholarshipStatus',
                        '$studentTransferCertificate->leavingMonth',
                        '$studentTransferCertificate->leavingYear',
                        '$studentTransferCertificate->leavingDate', 
                        '$studentTransferCertificate->monthOfExamination', 
                        '$studentTransferCertificate->yearOfExamination', 
                        '$studentTransferCertificate->isFeeConcessionReceived', 
                        '$studentTransferCertificate->tcPrefixId', 
                        '$studentTransferCertificate->admissonCourseId', 
                        '$studentTransferCertificate->admissionDeptId', 
                        '$studentTransferCertificate->leavingCourseId', 
                        '$studentTransferCertificate->leavingDeptId', 
                        '$studentTransferCertificate->studied_patterndeptId', 
                        '$studentTransferCertificate->studiedSubsId', 
                        '$studentTransferCertificate->lstExmCourseId', 
                        '$studentTransferCertificate->lstExmDeptId', 
                        '$studentTransferCertificate->lstExmSemId', 
                        '$studentTransferCertificate->hasAppeared', 
                        '$studentTransferCertificate->remarks', 
                        '$studentTransferCertificate->isDeleted', 
                        '$studentTransferCertificate->isAlumini', 
                        '$studentTransferCertificate->studentPassedStatus', 
                        '$studentTransferCertificate->lastExamStatus',
                        '$studentTransferCertificate->classOfAdmission',
                        '$studentTransferCertificate->classOfLeaving',
                        '$studentTransferCertificate->subjectStudied',
                        '$studentTransferCertificate->tcPrintDate',
                        '$studentTransferCertificate->bookNo
                        FROM studentaccount sa, (SELECT @tcNo:= $lastTcNo) AS a "; 
                    if($selectedStudents){
                        $sql .=" WHERE sa.batchID = '$batchId' AND studentID NOT IN ( SELECT studentID FROM studentTransferCertificate WHERE is_deleted = 0 ) AND studentID IN ($selectedStudents) ORDER BY sa.regNo ASC";
                    }
                    else{
                        $sql .=" WHERE sa.batchID = '$batchId' AND studentID NOT IN ( SELECT studentID FROM studentTransferCertificate WHERE is_deleted = 0 ) ORDER BY sa.regNo ASC";
                    }
                    
                    $this->executeQuery($sql);
                }
                $sqlUpdate = "UPDATE studentaccount SET tcIssued = 1 WHERE batchID = '$batchId";
                if($selectedStudents){
                    $sqlUpdate .= " AND studentID IN ($selectedStudents";
                }
                $this->executeQuery($sqlUpdate);
                // $sqlUpdate="UPDATE certificatePrefixes SET value= value + ".count ( $students )." WHERE id =  $studentTransferCertificate->tcPrefixId";
                // $this->executeQuery($sqlUpdate);
                // if(CommonService::getInstance()->getSettings(SettingsConstents::CERTIFICATE, SettingsConstents::MOVE_STUDENTS_ISSUING_TC_BEFORE_BATCH_TC_ISSUED_DATE_TO_FAILED_LIST)) {
                //     $batchDetials = BatchService::getInstance()->getBatchById($batchId);
                //     if((strtotime($batchDetials->tcIssueDate) > strtotime($studentTransferCertificate->issueDate)) && !empty($studentTransferCertificate->issueDate)) {
                //         StudentService::getInstance()->moveStudentToFailedListByBatch($batchId);
                //     }
                // }
            }
        } catch (\Exception $e) {
            if($e->getCode() == "STUDENTS_ALREADY_IN_FAILED_LIST") {
                return ;
            }
            else {
                throw new ProfessionalException($e->getCode(), $e->getMessage());
            }
        }
        return true;
    }
    /**
     * Get Template name from multiple templates for batch
     * @param settings type
     * @param settings name
     * @throws ProfessionalException
     * @return string templateName
     * @author Anoop
     *
     */
    public function getCustomTemplateName ( $type, $name, $batchId ) {
        $batchId = $this->realEscapeObject($batchId);
        $customTemplate = NULL;
        try {
            $customTemplateJSON = CommonService::getInstance()->getSettings($type, $name);
            $customTemplateJSON = json_decode($customTemplateJSON, true);
            $customTemplate = $customTemplateJSON[$batchId] ? $customTemplateJSON[$batchId] : $customTemplateJSON['DEFAULT'];
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $customTemplate;
    }
    /**
     * Get Template name from multiple templates
     * @param settings type
     * @param settings name
     * @param patternCourseid patternCourseId
     * @throws ProfessionalException
     * @return string templateName
     * @author Anoop
     *
     */
    public function getCustomTemplate ( $type, $name, $patternCourseId = NULL ) {
        $patternCourseId = $this->realEscapeObject($patternCourseId);
        $customTemplate = NULL;
        try {
            $customTemplateJSON = CommonService::getInstance()->getSettings($type, $name);
            $customTemplateJSON = json_decode($customTemplateJSON);
            if (!empty($customTemplateJSON->custom)) {
                foreach ( $customTemplateJSON->custom as $template ) {
                    if ( in_array($patternCourseId, $template->patternCourseId ) ) {
                        $customTemplate = $template->templateId;
                    }
                }
            }
            $customTemplate = ($customTemplate && $patternCourseId != NULL) ? $customTemplate : $customTemplateJSON->default;
        } catch (\Exception $e) {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $customTemplate;
    }
    /**
     * Get Template name from multiple templates
     * @param settings type
     * @param settings name
     * @param courseTypeID
     * @throws batchID
     * @return string templateName
     *
     */
    public function getCustomTCform ( $type, $name, $courseType ,$batchID = null) 
    {
        $courseType = $this->realEscapeObject($courseType);
        $batchID = $this->realEscapeObject($batchID);
        $customTemplate = NULL;
        try {
            $customTemplateJSON = CommonService::getInstance()->getSettings($type, $name);
            $customTemplateJSON = json_decode($customTemplateJSON);
            $customTemplate = $customTemplateJSON->default;
            foreach($customTemplateJSON->TcFormats as $tcFormat)
            {
                if($tcFormat->courseType == $courseType )
                {
                    $customTemplate = $tcFormat->tcTemplate;
                }
            }
        } 
        catch (\Exception $e) 
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $customTemplate;
    }
    
    /**
     * get details of certificate prefix by type
     * @param int $id
     * @return $certificatePrefix
     */
    public function getCertificatePrefixByType($certificateType,$year = null)
    {
        $certificatePrefix=NULL;
        $cond = "";
        if($year){
            $cond .= " AND yearWise = '".$year."'";
        }
        $sql = "SELECT cp.id, cp.prefixName,cp.prefix, cp.value, bct.type_name as typeName, cp.startYear, cp.endYear, cp.certificateType, cp.courseTypeId, cp.prefixYear, cp.campusTypeId, ct.name as campusTypeName, fromDate, toDate FROM certificatePrefixes cp left JOIN batch_course_type bct ON cp.courseTypeId=bct.id left join campus_type ct on ct.id = cp.campusTypeID WHERE cp.certificateType = '$certificateType'".$cond;
        try
        {
            $certificatePrefix = $this->executeQueryForObject($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        
        return $certificatePrefix;
    }
    /**
     * Get all academic certificates
     * @param int $certificatID
     * @return string certificates
     *
     */
    public function getAllAcademicCertificates( $certificatID = null ) 
    {
        $certificatID = $this->realEscapeString($certificatID);
        $condition = $certificatID?"and ac.id = ".$certificatID:null;
        try 
        {
            $sql = "select ac.*,acc.id as child_id,acc.name as child_name,acc.code as child_code,acc.is_active as child_is_active, acc.description as child_description, acc.parent_id as child_parent_id, acc.remarks as child_remarks, acc.order_no as child_order_no, acc.rules as child_rules
            from academic_certificates ac
            left join academic_certificates acc on acc.parent_id = ac.id and acc.parent_id is not null and acc.is_active = 1
            where ac.parent_id is null $condition and ac.is_active = 1 order by ac.order_no,acc.order_no;";
            $certificates = $this->executeQueryForList($sql);
        } 
        catch (\Exception $e) 
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $certificates;
    }
    /**
     * get generated prefix using studentId and prefixId
     * @param int $studentId
     * @param int $prefixId
     * @throws ProfessionalException
     * @return string $slNo
     */
    public function getConductSlNoByPrefixId($studentId, $prefixId, $certificateType)
    {
        $slNo=NULL;
        $sql ="SELECT ccNo FROM studentCourseConductCertificate where studentId = $studentId and prefixId = $prefixId and certificateType = '$certificateType';";
        try
        {
            $slNo =  $this->executeQueryForObject($sql)->ccNo;
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
        return $slNo;
    }
    
    public function getUnknownTransferCertificate()
    {
        $sql ="SELECT * FROM studentTransferCertificate where studentId is null";
        try
        {
            return $this->executeQueryForList($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    
    public function getUnknownTransferCertificateById($tcId)
    {
        $sql ="SELECT * FROM studentTransferCertificate where id=$tcId";
        try
        {
            return $this->executeQueryForObject($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    
    public function deleteUnknownTransferCertificateById($tcId)
    {
        $sql ="DELETE FROM studentTransferCertificate where id=$tcId";
        try
        {
            $this->executeQuery($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    public function getTransferCertificateDetailsByStudentId($studentId)
    {
        $sql ="SELECT * FROM studentTransferCertificate where studentId =".$studentId." and is_deleted = 0; ";
        try
        {
            return $this->executeQueryForObject($sql);
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
    }
    /*
     * Get array of student CATEGORY for certicate
     */
    public function getStudentCategorys()
    {
        $characters = NULL;
        $arr = NULL;
        $arr = explode(';',CommonService::getInstance()->getSettings(SettingsConstants::CERTIFICATE, SettingsConstants::TC_STUDENT_CATEGORY));
        foreach ( $arr as $el )
        {
            $categorys[$el] = $el;
        }
        return $categorys;
    }
    /**
     * get values from studentTransferCertificate
     */
     public function getDynamicTransferCertificateValues($studentId,$selectValues,$fromStudentSide = null)
     {
        $studentId = $this->realEscapeString($studentId);
        $selectValues = $this->realEscapeString($selectValues);
        $fromStudentSide = $this->realEscapeString($fromStudentSide);
        $result = new stdClass();
        $result->dynamicResult = "";
        $result->studentSideResult = "";
        if($selectValues == "" && $fromStudentSide == "")
        {
            return $result;
        }
        if($selectValues)
        {
            $sql1 = "SELECT ".$selectValues." FROM studentTransferCertificate WHERE studentId =".$studentId;
            $result->dynamicResult= $this->executeQueryForObject($sql1);
        }
        if($fromStudentSide)
        {
            $sql2 = "SELECT ".$fromStudentSide." FROM studentaccount WHERE studentID =".$studentId;
            $result->studentSideResult = $this->executeQueryForObject($sql2);
        }
        try
        {
            return $result;
        }
        catch (\Exception $e)
        {
            throw new ProfessionalException($e->getCode(), $e->getMessage());
        }
     }
}