Your IP : 216.73.216.40


Current Path : /var/www/html/mmishra/erp/controllers/
Upload File :
Current File : /var/www/html/mmishra/erp/controllers/aaa_controller.php

<?php
//if (!class_exists($erpController)) {
	require_once __DIR__."/erp_controller.php";
//}
class aaaController extends erpController {

    var $model;    
	
    public function __construct($model) {
		// call parent constructor
		// parent::__construct();
        // initialize variables
		
		$this->model 			= $model;
		$this->model->tupleID	= $this->tuple;

		$this->userIP 			= $this->getIP(); 			// requires in log entry			
		$this->appURL 			= $_SERVER['REQUEST_URI'];	// this is Request URI for log entry
		$this->referer 			= $_SERVER['HTTP_REFERER'];	// requires for log entry, not mandatory

		// maintain erp activity log for inner contents
		if ($_SESSION['loginID'] && strpos($this->appURL, 'inner')) {
			$this->model->erpLog($this->userIP, $this->appURL, $this->referer);
		} else if ($this->model->getMenuProtection($this->menu)) {
			print("<h1>Session expired. Please sign-in again.</h1>");
			exit;
		}			
		//echo session_cache_expire();
    }

    public function __destruct() {
		
		//'Destroying: ', $this->moduleID, PHP_EOL;
        // log sql operation on corresponding table
        // call $erpModel->erpSql($sql);
        // print("Thanks.");
    }

	public function manageAlert($action, $alertID) {
		$this->model->tableID 		= 'aaa_autoalerts';
		$this->model->tupleID 		= $alertID;
		switch ($action) {
            case 'new':
			case 'edit':
				$this->editLock 		= '';
				break;
			case 'refresh':
            case 'open':
            case 'help':
			case 'trash':
				break;
			case 'removeAttachment':
				$attachment 			= $this->params[0];
				$this->model->removeAlertAttachments($alertID,$attachment);
				break;
			case 'save':
                // save record
            	$subjectID				= $_POST['subjectID'];
				$message				= $_POST['message'];
				$emailsTo				= $_POST['emailsTo'];
				$emailsCC				= $_POST['emailsCC'];
				$emailsBCC				= $_POST['emailsBCC'];
				$targetGroups			= implode(',', $_POST['targetGroups']);
				$schedule				= $_POST['schedule'];

				$this->model->saveAlert($subjectID,$message,$emailsTo,$emailsCC,$emailsBCC,$targetGroups,$schedule);
                //$this->model->sqlLog();
                $this->errorText 		= 'Alert record saved successfully.';
                break;
            case 'enable':
                // enable record
                $this->model->enableAlert();
                $this->model->sqlLog();
                $this->errorText 		= 'Alert record enabled successfully.';
                break;
            case 'disable':
                // disable record
                $this->model->disableAlert();
                $this->model->sqlLog();
                $this->errorText 		= 'Alert record disabled successfully.';
                break;
            case 'delete':
                // delete record
                $this->model->deleteAlert();
                $this->model->sqlLog();
                $this->errorText 		= 'Alert record deleted successfully.';
            	break;
			case 'mail':
				$alert 					= $this->model->getAlert($alertID); 	// fetch alert record
				$subject 				= $this->reminders[$alert['subjectID']];  // get subject text
				$message 				= $alert['message'];
				$emailsTo 				= $alert['emailsTo'];
				$emailsCC 				= $alert['emailsCC'];
				$emailsBCC 				= $alert['emailsBCC'];
				$targetGroups 			= $alert['targetGroups'];
				$attachments			= $alert['attachments'];
				$schedule				= $alert['schedule'];
				
				$programs 				= explode(',', $targetGroups);
				if ($programs) {
					foreach ($programs as $programID) {
						$defaulters 		= $this->model->listDefaulters($programID, $alert['subjectID']);
						foreach ($defaulters as $defaulter) {						
							if ($eno !='' && $eno != $defaulter['enrolmentNo']) {
								$no++;
								$emailTo = ($emailsTo ? $emailsTo : "$eno@iiita.ac.in");
								$body = "$message<br><br>
								<table width='100%' border='1' style='border-collapse: collapse'>
								<tr style='line-height: 40px' valign='middle'><th colspan='2' nowrap>Enrolment No.: $eno</th><th nowrap>Category: $dcat</th><th nowrap>Name: $dname</th></tr>
								<tr><th width='5%'>#</th><td width='15%'><b>Code</b></td><td width='30%'><b>Head</b></td><td width='50%'><b>Remark</b></td></tr>
								$defaultList
								</table>";
								if ($this->erpMailer($emailTo, $subject, $body, $emailsCC, $emailsBCC) == 'OK') {
									$this->errorText = "Alert record ($no) mailed successfully.";
								} else {
									$this->errorText = "Error in mailing alert to defaulters.";
								}
								$i = 0;
								$defaultList = '';
							}
							$i++;
							$eno 		= $defaulter['enrolmentNo'];
							$dname 		= $defaulter['nameEnglish']. ' (' .$defaulter['nameHindi']. ')';
							$dcat 		= $this->categorys[$defaulter['category']];
							$defaultList .= "<tr><td align='center'>$i</td><td>" .$defaulter['docheadCode']. "</td><td nowrap>" .$defaulter['docheadName']. "</td><td>" .$defaulter['remark']. "</td></tr>";
						}
					}
				} else {
					$this->erpMailer($emailsTo, $subject, $body, $emailsCC, $emailsBCC);	
					$this->errorText 	= "Mail has been spooled successfully.";
				}
				$this->model->updateAlert($alertID);
				break;
				
        }
		return $this->model->tupleID;
    }	

	public function manageCourse($action, $courseID) {
		$this->model->tableID 			= 'aaa_courses';
		$this->model->tupleID 			= $courseID;
		switch ($action) {
            case 'new':
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
            case 'help':
			case 'trash':
				break;
			case 'save':
                // save record
            	$courseCode				= strtoupper($_POST['courseCode']);
				$courseName				= ucwords($_POST['courseName']);
				$courseNameH			= $_POST['courseNameH'];
				
				$this->model->saveCourse($courseCode,$courseName,$courseNameH);
                $this->model->sqlLog();
                $this->errorText 		= 'Course record saved successfully.';				
                break;
            case 'enable':
                // enable record
                $this->model->enableCourse();
                $this->model->sqlLog();
                $this->errorText 		= 'Course record enabled successfully.';
                break;
            case 'disable':
                // disable record
                $this->model->disableCourse();
                $this->model->sqlLog();
                $this->errorText 		= 'Course record disabled successfully.';
                break;
            case 'delete':
                // delete record
                $this->model->deleteCourse();
                $this->model->sqlLog();
                $this->errorText 		= 'Course record deleted successfully.';
            	break;
        }
		return $this->model->tupleID;
    }	

	public function manageSpecialization($action, $specializationID) {
		$this->model->tableID 			= 'aaa_specializations';
		$this->model->tupleID 			= $specializationID;
		switch ($action) {
            case 'new':
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
            case 'help':
			case 'trash':
				break;
			case 'save':
                // save record
            	$specializationCode		= strtoupper($_POST['specializationCode']);
				$specializationName		= ucwords($_POST['specializationName']);
				$specializationNameH	= $_POST['specializationNameH'];
				
				$this->model->saveSpecialization($specializationCode,$specializationName,$specializationNameH);
                $this->model->sqlLog();
                $this->errorText 		= 'Specialization record saved successfully.';
                break;
            case 'enable':
                // enable record
                $this->model->enableSpecialization();
                $this->model->sqlLog();
                $this->errorText 		= 'Specialization record enabled successfully.';
                break;
            case 'disable':
                // disable record
                $this->model->disableSpecialization();
                $this->model->sqlLog();
                $this->errorText 		= 'Specialization record disabled successfully.';
                break;
            case 'delete':
                // delete record
                $this->model->deleteSpecialization();
                $this->model->sqlLog();
                $this->errorText 		= 'Specialization record deleted successfully.';
            	break;
        }
		return $this->model->tupleID;
    }	

	public function manageBranch($action, $branchID) {
		$this->model->tableID 			= 'aaa_branches';
		$this->model->tupleID 			= $branchID;
		switch ($action) {
            case 'new':
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
            case 'help':
			case 'trash':
				break;
			case 'save':
                // save record
            	$branchCode				= strtoupper($_POST['branchCode']);
				$branchName				= ucwords($_POST['branchName']);
				$branchNameH			= $_POST['branchNameH'];
				
				$this->model->saveBranch($branchCode,$branchName,$branchNameH);
                $this->model->sqlLog();
                $this->errorText 		= 'Branch record saved successfully.';
                break;
            case 'enable':
                // enable record
                $this->model->enableBranch();
                $this->model->sqlLog();
                $this->errorText 		= 'Branch record enabled successfully.';
                break;
            case 'disable':
                // disable record
                $this->model->disableBranch();
                $this->model->sqlLog();
                $this->errorText 		= 'Branch record disabled successfully.';
                break;
            case 'delete':
                // delete record
                $this->model->deleteBranch();
                $this->model->sqlLog();
                $this->errorText 		= 'Branch record deleted successfully.';
            	break;
        }
		return $this->model->tupleID;
    }	

	public function manageProgram($action, $programID) {
		$this->model->tableID 			= 'aaa_programs';
		$this->model->tupleID 			= $programID;
		switch ($action) {
            case 'new':
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
            case 'help':
			case 'trash':
				break;
			case 'save':
                // save record
                $programCode			= $_POST['programCode'];
				$programTitle			= ucwords($_POST['programTitle']);
				$programTitleH			= $_POST['programTitleH'];
				$courseID				= $_POST['courseID'];
				$branchID				= $_POST['branchID'];
				$specializationID		= $_POST['specializationID'];
				$degreeLevel			= $_POST['degreeLevel'];
				$timeDuration			= $_POST['timeDuration'];
				$rollnoPrefix			= $_POST['rollnoPrefix'];
				$entranceBoard			= $_POST['entranceBoard'];
				$entranceName			= $_POST['entranceName'];
				$intakeLimit			= $_POST['intakeLimit'];
				$lastRollno				= $_POST['lastRollno'];
				
				//$this->model->saveProgram($programCode,$programName,$programNameH,$branchName,$branchNameH,$specialization,$specializationH,$degreeLevel,$timeDuration,$rollnoPrefix,$entranceBoard,$entranceName,$intakeLimit,$lastRollno);
				$this->model->saveProgram($programCode,$programTitle,$programTitleH,$courseID,$branchID,$specializationID,$degreeLevel,$timeDuration,$rollnoPrefix,$entranceBoard,$entranceName,$intakeLimit,$lastRollno);
                $this->model->sqlLog();
                $this->errorText 		= 'Program record saved successfully.';
                break;
            case 'enable':
                // enable record
                $this->model->enableProgram();
                $this->model->sqlLog();
                $this->errorText 		= 'Program record enabled successfully.';
                break;
            case 'disable':
                // disable record
                $this->model->disableProgram();
                $this->model->sqlLog();
                $this->errorText 		= 'Program record disabled successfully.';
                break;
            case 'delete':
                // delete record
                $this->model->deleteProgram();
                $this->model->sqlLog();
                $this->errorText 		= 'Program record deleted successfully.';
            	break;
        }
		return $this->model->tupleID;
    }	

	public function manageFeehead($action, $feeheadID) {
		$this->model->tableID 			= 'aaa_feeheads';
		$this->model->tupleID 			= $feeheadID;
		switch ($action) {
            case 'new':
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
            case 'help':
			case 'trash':
				break;
			case 'save':
                // save record
				$feeheadCode	 		= strtoupper($_POST['feeheadCode']);
				$feeheadName	 		= ucwords($_POST['feeheadName']);
				$accountType 			= $_POST['accountType'];
				$paymentTerm 			= $_POST['paymentTerm'];

				$this->model->saveFeehead($feeheadCode,$feeheadName,$accountType,$paymentTerm);
				$this->model->sqlLog();
                $this->errorText 		= 'Feehead record saved successfully.';
                break;
			case 'delete':
				$this->model->deleteFeehead();
				$this->model->sqlLog();
                $this->errorText 		= 'Feehead record deleted successfully.';
                break;
        }
		return $this->model->tupleID;
    }	

	public function manageFeechart($action, $feechartID) {
		$this->model->tableID 			= 'aaa_feecharts';
		$this->model->tupleID 			= $feechartID;
		switch ($action) {
            case 'new':
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
            case 'help':
			case 'trash':
				break;
			case 'save':
                // save record
				$feeheadID	 			= $_POST['feeheadID'];
				$currency 				= $_POST['currency'];
				$feeAmount 				= $_POST['feeAmount'];
				if (!$feeAmount) $feeAmount = 0;
				$category 				= implode(',', $_POST['category']);
				$programID				= implode(',', $_POST['programID']);
				
				$this->model->saveFeechart($feeheadID,$currency,$feeAmount,$category,$programID);
				$this->model->sqlLog();
                $this->errorText 		= 'Feechart record saved successfully.';
                break;
			case 'delete':
				$this->model->deleteFeechart();
				$this->model->sqlLog();
                $this->errorText 		= 'Feechart record deleted successfully.';
                break;
        }
		return $this->model->tupleID;
    }	

	public function manageDochead($action, $docheadID) {
		$this->model->tableID 			= 'aaa_docheads';
		$this->model->tupleID 			= $docheadID;
		switch ($action) {
            case 'new':
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
            case 'help':
			case 'trash':
				break;
			case 'save':
				$docheadCode 			= strtoupper($_POST['docheadCode']);
				$docheadName 			= ucwords($_POST['docheadName']);
				$specification 			= $_POST['specification'];
				$original				= $_POST['original'];
				$category 				= implode(',', $_POST['category']);
				$programID				= implode(',', $_POST['programID']);
				
				$this->model->saveDochead($docheadCode,$docheadName,$specification,$original); 
				$this->model->sqlLog();
                $this->errorText 		= 'Dochead record saved successfully.';
				break;
			case 'delete':
				$this->model->deleteDochead();
				$this->model->sqlLog();
                $this->errorText 		= 'Dochead record deleted successfully.';
				break;
		}
		return $this->model->tupleID;
    }	

	public function manageDocchart($action, $docchartID) {
		$this->model->tableID 			= 'aaa_doccharts';
		$this->model->tupleID 			= $docchartID;
		switch ($action) {
            case 'new':
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
            case 'help':
			case 'trash':
				break;
			case 'save':
				$docheadID 				= $_POST['docheadID'];
				$category 				= implode(',', $_POST['category']);
				$programID				= implode(',', $_POST['programID']);
				
				$this->model->saveDocchart($docheadID,$category,$programID); 
				$this->model->sqlLog();
                $this->errorText 		= 'Docchart record saved successfully.';
				break;
			case 'delete':
				$this->model->deleteDocchart();
				$this->model->sqlLog();
                $this->errorText 		= 'Docchart record deleted successfully.';
				break;
		}
		return $this->model->tupleID;
    }	

	public function manageSeatMatrix($action, $matrixID) {
		$this->model->tableID 			= 'aaa_seatmatrix';
		$matrixID						= 1;
		$this->model->tupleID 			= $matrixID;
		$programID 						= $this->params[0];
		switch ($action) {
            case 'new':
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
            case 'help':
			case 'trash':
				break;
			case 'save':
				$matrixIDs				= $_POST['matrixID']; 	// array
				$categorys				= $_POST['category'];	// array
				$genders				= $_POST['gender'];		// array
				$seatNos				= $_POST['seatNo'];		// array
				$i 						= 0;
				
				foreach ($matrixIDs as $matrixID) {
					if (!$matrixID) $matrixID = 0;
					$this->model->tupleID= $matrixID;
					if (!$seatNos[$i]) $seatNos[$i] = 0;
					
					if ($seatNos[$i]) {
						$j++;
						$this->model->saveSeatmatrix($programID,$categorys[$i],$genders[$i],$seatNos[$i]); 
					} else {
						$this->model->deleteSeatmatrix();
					}
					$i++;
				}
				$this->model->sqlLog();
                $this->errorText 		= "Seatmatrix record ($j) saved successfully.";
				break;
		}
		return $this->model->tupleID;
    }	

	public function manageImport($action, $roundNo) {
		$this->model->tableID 			= 'aaa_candidates';
		$this->model->tupleID 			= $roundNo;
		$degreeLevel					= $this->params[0];
		switch ($action) {
			case 'refresh':
			case 'new':
			case 'open':
				$roundNo				= $this->model->getRoundNoByInstituteID($degreeLevel);
				$this->model->tupleID	= $roundNo;
				break;
			case 'dataUpload':
                // upload file and dump record
				if (isset($_FILES['fileToUpload']['name'])) {
					//validate whether uploaded file is a csv file
					$csvMimes 			= array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel', 'text/plain');
					
					$programID 			= 0; // updates thru manageOffer
					$degreeLevel		= ($degreeLevel ? $degreeLevel : $_POST['degreeLevel']);
					$sourceFile			= basename($_FILES['fileToUpload']['name']);
					$uploadFile			= strtolower('csv-' .$_SESSION['instituteID']. '-' .date('Y-m-d'). '-' .str_replace(' ','-',$sourceFile));
					$targetFile 		= __DIR__. "/../uploads/" .$uploadFile;
					$extName	 		= strtolower(pathinfo(basename($_FILES['fileToUpload']['name']), PATHINFO_EXTENSION));

					// remove existing old file
					if (file_exists($targetFile)) exec("rm -f $targetFile");

					if ($_FILES['fileToUpload']['size'] > 5500000) {
						$this->errorText = "Sorry, file size too large.";
						// Allow certain file formats
					} else if ($extName != "csv") {
						$this->errorText = "Sorry, only csv format supported.";
						// if everything is ok, try to upload file
					} else if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $targetFile)) {
						// data cleansing
						//if ($_POST['purgeOld'] == 1) $this->model->purgeCandidates($roundNo);

						//open uploaded csv file with read only mode
						$csvFile = fopen($targetFile, 'r');
						//skip first line
						fgetcsv($csvFile);
						$roundNo		= 0;
						//parse data from csv file line by line
						while(($line = fgetcsv($csvFile)) !== FALSE){
							$no++;
							$sn 		= trim($line[0]);			// serial no.
							$rollNo 	= trim($line[1]);			// roll no.
							$nameEnglish= ucwords(trim($line[2]));			// name
							$category 	= trim($line[3]);			// category
							$pwdStatus 	= (strtolower(trim($line[4])) == 'yes' ? 'Y' : 'N');		// PwD
							$gender 	= trim($line[5]);
							$dateBirth 	= str_replace('/', '-', trim($line[6]));		// DOB
							$stateEligibility	= trim($line[7]);	// state eligibility
							$nationality= trim($line[8]);
							$programName= trim($line[9]);			// allocated program
							$allotedCategory	= trim($line[10]); 	// allocated category
							$allotedRank= trim($line[11]);
							$allotedRank= ($allotedRank ? $allotedRank : 0);
							$choiceNo 	= trim($line[12]);
							$choiceNo	= ($choiceNo ? $choiceNo : 0);
							$quota 		= trim($line[13]);
							$roundName	= trim($line[14]);
							$willingness= trim($willingness[15]);
							$status 	= trim($line[16]);
							$rcName 	= trim($line[17]);
							$remark		= trim($line[18]); 			// eemarks by rc
							
							if ($no == 1) {
								$roundNo= $this->model->getRoundNoByInstituteID($degreeLevel);
								$roundNo++;
							}
							$candidateID= $this->model->getCandidateIDByRollNo($rollNo);
							$this->model->tupleID = ($candidateID ? $candidateID : 0);
							// if record exists, it will be updated with new roundNo

							$this->model->saveCandidate($programID,$roundNo,$degreeLevel,$rollNo,$nameEnglish,$category,$pwdStatus,$gender,$dateBirth,$stateEligibility,$nationality,$programName,$allotedCategory,$allotedRank,$choiceNo,$quota,$roundName,$willingness,$status,$rcName,$remark);
							$this->model->sqlLog();
						}
				
						//close opened csv file
						fclose($csvFile);
						echo "<h3 class='alert'>Candidate <a href='uploads/$uploadFile' target='new'>list</a> uploaded and $no records " .($candidateID ? "updated." : "created successfully."). " Please offer admission to these candidates.</h3>";
						$this->errorText = "$no records imported successfully.";

					} else {
						$this->errorText = "Error, please try again.";
					}
				} else {
					$this->errorText 	= "Select file to upload.";
				}
				$this->model->tupleID	= $roundNo;
				break;
        }
		return $this->model->tupleID;
    }	

	public function manageOffer($action, $roundNo) {
		$this->model->tableID 			= 'aaa_applicants';
		$this->model->tupleID 			= $roundNo;
		$degreeLevel					= $this->params[0];
		
		switch ($action) {
			case 'refresh':
			case 'new':
			case 'open':
				$roundNo				= $this->model->getRoundNoByInstituteID($degreeLevel);
				$this->model->tupleID	= $roundNo;
				break;
			case 'save':                // save record
                // set programID in candidates table
                $programNames 			= $_POST['aProgramIDs'];
                $programIDs 			= $_POST['oProgramIDs'];
                $aCategorys 			= $_POST['aCategorys'];
				$oCategorys 			= $_POST['oCategorys'];
				$i = 0;
				foreach ($programNames as $programName) {
					$this->model->setOfferedProgram($programName, $programIDs[$i], $roundNo);
					$i++;
	            }
				
				$j = 0;
				foreach ($aCategorys as $aCategory) {
					$this->model->setOfferedCategory($aCategory, $oCategorys[$j], $roundNo);
					$j++;
	            }
								
				// make offer
				$candidates 		= $this->model->listCandidates($degreeLevel);//, $roundNo);
				foreach ($candidates as $candidate) {
					$rollNo 		= $candidate['rollNo'];					
					$programID 		= $candidate['programID'];
					$allotedCategory= $candidate['allotedCategory']; 	// alloted category
					$allotedRank	= $candidate['allotedRank']; 		// alloted rank 
					$offerCategory 	= $candidate['offerCategory']; 		// offer category
					$offerRound		= $candidate['roundNo'];
					$remark 		= $candidate['remark']; 			// remarks by rc
				
					// for aaa_students table
					$nameEnglish 	= trim($candidate['nameEnglish']);	// name
					$gender 		= strtoupper(substr(trim($candidate['gender']), 0, 1));

					$dob			= str_replace('/', '-', trim($candidate['dateBirth']));
					$dt 			= explode('-', $dob);
					if (strlen($dt[0]) < 4 && strlen($dt[2]) == 2) {
						$dt[2]	= ($dt[2] > date('y') ? '19' : '20').$dt[2];
						$dateBirth		= implode('-', array_reverse($dt));
					} else { // date is already in yyyy-mm-dd format
						$dateBirth		= $dob;
					}		
					$category 		= ((strtolower(trim($candidate['category'])) == 'general' || strtolower(trim($candidate['category'])) == 'open') ? 'GEN' : trim($candidate['category']));
					$pwdStatus 		= substr(trim($candidate['pwdStatus']), 0, 1); // Y or N
					$state 			= explode(" (", $candidate['stateEligibility']);
				
					$homeState 		= $this->model->getStateIDByStateName($state[0]);
					$homeState 		= ($homeState ? $homeState : 0);				// StateEligibility
					$nationality 	= strtoupper(substr($candidate['nationality'], 0, 2));
					$phoneNo 		= date("hhiiss");

					$applicantID	= $this->model->getApplicantIDByRollNo($rollNo);
					$nameHindi		= '';
					$subCategory	= '';
					$religion		= 'H';
					$maritalStatus	= 'U';
					$aadhaarNo		= '';
					$fatherName 	= '';
					$motherName 	= '';
					$guardianName	= '';						
					$fatherPhone 	= $phoneNo;
					$motherPhone 	= $phoneNo;
					$guardianPhone	= $phoneNo;
					$email			= '';
					$fatherEmail	= $email;
					$motherEmail	= $email;
					$guardianEmail	= $email;
					$bloodGroup		= 'A';
					$homeAddress	= '';
					$commAddress	= '';
					$policeStation  = '';
					$fatherAddress	= '';
					$motherAddress	= '';
					$guardianAddress= '';
					$relationWith	= 'Father';
					$fatherProfession	= 'HOM';
					$motherProfession	= 'HOM';
					$guardianProfession	= 'HOM';
					$hhIncome		= 0;
					$homeState		= 0;
					$homeDistrict	= 0;
					$homePIN 		= 0;
					$commPIN 		= 0;
					$area			= 0;
					$xGrade			= '';
					$xYear 			= 0;
					$xBoard			= '';
					$xiiGrade		= '';
					$xiiYear 		= 0;
					$xiiBoard		= '';
					$ugGrade		= '';
					$ugYear 		= 0;
					$ugInstitute	= '';
					$pgGrade		= '';
					$pgYear 		= 0;
					$pgInstitute	= '';
					$lastScore		= $allotedRank;
				
					$studentID	= $this->model->getStudentIDByRollNo($rollNo);
					if (!$studentID) {
						$studentID	= 0;
						$parentID	= 0;
						$educationID= 0;
						$applicantID= 0;
						// insert student record
						$studentID 	= $this->model->saveStudent($studentID,$nameEnglish,$nameHindi,$dateBirth,$gender,$bloodGroup,$pwdStatus,$maritalStatus,$category,$subCategory,$religion,$nationality,$aadhaarNo,$hhIncome,$phoneNo,$email,$homeAddress,$homePIN,$homeState,$homeDistrict,$area,$policeStation,$commAddress,$commPIN,$remark,$status);
			
						// save parent record with studentID as foreign key
						$this->model->saveParent($parentID,$studentID,$fatherName,$fatherProfession,$fatherPhone,$fatherEmail,$fatherAddress,$motherName,$motherProfession,$motherPhone,$motherEmail,$motherAddress,$guardianName,$guardianProfession,$relationWith,$guardianPhone,$guardianEmail,$guardianAddress);
			
						// save education record with studentID as foreign key
						$this->model->saveEducation($educationID,$studentID,$xGrade,$xYear,$xBoard,$xiiGrade,$xiiYear,$xiiBoard,$ugGrade,$ugYear,$ugInstitute,$pgGrade,$pgYear,$pgInstitute,$lastScore);
					} else {
						// update student record
						// commented as it was 
						// $studentID 	= $this->model->saveStudent($studentID,$nameEnglish,$nameHindi,$dateBirth,$gender,$bloodGroup,$pwdStatus,$maritalStatus,$category,$subCategory,$religion,$nationality,$aadhaarNo,$hhIncome,$phoneNo,$email,$homeAddress,$homePIN,$homeState,$homeDistrict,$area,$policeStation,$commAddress,$commPIN,$remark,$status);
					}
					$no++;
					// save applicant record with studentID as foreign key
					$this->model->tupleID = $applicantID;
					$this->model->saveApplicant($rollNo,$studentID,$programID,$offerCategory,$offerRound,$remark);						

					// save sql log
					$this->model->sqlLog();
				}
				$this->errorText 		= "Offer to $no candidates made successfully.";
				$this->model->tupleID = $roundNo;
				break;
		}
		return $this->model->tupleID;
    }	

	public function manageCandidate($action, $candidateID) {
		$this->model->tableID 			= 'aaa_candidates';
		$this->model->tupleID 			= $candidateID;
		switch ($action) {
            case 'new':
				$this->editLock 		= '';
            	break;
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
				break;
			case 'save':
                // save record
				$programID				= $_POST['programID'];
				$programIDn				= $_POST['programIDn']; // new programID to make it editable (FTG)
				$roundNo				= $_POST['roundNo'];
				$rollNo					= $_POST['rollNo'];
				$roundName				= $_POST['roundName'];
				$allotedCategory		= $_POST['allotedCategory'];
				$allotedRank			= $_POST['allotedRank'];
				$choiceNo				= $_POST['choiceNo'] ? $_POST['choiceNo'] : 0;
				$quota					= $_POST['quota'];
				$willingness			= $_POST['willingness'];
				$status					= $_POST['status'];
				$rcName					= $_POST['rcName'];
				$remark 				= $_POST['remark'];
				
				$program				= $this->model->getProgram($programID);
				$degreeLevel			= $program['degreeLevel'];
				$programName			= $program['programName'];
				
				//get database values of below non editable fields
				$nameEnglish			= ucwords($_POST['nameEnglish']);
				$pwdStatus				= $_POST['pwdStatus'];
				$alumni					= $_POST['alumni'];	
				$gender					= $_POST['gender'];	
				$dateBirth				= $_POST['dateBirth'];
				$category				= $_POST['category'];
				$stateEligibility		= $_POST['stateEligibility'];
				$nationality			= $_POST['nationality'];
				$homeState 				= $this->model->getStateIDByStateName($stateEligibility);		// StateEligibility
				
				$enrolmentID			= $this->model->getEnrolmentIDByRollNo($rollNo);
				//if ($enrolmentID) {
				//	$this->errorText 	= "Enrollment of this candidate is already processed, can't change record now.";
				//} else {
					$this->model->saveCandidate($programIDn,$roundNo,$degreeLevel,$rollNo,$nameEnglish,$category,$pwdStatus,$gender,$dateBirth,$stateEligibility,$nationality,$programName,$allotedCategory,$allotedRank,$choiceNo,$quota,$roundName,$willingness,$status,$rcName,$alumni,$remark);

					$studentID			= $this->model->getStudentIDByRollNo($rollNo);
					$offerCategory		= $allotedCategory;
					$offerRound			= $roundNo;
					$this->model->tableID= 'aaa_applicants';
					
					if ($studentID) {
						$dob			= str_replace('/', '-', trim($dateBirth));
						$dt 			= explode('-', $dob);
						if (strlen($dt[0]) < 4 && strlen($dt[2]) == 2) {
							$dt[2]	= ($dt[2] > date('y') ? '19' : '20').$dt[2];
							$dateBirth	= implode('-', array_reverse($dt));
						} else { // date is already in yyyy-mm-dd format
							$dateBirth	= $dob;
						}		
						// save applicant record with studentID as foreign key
						$studentID 		= $this->model->saveStudent0($studentID,$nameEnglish,$dateBirth,$gender,$pwdStatus,$category,$nationality,$homeState,$remark);
						$this->model->tupleID= $this->model->getApplicantIDByRollNo($rollNo);
						$this->model->saveApplicant($rollNo,$studentID,$programIDn,$offerCategory,$offerRound,$remark);						
					} else {
						$no++;
						$studentID		= 0;
						$parentID		= 0;
						$educationID	= 0;
						$applicantID	= 0;
						// get form values of below editable fields
						$nameHindi		= '';
						$bloodGroup		= '';
						$maritalStatus	= 'U';
						$subCategory	= '';
						$religion		= 'H';
						$aadhaarNo		= '';

						$phoneNo		= '12345'; 	// unique
						$email			= '@'; 
						$homeAddress 	= '';
						$policeStation	= '';
						$commAddress 	= '';
						
						$xGrade 		= '';
						$xBoard 		= '';
						$xiiGrade 		= '';
						$xiiBoard 		= '';
						$ugGrade 		= '';
						$ugInstitute	= '';
						$pgGrade 		= '';
						$pgInstitute	= '';

						$fatherName		= '';
						$fatherProfession= ''; 	
						$fatherPhone	= '12345'; 		
						$fatherEmail	= '@'; 		
						$fatherAddress	= ''; 		
						$hhIncome		= 0;
						
						$motherName 	= '';
						$motherProfession= ''; 	
						$motherPhone	= ''; 		
						$motherEmail	= ''; 		
						$motherAddress	= ''; 		

						$guardianName	= '';
						$guardianProfession	= '';
						$relationWith	= 'Father';
						$guardianPhone	= '';
						$guardianEmail	= '';
						$guardianAddress= '';

						$area			= 0;
						$homeState		= 0;
						$homeDistrict	= 0;
						$homePIN		= 0;
						$commPIN		= 0;
						$xYear			= date("Y") - 7;
						$xiiYear		= date("Y") - 5;
						$ugYear			= date("Y") - 2;
						$pgYear			= date("Y");
						$lastScore		= 0;
						
						// save student record with phoneNo unique key
						$studentID 		= $this->model->saveStudent($studentID,$nameEnglish,$nameHindi,$dateBirth,$gender,$bloodGroup,$pwdStatus,$maritalStatus,$category,$subCategory,$religion,$nationality,$aadhaarNo,$hhIncome,$phoneNo,$email,$homeAddress,$homePIN,$homeState,$homeDistrict,$area,$policeStation,$commAddress,$commPIN,$remark,$status);
			
						// save parent record with studentID as foreign key
						$this->model->saveParent($parentID,$studentID,$fatherName,$fatherProfession,$fatherPhone,$fatherEmail,$fatherAddress,$motherName,$motherProfession,$motherPhone,$motherEmail,$motherAddress,$guardianName,$guardianProfession,$relationWith,$guardianPhone,$guardianEmail,$guardianAddress);
			
						// save education record with studentID as foreign key
						$this->model->saveEducation($educationID,$studentID,$xGrade,$xYear,$xBoard,$xiiGrade,$xiiYear,$xiiBoard,$ugGrade,$ugYear,$ugInstitute,$pgGrade,$pgYear,$pgInstitute,$lastScore);
			
						// save applicant record with studentID as foreign key
						$this->model->tupleID = $applicantID;
						$this->model->saveApplicant($rollNo,$studentID,$programIDn,$offerCategory,$offerRound,$remark);
					}
					
					// save sql log
					//$this->model->sqlLog();
					$this->model->tupleID= $candidateID;
					$this->errorText 	= 'Candidate record saved successfully.';
				//}
                break;
			case 'delete':
				if ($this->model->deleteCandidate() == 'Enrolled') {
					$this->errorText 	= "Candidate already enrolled, can't delete.";
				} else {
					$this->model->tupleID= 0;
					$this->errorText 	= 'Candidate record deleted successfully.';
				}
				break;
        }
		return $this->model->tupleID;
    }	

	public function manageExemption($action, $studentID) {
		$this->model->tableID 			= 'aaa_exemptions';
		$this->model->tupleID 			= $studentID;
		switch ($action) {
            case 'new':
			case 'edit':
				$this->editLock 		= '';
				break;
			case 'refresh':
            case 'open':
            case 'help':
			case 'trash':
				break;
			case 'save':
                // save record
				$docheadCodes			= $_POST['docheadCode'];
				$dateRemind				= $_POST['dateRemind'];
				$remark					= $_POST['remark'];
	            foreach ($docheadCodes as $docheadCode) {
	            	$this->model->saveExemption($studentID,$docheadCode,$dateRemind,$remark);
    	        }
    	        if ($docheadCode) {
    	        	$this->model->sqlLog();		
	                $this->errorText 	= 'Exemption granted successfully.';
            	} else {
                	$this->errorText 	= 'Nothing selected to grant.';
            	}
                break;
            case 'delete':
                // delete record
				$docheadCodes			= $_POST['docheadCode'];
	            foreach ($docheadCodes as $docheadCode) {
		            $this->model->deleteExemption($studentID, $docheadCode);
    	        }
    	        if ($docheadCode) {
    	        	$this->model->sqlLog();		
                	$this->errorText 	= 'Exemption revoked successfully.';
            	} else {
                	$this->errorText 	= 'Nothing selected to revoke.';
            	}
            	break;
        }
		return $this->model->tupleID;
    }	

	public function manageUpload($action, $studentID) {
		$this->model->tableID 			= 'aaa_uploads';
		$this->model->tupleID 			= $studentID; 

		$studentID 						= ($_POST['studentID'] ? $_POST['studentID'] : $studentID);
		$docheadCodes 					= $_POST['docheadCode'];
		$docCodes						= implode('-', $docheadCodes);
		
		$sourceFile						= basename($_FILES['fileToUpload']['name']);
		$extName						= strtolower(pathinfo($sourceFile, PATHINFO_EXTENSION));
				
		switch ($action) {
			case 'photoUpload':
				$targetPath 			= __DIR__. '/../uploads/photos/';
				$uploadFile				= strtolower("photo-{$studentID}-{$docCodes}.{$extName}");

			case 'signUpload':
				if (!$targetPath) {
					$targetPath 		= __DIR__. '/../uploads/signatures/';
					$uploadFile			= strtolower("sign-{$studentID}-{$docCodes}.{$extName}");
				}
				
			case 'docUpload':
                // save record, Check if image file is a actual image or fake image
				if (!$targetPath) {
					$targetPath 		= __DIR__. '/../uploads/documents/';
					$uploadFile			= strtolower("doc-{$studentID}-{$docCodes}.{$extName}");
				}
				$targetFile 			= $targetPath.$uploadFile;
				
				if ($_FILES['fileToUpload']['size'] > 1500000000) {
					$this->errorText = "Heavy file size";
					// Allow only certain file formats
				} else if ($extName == "jpg" || $extName == "jpeg" || $extName == "png" || $extName == "pdf") {
					// if everything is ok, try to upload file
					if (file_exists($targetFile)) {
						unlink($targetFile);
					}
					move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $targetFile);
					foreach ($docheadCodes as $code) {
						$this->model->tupleID = $this->model->saveUpload($studentID,$code,$uploadFile);
					}
					// reduce file size
					// convert  -resize 50% uploads/signatures/sign-915-sig.jpg uploads/signatures/sign-915-sig1.jpg
					// convert -resize 1024X768  source.png dest.jpg
					$this->model->sqlLog();
					$this->errorText 	= 'Upload successful.';
				} else {
					$this->errorText	= 'Only image/pdf files';
				}	
				$this->model->tupleID= $studentID;
				break;

			case 'attachmentUpload':
				$alertID				= $studentID;
				foreach ($_FILES['attachments']['error'] as $key => $error) {
					// upload attachments
					$tmpName 			= $_FILES['attachments']['tmp_name'][$key];
					$fileName 			= $targetPath. 'attachments/' .strtolower(basename($_FILES['attachments']['name'][$key]));
					if ($error == UPLOAD_ERR_OK) {
						move_uploaded_file($tmpName, $fileName);
						$this->errorText= 'Upload successful.';
						$attachments .= ($attachments ? ',' : '').strtolower(basename($_FILES['attachments']['name'][$key]));
					} else {
						$this->errorText= 'Error occurred.';
					}
				}
				if ($attachments) $this->model->saveAlertAttachments($alertID, $attachments);
				break;
			case 'photosUpload':
			case 'photosupload':
                $targetPath 			= __DIR__. '/../uploads/photos/';
				$this->errorText 		= '';
				$i 						= 0;
				$extName				= strtolower(pathinfo($_FILES['fileToUpload']['name'][$i], PATHINFO_EXTENSION));

				$graduand				= $this->model->getGraduand($studentID);
				$enrolmentNo 			= $graduand['enrolmentNo'];
				$uploadFile		 		= strtolower($enrolmentNo. '.' .$extName);
				$targetFile 			= $targetPath.$uploadFile;
				//Determine filetype
				//switch ($_FILES['fileToUpload']['type']) {
				//	case 'image/jpeg': $ext = "jpg"; break;
				//	case 'image/png': $ext 	= "png"; break;
				//	default: $ext = ''; break;
				//}
				if ($enrolmentNo) {
					if ($_FILES['fileToUpload']['size'][$i] > 1500000000) {
						$this->errorText = "Heavy file size";
						// Allow only certain file formats
					} else if ($extName == "jpg" || $extName == "jpeg" || $extName == "png") {
						// if everything is ok, try to upload file
						if (file_exists($targetFile)) unlink($targetFile);
						if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'][$i], $targetFile)) {
							$this->errorText = $uploadFile. ' Upload successful.';
						} else {
							$this->errorText = $uploadFile. ' Upload failed.';
						}
					} else {
						$this->errorText = 'JPG file only.';
					}
				} else {
					foreach ($_FILES['fileToUpload']['name'] as $photo) {
						$extName		= strtolower(pathinfo($photo, PATHINFO_EXTENSION));
						$photoFile 		= $targetPath. 'photos/' .strtolower($enrolmentNo. '.' .$extName);
						$no++;
						if ($_FILES['fileToUpload']['size'][$i] > 1500000000) {
							$this->errorText .= $no. ") $photo too big. ";
						} else if ($extName == "jpg" || $extName == "jpeg" || $extName == "png") {
							if (file_exists($photoFile)) unlink($photoFile);
							// Allow only jpg file format & if everything is ok, try to upload file
							move_uploaded_file($_FILES['fileToUpload']['tmp_name'][$i], $photoFile);
							$this->errorText .= $no. ") $enrolmentNo photo uploaded. ";
						} else {
							$this->errorText .= $no. ") $photo not jpg. ";
						}
						$i++;
					}
					if (!$photo) $this->errorText= "Select an image file.";
				}
				$this->model->tupleID 	= $studentID;
				break;
            
			case 'delete':
                // delete record
                $uploadID 				= $studentID; //we reach here with applicantID, however it is actually uploadID
				$row 					= $this->model->getUpload($uploadID);
				$fileName 				= $row['fileName'];
				$this->model->tupleID 	= $row['uploadID'];
				$this->model->deleteUpload();
                $this->model->sqlLog();
                
				shell_exec("rm -f {$targetPath}documents/{$fileNmae}");
                $this->errorText 		= 'Upload file deleted successfully.';
				$studentID				= $_POST['studentID'];
				$this->model->tupleID 	= $studentID;
				break;
        }
		return $this->model->tupleID;
    }	

	public function managePayment($action, $studentID) {
		$this->model->tableID 			= 'aaa_payments';
		$this->model->tupleID 			= 0;
		switch ($action) {
			case 'edit':
				$this->editLock 		= '';
				break;
			case 'online':
				$pg						= $this->params[0]; 	// ATOM or HDFC
				$accountType			= $this->params[1]; 	// 1 for fees, 2 for mess
				$paymentMode			= 'PG';			 		// online payment gateway
				$currency  				= 'INR';				// missing in PG response
				
				if ($pg == 'ATOM') {
					$paymentNo			= $_REQUEST['mmp_txn']; 	// transaction no.
					$datePayment		= date("Y-m-d"); // $_POST['date']; 		// date of transaction
					$bankName			= $_REQUEST['bank_name']; 	// name of bpayee bank
					$status				= $_REQUEST['f_code']; 	// status, OK for success, F for failure
					$amount				= $_REQUEST['amt']; 		// amount
					
					if (strtoupper($status) == 'OK') {
						$this->model->savePayment($studentID,$accountType,$paymentMode,$paymentNo,$bankName,$amount,$currency,$datePayment);
						$this->model->sqlLog();
						$this->errorText = "Transaction ID: $paymentNo => completed successfully.";
					} else {
						$this->errorText = $this->accountTypes[$accountType]. " payment transaction failed.";
					}
				} else if ($_POST['ResponseCode'] == 0) {						
					$paymentNo 			= $_POST['PaymentID'];	// payment ID
					$bankName 			= 'HDFC';				// missing in hdfc response
					$amount  			= $_POST['Amount'];
					$datePayment 		= $_POST['DateCreated'];
					
					$this->model->savePayment($studentID,$accountType,$paymentMode,$paymentNo,$bankName,$amount,$currency,$datePayment);
					$this->model->sqlLog();
					$this->errorText 	= "Transaction ID: $paymentNo => " .$_POST['ResponseMessage'];
				} else {
					$this->errorText 	= "Unidentified payment gateway.";
				}
				break;
			case 'save':
                // save record
				$accountType			= $this->params[0];
				$currency				= $this->params[2];
				
				$paymentMode			= $_POST['paymentMode'];
				$paymentNo				= $_POST['paymentNo'];
				$bankName				= ucwords($_POST['bankName']);
				$payAmount				= $_POST['payAmount'];
				$datePayment			= $_POST['datePayment'];
				
				if ($paymentNo) {
					$this->model->savePayment($studentID,$accountType,$paymentMode,$paymentNo,$bankName,$payAmount,$currency,$datePayment);
					$this->model->sqlLog();
					$this->errorText 	= $this->accountTypes[$accountType]. " payment saved successfully.";
				} else {
					$this->errorText 	= "Payment No. is missing.";
				}
				break;
			case 'change':
                // save record
				$paymentID				= $this->params[0];	
				$accountType			= $_POST['accountType']; 				
				$bankName				= ucwords($_POST['bankName']);
				$paymentMode			= $_POST['paymentMode'];
				$datePayment			= $_POST['datePayment'];
				$paymentNo				= $_POST['paymentNo'];
				$currency				= $_POST['currency'];
				$payAmount				= $_POST['payAmount'];
				
				if ($paymentNo) {
					$this->model->tupleID = $paymentID;
					$this->model->savePayment($studentID,$accountType,$paymentMode,$paymentNo,$bankName,$payAmount,$currency,$datePayment);
					$this->model->sqlLog();
					$this->errorText 	= $this->accountTypes[$accountType]. " payment saved successfully.";
				} else {
					$this->errorText 	= "Payment No. is missing.";
				}
				break;
			case 'excel':
				$programID				= $this->params[0];
				$rows 					= $this->model->paymentSummary($programID);
				foreach ($rows as $row) {
					$i++;	
					$j = 0;			
					$vals = '';
					foreach ($row as $key => $value) {
						if ($i == 1) $colh .= '"' .ucfirst($key). '",';
						$vals .= '"' .$value. '",';
					}
					$colv .= rtrim($vals, -1). "\n";
				}
				$data 					= rtrim($colh, -1). "\n" .$colv;
				$f 						= fopen("uploads/payment-{$programID}-" .$_SESSION['batchYear']. '.csv' , 'wb');
				fwrite($f , $data);
				fclose($f);
				return $programID;
				break;
        }
		$this->model->tupleID 			= $studentID;
		return $this->model->tupleID;
    }	

	public function manageApplicant($action, $applicantID) {
		$this->model->tableID 			= 'aaa_applicants';
		$this->model->tupleID 			= $applicantID;
		$rollNo							= $this->params[0];
		$this->editLock 				= '';
		switch ($action) {
			case 'edit':
				$this->editLock 		= '';
				break;		
			case 'save':
                // save record
				$candidateID			= $this->model->getCandidateIDByRollNo($rollNo);
                $candidate				= $this->model->getCandidate($candidateID);
				$programID				= $candidate['programID'];
				$offerCategory			= $candidate['offerCategory'];
				$remark 				= $candidate['remark'];
								
				$studentID				= $this->model->getStudentIDByRollNo($rollNo);
				$parentID				= $this->model->getParentIDByStudentID($studentID);  	// not allowed to change
				$educationID			= $this->model->getEducationIDByStudentID($studentID);	// not allowed to change
				$accountID				= $this->model->getAccountIDByStudentID($studentID);	// not allowed to change
								
				$applicant				= $this->model->getApplicant($applicantID);
				//get database values of below non editable fields
				$nameEnglish			= ucwords($applicant['nameEnglish']);	// not allowed to change
				$dateBirth				= $applicant['dateBirth'];		// not allowed to change
				$pwdStatus				= $applicant['pwdStatus'];		// not allowed to change
								
				// get form values of below editable fields
				$nameHindi				= $_POST['nameHindi'];
				$gender 				= $_POST['gender'];
				$bloodGroup				= $_POST['bloodGroup'];
				$maritalStatus			= $_POST['maritalStatus'];
				$category				= $_POST['category'];
				$subCategory			= $_POST['subCategory'];
				$religion				= $_POST['religion'];
				$nationality			= $_POST['nationality'];
				$aadhaarNo				= $_POST['aadhaarNo'];
				$hhIncome				= $_POST['hhIncome'];

				$phoneNo				= $_POST['phoneNo']; 			// unique
				$email					= $_POST['email']; 
				$homeAddress 			= $_POST['homeAddress'];
				$homePIN 				= $_POST['homePIN'];
				$area					= $_POST['area'];
				$policeStation			= $_POST['policeStation'];
				$homeState				= $_POST['homeState']; 			// changes for CCMT/DASA etc.
				$homeDistrict 			= $_POST['homeDistrict'];
				$commAddress 			= $_POST['commAddress'];
				$commPIN 				= $_POST['commPIN'];
				
				$xGrade 				= $_POST['xGrade'];
				$xYear 					= $_POST['xYear'];
				$xBoard 				= $_POST['xBoard'];
				$xiiGrade 				= $_POST['xiiGrade'];
				$xiiYear 				= $_POST['xiiYear'];
				$xiiBoard 				= $_POST['xiiBoard'];
				$ugGrade 				= $_POST['ugGrade'];
				$ugYear 				= $_POST['ugYear'];
				$ugInstitute			= $_POST['ugInstitute'];
				$pgGrade 				= $_POST['pgGrade'];
				$pgYear 				= $_POST['pgYear'];
				$pgInstitute 			= $_POST['pgInstitute'];
				$lastScore				= $_POST['lastScore'];
				$categoryRank			= $_POST['categoryRank'];

				$fatherName				= $_POST['fatherTitle']. ' ' .ucwords($_POST['fatherName']);
				$fatherProfession		= $_POST['fatherProfession']; 	
				$fatherPhone			= $_POST['fatherPhone']; 		
				$fatherEmail			= $_POST['fatherEmail']; 		
				$fatherAddress			= $_POST['fatherAddress']; 		
				
				$motherName 			= $_POST['motherTitle']. ' ' .ucwords($_POST['motherName']);
				$motherProfession		= $_POST['motherProfession']; 	
				$motherPhone			= $_POST['motherPhone']; 		
				$motherEmail			= $_POST['motherEmail']; 		
				$motherAddress			= $_POST['motherAddress']; 		

				$guardianName			= $_POST['guardianTitle']. ' ' .ucwords($_POST['guardianName']);
				$guardianProfession		= $_POST['guardianProfession']; 	
				$relationWith			= $_POST['relationWith'];
				$guardianPhone			= $_POST['guardianPhone']; 			
				$guardianEmail			= $_POST['guardianEmail']; 			
				$guardianAddress		= $_POST['guardianAddress']; 		

				$accountNo				= ($_POST['accountNo'] ? $_POST['accountNo'] : 0); 	
				$holderName				= ucwords($_POST['holderName']); 	
				$bankName				= ucwords($_POST['bankName']); 	
				$ifscCode				= strtoupper($_POST['ifscCode']); 	

				if (!$homePIN) 			$homePIN= 0;
				if (!$commPIN)			$commPIN= 0;
				if (!$xYear) 			$xYear 	= 0;
				if (!$xiiYear) 			$xiiYear= 0;
				if (!$ugYear) 			$ugYear	= 0;
				if (!$pgYear) 			$pgYear	= 0;
				if (!$lastScore) 		$lastScore = 0;
				if (!$categoryRank)		$categoryRank = intval($lastScore);

				if (!$parentID) 	$parentID 		= 0;
				if (!$educationID) 	$educationID	= 0;
				if (!$accountID) 	$accountID		= 0;
				
				if ($studentID) {
					// save student record with phoneNo unique key
					$studentID = $this->model->saveStudent($studentID,$nameEnglish,$nameHindi,$dateBirth,$gender,$bloodGroup,$pwdStatus,$maritalStatus,$category,$subCategory,$religion,$nationality,$aadhaarNo,$hhIncome,$phoneNo,$email,$homeAddress,$homePIN,$homeState,$homeDistrict,$area,$policeStation,$commAddress,$commPIN,$remark,$status);
						
					// save parent record with studentID as foreign key
					$this->model->saveParent($parentID,$studentID,$fatherName,$fatherProfession,$fatherPhone,$fatherEmail,$fatherAddress,$motherName,$motherProfession,$motherPhone,$motherEmail,$motherAddress,$guardianName,$guardianProfession,$relationWith,$guardianPhone,$guardianEmail,$guardianAddress);
						
					// save education record with studentID as foreign key
					$this->model->saveEducation($educationID,$studentID,$xGrade,$xYear,$xBoard,$xiiGrade,$xiiYear,$xiiBoard,$ugGrade,$ugYear,$ugInstitute,$pgGrade,$pgYear,$pgInstitute,$lastScore,$categoryRank);
						
					// save account record with studentID as foreign key
					$this->model->saveAccount($accountID,$studentID,$accountNo,$holderName,$bankName,$ifscCode);
						
					// save applicant record with studentID as foreign key
					$this->model->saveApplicant($rollNo,$studentID,$programID,$offerCategory,$offerRound,$remark);
				
					// save sql log
					$this->model->sqlLog();
					$this->errorText 	= 'Applicant record saved successfully.';
				} else {
					$this->errorText 	= 'Student record missing.';
				}
                break;
        }
		return $this->model->tupleID;
    }	

	public function manageEnrolment($action, $enrolmentID) {
		$this->model->tableID 			= 'aaa_enrolments';
		$this->model->tupleID 			= $enrolmentID;
		switch ($action) {
            case 'new':
				break;
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
			case 'help':
			case 'trash':
				break;
			case 'save':	
                // save record
				$studentID				= $_POST['studentID'];
				//$applicantID			= $this->model->getApplicantIDByStudentID($studentID);
				$rollNo					= $this->model->getRollNoByStudentID($studentID);
				$candidateID			= $this->model->getCandidateIDByRollNo($rollNo);
                $candidate				= $this->model->getCandidate($candidateID);
				$programID				= $candidate['programID'];
				$enrolCategory			= $candidate['offerCategory'];
				//$offerRound			= $candidate['roundNo'];
				//$homeState			= $candidate['stateEligibility']; // changes for CCMT/DASA
				$remark 				= $candidate['remark'];
				$status					= 'Enrolled';

                // check whether new or old enrolment
				$enrolmentNo			= $this->model->getEnrolmentNoByStudentID($studentID);
				if (!$enrolmentNo) { // new
					$program       		= $this->model->getProgram($programID);
                	$enrolmentID		= 0;
                	$this->model->tupleID	= $enrolmentID;
                	$enrolmentNo   		= $program['rollnoPrefix'] .$_SESSION['batchYear']. ($program['lastRollno'] < 9 ? '00' : ($program['lastRollno'] < 99 ? '0' : '')) . ($program['lastRollno'] + 1);				
				} else { // old
					$enrolmentID 		= $this->model->getEnrolmentIDByStudentID($studentID);
					//$allotteeID 		= $this->model->getAllotteeIDByAllotteeNo($enrolmentNo);
				}
				
				$parentID				= $this->model->getParentIDByStudentID($studentID);  	// not allowed to change
				$educationID			= $this->model->getEducationIDByStudentID($studentID);	// not allowed to change
				$accountID				= $this->model->getAccountIDByStudentID($studentID);	// not allowed to change
				
				if (!$parentID) 	$parentID 		= 0;
				if (!$educationID) 	$educationID	= 0;
				if (!$accountID) 	$accountID		= 0;

				// get form values of below editable fields
				$nameEnglish			= ucwords($_POST['nameEnglish']);	// not allowed to change
				$nameHindi				= $_POST['nameHindi'];
				$dateBirth				= $_POST['dateBirth'];		// not allowed to change
				$gender					= $_POST['gender'];			// not allowed to change
				$pwdStatus				= $_POST['pwdStatus'];		// not allowed to change
				$bloodGroup				= $_POST['bloodGroup'];
				$maritalStatus			= $_POST['maritalStatus'];
				$category				= $_POST['category'];
				$subCategory			= $_POST['subCategory'];
				$religion				= $_POST['religion'];
				$nationality			= $_POST['nationality'];
				$aadhaarNo				= $_POST['aadhaarNo'];
				$hbookNo				= $_POST['hbookNo'];
				$hhIncome				= $_POST['hhIncome'];
				$phoneNo				= $_POST['phoneNo']; 		// unique
				$email					= $_POST['email']; 
				$homeAddress 			= $_POST['homeAddress'];
				$homePIN 				= $_POST['homePIN'];
				$area					= $_POST['area'];
				$policeStation			= $_POST['policeStation'];
				$homeState				= $_POST['homeState'];		// changes for CCMT/DASA
				$homeDistrict 			= $_POST['homeDistrict'];
				$commAddress 			= $_POST['commAddress'];
				$commPIN 				= $_POST['commPIN'];
				$xGrade 				= $_POST['xGrade'];
				$xYear 					= $_POST['xYear'];
				$xBoard 				= $_POST['xBoard'];
				$xiiGrade 				= $_POST['xiiGrade'];
				$xiiYear 				= $_POST['xiiYear'];
				$xiiBoard 				= $_POST['xiiBoard'];
				$ugGrade 				= $_POST['ugGrade'];
				$ugYear 				= $_POST['ugYear'];
				$ugInstitute			= $_POST['ugInstitute'];
				$pgGrade 				= $_POST['pgGrade'];
				$pgYear 				= $_POST['pgYear'];
				$pgInstitute			= $_POST['pgInstitute'];
				$lastScore				= $_POST['lastScore'];
				$categoryRank			= $_POST['categoryRank'];
				$abookNo				= $_POST['abookNo1']. '-' .$_POST['abookNo2'];

				$fatherName				= $_POST['fatherTitle']. ' ' .ucwords($_POST['fatherName']);
				$fatherProfession		= $_POST['fatherProfession']; 	
				$fatherPhone			= $_POST['fatherPhone']; 		
				$fatherEmail			= $_POST['fatherEmail']; 		
				$fatherAddress			= $_POST['fatherAddress']; 		
				
				$motherName 			= $_POST['motherTitle']. ' ' .ucwords($_POST['motherName']);
				$motherProfession		= $_POST['motherProfession']; 	
				$motherPhone			= $_POST['motherPhone']; 		
				$motherEmail			= $_POST['motherEmail']; 		
				$motherAddress			= $_POST['motherAddress']; 		

				$guardianName			= $_POST['guardianTitle']. ' ' .ucwords($_POST['guardianName']);
				$guardianProfession		= $_POST['guardianProfession']; 	
				$relationWith			= $_POST['relationWith'];
				$guardianPhone			= $_POST['guardianPhone']; 		
				$guardianEmail			= $_POST['guardianEmail']; 		
				$guardianAddress		= $_POST['guardianAddress']; 	

				$accountNo				= $_POST['accountNo']; 	
				$holderName				= ucwords($_POST['holderName']); 	
				$bankName				= ucwords($_POST['bankName']); 	
				$ifscCode				= strtoupper($_POST['ifscCode']); 	
				$remark					= $_POST['remark'];	// AAA may over write remark
				
				if (!$homeDistrict)		$homeDistrict 	= 0;
				if (!$homePIN) 			$homePIN		= 0;
				if (!$commPIN)			$commPIN		= 0;
				if (!$xYear) 			$xYear 			= 0;
				if (!$xiiYear) 			$xiiYear		= 0;
				if (!$ugYear) 			$ugYear			= 0;
				if (!$pgYear) 			$pgYear			= 0;
				if (!$lastScore) 		$lastScore 		= 0;
				if (!$hbookNo)			$hbookNo		= 0;
				
				if ($studentID) {
					if ($enrolmentID) $this->model->tupleID = $enrolmentID; // so that multple enrolments of same student can be checked from multiple tabs 
					
					// save student record with phoneNo unique key
					$studentID = $this->model->saveStudent($studentID,$nameEnglish,$nameHindi,$dateBirth,$gender,$bloodGroup,$pwdStatus,$maritalStatus,$category,$subCategory,$religion,$nationality,$aadhaarNo,$hhIncome,$phoneNo,$email,$homeAddress,$homePIN,$homeState,$homeDistrict,$area,$policeStation,$commAddress,$commPIN,$remark,$status);
					$this->model->sqlLog();

					// save parent record with studentID as foreign key
					$this->model->saveParent($parentID,$studentID,$fatherName,$fatherProfession,$fatherPhone,$fatherEmail,$fatherAddress,$motherName,$motherProfession,$motherPhone,$motherEmail,$motherAddress,$guardianName,$guardianProfession,$relationWith,$guardianPhone,$guardianEmail,$guardianAddress);
					$this->model->sqlLog();

					// save education record with studentID as foreign key
					$this->model->saveEducation($educationID,$studentID,$xGrade,$xYear,$xBoard,$xiiGrade,$xiiYear,$xiiBoard,$ugGrade,$ugYear,$ugInstitute,$pgGrade,$pgYear,$pgInstitute,$lastScore,$categoryRank);
					$this->model->sqlLog();

					// save account record with studentID as foreign key
					$this->model->saveAccount($accountID,$studentID,$accountNo,$holderName,$bankName,$ifscCode);
					
					// save enrolment record with studentID as foreign key
					$this->model->saveEnrolment($enrolmentNo,$studentID,$programID,$enrolCategory,$hbookNo,$abookNo,$remark);
					$this->model->sqlLog();
					
					// hostel room allotment
					if ($_SESSION['batchYear'] == date('Y') && !$this->model->getAllotmentIDByAllotteeNo($enrolmentNo)) echo "<script language='text/javascript'>popWindow('https://erp.iiita.ac.in/inner/hms/booking/open/0/" .$this->model->tupleID. "', 'Hostel Allotment', 900, 300);</script>";

					$this->errorText	= $enrolmentNo. ' record saved successfully.';
				} else {
					$this->errorText= 'Student record missing.';
				}
				break;
			case 'mail':
				//send email acknowledgment to student
				$enrolment 				= $this->model->getEnrolment($this->model->tupleID);
				$emailsTo				= '';//$enrolment['enrolmentNo']. '@iiita.ac.in,' .$enrolment['email'];
				$subject				= 'Welcome at IIIT Allahabad';
				
				$body = "Dear <b>" .strtoupper($enrolment['nameEnglish']). "</b><br>
	Many many congratulation !!!<br>
You have been enrolled in <b>" .$enrolment['programCode']. "</b> program at IIIT Allahabad with following details.<br><br>";
					 
				$body .= "<table width='100%'>";
				foreach ($enrolment as $key => $value) {
					switch ($key) {
						case 'homeDistrict':
							$value 		= $this->model->getDistrictNameByDistrictID($value);
							break;
						case 'homeState':
							$value 		= $this->model->getStateNameByStateID($value);
							break;
						default:
							if (strpos($key, 'ID')) $value = '';
							else {
								$value 	= preg_replace( "/\r|\n/", '', $value );
								$value 	= str_replace(array("\r\n", "\r", "\n"), '', $value);
							}
							break;
					}
					
					if ($value && !intval($value)) $body .= "<tr valign='top'><td nowrap>" .ucfirst($key). "</td><td>:</td><td>$value</td></tr>";
					if (strlen($value) > 1 && intval($value)) $body .= "<tr valign='top'><td nowrap>" .ucfirst($key). "</td><td>:</td><td nowrap>$value</td></tr>";
			    }
			    $body .= "</table>";

				$this->erpMailer($emailTo, $subject, $body, $emailsCC, $emailsBCC);
                $this->errorText 		= 'Enrollment acknowledgement mailed successfully.';
				break;
            case 'delete':
                // delete record
                //$this->model->deleteEnrolment();
                //$this->model->sqlLog();
                $this->errorText 		= 'Enrollment record deletion not permitted';//ed successfully.';
            	break;
			case 'excel':
				$rows 					= $this->model->listStudents($programID);
				foreach ($rows as $row) {
					$i++;	
					$j = 0;			
					$vals = '';
					foreach ($row as $key => $value) {
						$j++;
						if ($j > 1) {
							if ($i == 1) $colh .= '"' .ucfirst($key). '",';
							$vals .= '"' .$value. '",';
						}
					}
					$colv .= rtrim($vals, -1). "\n";
				}
				$data 					= rtrim($colh, -1). "\n" .$colv;
				$f 						= fopen("uploads/enrolment-{$programID}-" .$_SESSION['batchYear']. '.csv' , 'wb');
				fwrite($f , $data);
				fclose($f);
				break;
        }
		return $this->model->tupleID;
    }	

	public function manageInsurence($action, $enrolmentID) {
		$this->model->tableID 			= 'aaa_mcaips';
		$this->model->tupleID 			= $enrolmentID;
		switch ($action) {
            case 'new':
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
            case 'help':
			case 'trash':
				break;
			case 'save':	
                // save insurence record
				//echo '<pre>' .var_dump($_POST). '</pre>';

				$spouseName				= $_POST['spouseName'];
               	$spouseAge 				= $_POST['spouseAge'];
				$spousePhone			= $_POST['spousePhone'];
				$spouseEmail			= $_POST['spouseEmail'];
				$spouseAddress			= $_POST['spouseAddress'];
				$spousePIN				= $_POST['spousePIN'];
				$child1Name				= $_POST['child1Name'];
				$child1Age		 		= $_POST['child1Age'];
				$child1Gender			= $_POST['child1Gender'];
				$child1Phone 			= $_POST['child1Phone'];
				$child1Email			= $_POST['child1Email'];
				$child1Address			= $_POST['child1Address'];
				$child1PIN				= $_POST['child1PIN'];
				$child2Name				= $_POST['child2Name'];
				$child2Age				= $_POST['child2Age'];
				$child2Gender 			= $_POST['child2Gender'];
				$child2Phone			= $_POST['child2Phone'];
				$child2Email			= $_POST['child2Email'];
				$child2Address			= $_POST['child2Address'];
				$child2PIN				= $_POST['child2PIN'];
				$knownDiseases			= $_POST['knownDiseases'];

               	if (!$spouseAge) 		$spouseAge 	= 0;
				if (!$spousePIN) 		$spousePIN	= 0;
				if (!$child1Age) 		$child1Age	= 0;
				if (!$child1PIN) 		$child1PIN	= 0;
				if (!$child2Age) 		$child2Age	= 0;
				if (!$child2PIN) 		$child2PIN	= 0;

				$this->model->saveInsurence($spouseName,$spouseAge,$spousePhone,$spouseEmail,$spouseAddress,$spousePIN,$child1Name,$child1Age,$child1Gender,$child1Phone,$child1Email,$child1Address,$child1PIN,$child2Name,$child2Age,$child2Gender,$child2Phone,$child2Email,$child2Address,$child2PIN,$knownDiseases);
				$this->model->sqlLog();
				$this->errorText 		= 'MCAIP record saved successfully.';
				break;
			case 'mail':
				//send email acknowledgment to student
				$data = $this->model->getInsurence($this->model->tupleID);
				$str = "Dear Student!
				<br><br>
				Congratulation!!!<br>
				You are enrolled at IIIT Allahabad with following details.
				<br><br>";
				 
				$str .= "<table width='100%'>";
				foreach ($data as $key => $value) {
					$str .= "<tr><td nowrap>" .ucfirst($key). "</td><td>$value</td></tr>";
				}
				$str .= "</table>";
				$this->erpMailer($data['email'], 'MCAIP Acknowledgment', $str);
                $this->errorText = 'MCAIP acknowledgment mailed to student.';
		}
		return $this->model->tupleID;
    }	

	public function manageSliding($action, $enrolmentID) {
		$this->model->tableID 			= 'aaa_enrolments';
		$this->model->tupleID 			= $enrolmentID;
		switch ($action) {
            case 'new':
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
            case 'help':
			case 'trash':
				break;
			case 'save':	
                // save enrollment record
				$programID				= $_POST['programID'];
				$remark					= $_POST['remark'];

				$xenrolment				= $this->model->getEnrolment($enrolmentID);
				$xprogramID				= $xenrolment['programID'];
				$programCode			= $xenrolment['programCode'];
				$xenrolmentNo			= $xenrolment['enrolmentNo'];
				$studentID				= $xenrolment['studentID'];
				$enrolCategory			= $xenrolment['enrolCategory'];
				$hbookNo				= $xenrolment['hbookNo'];
				$abookNo				= $xenrolment['abookNo'];
				$hostelID				= $xenrolment['hostelID'];
				$roomID					= $xenrolment['roomID'];
				$remark 				.= " [Slided from $programCode $xenrolmentNo]";

				$program 				= $this->model->getProgram($programID);
				$enrolmentNo			= $program['rollnoPrefix'] . $_SESSION['batchYear'] . ($program['lastRollno'] < 10 ? '00' : ($program['lastRollno'] < 100 ? '0' : '')) . ($program['lastRollno'] + 1);

				$this->model->saveSliding($enrolmentNo,$studentID,$programID,$enrolCategory,$hbookNo,$abookNo,$hostelID,$roomID,$remark);
				$this->model->sqlLog();
				
				$allotmentID			= $this->model->getAllotmentIDByAllotteeNo($xenrolmentNo);
				echo "<script language='text/javascript'>popWindow('inner/hms/booking/change/0/$enrolmentID/$enrolmentNo', 'Hostel Allotment', 1000, 600);</script>";
				
				// return to enrolment page for receipt and id card print
				$this->menu				= 'Enrolment';
				$this->params[0]		= $programID;
			
				$this->errorText 	= $enrolmentNo. ' record saved successfully.';	
				break;
			case 'mail':
				//send email acknowledgment to student
				$enrolment 				= $this->model->getEnrolment($enrolmentID);
				$emailsTo				= '';//$enrolment['enrolmentNo']. '@iiita.ac.in,' .$enrolment['email'];
				$subject				= 'Sliding enrollment acknowledment';
				
				$body = "Dear <b>" .strtoupper($enrolment['nameEnglish']). "</b><br>
	Many many congratulation !!!<br>
You have been enrolled in <b>" .$enrolment['programCode']. "</b> program at IIIT Allahabad with following details.<br><br>";
					 
				$body .= "<table width='100%'>";
				foreach ($enrolment as $key => $value) {
					switch ($key) {
						case 'homeDistrict':
							$value 		= $this->model->getDistrictNameByDistrictID($value);
							break;
						case 'homeState':
							$value 		= $this->model->getStateNameByStateID($value);
							break;
						default:
							if (strpos($key, 'ID')) $value = '';
							else {
								$value 	= preg_replace( "/\r|\n/", '', $value );
								$value 	= str_replace(array("\r\n", "\r", "\n"), '', $value);
							}
							break;
					}
					
					if ($value && !intval($value)) $body .= "<tr valign='top'><td nowrap>" .ucfirst($key). "</td><td>:</td><td>$value</td></tr>";
					if (strlen($value) > 1 && intval($value)) $body .= "<tr valign='top'><td nowrap>" .ucfirst($key). "</td><td>:</td><td nowrap>$value</td></tr>";
			    }
			    $body .= "</table>";

				$this->erpMailer($emailTo, $subject, $body, $emailsCC, $emailsBCC);
                $this->errorText 		= 'Enrollment acknowledgement mailed successfully.';
				break;
				
        }
		return $this->model->tupleID;
    }	

	public function manageWithdrawal($action, $withdrawID) {
		$this->model->tableID 			= 'aaa_withdrawals';
		$this->model->tupleID 			= $withdrawID;

		switch ($action) {
            case 'new':
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
            case 'help':
			case 'trash':
				break;
			case 'save':	
				// save withdrawal record
				$studentID				= $_POST['studentID'];
               	$dateWithdraw 			= $_POST['dateWithdraw'];
				$withdrawReason			= $_POST['withdrawReason'];
				$accountNo				= $_POST['accountNo'];
				$holderName				= $_POST['holderName'];
				$bankName				= $_POST['bankName'];
				$ifscCode				= $_POST['ifscCode'];
				$remark					= $_POST['remark'];

				if ($accountNo && $bankName && $ifscCode) { 
					// save account record with studentID as foreign key
					$accountID = $this->model->getAccountIDByStudentID($studentID);
					//echo $studentID.'-'.$accountID.'aa';
					$this->model->saveAccount($accountID,$studentID,$accountNo,$holderName,$bankName,$ifscCode);
					// save withdrawal
					$this->model->saveWithdrawal($studentID,$dateWithdraw,$withdrawReason,$accountNo,$holderName,$bankName,$ifscCode,$remark);
					$this->model->sqlLog();
					$this->errorText 	= 'Withdrawal record saved successfully.';
				} else {
					$this->errorText 	= 'Account details are mandatory here.';
				}
				break;
			case 'revoke':	
				// save withdrawal record
				$remark					= $_POST['remark'];
				$this->model->deleteWithdrawal($studentID,$remark);
				$this->model->sqlLog();
				$this->errorText 		= 'Withdrawal record deleted successfully.';
				break;
			case 'mail':
				$alertID				= $this->model->getAlertIDBySubjectID(7);
				$alert 					= $this->model->getAlert($alertID); 			// 7 is id of withdrawal alert
				$subject 				= $this->reminders[$alert['subjectID']];  		// get subject text
				$message 				= $alert['message'];
				$emailsTo 				= 'mmishra@iiita.ac.in';//$alert['emailsTo'];
				$emailsCC 				= 'mmishra@iiita.ac.in';//$alert['emailsCC'];
				$emailsBCC 				= 'mmishra@iiita.ac.in';//$alert['emailsBCC'];
				//$attachments			= $alert['attachments'];
				
				$enrolmentID			= $this->model->getEnrolmentIDByWithdrawID($withdrawID);
				$enrolment 				= $this->model->getEnrolment($enrolmentID);
				$body = $message. "<br><br>
				<table width='100%' border='1' style='line-height: 40px; border-collapse: collapse'>
				<tr valign='middle'>
				<th width='25%' nowrap>Enrolment No.: " .$enrolment['enrolmentNo']. "</th>
				<th width='50%' nowrap>Name: " 			.$enrolment['nameEnglish']. ' (' .$enrolment['nameHindi']. ")</th>
				<th width='30%' nowrap>Category: " 		.$enrolment['category']. "</th>
				</tr><tr>
				<th nowrap>Enrollment Date: " 			.$enrolment['dateEnrolment']. "</th>
				<th>Remark: " 							.$enrolment['remark']. "</th>
				<th nowrap>Program: " 					.$enrolment['programCode']. "</th>
				</tr>
				</table>";
				echo $body;//$this->erpMailer($emailsTo, $subject, $body, $emailsCC, $emailsBCC);
				
				//$this->model->updateAlert($alertID);
				$this->errorText 		= 'Admission withdrawn notification mailed.';
        		break;
		}
		return $this->model->tupleID;
    }	

	public function manageNodeficit($action, $studentID) {
		$this->model->tableID 			= 'aaa_uploads';
		$this->model->tupleID 			= $studentID;
		
		switch ($action) {
			case 'docUpload': // deficit document upload
				// save record
				$docheadCodes 			= $_POST['docheadCode'];
				$docCodes				= implode('-', $docheadCodes);

				$studentID 				= $_POST['studentID'] ? $_POST['studentID'] : $studentID;
				$enrolmentNo			= $this->model->getEnrolmentNoByStudentID($studentID);
				
				// save record
				if (isset($_FILES['fileToUpload']['name'])) {
					// Check if image file is a actual image or fake image
					$sourceFile			= basename($_FILES['fileToUpload']['name']);
					$extName			= strtolower(pathinfo($sourceFile, PATHINFO_EXTENSION));
					$uploadFile			= strtolower("doc-{$enrolmentNo}-{$docCodes}.{$extName}");
					$targetFile 		= __DIR__. "/../uploads/documents/" .$uploadFile;

					if ($_FILES['fileToUpload']['size'] > 1500000000) {
						$this->errorText = "Heavy file size";
						// Allow certain file formats
					} else if ($extName == "pdf") {
						// if everything is ok, try to upload file
						if (file_exists($targetFile)) {
							$this->errorText = "File already exists.";
						} else {
							move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $targetFile);
						}
						foreach ($docheadCodes as $code) {
							$this->model->saveUpload($studentID, $code, $uploadFile);
							$this->model->deleteExemption($studentID, $code);
						}
						$this->model->sqlLog();
						$this->errorText= 'Successful.';
					} else {
						$this->errorText= 'Document should be a PDF file.';
					}
				} else {
					$this->errorText 	= 'Document should be a PDF file.';
				}
				break;
            case 'delete':
                // delete record
				//$docheadCode			= $this->controller->params[0];
				//$this->model->deleteExemption($studentID, $docheadCode);
                //$this->errorText 		= 'Exemption revoked successfully.';
            	break;
        }
		return $this->model->tupleID;
    }	

	public function manageSection($action, $sectionID) {
		$this->model->tableID 			= 'aaa_sections';
		$this->model->tupleID 			= $sectionID;
		switch ($action) {
            case 'new':
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
            case 'help':
			case 'trash':
				break;
			case 'save':
                // save record
            	$sectionCode			= strtoupper($_POST['sectionCode']);
				$programID				= $this->params[0];		
				$enrolmentID			= $_POST['enrolmentID'];
				$strength				= $_POST['strength'];
				
				$this->model->saveSection($sectionCode,$programID,$enrolmentID,$strength);
                $this->model->sqlLog();
                $this->errorText 		= 'Section record saved successfully.';				
                break;
            case 'enable':
                // enable record
                $this->model->enableSection();
                $this->model->sqlLog();
                $this->errorText 		= 'Section record enabled successfully.';
                break;
            case 'disable':
                // disable record
                $this->model->disableSection();
                $this->model->sqlLog();
                $this->errorText 		= 'Section record disabled successfully.';
                break;
            case 'delete':
                // delete record
                $this->model->deleteSection();
                $this->model->sqlLog();
                $this->errorText 		= 'Section record deleted successfully.';
            	break;
        }
		return $this->model->tupleID;
    }	

	public function manageBranchChange($action, $enrolmentID) {
		$this->model->tableID 			= 'aaa_enrolments';
		$this->model->tupleID 			= $enrolmentID;
		switch ($action) {
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
            case 'help':
				break;
			case 'save':	
                // save enrollment record
				$programID				= $_POST['programID'];			// new program ID
				$enrolmentNo			= $_POST['enrolmentNo'];		// new enrolment no.
				$remark					= $_POST['remark'];		
								
				if ($enrolmentNo) $this->model->saveBranchChange($enrolmentNo,$programID,$remark);
				$this->model->sqlLog();
				
				$this->errorText		= $enrolmentNo. ' record saved successfully.';
				break;
        }
		return $this->model->tupleID;
    }	

	public function manageStudent($action, $programID) {
		$this->model->tableID 			= 'aaa_enrolments';
		$this->model->tupleID 			= $programID;
		switch ($action) {
            case 'open':
            case 'help':
			case 'excel':
				$rows 					= $this->model->listStudents($programID);
				foreach ($rows as $row) {
					$i++;	
					$j = 0;			
					$vals = '';
					foreach ($row as $key => $value) {
						$j++;
						if ($j > 1) {
							if ($i == 1) $colh .= '"' .ucfirst($key). '",';
							$vals .= '"' .$value. '",';
						}
					}
					$colv .= rtrim($vals, -1). "\n";
				}
				$data = rtrim($colh, -1). "\n" .$colv;
				
				$f = fopen("uploads/student-{$programID}-" .$_SESSION['batchYear']. '.csv' , 'wb');
				fwrite($f , $data);
				fclose($f);
				break;
			case 'mail':
				//send email acknowledgment to student
				$data = $this->model->getEnrolment($this->model->tupleID);
				$str = "Dear " .$data['nameEnglish']. "!
				<br><br>
				Congratulation!!!<br>
				You are enrolled at IIIT Allahabad with following details.
				<br><br>";
					 
				$str .= "<table width='100%'>";
				foreach ($data as $key => $value) {
					$str .= "<tr><td nowrap>" .ucfirst($key). "</td><td>$value</td></tr>";
				}
			    $str .= "</table>";
				$this->erpMailer($data['email'], 'Enrollment Acknowledgment', $str);
                $this->errorText 		= 'Enrollment acknowledgment mailed to student.';
        }
		return $this->model->tupleID;
    }	

	public function manageLDAP($action, $enrolmentID) {
		$this->model->tableID 			= 'aaa_enrolments';
		$this->model->tupleID 			= $enrolmentID;
		switch ($action) {
            case 'new':
			case 'edit':
				$this->editLock 		= '';
				break;
            case 'open':
            case 'help':
			case 'trash':
				break;
			case 'save':
                // save record
				//$ds 					= ldap_connect("ldaps://172.31.1.41:636");
				$ds 					= ldap_connect("ldap://172.31.1.41:389");
				ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
				$q 						= ldap_search($ds, "ou=applicants,ou=aaa,dc=iiita,dc=ac,dc=in", "(&(uid=$rollNo)(objectclass=posixAccount))");
				$info 					= ldap_get_entries($ds, $q);
        		$dn 					= $info[0]['dn'];

				$ldapOTP = rand(111111, 999999);
				if ($info['count'] == 0) {
               		ldap_bind($ds, "cn=Manager,dc=iiita,dc=ac,dc=in","\$dollfinn");
       				//$pwd1 			= 'iiita' . rand(111,999);
       				//$pwd 				= '{CRYPT}' . crypt($pwd1);
       				$pwd 				= "{SHA}" . base64_encode(pack("H*", sha1($ldapOTP)));
       				$info1['uid'] 		= "$rollNo";
       				$info1['cn'] 		= "aaa applicant";
       				$info1['gecos'] 	= date("Y-m-d");
       				$info1['userPassword']= "$pwd";
	
        			if (ldap_add($ds, $dn, $info1)) {
						$str 			= "Applicant account added successfully.";
					} else {
						$str 			= "Sorry! error occured in LDAP add.";
					}
				} else {
					$str 				= "LDAP account already exists.";
				}
				ldap_close($ds);
		
                $this->errorText = 'Applicant record created successfully.';
                break;
            case 'delete':
                // delete record
				//$ds 					= ldap_connect("ldaps://172.31.1.41:636");
				$ds 					= ldap_connect("ldap://172.31.1.41:389");
				ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
				$q 						= ldap_search($ds, "ou=applicants,ou=aaa,dc=iiita,dc=ac,dc=in", "(&(uid=$rollNo)(objectclass=posixAccount))");
				$info 					= ldap_get_entries($ds, $q);
        		$dn 					= $info[0]['dn'];

           		ldap_bind($ds, "cn=Manager,dc=iiita,dc=ac,dc=in","\$dollfinn");
       			if (ldap_delete($ds, $dn)) {
					$str 				= "Applicant account deleted successfully.";
				} else {
					$str 				= "Sorry! error occured in LDAP delete.";
				}
				ldap_close($ds);
                $this->errorText 		= 'Applicant record deleted successfully.';
            	break;
			case 'mail':
				// mail OTP
				echo $this->erpMailer('mmishra@iiita.ac.in', 'IIITA Applicant OTP - confidential', 'This is a test mail');
				break;
        }
		return $this->model->tupleID;
    }	

	public function manageDegree($action, $degreeID) {
		$this->model->tableID 			= 'aaa_degrees';
		$this->model->tupleID 			= $degreeID;
		switch ($action) {
			case 'edit':
			case 'open':
			case 'print':
				break;
			case 'save':
                // save record
				$programID				= $_POST['programID'];
				$hindiText1				= $_POST['hindiText1'];
				$hindiText2				= $_POST['hindiText2'];
				$hindiText3				= $_POST['hindiText3'];
				$hindiText4				= $_POST['hindiText4'];
				$englishText1			= $_POST['englishText1'];
				$englishText2			= $_POST['englishText2'];
				$englishText3			= $_POST['englishText3'];
				$englishText4			= $_POST['englishText4'];
				
				// save degree record 
				$this->model->saveDegree($programID,$hindiText1,$hindiText2,$hindiText3,$hindiText4,$englishText1,$englishText2,$englishText3,$englishText4);
						
				// save sql log
				$this->model->sqlLog();
				$this->errorText 		= 'Degree record saved successfully.';
                break;
        }
		return $this->model->tupleID;
    }	

	public function manageGraduand($action, $graduandID) {
		$this->model->tableID 			= 'aaa_graduands';
		$this->model->tupleID 			= $graduandID;
		
		switch ($action) {
			case 'edit':
				$this->editLock 		= '';
				break;
			case 'open':
			case 'print':
				break;
			case 'feesPayment':
				break;
			case 'save':
                // save record
				$programID				= $this->params[0];
				$enrolmentNo			= $_POST['enrolmentNo'];
				$nameEnglish			= $_POST['nameEnglish'];
				$nameHindi				= $_POST['nameHindi'];
				$gradePoint				= $_POST['gradePoint'];
				$contactNo				= $_POST['contactNo'];
				$email					= $_POST['email'];
				$topicPHD				= $_POST['topicPHD'];

				$nameEnglishx			= $_POST['nameEnglishx'];
				$nameHindix 			= $_POST['nameHindix'];
				$moderateE				= $_POST['moderateE'];
				$moderateH				= $_POST['moderateH'];
				
				if ($moderateE == 1 && $nameEnglishx)	$nameEnglish 	= $nameEnglishx;
				if ($moderateH == 1 && $nameHindix)		$nameHindi 		= $nameHindix;
				
				// save graduand record 
				$this->model->saveGraduand($programID,$enrolmentNo,$nameEnglish,$nameHindi,$gradePoint,$topicPHD,$contactNo,$email);
						
				// save sql log
				$this->model->sqlLog();
				$this->errorText 		= 'Graduand record saved successfully.';
                break;
			case 'excel':
				$programID				= $graduandID;
				$rows 					= $this->model->printGraduands($programID);
				foreach ($rows as $row) {
					$i++;	
					$j = 0;			
					$vals = '';
					foreach ($row as $key => $value) {
						if ($i == 1) $colh .= '"' .ucfirst($key). '",';
						$vals .= '"' .$value. '",';
					}
					$colv .= rtrim($vals, -1). "\n";
				}
				$data = rtrim($colh, -1). "\n" .$colv;
				
				$f = fopen("uploads/graduand-{$programID}-" .$_SESSION['batchYear']. '.csv' , 'wb');
				fwrite($f , $data);
				fclose($f);
				break;
        }
		return $this->model->tupleID;
    }	

	public function manageTravelplan($action, $planID) {
		$this->model->tableID 			= 'aaa_travelplans';
		$this->model->tupleID 			= $planID;
		
		switch ($action) {
			case 'edit':
				$this->editLock 		= '';
				break;
			case 'save':
                // save record
				$enrolmentNo			= $this->params[0];
				$dateArrival			= $_POST['dateArrival'];
				$dateDeparture			= $_POST['dateDeparture'];
				$campusStay				= $_POST['campusStay'];
				$companion				= $_POST['companion'];
				$contactNo				= $_POST['contactNo'];
				$email					= $_POST['email'];
				$remark					= $_POST['remark'];
				
				// save graduand record 
				$this->model->saveTravelplan($enrolmentNo,$dateArrival,$dateDeparture,$campusStay,$companion,$contactNo,$email,$remark);
						
				// save sql log
				$this->model->sqlLog();
				$this->errorText 		= 'Graduand record saved successfully.';
                break;
        }
		return $this->model->tupleID;
    }	




}

// **********************************************************************
//							Payment processing
// **********************************************************************

class payment_config_test {
	var $Url 							= "https://paynetzuat.atomtech.in/paynetz/epi/fts";
	var $Login							= "160";
	var $Password						= "Test@123";
	//var $MerchantName					= "ATOM";
	var $MerchantName					= "NSE";
	var $TxnCurr						= "INR";
	var $TxnScAmt						= "0";
}

class payment_config {
	var $Url 							= "https://payment.atomtech.in/paynetz/epi/fts";
	var $Login							= "18589";
	var $Password						= "IIIT@123";
	var $MerchantName					= "IIIT";
	var $TxnCurr						= "INR";
	var $TxnScAmt						= "0";
}


class payment {
	var $url 							= null;

	function sendInfo($data){
		$ch 							= curl_init();

		curl_setopt($ch, CURLOPT_URL, $this->url);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_PORT , 443); 
		//curl_setopt($ch, CURLOPT_SSLVERSION,3);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

		$returnData 					= curl_exec($ch);

		curl_close($ch);
			return $returnData;
	}
}

class ProcessPayment {
	function __construct() {
		$this->paymentConfig 			= new payment_config();
	}

	function requestMerchant() {
		$payment 						= new payment();
		$datenow 						= date("d/m/Y h:m:s");
		$modifiedDate 					= str_replace(" ", "%20", $datenow);
		$payment->url 					= $this->paymentConfig->Url;
		$postFields  					= "";
		
		$postFields .= "&login=" 		.$this->paymentConfig->Login;
		$postFields .= "&pass=" 		.$this->paymentConfig->Password;
		$postFields .= "&ttype=" 		.$_POST['TType'];
		$postFields .= "&prodid=" 		.$_POST['product'];
		$postFields .= "&amt=" 			.$_POST['amount'];
		$postFields .= "&txncurr=" 		.$this->paymentConfig->TxnCurr;
		$postFields .= "&txnscamt=" 	.$this->paymentConfig->TxnScAmt;
		$postFields .= "&clientcode=" 	.urlencode(base64_encode($_POST['clientcode']));//rollno
		$postFields .= "&txnid=" 		.rand(0,999999);
		$postFields .= "&date=" 		.$modifiedDate;
		$postFields .= "&custacc=" 		.$_POST['AccountNo'];
		$postFields .= "&ru=https://erp.iiita.ac.in/outer/aaa/PGResponse/online/" .$_REQUEST['udf6']. "/ATOM/1";
		$postFields .= "&udf1=" 		.$_POST['udf1']; //name
		$postFields .= "&udf2=" 		.$_POST['udf2']; //email
		$postFields .= "&udf3=" 		.$_POST['udf3']; //mobile
		$postFields .= "&udf4=" 		.$_POST['udf4']; //program
		$postFields .= "&udf5=" 		.$_POST['udf5']; //batch
		$postFields .= "&udf6=" 		.$_REQUEST['udf6']; //studentID
		$postFields .= "&udf9=" 		.$_POST['udf9']; //semester

		$sendUrl = $payment->url. '?' 	.substr($postFields,1). "\n";

		$this->writeLog($sendUrl);

		$returnData 					= $payment->sendInfo($postFields);
		$this->writeLog($returnData. "\n");
		$xmlObjArray 					= $this->xmltoarray($returnData);

		$url 							= $xmlObjArray['url'];
		$postFields  					= "";
		$postFields .= "&ttype=" 		.$_POST['TType'];
		$postFields .= "&tempTxnId=" 	.$xmlObjArray['tempTxnId'];
		$postFields .= "&token=" 		.$xmlObjArray['token'];
		$postFields .= "&txnStage=1";
		$url = $payment->url. '?' 		.$postFields;
		$this->writeLog($url. "\n");

		header("Location: " .$url);
	}

	function writeLog($data){
		$fileName 						= date("Y-m-d").".txt";
		$fp 							= fopen("log/".$fileName, 'a+');
		$data 							= date("Y-m-d H:i:s")." - ".$data;
		fwrite($fp,$data);
		fclose($fp);
	}

	function xmltoarray($data){
		$parser 						= xml_parser_create('');
		xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8");
		xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
		xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
		xml_parse_into_struct($parser, trim($data), $xml_values);
		xml_parser_free($parser);

		$returnArray 					= array();
		$returnArray['url'] 			= $xml_values[3]['value'];
		$returnArray['tempTxnId'] 		= $xml_values[5]['value'];
		$returnArray['token'] 			= $xml_values[6]['value'];

		return $returnArray;
	}
}

?>