<?php

/* Business Logic Class.	App:b2b@solarexplosives.com Company:softwareCREATIONS Author:dashgandhi@yahoo.com Contact:+919819603482 */

class BusiLogic {

const BaseApp				= 'b2b';					// 'b2b' | 'scm'
const DBNameTrade			= 'b2b_solar_sc';		// Should keep in sink in b2b.index.php, b2b.class.BusiLogic & b2b.ajax.php 
const DBNameNonTrade		= 'cib2b_solar_sc';
const DBNameExport			= 'exb2b_solar_sc';
const DEFCUSTOMERCD 		= 'ZZZZZZZZZZ';
const DEFCOMPANYCD			= 1800;
const CUSTMAXDAY			= 25;		// Def.Max.Day in every Month, till which Customer can Add/Edit Next Month's Target
const CUSTMINDAY			= 20;		// Def.Max.Day in every Month, till which Customer can Add/Edit Next Month's Target
const SUBDEALERMINDAY			= 20;		// Def.Max.Day in every Month, till which Subdealer can Add/Edit Next Month's Target
const SUBDEALERMAXDAY			= 23;		// Def.Max.Day in every Month, till which Subdealer can Add/Edit Next Month's Target
const MinDailyStockAddTime	= '00:01:00';		// DailyStock Add Min.Time for Today For Customer
const UTCustomer			= 11;		// UT:UserType. Customer. so_user_type_m.UserType for so_user_type_m.IsCustomer
const UTSubDealer			= 12; // UT:UserType. Sub Dealer. so_user_type_m.UserType for so_user_type_m.IsSubDealer
    /* const UTPOReadier	= 31;
/* const UTPOReadier	= 31;
const UTASM		= 21;
const UTSalesCoord	= 22;*/
const DTUserM				= 'b2b_solar_sc.so_user_m';				// DT:DatabaseTable. Some Masters are always to be used (even for Non-TradeSector) from b2b_solar_sc
const DTUserTypeM			= 'b2b_solar_sc.so_user_type_m';
const DTSectorM				= 'b2b_solar_sc.so_sector_m';

const POStatusPending		= 'W';
const POStatusReady			= 'E';
const POStatusConfirm		= 'N';
const POStatusTerminate		= 'T';
const POStatusDespatch		= 'S';			// Accessory Manually Completed
const POStatusGoodsReceipt	= 'B';
const POStatusTradeUnlock	= 'U';		// PO+Accessory Status. For Trade, Unlock = U:Unapproved. For Non-Trade, Lock = N:Confirm, C:Complete, S:Despatch, B:Goods Receipt
const POStatusNonTradeLock	= 'NCSB';
const doDebug	= 'False';

/* -1:Internal:InternalCall. 0:All 1:Unapprove:Unapproved(Allow mass Approval) 2:Approve:Approved 3:Pending 4:Complete:Completed/Despatched 
	5:Terminate:Terminated 6:Held 7:Ready(NonTrade:Allow mass Approval) 8:Confirm:Confirmed. Add +100 if want to allow New		*/
public static $POStatus = array('Internal' => -1, 'All'=>0, 'Unapprove'=>1, 'Approve'=>2, 'Pending'=>3
		, 'Complete'=>4, 'Terminate'=>5, 'Expired'=>10, 'Held'=>6, 'Ready'=>7, 'Confirm'=>8, 'GoodsReceipt'=>9, 'GuardPhotoVerify'=>11);

public static $PendingReason = array('1' => 'WrongRE11 No', '2'=>'Digital sign missing / single side sign', '3'=>'Corrupt Re-11', 4 =>'Missing van no', 
	5 =>'Holded by customer',  6=>'Route map not available', 7=> 'Van provided already servicing PO' );
private 	$objDBQuery;
private		$dbName;
protected	$lastInsertTranNo;
	
public function __construct($objDBQuery, $dbName) {
	$this->objDBQuery			= $objDBQuery;
	$this->dbName				= $dbName;
	$this->lastInsertTranNo		= 0;
	date_default_timezone_set('Asia/Kolkata');
}
	
public function execUpdateQuery($updateQuery) {
	return $this->objDBQuery->execUpdateQuery($updateQuery);
}

public function execSelectQuery($execQuery, $resultType=0, &$preResults=NULL) {
	return $this->objDBQuery->execSelectQuery($execQuery, $resultType, $preResults);
}

public function manageTransaction($SetRollbackCommit) {
	$this->objDBQuery->manageTransaction($SetRollbackCommit);
}

public function getInsertId() {
	return $this->objDBQuery->objDBConnect->insert_id;
}

public function getInsertTranNo() {
	return $this->lastInsertTranNo;
}

public function getRelNamedLock($GetLock, $TableRLockName, $ColValArr=NULL) {
	if ($GetLock) {
		$ColValStr = '';
		foreach ($ColValArr as $key => $value) {			// while (list($key, $value) = each($ColValArr))
			$ColValStr .= $key . ':' . $value . ',';
		}
		$NamedLock	= $this->dbName . '@' . $TableRLockName . '-' . $ColValStr;
		$Success = 0;
		while (!$Success) {
			$sql		= "SELECT GET_LOCK('$NamedLock', 10) AS Success";
			$SuccessArr = $this->execSelectQuery($sql);
			$Success	= $SuccessArr[0]['Success'];
		}
		return $NamedLock;
	} else {
		$sql		= "SELECT RELEASE_LOCK('$TableRLockName') AS Success";
		$SuccessArr = $this->execSelectQuery($sql);
		$Success	= $SuccessArr[0]['Success'];
		return (isset($Success) && $Success) ? '' : 'Release Lock: '. $TableRLockName .' Failure!';
	}
}


public function genrateCustomeritemtype() {
			$sql		= "SELECT * from so_customer_m ";
			$SuccessArr = $this->execSelectQuery($sql);
			
		foreach ($SuccessArr as $value) {		
			$CustomerCd=$value['CustomerCd'];	
			$sql1		= "SELECT * from so_item_m where CompanyCd = '1110' ";
			$itemArr = $this->execSelectQuery($sql1);
			foreach ($itemArr as $val) {
				$sql2	= "INSERT INTO so_customer_m_item_rate_type (CustomerCd, ItemCd)
				VALUES( '".$CustomerCd."', ".$val['ItemCd'].")";
				$queryResult= $this->execUpdateQuery($sql2);
			}
		}
}




// General Functions -------------------------------------------------------------------------------------------------------------------------------------

public function strPositSubstitute($strSource, $para1DArray = NULL, $para2DArray = NULL) {
/*
Substitute source string containing </./> tag delimited positional paras with positional values specified in $para1DArray & $para2DArray
$para1DArray is 1 dimensional array for </0/>, </1/>, ... 
$para2DArray is 2 dimensional array for </00/>, </01/>, .... Source is expected to include \r\n at end of the this positional para row
Routine should treat these positional values as 1st Row of a table & replace with as many times as no. of rows in $para2DArray

$strSource = 'Dear sir, Please note that your P.O. No. </0/> dated </1/> Is approved by us with Token No. </2/>' . "\r\n";
$strSource .= 'Rates of following Items have been changed:' . "\r\n";
$strSource .= 'Item			OldRate			NewRate' . "\r\n";
$strSource .= '</00/>			</01/>			</02/>' . "\r\n";
$strSource .= 'Please do check in b2b too.' . "\r\n";
$para1DArray = array('123456','10/12/2012','T12234');
$para2DArray = array(	array('Item1','OldRate','NewRate'),	array('Item2','OldRate','NewRate'),	array('Item3','OldRate','NewRate')	);
$fstr = $objSolarCustomer->strPositSubstitute($strSource, $para1DArray ,$para2DArray );
*/
	if (isset($para1DArray) && is_array($para1DArray)) {
		$arrSearch = array();
		for ($paraCur=0; $paraCur <= count($para1DArray); ++$paraCur) {
			$arrSearch[$paraCur] = '</' . $paraCur . '/>';
		}
		$strSource = str_replace($arrSearch, $para1DArray, $strSource);
	}

	if (isset($para2DArray) && is_array($para2DArray)) {
		$countRow = count($para2DArray);
		$countCol = count($para2DArray[0]);
		$valRowBeg = strpos($strSource,'</00/>');
		$lastPosPara = '</0' . (string)($countCol-1) . '/>';
		$valRowEnd = strpos($strSource, $lastPosPara) + strlen($lastPosPara);
		$strPositional = substr($strSource, $valRowBeg, $valRowEnd-$valRowBeg);
		$strSourceEnd = substr($strSource, $valRowEnd);
		$strSource = substr($strSource, 0, $valRowBeg);
		
		$arrSearch = array();
		for ($paraCur=0; $paraCur < $countCol; ++$paraCur) {
			$arrSearch[$paraCur] = '</0' . $paraCur . '/>';
		}
		for ($curRow=0; $curRow<$countRow; ++$curRow) {
			$strSource .= str_replace($arrSearch, $para2DArray[$curRow], $strPositional) . ($curRow < $countRow-1 ? "\r\n" : '');
		}
		$strSource .= $strSourceEnd;
	}
	return $strSource;
}

public function convertDate($dateString, $brit2Ansi, $bmDateTimePart=3) {		// $bmDateTimePart: 1:Date, 2:Time, 3:Both
	if ($brit2Ansi) {		// British (dd-mm-yyyy) to ANSI (yyyy-mm-dd)
		$returnVal = preg_replace('/(\d{2})[-\/](\d{2})[-\/](\d{4})/', "$3-$2-$1", $dateString);
	} else {				// ANSI to British
		$returnVal = (substr($dateString,0,4)=="0000" ? "" : preg_replace('/(\d{4})[-\/](\d{2})[-\/](\d{2})/', "$3-$2-$1", $dateString));
	}

	if ($bmDateTimePart == 3) {
		return $returnVal;
	} elseif (($bmDateTimePart & 1) == 1) {
		return substr($returnVal,0,10);
	} else {
		return substr($returnVal,11,8);
	}
}

public function addDate($date2Add = NULL, $days2Add, $returnBritish = TRUE) {
// $date2Add: Null:Today. Must be ANSIDate.
// $days2Add: A.Complete expression eg '+1 day', '-1 day', '+1 week 2 days 4 hours 2 seconds'. ('next Thursday':will NOT work) B.Just No. of Days to ADD
	$date2Add = isset($date2Add) ? $date2Add : 'now';
	$days2Add = in_array(substr($days2Add, 0, 1), array('+','-')) ? $days2Add : '+ ' . $days2Add .' day';
	$date2Add = strtotime($days2Add, strtotime($date2Add));
	return date(($returnBritish ? 'd-m-Y' : 'Y-m-d'), $date2Add);
}

public function getUniqueFileName($fileFolder, $prefix, $extension) {
	while (true) {
		$fileName = $fileFolder . uniqid($prefix, true) . $extension;
		if (!file_exists($fileName))
			break;
	}
	return ($fileName);
}

public function array_sum_key($arr, $index = null) {
	if (!is_array($arr) || count($arr) < 1) {
		return 0;
	}
	$ret = 0;
	foreach ($arr as $id => $data) {
		if (isset($index)) {
			$ret += (isset($data[$index])) ? $data[$index] : 0;
		} else {
			$ret += $data;
		}
	}
	return $ret;
}

public function searchSubArray(Array $array, $key, $value) {
    foreach ($array as $subArray) {
        if (isset($subArray[$key]) && $subArray[$key] == $value)
          return $subArray;
    }
	return FALSE;
}

public function fillMasterDropDown($keyCd, $arrCodeMDisp, $showPlSelect, $curValue, $colDescript=NULL, $dataColName=NULL) {
	$colDescript	= isset($colDescript) ? $colDescript : 'Descript';
	$isSelected	= FALSE;
	$selected	= $htmlStr = $dataStr = '';
	if ($showPlSelect) {
		$selected = "selected='selected'";
		$htmlStr .= "<option value='' " . $selected . "> " . 'Please Select' . "</option>";
	}
	foreach ($arrCodeMDisp as $mData) {
		$selected = "";
		if ($curValue==$mData[$keyCd]) {
			$selected = "selected='selected'";
			$isSelected = TRUE;
		}
		$dataStr = $this->fillMasterDropDownDataCol($dataColName, $mData);		// isset($dataColName) ? "data-$dataColName='{$mData[$dataColName]}' " : ""
		$htmlStr .= "<option $dataStr value='{$mData[$keyCd]}' $selected > {$mData[$colDescript]} </option>";
	}

	if (!$isSelected && $curValue!='') {
		$selected = "selected='selected'";
		$dataStr = $this->fillMasterDropDownDataCol($dataColName, NULL);	// isset($dataColName) ? "data-$dataColName='' " : ""
		$htmlStr .= "<option $dataStr value='{$curValue}' $selected > {$curValue} Missing </option>";
	}

	return $htmlStr;
}

public function fillMasterDropDownDataCol($dataColNameArr, $mData=NULL) {
	$dataStr	= '';
	if (isset($dataColNameArr)) {
		if ((array)($dataColNameArr) !== $dataColNameArr) {		// !is_array($dataColNameArr)
			$dataColNameArr = array($dataColNameArr);
		}
		$max	= count($dataColNameArr);
		for ($j=0; $j<$max; $j++) {
			$dataColName	= $dataColNameArr[$j];
			$dataColVal		= '';
			if (isset($mData)) {
				$dataColVal	=  $mData[$dataColName];
			}
			$dataStr .= "data-$dataColName='$dataColVal' " ;
		}
	}
	return $dataStr;
} 

public static function SolarEncrypt($string) {
	$output = false;
	$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
	// initialization vector
	$iv = md5(md5($key));

	$output = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, $iv);
	$output = base64_encode($output);
	$output = str_replace(array("+", "/", "="), array("PLUS", "SLASH", "EQUAL"), $output);

	return trim($output);
}

public static function SolarDecrypt($string) {
	$output = false;
	$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
	// initialization vector
	$iv = md5(md5($key));

	$string = str_replace(array("PLUS", "SLASH", "EQUAL"), array("+", "/", "="), $string);
	$output = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, $iv);
	$output = rtrim($output, "");

	return trim($output);
}



public function getPlantMDisp($PlantCd=0) {
	$sql		= "SELECT * FROM scm_solar_sc.scm_plant_m " . (empty($PlantCd) ? "WHERE PlantCd<>0" : "WHERE PlantCd=$PlantCd") . " ORDER BY Descript;";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getSoItemMDisp() {
	$sql		= "SELECT ItemCd,Descript FROM so_item_m ORDER BY 2";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;	
}

public function makeTabReport($reportData, $repPartBitmap=3,  $fileName='', $handle=-1, $repTitle='', $hasSerial=FALSE, $breakFlds=0, $sumFlds='') {
// $reportData: Must be Numeric+Associative Array ie execSelectQuery($execQuery, $resultType=2)
// $repPartBitmap: 1:FirstReport, 2:LastReport. $fileName is must for FirstReport &| LastReport. $handle is set for FirstReport & must for Not-FirstReport
// $repTitle: If '', consider the report as GrandTotal of Detail Report & do not print ColumnHeader, skip a line & also skip SrNo column, if $hasSerial

	$isFirstReport = ($repPartBitmap & 1) == 1;
	$isLastReport = ($repPartBitmap & 2) == 2;
	if ($isFirstReport) $handle = fopen($fileName,'wb');
	$isDetailReport = $repTitle!='';

	$arrayKeys = array_keys($reportData[0]);
	$tildeCount =0;
	foreach ($arrayKeys as $keyValue) {
		$tildeCount = max($tildeCount, substr_count($keyValue, '~'));
	}
		
	if ($isDetailReport) {
		if (!$isFirstReport) 	fwrite($handle, "\r\n\r\n");	// leave 2 lines for any subsequent Detail report
		fwrite($handle, $repTitle . "\r\n");
		fwrite($handle, "\r\n");
	}
	
	if ($isDetailReport) {
		for ($tildeCur=0; $tildeCur <= $tildeCount; $tildeCur++) {
			if ($hasSerial)
				fwrite($handle, (($tildeCur==0) ? 'Sr Number' : "") . "\t");
			for ($i=1; $i<count($arrayKeys); $i+=2) {
				$partArr = explode('~',$arrayKeys[$i]);
//				$separatorAt = strpos($arrayKeys[$i], '~');
				$colVal = (count($partArr) > $tildeCur) ? $partArr[$tildeCur] : "";
				fwrite($handle, $colVal . "\t");
			}
			fwrite($handle, "\r\n");
		}
	}
	else if(!$isDetailReport) {
		for ($tildeCur=0; $tildeCur <= $tildeCount; $tildeCur++) {
			if ($hasSerial)
				fwrite($handle, (($tildeCur==0) ? 'Sr.' : "") . "\t");
			for ($i=1; $i<count($arrayKeys); $i+=2) {
				$partArr = explode('~',$arrayKeys[$i]);
//				$separatorAt = strpos($arrayKeys[$i], '~');
				$colVal = (count($partArr) > $tildeCur) ? $partArr[$tildeCur] : "";
				fwrite($handle, $colVal . "\t");
			}
			fwrite($handle, "\r\n");
		}
	}

// array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = false ]] )
	$columnCount = count($reportData[0])/2;
	$SrNo = 1;

	for ($i=0; $i<count($reportData); $i++) {
		if ($hasSerial)
			fwrite($handle, ($isDetailReport ? $SrNo : '')."\t");
		if ($i>0 && $breakFlds>0) {
			$curBreakValArr = array_slice($reportData[$i], 0, $breakFlds*2, TRUE);
			$diffArray = array_diff_assoc($preBreakValArr, $curBreakValArr);
		}
		
		for ($j=0; $j<$columnCount; $j++) {
			fwrite($handle, (($i==0 || $j>=$breakFlds || $diffArray) ? preg_replace('/\s+/', ' ', trim($reportData[$i][$j])). "\t" : "\t"));
		}
		fwrite($handle, "\r\n" );
		if ($breakFlds>0)
			$preBreakValArr = array_slice($reportData[$i], 0, $breakFlds*2, TRUE);
		$SrNo += 1;
	}
	
	if ($isLastReport) {
		fclose($handle);
		echo "<script language='javascript'>window.location.href='includes/download.php?fileName=$fileName&baseDir=./../wrk/';</script>";
		return 0;
	} else return $handle;
}

function reportDownload($reportData, $fileName) {
	$handle = fopen($fileName,'wb');
	for ($curRow=0; $curRow < count($reportData); $curRow++) {
		for ($curColumn=0; $curColumn < count($reportData[$curRow]); $curColumn++ ) {
			fwrite($handle, $reportData[$curRow][$curColumn]. "\t");
		}
		fwrite($handle, "\r\n");
	}
	fclose($handle);
	return 0;
}

// Common Functions used for Display/Select Master+Description in many forms --------------------------------------------------------------------------------

public function pr($data){
	echo "<pre>";
	print_r($data);
	echo "<pre>";
}

public function getUserTypeMDisp() {
	$sql		= "SELECT UserType, Descript FROM " . self::DTUserTypeM . " ORDER BY UserType";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getUserMDisp($strActiveFlag='') {		// $strActiveFlag: Can be , delimited ActiveFlag list to filter
	$sql		= "SELECT UserName, Descript, UserType, CustomerCd, ActiveFlag, PhoneFlag FROM " . self::DTUserM . ((empty($strActiveFlag)) ? "" : " WHERE ActiveFlag IN (".$strActiveFlag.")");
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getCustomerPOList($CustomerCd=NULL, $IdExpDet=NULL) {		// $strActiveFlag: Can be , delimited ActiveFlag list to filter
	if(isset($CustomerCd) && trim($CustomerCd)!=''){  $Custcond = "A.CustomerCd ='".$CustomerCd."'"; } else { $Custcond= 1; };
	if(isset($IdExpDet) && trim($IdExpDet)!=''){  $pocond = "A.IdExpDet ='".$IdExpDet."'"; } else{ $pocond=1; };
	$sql		= "SELECT A.*, B.RE11No, B.RE11Date  FROM so_expdet A JOIN so_expdet_magazine B ON A.IdExpdet = B.IdExpDet  WHERE ".$Custcond." AND ".$pocond." AND  A.StatusCd='A'";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getVanDriverMDisp($DriverLicNo=NULL) {
	$sql		= "SELECT DriverLicNo, Descript, TransporterTypeCd, DriverLicValidUptoDate, HazardLicValidUptoDate, TelNo
					FROM scm_solar_sc.vm_van_driver_m " . ((isset($DriverLicNo) && trim($DriverLicNo)!='')  ? " WHERE DriverLicNo='$DriverLicNo'" : ""). " ORDER BY DriverLicNo;";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getVanMDisp($VanNo=NULL) {
	$sql		= "SELECT * FROM scm_solar_sc.vm_van_m " . ((isset($VanNo) && trim($VanNo)!='')  ? " WHERE VanNo='$VanNo'" : ""). " ORDER BY VanNo;";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

/*
public function getVanTransporterMDisp($IdVan=NULL) {
	$sql	= "SELECT A.UniqueId, A.IdVan, A.TransporterCd, B.PartyCd, IFNULL(B.Descript, A.TransporterCd ) AS Descript FROM scm_solar_sc.vm_van_m_transporter A 
				LEFT OUTER JOIN scm_solar_sc.scm_party_m B ON A.TransporterCd=B.PartyCd WHERE A.IdVan=$IdVan ORDER BY A.UniqueId";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}
*/
public function getVanTransporterMDisp($IdVan=NULL) {
	$sql	= "SELECT A.UniqueId, A.IdVan, A.TransporterCd, B.PartyCd, IFNULL(B.Descript, A.TransporterCd ) AS Descript,C.TransporterName FROM scm_solar_sc.vm_van_m_transporter A LEFT OUTER JOIN scm_solar_sc.scm_party_m B ON A.TransporterCd=B.PartyCd  INNER JOIN  scm_solar_sc.vm_van_m C ON  A.IdVan = C.IdVan  WHERE A.IdVan=$IdVan ORDER BY A.UniqueId";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}


public function getVanIdFromPO($IdExpDet) {
	$sql	= "SELECT A.IdVan,C.DriverLicNo, D.IdSecurityGuard, D.IdCardNo, D.IdCardType  FROM scm_solar_sc.vm_van_m A 
	INNER JOIN b2b_solar_sc.so_expdet B ON A.VanNo = B.VehicleNo
	INNER JOIN scm_solar_sc.vm_gate_tran C ON A.IdVan = C.IdVan
	INNER JOIN scm_solar_sc.vm_security_guard_m D ON C.IdSecurityGuard = D.IdSecurityGuard
	WHERE B.IdExpDet = '".$IdExpDet."'";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function VehicleSCMStatus($VanNo=NULL, $IdExpDet=NULL) {
	$sql1 		= " SELECT B.* FROM scm_solar_sc.vm_gate_tran B INNER JOIN scm_solar_sc.vm_van_m A  ON A.IdVan = B.IdVan WHERE A.VanNo = '".$VanNo."' ORDER BY DateTime DESC LIMIT 1";
	$returnData1 = $this->execSelectQuery($sql1);
	$sql2 		= " SELECT * FROM so_van_driver_auth WHERE IdExpdet = '".$IdExpDet."'";
	$returnData2 = $this->execSelectQuery($sql2);
	$returnData = array_merge($returnData1,$returnData2);
	return $returnData;
	//$sql		= " SELECT * from vm_gate_tran  where IdVan = (SELECT IdVan FROM scm_solar_sc.vm_van_m  WHERE VanNo='$VanNo')";
	//$returnData	= $this->execSelectQuery($sql);
	//return $returnData;	
}

public function getSecurityGuardMDisp($IdSecurityGuard=NULL){
	$sql = "  SELECT IdSecurityGuard, Descript,SecurityAgencyCd,TelNo,Address,Age FROM scm_solar_sc.vm_security_guard_m " . ((isset($IdSecurityGuard) && trim($IdSecurityGuard)!='')  ? " WHERE IdSecurityGuard='$IdSecurityGuard'" : ""). " ORDER BY IdSecurityGuard;";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getTransporterMDisp($PartyCd = NULL){
	$sql = "  SELECT * FROM scm_solar_sc.scm_party_m  WHERE " . ((isset($PartyCd) && trim($PartyCd)!='')  ? "  PartyCd='$PartyCd' AND " : ""). "PartyTypeCd IN(2,4) ORDER BY PartyCd";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}


public function getVANDriverAuthDetails($VanDriverAuthId = NULL){
	$sql = "  SELECT * FROM so_van_driver_auth  WHERE " . ((isset($VanDriverAuthId) && trim($VanDriverAuthId)!='')  ? "  VanDriverAuthId='$VanDriverAuthId'  " : ""). "ORDER BY VanDriverAuthId";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}


public function insertVanDriverAuthQuery(){
	$sql = "INSERT INTO so_van_driver_auth 	(CustomerCd,IdExpDet,DriverLicNo,TransportHazardous,IsVan_Own_Trans,IdVanTransport,IdSecurityGuard,GaurdPhotoIdNo,TransUserName,TransDateTime) VALUES('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')";
	return $sql;
}

public function insertVanDriverAuth($data){
	
	$queryInsert		=   $this->insertVanDriverAuthQuery();
	$CustomerCd			= 	$data['CustomerCdInput'];
	$IdExpDet  			=	$data['IdExpDet'];
	$DriverLicNo		= 	$data['DriverLicNo'];
	$TransportHazardous = 	$data['TransportHazardous'];
	$VanTransporter 	= 	$data['VanTransporter'];
	$VanTransportName 	= 	$data['VanTransportName'];
	$GaurdCd			= 	$data['GaurdNameDisp'];
	$GaurdPhotoIdNo		= 	$data['GaurdPhotoIdNo'];
	$UserName			= 	$_SESSION['UserName'];
	$TransDateTime	=	date('Y-m-d H:i:s');
	
	$inputArr			=	array();
	$inputArr			=	array($CustomerCd,$IdExpDet,$DriverLicNo,$TransportHazardous,$VanTransporter,$VanTransportName,$GaurdCd,$GaurdPhotoIdNo,$UserName,$TransDateTime	);
	$sql				=	vsprintf($queryInsert,$inputArr);
	$returnData			= 	$this->execUpdateQuery($sql);
}
public function isExistVanDriverAuth($CustomerCd,$IdExpDet){
	$sql			= "SELECT * FROM so_van_driver_auth  WHERE  CustomerCd	='".$CustomerCd."' AND IdExpDet = '".$IdExpDet."'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function UpdateFileName($Filename,$FieldName,$Condition,$TableName){
	$sql 				= "UPDATE ".$TableName." SET ".$FieldName." = '".$Filename."' WHERE ".$Condition." ";
	$returnData			= 	$this->execUpdateQuery($sql);
	return $returnData;
}

public function SendMailUploadvanauthletter($IdExpDet, $Status) {
	//$senduploadlettermail = $this->SendMailUploadvanauthletter($Condition, 1);
	
	switch ($Status) {
	case 1:
		$Emailtemplate	= 59;
		$TableName		= 'so_expdet';
		$TransId		= 'IdExpDet';
		$Date			= 'DateTime';
		break;
	}
	
	$templateArr = $this->getEMailTemplate($Emailtemplate);
	$sql = "SELECT A.$TransId AS IdExpDet, DATE_FORMAT(A.$Date,'%d-%m-%Y') AS Date, B.EMailId, B.Descript FROM $TableName A INNER JOIN so_customer_m B
		ON A.CustomerCd=B.CustomerCd WHERE A.IdExpDet = '$IdExpDet'";
	
	$eMailDetailArr = $this->execSelectQuery($sql);
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($eMailDetailArr[0]['Descript'], $eMailDetailArr[0]['IdExpDet']));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail('solartrade@solargroup.com', $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	
}


public function getCustomerMDisp($flagColumns=0, $CustomerCd='', $filterCond='', $isCib2bTarget=FALSE) {
// flagColumns: CustomerCd,Descript,SectorCd,HasSubdealer,HasDailyStock always. 1:IsInState,TaxType,IsRE11MustInPO,AllowCompanyVan
// Preference. $CustomerCd, $filterCond, HasCustomer

	$listColumns = "CustomerCd,Descript,SectorCd,City,HasSubdealer,HasDailyStock, CustomerCtgCd, MaxMonthlyTargetDate,AssociateFrom,PAN";
	switch ($flagColumns) {
		case 1:
		$listColumns .= ",IsInState,TaxType,IsRE11MustInPO,AllowCompanyVan,DummyVanAllowPO";
		break;
		
		case 2:
		$listColumns .= ",IsActive,TelNo,EMailId,StateCd";
		break;
		
		default:
		break;
	}
	$addCond	= ($isCib2bTarget ? "CustomerCtgCd='Z'" : "CustomerCtgCd<>'Z'");		// Z: TargetGroup
	$finalCond	= '';
	if (!empty($CustomerCd)) {
		$finalCond	= " WHERE CustomerCd='$CustomerCd' AND $addCond";
	} elseif (!empty($filterCond)) {
		$finalCond	= " WHERE " . $filterCond . " AND $addCond";
	} 
	elseif(!isset($_SESSION['HasCustomer'])) {
		$finalCond = " WHERE UserName='{$_SESSION['UserName']}' AND $addCond";
	}
	else {
		$finalCond	= " WHERE $addCond";
	}
	if (isset($_SESSION['SectorCd'])) {
		$finalCond	.= (empty($finalCond) ? ' WHERE' : ' AND ') . " SectorCd='{$_SESSION['SectorCd']}'";
	}
	$sql		= "SELECT ".$listColumns." FROM so_customer_m" . $finalCond . " ORDER BY Descript";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
	//return $sql;	
}

public function getStatewiseCustList($StateCd) {
	if($StateCd=='0'){ $StateCscond="1"; } else{ $StateCscond="A.StateCd='$StateCd'"; }
	$searchCnd = " WHERE ". $StateCscond ." and A.IsActive ='1' and  A.SectorCd='{$_SESSION['SectorCd']}'";
	$sql		= "SELECT A.*,IFNULL(B.Descript,A.StateCd) AS State FROM so_customer_m A LEFT OUTER JOIN so_state_m B ON A.StateCd=B.StateCd 
					" . $searchCnd . "	ORDER BY A.IsActive DESC, B.DispOrder, A.CustomerCtgCd, A.Descript";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getStatewiseSubdealerList($StateCd) {
	if($StateCd=='0'){ $StateCscond="1"; } else{ $StateCscond="A.StateCd='$StateCd'"; }
	$searchCnd = " WHERE ". $StateCscond ." and A.IsActive ='1'";
	$sql		= "SELECT A.*,IFNULL(B.Descript,A.StateCd) AS State FROM so_subdealer_m A LEFT OUTER JOIN so_state_m B ON A.StateCd=B.StateCd " . $searchCnd . " ORDER BY A.IsActive DESC, B.DispOrder, A.Descript";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getAssociateCustList($AssociateCust) {
	$searchCnd = " WHERE AssociateFrom='$AssociateCust' and CustomerCd <> '$AssociateCust' and  SectorCd='{$_SESSION['SectorCd']}'";
	$sql		= "SELECT A.*,IFNULL(B.Descript,A.StateCd) AS State FROM so_customer_m A LEFT OUTER JOIN so_state_m B ON A.StateCd=B.StateCd " . $searchCnd . " ORDER BY A.IsActive DESC, B.DispOrder, A.CustomerCtgCd, A.Descript";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getDealerSubdealerList($CustomerCd) {
	$searchCnd = " WHERE CustomerCd='$CustomerCd' and B.IsActive='1' ";
	$sql		= "SELECT A.*, B.Descript, B.EMailId, B.TelNo FROM so_subdealer_m_dealer A LEFT OUTER JOIN so_subdealer_m B ON A.IdSubdealer=B.IdSubdealer" . $searchCnd . " ORDER BY B.Descript";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getSubDealerDealerList($IdSubdealer) {
	$searchCnd = " WHERE A.IdSubdealer='$IdSubdealer' ";
	$sql		= "SELECT A.*,  B.Descript, B.StateCd FROM so_subdealer_m_dealer A LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd " . $searchCnd . " ORDER BY B.Descript";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getCustomerOfSector($SectorCd) {
	return $this->getCustomerMDisp(0, '', "SectorCd='$SectorCd'");
}

public function getSubdealerMDisp($CustomerCd='', $AddFilter='') {
	$DBNameTrade = $this::DBNameTrade;
	$sql	= "SELECT A.IdSubdealer, A.SubDealerCd, A.City, A.StateCd, CONCAT(A.Descript,', ',A.City) AS Descript FROM $DBNameTrade.so_subdealer_m A";
	if ($CustomerCd=='') {
		$sql	.= " WHERE A.IsActive=1";
	} else {
		$sql	.= " INNER JOIN $DBNameTrade.so_subdealer_m_dealer B ON A.IdSubdealer=B.IdSubdealer WHERE B.CustomerCd='" . $CustomerCd . "' AND A.IsActive=1 ";
	}
	$sql	.= ($AddFilter=='' ? "" : " AND " . $AddFilter) . " ORDER BY A.Descript";

	$returnData = $this->execSelectQuery($sql);
	return $returnData;	
}

public function getSectorUserMDisp($SectorCd) {
/*	$UserType	= ($SectorCd=='I') ? self::UTSalesCoord : (($SectorCd=='C') ? self::UTASM : -1);
	$sql		= "SELECT UserName, Descript FROM " . self::DTUserM . " WHERE ActiveFlag = 0 AND UserType=$UserType";
	$UserType	= ($SectorCd=='I') ? self::UTSalesCoord : (($SectorCd=='C') ? self::UTASM : -1);	*/
	$sql		= "SELECT UserName, Descript FROM " . self::DTUserM . " WHERE ActiveFlag = 0 AND SectorCd='$SectorCd'";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getItemMDisp() {
// Always send UOM
	$sql		= "SELECT ItemCd,Descript,UOM FROM so_item_m ORDER BY Descript";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getItemTargetGroupMDisp() {
	$sql		= "SELECT ItemTargetGroupCd,Descript FROM so_item_targetgroup_m ORDER BY Descript";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getCompanyMDisp($CompanyCd=NULL) {
	if($_SESSION['SectorCd'] == 'E' && $CompanyCd != NULL){
		$CompanyCd = (($CompanyCd == '1110' || $CompanyCd == '1122') ? 1100 : 1800);		
	}
	$sql = "SELECT * FROM so_company_m WHERE CompanyCd IN('1800','1100') " . ((isset($CompanyCd)) ? " AND CompanyCd=$CompanyCd" : "") ;
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getPlaceofMagazineMDisp() {
	$sql		= "SELECT * FROM 	placeofmagazine_m order by  ConsigneeName";		// MagazineLicNo is removed
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getMagazineMDisp() {
	$sql		= "SELECT MagazineCd,Descript,MagazineDetail FROM so_magazine_m order by  Descript";		// MagazineLicNo is removed
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getItemCtgMDisp() {
// Always send UOM
	$sql		= "SELECT ItemCtgCd,Descript,UOM FROM so_item_ctg_m ORDER BY ItemCtgCd";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getSubDealerSaleItem() {
	$sql		= "SELECT * FROM subdealer_yearly_performance_item order by item_id";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;	
	}
	
public function getStateMDisp($StateCd=null) {
	$sql		= "SELECT StateCd,Descript  FROM so_state_m where".((isset($StateCd) && trim($StateCd)!='')  ? "  StateCd='$StateCd' " : "1") ." order by Descript";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;	
}
public function getStateM($StateCd) {
	$sql		= "SELECT StateCd,Descript,CCOfficeAddress  FROM so_state_m  where StateCd ='$StateCd' order by Descript";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;	
}

public function getRE11StatusMDisp() {
	$SectorCd	= $_SESSION['SectorCd'];
	$sql		= "SELECT * FROM so_re11_status_m WHERE (AppSector='' OR INSTR(AppSector, '+$SectorCd+'))";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;	
}

public function getCustomerCtgMDisp() {
	$sql		= "SELECT CustomerCtgCd,Descript FROM so_customer_ctg_m";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;	
}

public function getSubdealerCtgMDisp() {
	$sql		= "SELECT SubdealerCtgCd,Descript FROM so_subdealer_ctg_m";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;	
}

public function getAccessoryCtgM($AccessoryCtgCd) {
	$sql		= "SELECT CompanyCd, AccessoryCtgCd,Descript,HasLength,HasDelayTime,HasLDSNo,HasDelayNo,HasRelayTime,AcceptDirect,AcceptRate,UOM,UOMType FROM so_accessory_ctg_m WHERE AccessoryCtgCd=$AccessoryCtgCd ORDER BY AccessoryCtgCd";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getStatusMDisp($StatusCd, $ForForm, $AddFilter='') {
	$SectorCd	= $_SESSION['SectorCd'];
	$sql	= "SELECT A.StatusAppCd AS StatusCd, B.Descript FROM so_status_app A LEFT OUTER JOIN so_status_m B ON A.StatusAppCd=B.StatusCd WHERE A.StatusCd='" .$StatusCd. "'"
				. " AND LOCATE('".$ForForm."', B.AppForm) > 0 AND (AppSector='' OR INSTR(AppSector, '+$SectorCd+'))" . ($AddFilter=='' ? "" : " AND ".$AddFilter)
				. " ORDER BY B.Descript";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;	
}

public function getproductid() {
	$sql	= "SELECT * FROM so_dailydispatch_rep_item order by ProductId";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;	
}

public function getStatusM2Disp($ForForm, $AddFilter='') {
	$sql	= "SELECT A.StatusCd, A.Descript FROM so_status_m A WHERE LOCATE('".$ForForm."', A.AppForm) > 0" . ($AddFilter=='' ? "" : " AND ".$AddFilter)
				. " ORDER BY A.Descript";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;	
}

public function getSectorMDisp($SectorCdStr='') {
	$sql		= "SELECT * FROM " . self::DTSectorM . " WHERE !IsOverall " . (empty($SectorCdStr) ? "" : " AND LOCATE(SectorCd, '$SectorCdStr') > 0") . " ORDER BY Descript";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function setVanPriority($PlantCd, $SectorCdStr, $StateCd, $ItemCdStr) {
		$inputArr 		= array($PlantCd, $SectorCdStr, $StateCd, $ItemCdStr);
		$paraString		= vsprintf("%s, '%s', '%s', '%s'", $inputArr);
		$sql			= "call sp_reportOnlineVanStatusDispatch(" . $paraString. ")";
		$returnData 	= $this->classBusiLogic->execSelectQuery($sql, 2);
		return $returnData;
	}
	
public function getSectorCtrlData($SectorCd) {
	$sql		= "SELECT * FROM " . self::DTSectorM . " WHERE SectorCd='$SectorCd'";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getVehicleMDisp() {
	$sql		= "SELECT VehicleNo,Descript,CustomerCd,Transporter FROM so_vehicle_m ORDER BY Descript;";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;	
}

/*public function getSectorMPayDay($SectorCd) {
	$sql		= "SELECT PayDayMin,PayDayMax,PayDayDef FROM " . self::DTSectorM . " WHERE SectorCd='$SectorCd'";
	$returnData	= $this->execSelectQuery($sql);

	return $returnData;	
}*/


public function getControlData($DateANSI = NULL) {
	$DateANSI = (is_null($DateANSI)) ? date('Y-m-d') : $DateANSI;
	$sql = "SELECT * FROM so_control A WHERE A.Date = (SELECT MAX(Date) FROM so_control B WHERE B.Date <= '" . $DateANSI . "') ;";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

function getTargetYear($DateANSI=NULL, &$curMonth=NULL, &$curLogMonth=NULL, &$curYear=NULL) {
	$DateANSI		= (is_null($DateANSI)) ? 'now' : $DateANSI;
	$DateANSI		= new DateTime($DateANSI);
	$curMonth		= $DateANSI->format('n');
	$curLogMonth	= (($curMonth+8) % 12) + 1;				// Logical Month: April-1, May-2, ..., Dec-9, Jan-10, Feb-11, Mar-12
	$curYear		= $DateANSI->format('Y');
	$targetYear	= $curYear - ($curMonth<=3 ? 1 : 0);
	$targetYear	= $targetYear . '-' . ($targetYear+1);			// eg 2011-2012
	return $targetYear;
}

function monthName($monthNoLogical, $isFull=FALSE) {
// Return Full/Short Month Name of given Logical Month No.
	return date(($isFull) ? 'F' : 'M', mktime(0, 0, 0, ($monthNoLogical+4)%12-1, 1, 2000));
}

// Utility Functions --------------------------------------------------------------------------------------------------------------------------------------
public function importData($srcFile, $tableName, $row1Status=1) {
// Import data from Tab limited Text file in specified Table. 
// row1Status 0: No Column Names in 1st Row. Data starts from 1st row. Assume ALL column values given in proper order. Can not skip any column
// 			  1: 1st Row with proper Column Names. (May contain Spaces, which are removed by this proc). Can skip any column (provided they have Null allowed or Default Values)
//			 -1: 1st Row with Column Names which have to be ignored. Data starts from 2nd row, but act as row1Status=0
$sql = "TRUNCATE TABLE ". $tableName;
$queryResult	= $this->execUpdateQuery($sql);

$handle = fopen($srcFile, "r");
if ($handle) { 
	$arrSrcData = explode("\n", fread($handle, filesize($srcFile))); 
}
$sizearrSrcData = count($arrSrcData);
$dataRow = ($row1Status==0) ? 0 : 1;

$columnCount	= 1000;
if ($row1Status == 1) {
	$curRec	= explode("\t", $arrSrcData[0]);
	$j		= count($curRec)-1;
	$isEmptyHead	= TRUE;
	while ($isEmptyHead && $j >= 0 ) {
		if (trim($curRec[$j])=='') {
			$j--;
		} else {
			$isEmptyHead = FALSE;
		}
	}
	$curRec	= array_slice($curRec, 0, $j+1);
	$columnCount= count($curRec);
	$columnList	= str_replace(' ', '', "`" . trim(implode("`,`", $curRec)) . "`");
}

for (; $dataRow < $sizearrSrcData; $dataRow++) {
	$curRec	= explode("\t", $arrSrcData[$dataRow]);
	$curRec	= array_slice($curRec, 0, $columnCount);
	$curRec	= preg_replace('/"$/','',preg_replace('/^"/', '', $curRec));	// remove " at Start & End of any string (put by Excel when converting Strings including ,)
	$curRec	= str_replace("'","\'",$curRec);		// Escape embeded 's with \'s
	
	$rowData		= str_replace("\r", '', implode("", $curRec));
	if (!empty($rowData)) {
		$rowData	= trim(implode("','", $curRec));
		$rowData	= "'" . $rowData . "'";
		$sql		= "INSERT INTO " . $tableName . ($row1Status==1 ? "(" . $columnList . ")" : "") . " VALUES (" . $rowData . ");";
		$queryResult= $this->execUpdateQuery($sql);
	}
}
}

public function exportTargetMonth($data) {
// Though utility, actually a Report which is downloaded
	$DTSAnsi		= $this->MY2AnsiDate($data['MYS']);
	$Year			= $this->getTargetYear($DTSAnsi, $curMonth, $curLogMonth);
	$displayYear	= substr($Year, ($curLogMonth<=9) ? 0 : 5, 4);

	$MonthName		= $this->monthName($curLogMonth, FALSE);
	$inputArr 		= array(1, $Year, $curLogMonth, $DTSAnsi);
	$paraString		= vsprintf("%s, '%s',%s, '%s'", $inputArr);
	$sql			= "call sp_exportTarget(". $paraString. ")";
	$reportData	= $this->execSelectQuery($sql);
	If (count($reportData)==0) {
		echo '<script>alert("No data to print for specified Month.")</script>';
		return;
	}

	$fileName = 'wrk/exportMonthlyTarget-' . $MonthName . '-'.  $displayYear . '.txt';
	$handle = fopen($fileName,'wb');

	fwrite($handle, str_repeat("\t",3) . "Monthly Target for " . $MonthName . ','.  $displayYear . "\r\n");
	fwrite($handle, "\r\n");	


	fwrite($handle, "CompanyCd\t" . "CustomerCd\t" . "ItemCd\t" . "TargetFrom\t" . "TargetUpto\t" . "TargetReceiptDate\t" . "SalesOrg\t" . "Dist.Channel\t" . "Cust.Quantity\t" . "\r\n");
	for ($i=0; $i<count($reportData); $i++) {
		fwrite($handle, $reportData[$i]['CompanyCd']."\t" . $reportData[$i]['CustomerCd']."\t" . $reportData[$i]['ItemCd']."\t" . $reportData[$i]['TargetFrom']."\t" 
			. $reportData[$i]['TargetUpto']."\t" . $reportData[$i]['Date']."\t" . $reportData[$i]['SalesOrg']."\t" . $reportData[$i]['DistChannel']."\t" . $reportData[$i]['Quantity']."\t" 
		. "\r\n");
	}

	fclose($handle);
	echo "<script language='javascript'>window.location.href='includes/download.php?fileName=$fileName&baseDir=./../wrk/';</script>";
}

public function exportTargetYear($data) {
// Though utility, actually a Report which is downloaded
	$DTSAnsi		= $this->MY2AnsiDate($data['MYS']);
	$Year			= $this->getTargetYear($DTSAnsi, $curMonth, $curLogMonth);
	$displayYear	= substr($Year, ($curLogMonth<=9) ? 0 : 5, 4);

	$MonthName		= $this->monthName($curLogMonth, FALSE);
	$inputArr 		= array(0, $Year, $curLogMonth, $DTSAnsi);
	$paraString		= vsprintf("%s, '%s',%s, '%s'", $inputArr);
	$sql			= "call sp_exportTarget(". $paraString. ")";
	$reportData	= $this->execSelectQuery($sql);
	If (count($reportData)==0) {
		echo '<script>alert("No data to print for specified Year+Month.")</script>';
		return;
	}


	$fileName = 'wrk/exportYearlyTarget-' . $MonthName . '-'.  $displayYear . '.txt';
	$handle = fopen($fileName,'wb');

	fwrite($handle, str_repeat("\t",3) . "Yearly Target for " . $MonthName . ','.  $displayYear . "\r\n");
	fwrite($handle, "\r\n");	


	fwrite($handle, "CompanyCd\t" . "CustomerCd\t" . "ItemCd\t" . "TargetFrom\t" . "TargetUpto\t" . "TargetReceiptDate\t" . "SalesOrg\t" . "Dist.Channel\t" . "Cust.Quantity\t" . "\r\n");
	for ($i=0; $i<count($reportData); $i++) {
		fwrite($handle, $reportData[$i]['CompanyCd']."\t" . $reportData[$i]['CustomerCd']."\t" . $reportData[$i]['ItemCd']."\t" . $reportData[$i]['TargetFrom']."\t" 
			. $reportData[$i]['TargetUpto']."\t" . $reportData[$i]['Date']."\t" . $reportData[$i]['SalesOrg']."\t" . $reportData[$i]['DistChannel']."\t" . $reportData[$i]['Quantity']."\t" 
		. "\r\n");
	}

	fclose($handle);
	echo "<script language='javascript'>window.location.href='includes/download.php?fileName=$fileName&baseDir=./../wrk/';</script>";
}

public function getEMailTemplate($EMailTemplateNo) {
	$sql = "SELECT Subject, Body, EMailIdCC FROM so_email_template_m WHERE EMailTemplateNo=$EMailTemplateNo" ;
	$templateArr = $this->execSelectQuery($sql);
	$templateArr = array_map('trim', $templateArr[0]); 
	return 	$templateArr;
}

// Reports  ----------------------------------------------------------------------------------------------------------------------------------------------
public function reportTargetMonthly($data) {
	$DTSAnsi		= $this->MY2AnsiDate($data['MYS']);
	$Year			= $this->getTargetYear($DTSAnsi, $curMonth, $curLogMonth);
	$displayYear	= substr($Year, ($curLogMonth<=9) ? 0 : 5, 4);

	$MonthName		= $this->monthName($curLogMonth, FALSE);
	$inputArr 		= array($Year, $curLogMonth);
	$paraString		= vsprintf("'%s',%s", $inputArr);
	$sql			= "call sp_repTargetMonthly(". $paraString. ")";
	$pivotColSupAr = array();
	$flatDataAr	= $this->execSelectQuery($sql, 0, $pivotColSupAr);
	$pivotColAr	= $pivotColSupAr[0];
	If (count($flatDataAr)==0) {
		echo '<script>alert("No data to print for the specified Month.")</script>';
		return;
	}
	$pivotDataAr = array();
	$flatDataArCnt = count($flatDataAr);
	for ($i=0; $i<$flatDataArCnt; $i++) {
		$curCustCd	= $flatDataAr[$i]['CustomerCd'];
		$curItem	= $flatDataAr[$i]['Item'];
		$pivotDataAr[$curCustCd]['State']			= $flatDataAr[$i]['State'];
		$pivotDataAr[$curCustCd]['CustomerCtgCd']	= $flatDataAr[$i]['CustomerCtgCd'];
		$pivotDataAr[$curCustCd]['Customer']		= $flatDataAr[$i]['Customer'];
		$pivotDataAr[$curCustCd]['City']			= $flatDataAr[$i]['City'];
		$pivotDataAr[$curCustCd]['Date']			= $flatDataAr[$i]['Date'];
		$pivotDataAr[$curCustCd][$curItem]['MonthStock']	= $flatDataAr[$i]['MonthStock'];
		$pivotDataAr[$curCustCd][$curItem]['Quantity']		= $flatDataAr[$i]['Quantity'];
	}

	$tableKeys = array_keys($pivotDataAr);
//	$totalAr	= array_fill(0, count($pivotColAr), 0);
	$totalAr	= array();
	for ($j=0; $j<count($pivotColAr); $j++) {
		$totalAr[$j]['Quantity']=0;
		$totalAr[$j]['MonthStock']=0;
	}
	
	$fileName = 'wrk/repTarget-' . $MonthName . '-'.  $displayYear . '.txt';
	$handle = fopen($fileName,'wb');
	
	fwrite($handle, str_repeat("\t",3) . "Monthly Target for " . $MonthName . ','.  $displayYear . "\r\n");
	fwrite($handle, "\r\n");	

	fwrite($handle, "Sr.\t" . "State\t" . "Ctg\t" . "Customer\t" . "City\t" . "Rcpt.Date\t" );
	fwrite($handle, "\t");
	foreach ($pivotColAr as $pivotColArRow) {
		fwrite($handle, str_pad("Stock",10,'-',STR_PAD_BOTH)."\t");
	}
	fwrite($handle, "\t");
	foreach ($pivotColAr as $pivotColArRow) {
		fwrite($handle, str_pad("Target",10,'-',STR_PAD_BOTH)."\t");
	}
	fwrite($handle, "\r\n");

	fwrite($handle, "No.\t" . "\t" . "\t" . "\t" . "\t" . "\t" );
	fwrite($handle, "\t");
	foreach ($pivotColAr as $pivotColArRow) {
		fwrite($handle, $pivotColArRow['Item'] . "\t");
	}
	fwrite($handle, "\t");
	foreach ($pivotColAr as $pivotColArRow) {
		fwrite($handle, $pivotColArRow['Item'] . "\t");
	}
	fwrite($handle, "\r\n");

	$SrNo = 1;
	foreach ($tableKeys as $tableKey) {
		$Row = $pivotDataAr[$tableKey];
		fwrite($handle, $SrNo."\t" . $Row['State']."\t" . $Row['CustomerCtgCd']."\t" . $Row['Customer']."\t" . $Row['City']."\t" . $Row['Date']."\t");

		fwrite($handle, "\t");
		$j = 0;
		foreach ($pivotColAr as $pivotColArRow) {
			$curQty	= (isset($Row[$pivotColArRow['Item']])) ? $Row[$pivotColArRow['Item']]['MonthStock'] : 0;
			fwrite($handle, $curQty . "\t");
			$totalAr[$j]['MonthStock'] += $curQty;
			$j += 1;
		}
		fwrite($handle, "\t");
		$j = 0;
		foreach ($pivotColAr as $pivotColArRow) {
			$curQty	= (isset($Row[$pivotColArRow['Item']])) ? $Row[$pivotColArRow['Item']]['Quantity'] : 0;
			fwrite($handle, $curQty . "\t");
			$totalAr[$j]['Quantity'] += $curQty;
			$j += 1;
		}
		fwrite($handle, "\r\n");
		$SrNo += 1;
	}
	
	fwrite($handle, "\r\n");
	fwrite($handle, "\t" . "\t" . "\t" . "T O T A L\t" . "\t" . "\t" );
	fwrite($handle, "\t");
	for ($j=0; $j<count($totalAr); $j++) fwrite($handle, $totalAr[$j]['MonthStock'] . "\t");
	fwrite($handle, "\t");
	for ($j=0; $j<count($totalAr); $j++) fwrite($handle, $totalAr[$j]['Quantity'] . "\t");
	fwrite($handle, "\r\n");
		
	fclose($handle);
	echo "<script language='javascript'>window.location.href='includes/download.php?fileName=$fileName&baseDir=./../wrk/';</script>";
}

public function reportTargetYearly($data) {
	$DTSAnsi		= $this->convertDate($data['DTS'], TRUE, 1);
	$Year			= $this->getTargetYear($DTSAnsi);

	$inputArr 		= array($Year);
	$paraString		= vsprintf("'%s'", $inputArr);
	$sql			= "call sp_repTargetYearly(". $paraString. ")";
	$reportData	= $this->execSelectQuery($sql, 2);
	If (count($reportData)==0) {
		echo '<script>alert("No data to print for the specified Year.")</script>';
		return;
	}
	$arrayKeys = array_keys($reportData[0]);		// 1,3,5

	$fileName = 'wrk/repTarget-' .  $Year . '.txt';
	$handle = fopen($fileName,'wb');
	
	fwrite($handle, str_repeat("\t",3) . "Yearly Target for " . $Year . "\r\n");
	fwrite($handle, "\r\n");
	fwrite($handle, "Sr." . "\t");
	for ($i=1; $i<count($arrayKeys); $i+=2) {
		$separatorAt = strpos($arrayKeys[$i], '~');
		if ($separatorAt===FALSE)
			fwrite($handle, $arrayKeys[$i] . "\t");
		else
			fwrite($handle, substr($arrayKeys[$i],0,$separatorAt) . "\t");
	}
	fwrite($handle, "\r\n");	
	fwrite($handle, "\t");
	for ($i=1; $i<count($arrayKeys); $i+=2) {
		$separatorAt = strpos($arrayKeys[$i], '~');
		if ($separatorAt===FALSE)
			fwrite($handle, "\t");
		else
			fwrite($handle, substr($arrayKeys[$i],$separatorAt+1) . "\t");
	}
	fwrite($handle, "\r\n");	


	$columnCount = count($reportData[0])/2;
	$SrNo = 1;
	for ($i=0; $i<count($reportData); $i++) {
		fwrite($handle, $SrNo."\t");
		for ($j=0; $j<$columnCount; $j++) {
			fwrite($handle, $reportData[$i][$j] . "\t");
		}
		fwrite($handle, "\r\n" );
		$SrNo += 1;
	}

	fclose($handle);
	echo "<script language='javascript'>window.location.href='includes/download.php?fileName=$fileName&baseDir=./../wrk/';</script>";
}

function getdailyaedsoldNstockposition($customerCd, $podate){
$currentdate= date('Y-m-d');
if($customerCd!=''){
$customerCdwhere = "C.CustomerCd='$customerCd'";
}
else{ 
$customerCdwhere=1; 
}
if($podate !=''){

$podatewhere  ="DATE(B.DATETIME)='$podate'";
}
else{
$podatewhere="DATE(B.DATETIME)='$currentdate'";
}
$arritemcd = array("20000120", "20001340", "20001341", "20002672");

$resultArr= array();
$arrCustomerMDisp	= $this->getCustomerMDisp(1, $customerCd);
$m=sizeof($arritemcd);
foreach($arrCustomerMDisp as $customer){
	$cus=$customer['CustomerCd'];
	$i=0;
	for($i=0;$i<$m; $i++){
		$sql = "SELECT A.*, B.*, C.* From so_expdet_magazine_item A JOIN so_expdet B ON A.IdExpDet= B.IdExpDet JOIN  so_customer_m C ON B.CustomerCd=C.CustomerCd
		WHERE  B.CustomerCd='$cus' and A.ItemCd='$arritemcd[$i]'" ;
		$queryArr = $this->execSelectQuery($sql);
		$resultArr = array_merge($resultArr, $queryArr);
		}
}
return $resultArr;
}


//CIL+Instution Yearly and Target Report
public function reportTargetMonthlyCib2b($data) {
	$DTSAnsi		= $this->MY2AnsiDate($data['MYS']);
	$Year			= $this->getTargetYear($DTSAnsi, $curMonth, $curLogMonth);
	$displayYear	= substr($Year, ($curLogMonth<=9) ? 0 : 5, 4);

	$MonthName		= $this->monthName($curLogMonth, FALSE);
	$inputArr 		= array($Year, $curLogMonth, $_SESSION['SectorCd']);
	$paraString		= vsprintf("'%s',%s,'%s'", $inputArr);
	$sql			= "call sp_repTargetMonthlyCib2b(". $paraString. ")";
	$pivotColSupAr = array();
	$flatDataAr	= $this->execSelectQuery($sql, 0, $pivotColSupAr);
	
	$pivotColAr	= $pivotColSupAr[0];

	If (count($flatDataAr)==0) {
		echo '<script>alert("No data to print for the specified Month.")</script>';
		return;
	}
	$pivotDataAr = array();
	$flatDataArCnt = count($flatDataAr);
	for ($i=0; $i<$flatDataArCnt; $i++) {
		$curCustCd	= $flatDataAr[$i]['CustomerCd'];
		$curItem	= $flatDataAr[$i]['Item'];
		$pivotDataAr[$curCustCd]['State']			= $flatDataAr[$i]['State'];
		$pivotDataAr[$curCustCd]['CustomerCtgCd']	= $flatDataAr[$i]['CustomerCtgCd'];
		$pivotDataAr[$curCustCd]['Customer']		= $flatDataAr[$i]['Customer'];
		$pivotDataAr[$curCustCd]['City']			= $flatDataAr[$i]['City'];
		$pivotDataAr[$curCustCd]['Date']			= $flatDataAr[$i]['Date'];
		$pivotDataAr[$curCustCd][$curItem]['MonthStock']	= $flatDataAr[$i]['MonthStock'];
		$pivotDataAr[$curCustCd][$curItem]['Quantity']		= $flatDataAr[$i]['Quantity'];
	}

	$tableKeys = array_keys($pivotDataAr);
//	$totalAr	= array_fill(0, count($pivotColAr), 0);
	$totalAr	= array();
	for ($j=0; $j<count($pivotColAr); $j++) {
		$totalAr[$j]['Quantity']=0;
		$totalAr[$j]['MonthStock']=0;
	}
	
	$fileName = 'wrk/repTarget-' . $MonthName . '-'.  $displayYear . '.txt';
	$handle = fopen($fileName,'wb');
	
	fwrite($handle, str_repeat("\t",3) . "Monthly Target for " . $MonthName . ','.  $displayYear . "\r\n");
	fwrite($handle, "\r\n");	

	fwrite($handle, "Sr.\t" . "State\t" . "Customer\t" . "City\t" . "Rcpt.Date\t" );
	fwrite($handle, "\t");
	/*foreach ($pivotColAr as $pivotColArRow) {
		fwrite($handle, str_pad("Stock",10,'-',STR_PAD_BOTH)."\t");
	}
	fwrite($handle, "\t");*/
	foreach ($pivotColAr as $pivotColArRow) {
		fwrite($handle, str_pad("Target",10,'-',STR_PAD_BOTH)."\t");
	}
	fwrite($handle, "\r\n");

	fwrite($handle, "No.\t" . "\t" . "\t" . "\t" . "\t" );
	/*fwrite($handle, "\t");
	foreach ($pivotColAr as $pivotColArRow) {
		fwrite($handle, $pivotColArRow['Item'] . "\t");
	}*/
	fwrite($handle, "\t");
	foreach ($pivotColAr as $pivotColArRow) {
		fwrite($handle, $pivotColArRow['Item'] . "\t");
	}
	fwrite($handle, "\r\n");

	$SrNo = 1;
	foreach ($tableKeys as $tableKey) {
		$Row = $pivotDataAr[$tableKey];
		fwrite($handle, $SrNo."\t" . $Row['State']."\t" . $Row['Customer']."\t" . $Row['City']."\t" . $Row['Date']."\t");

		fwrite($handle, "\t");
		$j = 0;
		/*foreach ($pivotColAr as $pivotColArRow) {
			$curQty	= (isset($Row[$pivotColArRow['Item']])) ? $Row[$pivotColArRow['Item']]['MonthStock'] : 0;
			fwrite($handle, $curQty . "\t");
			$totalAr[$j]['MonthStock'] += $curQty;
			$j += 1;
		}
		fwrite($handle, "\t");*/
		$j = 0;
		foreach ($pivotColAr as $pivotColArRow) {
			$curQty	= (isset($Row[$pivotColArRow['Item']])) ? $Row[$pivotColArRow['Item']]['Quantity'] : 0;
			fwrite($handle, $curQty . "\t");
			$totalAr[$j]['Quantity'] += $curQty;
			$j += 1;
		}
		fwrite($handle, "\r\n");
		$SrNo += 1;
	}
	
	fwrite($handle, "\r\n");
	fwrite($handle, "\t" . "\t" . "T O T A L\t" . "\t" . "\t" );
	fwrite($handle, "\t");
	/*for ($j=0; $j<count($totalAr); $j++) fwrite($handle, $totalAr[$j]['MonthStock'] . "\t");
	fwrite($handle, "\t");*/
	for ($j=0; $j<count($totalAr); $j++) fwrite($handle, $totalAr[$j]['Quantity'] . "\t");
	fwrite($handle, "\r\n");
		
	fclose($handle);
	echo "<script language='javascript'>window.location.href='includes/download.php?fileName=$fileName&baseDir=./../wrk/';</script>";
}


public function reportTargetYearlyCib2b($data) {
	$DTSAnsi		= $this->convertDate($data['DTS'], TRUE, 1);
	$Year			= $this->getTargetYear($DTSAnsi);

	$inputArr 		= array($Year,$_SESSION['SectorCd']);
	$paraString		= vsprintf("'%s','%s'", $inputArr);
	$sql			= "call sp_repTargetYearlyCib2b(". $paraString. ")";

	$reportData	= $this->execSelectQuery($sql, 2);

	If (count($reportData)==0) {
		echo '<script>alert("No data to print for the specified Year.")</script>';
		return;
	}
	$arrayKeys = array_keys($reportData[0]);		// 1,3,5

	$fileName = 'wrk/repTarget-' .  $Year . '.txt';
	$handle = fopen($fileName,'wb');
	
	fwrite($handle, str_repeat("\t",3) . "Yearly Target for " . $Year . "\r\n");	
	
	$columnCount = count($reportData[0])/2;
	$SrNo = 1;	
	$previousCustomerCd = 0;
	for ($i=0; $i<count($reportData); $i++) {
		if($reportData[$i][0] != $previousCustomerCd){
			fwrite($handle, "\r\n" );
			$previousCustomerCd = $reportData[$i][0];
			fwrite($handle, 'Customer' . "\t");
			fwrite($handle, $reportData[$i][1] . "\t");
			fwrite($handle, "\r\n" );
			fwrite($handle, "\r\n");
			fwrite($handle, "Sr." . "\t");
			for ($z=1; $z<count($arrayKeys); $z+=2) {		
				if ($arrayKeys[$z]!='Customer' && $arrayKeys[$z]!='CustomerCd')	fwrite($handle, $arrayKeys[$z] . "\t");
			}
			fwrite($handle, "\r\n");	
			fwrite($handle, "\t");
			for ($x=1; $x<count($arrayKeys); $x+=2) {
				if ($arrayKeys[$x]!='Customer' && $arrayKeys[$x]!='CustomerCd')	fwrite($handle, "\t");
			}
			fwrite($handle, "\r\n");
			
		}
		fwrite($handle, $SrNo."\t");
		for ($j=2; $j<$columnCount; $j++) {
			fwrite($handle, $reportData[$i][$j] . "\t");
		}
		fwrite($handle, "\r\n" );
		$SrNo += 1;
	}

	fclose($handle);
	echo "<script language='javascript'>window.location.href='includes/download.php?fileName=$fileName&baseDir=./../wrk/';</script>";
}

public function reportMissingTargetCib2b($data) {
	$DTSAnsi	= $this->MY2AnsiDate($data['MYS']);
	$reportData	= $this->MissingTargetDataCib2b($DTSAnsi, $Year, $displayYear, $MonthName);
	If (count($reportData)==0) {
		echo '<script>alert("No data to print for specified Year+Month.")</script>';
		return;
	}

	$fileName = 'wrk/repMissingTarget-' . $MonthName . '-'.  $displayYear . '.txt';
	$handle = fopen($fileName,'wb');

	fwrite($handle, str_repeat("\t",1) . "List of Customers for Missing Monthly Target for " . $MonthName . ','.  $displayYear . "\r\n");
	fwrite($handle, "\r\n");	


	fwrite($handle, "Customer Code\t" . "Customer Name\t" . "\r\n");
	for ($i=0; $i<count($reportData); $i++) {
		fwrite($handle, $reportData[$i]['CustomerCd']."\t" . $reportData[$i]['Descript']."\t" . "\r\n");
	}

	fclose($handle);
	echo "<script language='javascript'>window.location.href='includes/download.php?fileName=$fileName&baseDir=./../wrk/';</script>";
}

public function MissingTargetDataCib2b($DTSAnsi, &$Year, &$displayYear, &$MonthName) {
	$Year			= $this->getTargetYear($DTSAnsi, $curMonth, $curLogMonth);
	$displayYear	= substr($Year, ($curLogMonth<=9) ? 0 : 5, 4);
	$MonthName		= $this->monthName($curLogMonth, FALSE);
	$inputArr 		= array(1, $Year, $curLogMonth, $_SESSION['SectorCd']);
	$paraString		= vsprintf("%s, '%s', %s, '%s'", $inputArr);
	$sql			= "call sp_repMissingTargetCib2b(". $paraString. ")";

	$reportData	= $this->execSelectQuery($sql);
	return $reportData;
}

//END of CIL+Institution Yearly and Monthly Target Report
//------------------------------------------------------------------------------------


public function MY2AnsiDate($MY) {		// mm-yyyy to 1st Day Ansi Date ie 03-2013 --> 2013-03-01
	return substr($MY, 3, 4) . '-' . substr($MY, 0, 2) . '-' . '01';
}

public function MissingTargetData($DTSAnsi, &$Year, &$displayYear, &$MonthName) {
	$Year			= $this->getTargetYear($DTSAnsi, $curMonth, $curLogMonth);
	$displayYear	= substr($Year, ($curLogMonth<=9) ? 0 : 5, 4);
	$MonthName		= $this->monthName($curLogMonth, FALSE);
	$inputArr 		= array(1, $Year, $curLogMonth);
	$paraString		= vsprintf("%s, '%s',%s", $inputArr);
	$sql			= "call sp_repMissingTarget(". $paraString. ")";
	$reportData	= $this->execSelectQuery($sql);
	return $reportData;
}

public function MissingTargetDataTrade($DTSAnsi, &$Year, &$displayYear, &$MonthName) {
	$Year			= $this->getTargetYear($DTSAnsi, $curMonth, $curLogMonth);
	$displayYear	= substr($Year, ($curLogMonth<=9) ? 0 : 5, 4);
	$MonthName		= $this->monthName($curLogMonth, FALSE);
	$inputArr 		= array(1, $Year, $curLogMonth);
	$paraString		= vsprintf("%s, '%s',%s", $inputArr);
	$sql			= "call sp_repMissingTargetTrade(". $paraString. ")";
	$reportData	= $this->execSelectQuery($sql);
	return $reportData;
}

public function SubdealerMissingTargetData($DTSAnsi, &$Year, &$displayYear, &$MonthName) {
	$Year			= $this->getTargetYear($DTSAnsi, $curMonth, $curLogMonth);
	$displayYear	= substr($Year, ($curLogMonth<=9) ? 0 : 5, 4);
	$MonthName		= $this->monthName($curLogMonth, FALSE);
	$inputArr 		= array(1, $Year, $curLogMonth);
	$paraString		= vsprintf("%s, '%s',%s", $inputArr);
	$sql			= "call sp_repSubdealerMissingTarget(". $paraString. ")";
	$reportData	= $this->execSelectQuery($sql);
	return $reportData;
}


public function reportMissingTarget($data) {
	$DTSAnsi	= $this->MY2AnsiDate($data['MYS']);
	$reportData	= $this->MissingTargetData($DTSAnsi, $Year, $displayYear, $MonthName);
	If (count($reportData)==0) {
		echo '<script>alert("No data to print for specified Year+Month.")</script>';
		return;
	}

	$fileName = 'wrk/repMissingTarget-' . $MonthName . '-'.  $displayYear . '.txt';
	$handle = fopen($fileName,'wb');

	fwrite($handle, str_repeat("\t",1) . "List of Customers for Missing Monthly Target for " . $MonthName . ','.  $displayYear . "\r\n");
	fwrite($handle, "\r\n");	


	fwrite($handle, "Customer Code\t" . "Customer Name\t" . "Email Id \t" . "\r\n");
	for ($i=0; $i<count($reportData); $i++) {
		fwrite($handle, $reportData[$i]['CustomerCd']."\t" . $reportData[$i]['Descript']."\t" . $reportData[$i]['EMailId']."\t" . "\r\n");
	}

	fclose($handle);
	echo "<script language='javascript'>window.location.href='includes/download.php?fileName=$fileName&baseDir=./../wrk/';</script>";
}

public function sendEMailMissingTarget() {
	$templateArr = $this->getEMailTemplate(6);
	
	$objDTSAnsi = new DateTime(date('Y-m') . '-01');
	$objDTSAnsi->add(new DateInterval('P1M'));
	$DTSAnsi	= $objDTSAnsi->format('Y-m-d');
	$eMailDetailArr	= $this->MissingTargetData($DTSAnsi, $Year, $displayYear, $MonthName);
	//$EmailId = 'websupport@solargroup.com';
	foreach ($eMailDetailArr as $eMailDetailRow) {
		$EmailId= $eMailDetailRow['EMailId'];
		$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($MonthName.','.$displayYear));
		$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
		$objSolarMailer = new solarMailer();
		$objSolarMailer->sendSolarMail($eMailDetailRow['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	}
}


public function getitemforTargetVsAchieveNew($data) {
	$CustomerCd = ($_SESSION['IsCustomer']) ? $_SESSION['CustomerCd'] : $data['CustomerCd'];
	$DTS =  $this->convertDate($data['DTS'], TRUE, 1);
	$DTE =  $this->convertDate($data['DTE'], TRUE,1);
	$Year 	= $this->getTargetYear($DTS);
	$Year2	= $this->getTargetYear($DTE);
	if ($Year != $Year2) {
		$headerData['DTE'] = '31-03-' . substr($Year, 0, 4);
		$DTE		= $this->convertDate($headerData['DTE'], TRUE, 1);
	}
	$sql = "Select F.ItemCd, F.Descript from (SELECT Distinct(A.ItemCd) as ItemCd From so_expdet_magazine_item A JOIN so_expdet B ON A.IdExpDet= B.IdExpDet 
			WHERE  B.CustomerCd='$CustomerCd' and B.DateTime between '$DTS' and '$DTE'
			UNION 
			SELECT Distinct(C.ItemCd) As ItemCd From so_target_item C JOIN so_target D  ON C.Year = D.Year and C.Month=D.Month and C.CustomerCd= D.CustomerCd and C.YMFlag= D.YMFlag
			WHERE  D.CustomerCd='$CustomerCd' and D.Year = '$Year' ) E JOIN so_item_m F ON E.ItemCd =F.ItemCd  order by F.DispOrder" ;
	$resultData = $this->execSelectQuery($sql);
	return $resultData;
		
}



public function reportTargetVsAchieve($data) {
	$CustomerCd = ($_SESSION['IsCustomer']) ? $_SESSION['CustomerCd'] : $data['CustomerCd'];
	if ($CustomerCd=='') return;

	$data['DTS']	= preg_replace('/(\d{2})[-\/](\d{2})[-\/](\d{4})/', "01-$2-$3", $data['DTS']);
	$DTSAnsi		= $this->convertDate($data['DTS'], TRUE, 1);
	$DTEAnsi		= $this->convertDate($data['DTE'], TRUE, 1);
	$Year			= $this->getTargetYear($DTSAnsi);
	$Year2			= $this->getTargetYear($DTEAnsi);
	if ($Year != $Year2) {
		$data['DTE'] = '31-03-' . substr($Year, 0, 4);
		$DTEAnsi	 = $this->convertDate($data['DTE'], TRUE, 1);
	}
	$inputArr 		= array($Year, $DTSAnsi, $DTEAnsi, $CustomerCd);
	$paraString		= vsprintf("'%s','%s','%s','%s'",$inputArr);
	$sql			= "call sp_repTargetVsAchieve(". $paraString. ")";

	$reportData	= $this->execSelectQuery($sql, 2);
	If (count($reportData)==0) {
		echo '<script>alert("No data to print for the specified Date Range")</script>';
		return;
	}

	$DTS1 = $data['DTS'];			// preg_replace('/(\d{2})[-\/](\d{2})[-\/](\d{4})/', "01-$2-$3", $data['DTS']);
	$arrCustomerMDisp = $this->getCustomerMDisp(0, $CustomerCd);
	$repName = $arrCustomerMDisp[0]['Descript'] . ' for ' . $DTS1 . ' to ' . $data['DTE'];

	$reportTitle = "Target v/s Achievement of " . $repName;
	$classBusiLogic = $this;
	$actionBM = 1 + 0;
	include_once("includes/inc.view.report.php");
	return;


// Following script is for Downloading the Report. Not in use currently
	$arrayKeys = array_keys($reportData[0]);		// 1,3,5

	$repName = 'Cust.' . $CustomerCd . ' for ' . $data['DTS'] . '-' . $data['DTE'];
	$fileName = 'wrk/repTargetVsAchieve-' . $repName . '.txt';
	$handle = fopen($fileName,'wb');
	
	fwrite($handle, str_repeat("\t",1) . "Target v/s Achievement for " . $repName . "\r\n");
	fwrite($handle, "\r\n");
	fwrite($handle, "Sr." . "\t");
	for ($i=1; $i<count($arrayKeys); $i+=2) {
		$separatorAt = strpos($arrayKeys[$i], '~');
		if ($separatorAt===FALSE)
			fwrite($handle, $arrayKeys[$i] . "\t");
		else
			fwrite($handle, substr($arrayKeys[$i],0,$separatorAt) . "\t");
	}
	fwrite($handle, "\r\n");	
	fwrite($handle, "\t");
	for ($i=1; $i<count($arrayKeys); $i+=2) {
		$separatorAt = strpos($arrayKeys[$i], '~');
		if ($separatorAt===FALSE)
			fwrite($handle, "\t");
		else
			fwrite($handle, substr($arrayKeys[$i],$separatorAt+1) . "\t");
	}
	fwrite($handle, "\r\n");	


	$columnCount = count($reportData[0])/2;
	$SrNo = 1;
	for ($i=0; $i<count($reportData); $i++) {
		fwrite($handle, $SrNo."\t");
		for ($j=0; $j<$columnCount; $j++) {
			fwrite($handle, $reportData[$i][$j] . "\t");
		}
		fwrite($handle, "\r\n" );
		$SrNo += 1;
	}

	fclose($handle);
	echo "<script language='javascript'>window.location.href='includes/download.php?fileName=$fileName&baseDir=./../wrk/';</script>";
}


public function sendEMailTargetVSAchievement($eMailDetailArr, $CustomerCd, $EmailId, $CustomerName, $DTS, $DTE) {
	$templateArr = $this->getEMailTemplate(58); // Body not in use: EmialID CC is Used 
	$eMailDetailRowCount = count($eMailDetailArr);
	$curRow=0;
	$eMailBody = "Dear ".$CustomerName.",<br/> For your information, your Target vs achievement for ".$DTS." to ". $DTE;
	$eMailBody .= "<br/><br/><table width='50%' cellspacing='1' cellpadding='5' border='1' style='border-collapse:collapse; font-size:12px;' class='grid report'>";
	$eMailBody .= "<tr style='background-color:#94E9FF'>
					<th>Item</th>
					<th>Target </th>
					<th>Achievement</th>
					<th>Variation</th>
					<th>Percentage</th>
				</tr>";

	while ($curRow < $eMailDetailRowCount) {
		$curCustomer = $CustomerCd;
		$curEMailId = $EmailId;
		//$curEMailId = 'websupport@solargroup.com';
		$Dim2Arr = array();
		$Dim2ArrCurRow = 0;
		$Month = date('M');
		
		while ($curRow < $eMailDetailRowCount  && $curCustomer == $CustomerCd) {
			$Dim2Arr[$Dim2ArrCurRow] = array($eMailDetailArr[$curRow]['Item'], $eMailDetailArr[$curRow][$Month.'~TargetMonth']
											, $eMailDetailArr[$curRow][$Month.'~Achievement']);
			$eMailBody .= "<tr>";
			$eMailBody .= "<td width='26%'>".$eMailDetailArr[$curRow]['Item']."</td>";
			$eMailBody .= "<td width='8%' align='right'>".$eMailDetailArr[$curRow][$Month.'~TargetMonth']."</td>";
			$eMailBody .= "<td width='8%' align='right'>".$eMailDetailArr[$curRow][$Month.'~Achievement']."</td>";
			$eMailBody .= "<td width='8%' align='right'>".sprintf('%.2f', ($eMailDetailArr[$curRow][$Month.'~Achievement'] - $eMailDetailArr[$curRow][$Month.'~TargetMonth'])) ."</td>";
			$eMailBody .= "<td width='8%' align='right'>".sprintf('%.2f', ((($eMailDetailArr[$curRow][$Month.'~Achievement'] * 100)/$eMailDetailArr[$curRow][$Month.'~TargetMonth'])-100)) ."%</td>";
			$eMailBody .= "</tr>";
			$Dim2ArrCurRow++;
			$curRow++;
		}
		//$eMailBody = $this->strPositSubstitute($templateArr['Body'], NULL, $Dim2Arr);
		//$eMailBody = str_replace(array('\r','\n','\t'),array("\r","\n","\t"), $eMailBody);
	}
	
	$eMailBody .= "</table><br/><br/>";
	$eMailBody .= "Thanks & Regards.<br/> Customer Service Department";
	$objSolarMailer = new solarMailer();
	$objSolarMailer->IsHTML(true);  
	$objSolarMailer->sendSolarMail($curEMailId, $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC'], NULL, True);
	return $eMailBody;
}

public function sendSMSTargetVSAchievement($data, $TelNo){
	$uname = 'SIILJPRO'; //'SIILJPRP';
	$password = 'S(ol)!ar';// 'E9W!f9Y~';
	$info ='1';
	$test = '0';
	$from = 'iSOLAR';
	$dest =  '8793653028';   //'9765933450'; // $TelNo;  //'8793653028' //'919649569999'; //'918600993992';
	//$dest =  $TelNo;   //'9765933450'; // $TelNo;  //'8793653028' //'919649569999'; //'918600993992';
	$messages = "Dear Customer, Your Target v/s Achievment as under ";
	
	$curRow=0;
	$dataCount = count($data);
	$Month = date('M');
	while ($curRow < $dataCount) {
		$messages .= ' '. $data[$curRow]['Item'] .' Target - ' . $data[$curRow][$Month.'~TargetMonth'] .', Achv. - '.$data[$curRow][$Month.'~Achievement'];
		$curRow++;
	}
	
	$data ="uname=".$uname."&pass=".$password."&msg=".$messages."&send=".$from."&dest=".$dest;
	$ch = curl_init("http://api.unicel.in/SendSMS/sendmsg.php?");
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	$result = curl_exec($ch);
	curl_close($ch);
//return $result;
}




public function reportItemRate($data) {
	$CustomerCd = ($_SESSION['IsCustomer']) ? $_SESSION['CustomerCd'] : $data['CustomerCd'];
	if ($CustomerCd=='') return;

	$inputArr 		= array($CustomerCd);
	$paraString		= vsprintf("'%s'", $inputArr);
	$sql			= "call sp_repItemRate(". $paraString. ")";
	$reportData	= $this->execSelectQuery($sql, 2);
	If (count($reportData)==0) {
		echo '<script>alert("No data to print for the specified Date Range")</script>';
		return;
	}

	$arrCustomerMDisp = $this->getCustomerMDisp(0, $CustomerCd);
	
	$reportTitle = "Item Rate List for " .$arrCustomerMDisp[0]['Descript'];
	$classBusiLogic = $this;
	$actionBM = 1 + 0;
	include_once("includes/inc.view.report.php");
	return;
}

public function reportCustItemDetail($data) {
	$CustomerCd = $data['CustomerCd'];

	$inputArr 		= array($CustomerCd);
	$paraString		= vsprintf("'%s'", $inputArr);
	$sql			= "call sp_repCustItemDetail(". $paraString. ")";
	$reportData	= $this->execSelectQuery($sql, 2);
	If (count($reportData)==0) {
		echo '<script>alert("No data to print for the specified Customer.")</script>';
		return;
	}

	$fileName = 'wrk/repCustItemDetail' . '.xls';

	$repTitle = str_repeat("\t",1) . "Customer Retlated Item Details";
	$this->makeTabReport($reportData, 3, $fileName, -1, $repTitle, FALSE, 5);
	return;
}

public function reportCustItemDetailVK11($data, $isDownload) {
	$CustomerCd = $data['CustomerCd'];
	$CompanyCd  = $data['CompanyCd'];
	$ItemCd	    = $data['ItemCd'];

	$inputArr 		= array($CustomerCd, $CompanyCd, $ItemCd);
	$paraString		= vsprintf('"%s", "%s", "%s"', $inputArr);
	 $sql			= "call sp_repCustItemDetailVK11(". $paraString. ")";
	$reportData	= $this->execSelectQuery($sql, 2);
	
	if($isDownload){
	If (count($reportData)==0) {
		echo '<script>alert("No data to print for the specified Customer.")</script>';
		return;
	}
	$fileName = 'wrk/repCustItemDetail_VK11' .date('d-m-Y'). '.xls';
	//$repTitle = str_repeat("\t",1) . "VK11 EXW/ DAF";
	$repTitle = "";
	$this->makeTabReport($reportData, 3, $fileName, -1, $repTitle, FALSE, 5);
	return;
	}
	else{
		$arrayKeys = array_keys($reportData);		// 1,3,5
		$fileName = 'upload/VK11/VK11_' .$CompanyCd.'_'. date('d-m-Y').'_'.date('His'). '.txt';
		$handle = fopen($fileName,'wb');
		
		//fwrite($handle, "\r\n");	
		fwrite($handle, "\t");
		for ($i=1; $i<count($arrayKeys); $i+=2) {
			$separatorAt = strpos($arrayKeys[$i], '~');
			if ($separatorAt===FALSE)
				fwrite($handle, "\t");
			else
				fwrite($handle, substr($arrayKeys[$i],$separatorAt+1) . "\t");
		}
		//fwrite($handle, "\r\n");	
		$columnCount = count($reportData[0])/2;
		for ($i=0; $i<count($reportData); $i++) {
			for ($j=0; $j<$columnCount; $j++) {
				fwrite($handle, $reportData[$i][$j] . "\t");
			}
			fwrite($handle, "\r\n" );
		}
		fclose($handle);
	}
}

public function reportDespatchPlanNonal_SO_updation($data) {
	$CompanyCd		= $data['CompanyCd'];
	$SAPSODateSAnsi = $this->convertDate($data['SAPSODateS'], TRUE, 1);
	$SAPSODateEAnsi = $this->convertDate($data['SAPSODateE'], TRUE, 1);
	$DespatchMode	= $data['DespatchMode'];
	
	$inputArr 		= array($CompanyCd, $DespatchMode, $SAPSODateSAnsi, $SAPSODateEAnsi, $_SESSION['SectorCd']);
	$paraString		= vsprintf("%s, '%s','%s', '%s', '%s'", $inputArr);
	$sql			= "call sp_repDespatchPlanNonal_SO_updation(". $paraString. ")";
	
	$reportData	= $this->execSelectQuery($sql, 2);
	If (count($reportData)==0) {
		echo '<script>alert("No data to print for the specified Customer.")</script>';
		return;
	}

	$fileName = 'wrk/repNonal_so_updation' . '.txt';

	//$repTitle = str_repeat("\t",1) . "SO Updation ";
	$repTitle = "";
	$this->makeTabReport($reportData, 3, $fileName, -1, $repTitle, FALSE, 5);
	return;
}

public function reportDespatchPlan($DespatchMode, $data) {
	$CompanyCd		= $data['CompanyCd'];
	$SAPSODateSAnsi = $this->convertDate($data['SAPSODateS'], TRUE, 1);
	$SAPSODateEAnsi = $this->convertDate($data['SAPSODateE'], TRUE, 1);
	$DespatchModeDtl	= ($DespatchMode=='X' ? 'Ex-Factory' : 'F.O.R.');
	$inputArr 		= array($CompanyCd, $DespatchMode, $SAPSODateSAnsi, $SAPSODateEAnsi, $_SESSION['SectorCd']);
	$paraString		= vsprintf("%s, '%s','%s', '%s', '%s'", $inputArr);
	$sql			= "call sp_repDespatchPlan(" . $paraString. ")";
	$reportData 	= $this->execSelectQuery($sql);
	If (count($reportData)==0) {
		echo '<script>alert("No data to print for specified Date.")</script>';
		return;
	}
	
	$sql			= "call sp_repDespatchPlanSummary(" . $paraString. ")";
	$summaryData 	= $this->execSelectQuery($sql);

// DIRECTORY_SEPARATOR, PATH_SEPARATOR, PHP_OS, sys_get_temp_dir();
//	$fileName = $this->getUniqueFileName('wrk/', 'rep', '.txt');
	$arrCompanyMDisp	= $this->getCompanyMDisp($data['CompanyCd']);
	$fileName = 'wrk/repDespatchPlan' . $DespatchModeDtl . '_' . $CompanyCd .  '-' . $SAPSODateSAnsi . '_' . $SAPSODateEAnsi.'.txt';
	$handle = fopen($fileName,'wb');
	
	fwrite($handle, str_repeat("\t",2) . "Despatch Plan - " . $DespatchModeDtl . " of " . $arrCompanyMDisp[0]['Descript'] . " for " . $data['SAPSODateS'] . " - " . $data['SAPSODateE'] . "\r\n");
	fwrite($handle, "\r\n");

	if ($DespatchMode=='X' && FALSE) {		// to be removed this part of if
		fwrite($handle, "S.O.No.\t" . "S.O. Date\t" . "Customer\t" . "License No.\t" . "Lic.Expiry\t" . "Capacity\t" . "Item\t" . "Order(Box)\t" . "Rate\t" . "Vehicle No.\t" . "RE-11 No.\t" . "RE-11 Date\t" . "Token No.\t" . "\r\n");
		$SAPSONoPre = "";
		for ($i=0; $i<count($reportData); $i++) {
			$SAPSONo = $reportData[$i]['SAPSONo'];
			if ($SAPSONoPre != $SAPSONo) {
				fwrite($handle, "\r\n");
				fwrite($handle, $reportData[$i]['SAPSONo']."\t" . $reportData[$i]['SAPSODate']."\t" . $reportData[$i]['Customer']."\t" . $reportData[$i]['MagazineLicNo']."\t" . $reportData[$i]['LicExpiryDate']."\t" . $reportData[$i]['Capacity']."\t" . $reportData[$i]['Item']."\t" . $reportData[$i]['OrderBox']."\t" . $reportData[$i]['Rate']."\t" . $reportData[$i]['VehicleNo']."\t" . $reportData[$i]['RE11No']."\t" . $reportData[$i]['RE11Date']."\t" . $reportData[$i]['TokenNoFull']."\t" . "\r\n" );
				$SAPSONoPre = $SAPSONo;
			} else {
				fwrite($handle, str_repeat("\t",5) . $reportData[$i]['Capacity'] ."\t" . $reportData[$i]['Item']."\t" . $reportData[$i]['OrderBox']."\t" . $reportData[$i]['Rate']."\t" . "\r\n");
			}
		}
	} else {
		fwrite($handle, "S.O.No.\t" . "S.O. Date\t" . "Customer\t" . "License No.\t" . "Lic.Expiry\t"  . "Capacity\t" . "Item\t" . "Order(Box)\t" . "Rate\t" . "RE-11 No.\t" . "RE-11 Date\t" . "Token No.\t" . "\r\n");
		$VehicleNoPre = "";
		$SAPSONoPre = "";
		for ($i=0; $i<count($reportData); $i++) {
			$VehicleNo = $reportData[$i]['VehicleNo'];
			$SAPSONo = $reportData[$i]['SAPSONo'];
			if ($VehicleNoPre != $VehicleNo || $SAPSONoPre != $SAPSONo) {
				if ($VehicleNoPre != $VehicleNo) {
					fwrite($handle, "\r\n");
					fwrite($handle, "Vehicle No.:\t" . $reportData[$i]['VehicleNo']."\t" . "\r\n");
				}
				fwrite($handle, "\r\n");
				fwrite($handle, $reportData[$i]['SAPSONo']."\t" . $reportData[$i]['SAPSODate']."\t" . $reportData[$i]['Customer']."\t" . $reportData[$i]['MagazineLicNo']."\t" . $reportData[$i]['LicExpiryDate']."\t" . $reportData[$i]['Capacity']."\t" . $reportData[$i]['Item']."\t" . $reportData[$i]['OrderBox']."\t" . $reportData[$i]['Rate']."\t" . $reportData[$i]['RE11No']."\t" . $reportData[$i]['RE11Date']."\t" . $reportData[$i]['TokenNoFull']."\t" . "\r\n" );
				$VehicleNoPre = $VehicleNo;
				$SAPSONoPre = $SAPSONo;
			} else {
				fwrite($handle, str_repeat("\t",5) . $reportData[$i]['Capacity'] . "\t" .$reportData[$i]['Item']."\t" . $reportData[$i]['OrderBox']."\t" . $reportData[$i]['Rate']."\t" . "\r\n");
			}
		}
	}

	fwrite($handle, "\r\n");
	fwrite($handle, str_repeat("\t",2) . "Summary Despatch Plan - " . $DespatchModeDtl . " of " . $arrCompanyMDisp[0]['Descript'] . " for " . $data['SAPSODateS']  . " - " . $data['SAPSODateE'] . "\r\n");
	fwrite($handle, "\r\n");
	fwrite($handle, str_repeat("\t",2)  . "ITEM\t" . "ORDER(Box)\t" . "QUANTITY\t" . "UNIT\t"  . "\r\n");
	$totalBox = 0;
	for ($i=0; $i<count($summaryData ); $i++) {
		fwrite($handle, str_repeat("\t",2) . $summaryData [$i]['Item']."\t" . $summaryData [$i]['OrderBox']."\t" . $summaryData [$i]['OrderQty']."\t" . $summaryData [$i]['UOM']."\t" . "\r\n");
		$totalBox += $summaryData [$i]['OrderBox'];
	}
	fwrite($handle, "\r\n");
	fwrite($handle, str_repeat("\t",2)  . "T O T A L\t" . $totalBox . "\t" . "\r\n");

	fclose($handle);
	echo "<script language='javascript'>window.location.href='includes/download.php?fileName=$fileName&baseDir=./../wrk/';</script>";
//	return ($fileName);
//	$this->downloadFile($fileName);
//	download.php?f=phptutorial.zip
} 



public function docPOPrint($data) {
	$DTSAnsi = $this->convertDate($data['DTS'], TRUE, 1);
	$DTEAnsi = $this->convertDate($data['DTE'], TRUE, 1);
	$inputArr 		= array($DTSAnsi, $DTEAnsi);
	$paraString		= vsprintf("'%s','%s'",$inputArr);
	$sql			= "call sp_docPOHeader(" . $paraString. ")";
	$reportData 	= $this->execSelectQuery($sql, 2);
	$totalPO		= count($reportData);
	If ($totalPO==0) {
		echo '<script>alert("No data to print for specified Date.")</script>';
		return;
	}
	
	$fileName = 'wrk/docPO-' . $DTSAnsi . ($DTSAnsi==$DTEAnsi ? '' : '-To-') . $DTEAnsi .'.pdf';
	$headerPrompt = 'Company,,P.O.No.,P.O.Date,Sold To Party,Party Code,Shipped To Party,Magazine Code,Despatch Mode,Sales Contract No.'
			. ',Vehicle No.,Veh.Arrival Date,RE-11 No.,RE-11 Date,Token No,,S.O. No.,S.O. Date,Approved By,Approval Date'	;
	$headerPromptArr = explode(',',$headerPrompt);

	$colWidth = array(35, 90, 35, 30);
	$colHeight = 6;
	
	require_once('./classes/class.fpdf.php');
	$pdf = new FPDF();
	for ($i=0; $i<$totalPO; $i++) {
		$pdf->AddPage();
		$pdf->SetFont('Arial','BU',16);
		$pdf->Cell(200,$colHeight,'PURCHASE ORDER',0,1,'C');
		$pdf->Ln();
		$pdf->SetFont('Times','',12);
		for ($k=0; $k<18; $k++) {		// 0-17 => Company-S.O.Date
			if ($k % 2) {
				$pdf->Cell($colWidth[2],$colHeight,$headerPromptArr[$k],0);
				$pdf->Cell($colWidth[3],$colHeight,$reportData[$i][$k],0);
				$pdf->Ln();
			} else {
				$pdf->Cell($colWidth[0],$colHeight,$headerPromptArr[$k],0);
				$pdf->Cell($colWidth[1],$colHeight,$reportData[$i][$k],0);
			}
		}
/*		$pdf->Cell($colWidth[0],$colHeight,'Company',0);
		$pdf->Cell($colWidth[1],$colHeight,$reportData[$i]['Company'],0);
		$pdf->Ln();
		$pdf->Cell($colWidth[0],$colHeight,'P.O.No.',0);
		$pdf->Cell($colWidth[1],$colHeight,$reportData[$i]['IdPO'],0);
		$pdf->Cell($colWidth[2],$colHeight,'P.O.Date',0);
		$pdf->Cell($colWidth[3],$colHeight,$reportData[$i]['Date'],0);
		$pdf->Ln();
		$pdf->Cell($colWidth[0],$colHeight,'Sold To Party',0);
		$pdf->Cell($colWidth[1],$colHeight,$reportData[$i]['Customer'],0);
		$pdf->Cell($colWidth[2],$colHeight,'Party Code',0);
		$pdf->Cell($colWidth[3],$colHeight,$reportData[$i]['CustomerCd'],0);
		$pdf->Ln();
		$pdf->Cell($colWidth[0],$colHeight,'Shipped To Party',0);
		$pdf->Cell($colWidth[1],$colHeight,$reportData[$i]['MagazineLicNo'],0);
		$pdf->Cell($colWidth[2],$colHeight,'Magazine Code',0);
		$pdf->Cell($colWidth[3],$colHeight,$reportData[$i]['MagazineCd'],0);
		$pdf->Ln();
		$pdf->Cell($colWidth[0],$colHeight,'Despatch Mode',0);
		$pdf->Cell($colWidth[1],$colHeight,($reportData[$i]['DespatchMode']=='X' ? 'Ex-Factory' : 'F.O.R.'),0);
		$pdf->Cell($colWidth[2],$colHeight,'Sales Contract No.',0);
		$pdf->Cell($colWidth[3],$colHeight,$reportData[$i]['ContractNo'],0);
		$pdf->Ln();
		$pdf->Cell($colWidth[0],$colHeight,'Vehicle No.',0);
		$pdf->Cell($colWidth[1],$colHeight,$reportData[$i]['VehicleNo'],0);
		$pdf->Cell($colWidth[2],$colHeight,'Veh.Arrival Date',0);
		$pdf->Cell($colWidth[3],$colHeight,$reportData[$i]['ExpVehicleArrDate'],0);
		$pdf->Ln();
		$pdf->Cell($colWidth[0],$colHeight,'RE-11 No.',0);
		$pdf->Cell($colWidth[1],$colHeight,$reportData[$i]['RE11No'],0);
		$pdf->Cell($colWidth[2],$colHeight,'RE-11 Date',0);
		$pdf->Cell($colWidth[3],$colHeight,$reportData[$i]['RE11Date'],0);
		$pdf->Ln();
		$pdf->Cell($colWidth[0],$colHeight,'Token No.',0);
		$pdf->Cell($colWidth[1],$colHeight,$reportData[$i]['TokenNo'],0);
		$pdf->Ln();
		$pdf->Cell($colWidth[0],$colHeight,'S.O. No.',0);
		$pdf->Cell($colWidth[1],$colHeight,$reportData[$i]['SAPSONo'],0);
		$pdf->Cell($colWidth[2],$colHeight,'S.O. Date',0);
		$pdf->Cell($colWidth[3],$colHeight,$reportData[$i]['SAPSODate'],0);
		$pdf->Ln();
		$pdf->Cell($colWidth[0],$colHeight,'Approved By',0);
		$pdf->Cell($colWidth[1],$colHeight,$reportData[$i]['ApprovedByUserName'],0);
		$pdf->Cell($colWidth[2],$colHeight,'Approval Date',0);
		$pdf->Cell($colWidth[3],$colHeight,$reportData[$i]['ApprovalDate'],0);
*/		$pdf->Ln();
		$pdf->Cell(array_sum($colWidth),$colHeight,'','T');
		$pdf->Ln();
		$pdf->SetFont('Arial','U',12);
		$pdf->Cell(100,7,'P.O. Product Details:',0,0,'L');
		$pdf->SetFont('Times','',12);
		$pdf->Ln();

		$inputArr 		= array($reportData[$i]['IdPO']);
		$paraString		= vsprintf("%s",$inputArr);
		$sql			= "call sp_docPOItemDetail(" . $paraString. ")";
		$itemData 		= $this->execSelectQuery($sql);
		$dtlcolWidth	= array(15, 85, 15, 20, 10, 20, 25);
		$pdf->Cell($dtlcolWidth[0],7,'Sr.No.',1,0,'C');
		$pdf->Cell($dtlcolWidth[1],7,'Product Description',1,0,'C');
		$pdf->Cell($dtlcolWidth[2],7,'Boxes',1,0,'C');
		$pdf->Cell($dtlcolWidth[3],7,'Quantity',1,0,'C');
		$pdf->Cell($dtlcolWidth[4],7,'Unit',1,0,'C');
		$pdf->Cell($dtlcolWidth[5],7,'Net Rate',1,0,'C');
		$pdf->Cell($dtlcolWidth[6],7,'Net Amount',1,0,'C');
		$pdf->Ln();

		for ($j=0; $j<count($itemData); $j++) {
			$pdf->Cell($dtlcolWidth[0],$colHeight,$j+1,1,0,'C');
			$pdf->Cell($dtlcolWidth[1],$colHeight,$itemData[$j]['Item'],1,0,'L');
			$pdf->Cell($dtlcolWidth[2],$colHeight,$itemData[$j]['OrderBox'],1,0,'R');
			$pdf->Cell($dtlcolWidth[3],$colHeight,$itemData[$j]['OrderQty'],1,0,'R');
			$pdf->Cell($dtlcolWidth[4],$colHeight,$itemData[$j]['UOM'],1,0,'C');
			$pdf->Cell($dtlcolWidth[5],$colHeight,$itemData[$j]['NetRate'],1,0,'R');
			$pdf->Cell($dtlcolWidth[6],$colHeight,$itemData[$j]['TotAmt'],1,0,'R');
			$pdf->Ln();
		}
		$pdf->SetFont('Times','B',12);
		$pdf->Cell($dtlcolWidth[0],$colHeight,'',1,0,'C');
		$pdf->Cell($dtlcolWidth[1],$colHeight,'T O T A L',1,0,'C');
		$pdf->Cell($dtlcolWidth[2],$colHeight,$this->array_sum_key($itemData,'OrderBox'),1,0,'R');
		$pdf->Cell($dtlcolWidth[3],$colHeight,'',1,0,'R');
		$pdf->Cell($dtlcolWidth[4],$colHeight,'',1,0,'C');
		$pdf->Cell($dtlcolWidth[5],$colHeight,'',1,0,'R');
		$pdf->Cell($dtlcolWidth[6],$colHeight,$reportData[$i]['TotAmt'],1,0,'R');
		$pdf->Ln();
		$pdf->SetFont('Times','',12);
		$pdf->Ln();
		$pdf->Ln();
		$pdf->Ln();

		for ($k=18; $k<20; $k++) {		// 18-19 => ApprovedBy, Aprovaldate
			if ($k % 2) {
				$pdf->Cell($colWidth[2],$colHeight,$headerPromptArr[$k],0);
				$pdf->Cell($colWidth[3],$colHeight,$reportData[$i][$k],0);
				$pdf->Ln();
			} else {
				$pdf->Cell($colWidth[0],$colHeight,$headerPromptArr[$k],0);
				$pdf->Cell($colWidth[1],$colHeight,$reportData[$i][$k],0);
			}
		}
		$pdf->Ln();
		$pdf->Cell(array_sum($colWidth),$colHeight,'','T');
		$pdf->Ln();
	}

	$pdf->Output($fileName, 'F');
	echo "<script language='javascript'>window.location.href='includes/download.php?fileName=$fileName&baseDir=./../wrk/';</script>";
}

public function reportAccessory($data) {
	$DTSAnsi = $this->convertDate($data['DTS'], TRUE, 1);
	$DTEAnsi = $this->convertDate($data['DTE'], TRUE, 1);
	$inputArr 		= array($_SESSION['SectorCd'], $DTSAnsi, $DTEAnsi);
	$paraString		= vsprintf("'%s','%s','%s'",$inputArr);
	$sql			= "call sp_repAccessory(" . $paraString. ")";
	$reportData		= $this->execSelectQuery($sql, 2);
	If (count($reportData)==0) {
		echo '<script>alert("No data to print.")</script>';
		return;
	}
	$period = $data['DTS'] . (($data['DTE']=='' || $data['DTS']==$data['DTE']) ? '' : '_'.$data['DTE']);
	$fileName = 'wrk/repAccessory-' . $period  . '.xls';

	$repTitle = str_repeat("\t",3) . "Accessory Order List for " . $period;
	$this->makeTabReport($reportData, 3, $fileName, -1, $repTitle, FALSE, 5);
}

public function PendingreportAccessory() {
	$inputArr 		= array($_SESSION['SectorCd']);
	$paraString		= vsprintf("'%s'",$inputArr);
	$sql			= "call sp_PendingrepAccessory(" . $paraString. ")";
	$reportData		= $this->execSelectQuery($sql, 2);
	If (count($reportData)==0) {
		echo '<script>alert("No data to print.")</script>';
		return;
	}
	return $reportData;
}

public function DailyDispatchReport() {
	$sql			= "select * from so_dailydispatch_rep_item";
	$reportData		= $this->execSelectQuery($sql);
	return $reportData;
}

public function reportPendingPO() {
	$sql			= "call sp_repPendingPO()";
	$reportData	= $this->execSelectQuery($sql, 2);
	If (count($reportData)==0) {
		echo '<script>alert("No data to print.")</script>';
		return;
	}
	$repAsOn = date('d-m-Y');
	$fileName = 'wrk/repPendingPO-' . $repAsOn . '.txt';

	$repTitle = str_repeat("\t",3) . "Pending P.O. List as on " . $repAsOn;
	$this->makeTabReport($reportData, 3, $fileName, -1, $repTitle, FALSE);
}

public function reportLicExpiryMagazine($ForMonths) {
	$ForDate = date('Y-m-d');
	$objUptoDate = new DateTime($ForDate);
	$Interval = 'P'.$ForMonths.'M';
	$objUptoDate->add(new DateInterval($Interval));
	$UptoDate = $objUptoDate->format('Y-m-d');
	$UptoDateBrit = $objUptoDate->format('d-m-Y');

	$sql	= "SELECT A.CustomerCd, IFNULL(B.Descript,A.CustomerCd) AS Customer, A.MagazineCd, A.Descript, DATE_FORMAT(A.LicExpiryDate, '%d-%m-%Y') AS LicExpiryDate FROM so_magazine_m A "
		. " LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd WHERE A.LicExpiryDate<='$UptoDate' AND B.IsActive=1 ORDER BY A.LicExpiryDate";
	$reportData	= $this->execSelectQuery($sql, 2);
	If (count($reportData)==0) {
		echo "<script>alert('No Magazine with Lic.Expiry within Next $ForMonths Months.')</script>";
		return;
	}

	$fileName = 'wrk/repLicExpiryMagazine-Upto-' . $UptoDateBrit . '.txt';
//	$handle = fopen($fileName,'wb');

	$repTitle = str_repeat("\t",2) . "Lic.Expiring Magazine List upto " . $UptoDateBrit;
	$this->makeTabReport($reportData, 3, $fileName, -1, $repTitle, TRUE);

/*	fwrite($handle, $repTitle . "\r\n");
	fwrite($handle, "\r\n");
	fwrite($handle, "Sr.\t" . "CustomerCd\t" . "Customer\t" . "MagazineCd\t" . "Magazine\t" . "Lic.ExpiryDate\t" );
	fwrite($handle, "\r\n");	
	$SrNo = 1;
	for ($i=0; $i<count($reportData); $i++) {
		fwrite($handle, $SrNo."\t" . $reportData[$i]['CustomerCd']."\t" . $reportData[$i]['Customer']."\t" . $reportData[$i]['MagazineCd']."\t" . $reportData[$i]['Descript']."\t" . $reportData[$i]['LicExpiryDate']."\t");
		fwrite($handle, "\r\n" );
		$SrNo += 1;
	}

	fclose($handle);
	echo "<script language='javascript'>window.location.href='includes/download.php?fileName=$fileName&baseDir=./../wrk/';</script>";
*/	
}

public function XXXreportDailyStock($data, $IsAED) {
	$DTSDays		= $data['DTSDays'];
	$DTE			= $data['DTE'];
	$DTEAnsi		= $this->convertDate($DTE, TRUE, 1);
	$DTS			= $this->addDate($DTEAnsi, '-' . $DTSDays . ' day', TRUE);
	$inputArr 		= array($DTSDays, $DTEAnsi, $IsAED);
	$paraString		= vsprintf("%s, '%s', %s",$inputArr);
	$sql			= "call sp_repDailyStockExpl(" . $paraString. ")";	// Returns 4 Recordsets 0:@ColumnStru,... (to ignore) 1:Details 2:GrandTotal 3:NoDailyStockCustomerList
	$preResultsAr	= array();
	$noStockCustAr	= $this->execSelectQuery($sql, 2, $preResultsAr);
	if (count($preResultsAr)<=1) {
		echo '<script>alert("No data to print.")</script>';
		return;
	}

	$subHead = ($IsAED ? 'AED' : 'Explosives');
	$fileName = 'wrk/repDailyStock'.$subHead.'-' . $DTE . '.txt';

	$reportData = $preResultsAr[1];
	$hasMissingCust = (count($noStockCustAr)>0);
	If (count($reportData)==0 && !$hasMissingCust) {
		echo '<script>alert("No data to print.")</script>';
		return;
	}
	$gTotalData = $preResultsAr[2];

	If (count($reportData)==0) {
		$repTitle = str_repeat("\t",1) . $subHead. ' -  Customers w/o Daily Stock & Despatch Position for ' . $DTE;
		$this->makeTabReport($noStockCustAr, 3, $fileName, -1, $repTitle, TRUE);
	} else {
		$repTitle = str_repeat("\t",1) . $subHead. ' -  Daily Stock & Despatch Position' . ($DTSDays==0 ? ' as on ' . $DTE : ' for ' . $DTS . ' TO ' . $DTE);
		$handle = $this->makeTabReport($reportData, 1, $fileName, -1, $repTitle, TRUE);
		$this->makeTabReport($gTotalData, ($hasMissingCust?0:2), $fileName, $handle, '', TRUE);
		If ($hasMissingCust) {
			$repTitle = str_repeat("\t",1) . $subHead. ' -  Customers w/o Daily Stock & Despatch Position for ' . $DTE;
			$this->makeTabReport($noStockCustAr, 2, $fileName, $handle, $repTitle, TRUE);
		}
	}
}

public function reportDailyStock($SectorCd, $DTSDays, $DTE, $IsAED) {
	$DTEAnsi		= $this->convertDate($DTE, TRUE, 1);
	$DTS			= $this->addDate($DTEAnsi, '-' . $DTSDays . ' day', TRUE);
	$inputArr 		= array($SectorCd, $DTSDays, $DTEAnsi, $IsAED);
	$paraString		= vsprintf("'%s', %s, '%s', %s",$inputArr);
	$sql			= "call sp_repDailyStockExpl(" . $paraString. ")";	// Returns 4 Recordsets 0:@ColumnStru,... (to ignore) 1:DailyStockDetails 2:GrandTotal 3:NoDailyStockCustomerList
	$preResults		= '';
	$returnData 	= $this->execSelectQuery($sql, 2, $preResults);
	return $preResults;
}

public function reportDailySaleDealerSubdealer($DTS, $DTE, $CustomerCd, $IdSubdealer, $ReportType, $StateCd) {
	$DTS			= $this->convertDate($DTS, TRUE, 1);
	$DTE			= $this->convertDate($DTE, TRUE, 1);
	$inputArr 		= array($DTS, $DTE, $CustomerCd, $IdSubdealer, $ReportType, $StateCd);
	$paraString		= vsprintf("'%s', '%s', '%s', %s, %s, '%s'", $inputArr);
	//$paraString		= "'$DTS', '$DTE', '$CustomerCd', '$IdSubdealer', '$ReportType', '$StateCd'";
	$sql			= "call sp_getDailySaleDealerSubdealer(" . $paraString. ")";
	$preResults		= '';
	$returnData 	= $this->execSelectQuery($sql, 2, $preResults);
	return $preResults;
}

public function reportImportSAPSONoDate($reportData) {
// Report of unupdated POs because StatusCd='U' in importSAPSONoDate
	If (count($reportData)==0) {
		echo "<script>alert('All S.O.No. from SAP are updated successfully.')</script>";
		return;
	}

	$fileName = 'wrk/repImportSAPSONoDate.txt';

	$repTitle = str_repeat("\t",1) . "Un-updated POs because of StatusCd='U' at SO No. updation in P.O.";
	$this->makeTabReport($reportData, 3, $fileName, -1, $repTitle, TRUE);
}

public function reportImportSAPInvNoDate($reportData) {
// Report of Not-Found SO Ref. in importSAPInvNoDate
	If (count($reportData)==0) {
		echo "<script>alert('All Inv.No. from SAP are updated successfully.')</script>";
		return;
	}

	$fileName = 'wrk/repImportSAPInvNoDate.txt';

	$repTitle = str_repeat("\t",1) . "Missing S.O. Ref found at Invoice No. updation in P.O.";
	$this->makeTabReport($reportData, 3, $fileName, -1, $repTitle, TRUE);


/*	$handle = fopen($fileName,'wb');
	
	fwrite($handle, str_repeat("\t",1) . "Missing S.O. Ref found at Invoice No. updation in P.O.\r\n");
	fwrite($handle, "\r\n");
	fwrite($handle, "Sr.\t" . "SAPInvNo.\t" . "SAPInvDate\t" . "S.O.No.\t"  . "CustomerCd\t" . "MagazineCd\t");
	fwrite($handle, "\r\n");	
	$SrNo = 1;
	for ($i=0; $i<count($reportData); $i++) {
		fwrite($handle, $SrNo."\t" . $reportData[$i]['SAPInvNo']."\t" . $reportData[$i]['SAPInvDate']."\t" . $reportData[$i]['SAPSONo']."\t" . $reportData[$i]['CustomerCd']."\t" . $reportData[$i]['MagazineCd']."\t");
		fwrite($handle, "\r\n" );
		$SrNo += 1;
	}

	fclose($handle);
	echo "<script language='javascript'>window.location.href='includes/download.php?fileName=$fileName&baseDir=./../wrk/';</script>";
*/	
}

public function exportDailyStock($data) {
// Though termed as export, actually a plain report downloaded w/o the Headings
	$SectorCd = $_SESSION['SectorCd'];
	$DTSAnsi = $this->convertDate($data['DTS'], TRUE, 1);
	$DTEAnsi = $this->convertDate($data['DTE'], TRUE, 1);
	$inputArr 		= array($SectorCd, $DTSAnsi, $DTEAnsi);
	$paraString		= vsprintf("'%s', '%s','%s'",$inputArr);
	$sql			= "call sp_exportDailyStock(" . $paraString. ")";
	$reportData 	= $this->execSelectQuery($sql, 2);

	$fileName = 'wrk/exportDailyStock-' . $data['DTS'] . ($data['DTS']==$data['DTE'] ? '' : '_'. $data['DTE']) . '.txt';
	$this->makeTabReport($reportData, 3,  $fileName, -1, '', FALSE);
}

// Login & UserMgmt Function ------------------------------------------------------------------------------------------------------------------------------
public function getLoginDetail($data) {
	$DBNameNonTrade = $this::DBNameNonTrade;
	$DBNameExport = $this::DBNameExport;
    $DBNameTrade = $this::DBNameTrade;

    $stmt           = "SELECT A.*, B.Descript AS UserTypeName, B.IsAdmin, B.IsSubAdmin, B.IsReadAdmin, B.IsCustomer, B.IsSubDealer, B.IsASM, B.IsSalesCoordinator, 
	B.IsPOReadier, B.HasCustomer, IF(B.IsCustomer,IFNULL(IFNULL(C.Descript,D.Descript),A.CustomerCd),'') AS Customer, IF(B.IsSubDealer,
	IFNULL(F.Descript,A.SubDealerCd),'') AS SubDelaer, A.SectorCd, IFNULL(E.Descript,A.SectorCd) AS Sector, IFNULL(IFNULL(C.HasSubdealer,D.HasSubdealer),0) AS HasSubdealer, 
	IFNULL(IFNULL(C.HasDailyStock,D.HasDailyStock),0) AS HasDailyStock, C.StateCd FROM " . self::DTUserM . " A INNER JOIN " . self::DTUserTypeM . " B 
	ON A.UserType=B.UserType LEFT OUTER JOIN so_customer_m C ON A.CustomerCd=C.CustomerCd LEFT OUTER JOIN $DBNameNonTrade.so_customer_m D ON A.CustomerCd=D.CustomerCd
	LEFT OUTER JOIN $DBNameExport.so_customer_m G ON A.CustomerCd=G.CustomerCd LEFT OUTER JOIN $DBNameTrade.so_subdealer_m F 
	ON (A.SubdealerCd = F.IdSubdealer AND F.IdSubdealer <> '') LEFT OUTER JOIN " . self::DTSectorM . " E ON A.SectorCd=E.SectorCd 
	WHERE A.UserName='%s' and A.ActiveFlag IN (0,2)";
	$inputArr       = array(strtolower($data['UserName']));
	$sql            = vsprintf($stmt, $inputArr);
    $returnData     = $this->execSelectQuery($sql);
/*	if(mysql_num_rows($returnData)){
    if($doDebug) {
       // We are debugging so show some nice error output
       echo "Query failed\n<br><b>$sql</b>\n";
       echo mysql_error(); // (Is that not the name)
	   return $returnData;
     }
     else {
      // Might want an error message to the user here.
	  $msg ="Invalid Query";
	  return false;
     }
     exit();
  }*/
   return $returnData;
	
	
}

public function getLoginMessage() {
	$dbName			= $_SESSION['DBName'];
	$inputArr 		= array(date('Y-m-d'), $_SESSION['CustomerCd']);
	$paraString		= vsprintf("'%s','%s'",$inputArr);
	$sql			= "call $dbName.sp_getLoginMessage(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql);

	$msg = '';

	for ($i=0; $i<count($returnData); $i++) {
		$curMsg = str_replace("\r\n", '\r\n', $returnData[$i]['Message']);
		$msg .= ($i+1).'. '.($returnData[$i]['MessageType']=='C' ? 'Expiry of '.$curMsg.' on'.$this->convertDate($returnData[$i]['LicExpiryDate'], FALSE, 1) : $curMsg)
				. '\r\n';
	}
	return $msg;
}

public function getUserList($searchVal) {
	$DBNameTrade = $this::DBNameTrade;
	$SectorCd  = $_SESSION['SectorCd'];
    $searchCnd = (isset($searchVal)) ? " AND (A.Descript like '" . $searchVal . "%' OR A.UserName LIKE '" . $searchVal . "%')" : "";

	$sql = "SELECT A.UserName,A.Descript,IFNULL(C.Descript,A.UserType) AS UserType, A.ActiveFlag, A.PhoneFlag, IFNULL(B.Descript,IFNULL(E.Descript,A.CustomerCd)) AS Customer FROM " . self::DTUserM . " A LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd LEFT OUTER JOIN $DBNameTrade.so_subdealer_m E ON (A.SubdealerCd = E.IdSubdealer AND E.IdSubdealer <>'') LEFT OUTER JOIN " . self::DTUserTypeM . " C ON A.UserType=C.UserType WHERE A.ActiveFlag!=3 AND A.SectorCd='$SectorCd' $searchCnd GROUP BY A.UserName ORDER BY A.UserType, B.Descript, E.Descript, A.UserName";
		
    $returnData = $this->execSelectQuery($sql);
    return $returnData;
}
	
public function getUser($UserName) {
	$stmt		= "SELECT  * FROM " . self::DTUserM . " WHERE UserName='%s' ";
	$inputArr	=  array($UserName);
	$sql		= vsprintf($stmt, $inputArr);
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getSemiActiveReason(){
	$sql = "SELECT * FROM so_semi_active_reson ";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function isExistUser($mcode) {
	$sql			= "SELECT * FROM " . self::DTUserM . " WHERE UserName='". $mcode. "'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function insertUser($data) {
	$TransDateTime = date('Y-m-d H:i:s');
	$stmt	= "INSERT INTO " . self::DTUserM . " (UserName, Descript, Password, UserType, SectorCd, CustomerCd, SubdealerCd, ActiveFlag, PhoneFlag, SemiActiveReason, IPBound, CreatedBy,CreatedDateTime)
				VALUES('%s', '%s', '%s', %s, '%s', '%s', '%s', %s, %s, '%s', '%s', '%s', '%s');";
	$CustomerCd = ($data['UserType']==self::UTCustomer ? $data['CustomerCd'] : '');
	$SubdealerCd = ($data['UserType'] == self::UTSubDealer ? $data['SubdealerCd'] : '');
	$inputArr	= array(addslashes(trim($data['UserName'])), addslashes($data['Descript']), trim(md5($data['Password'])), (int)$data['UserType'], $data['SectorCd'], $CustomerCd, $SubdealerCd, (int)$data['ActiveFlag'],
            (int) $data['PhoneFlag'], $data['SemiActiveReason'],  '1', $_SESSION['UserName'],$TransDateTime);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function updateUser($data) {
	$TransDateTime = date('Y-m-d H:i:s');
	$CustomerCd = ($data['UserType']==self::UTCustomer ? $data['CustomerCd'] : '');
	$SubdealerCd = ($data['UserType'] == self::UTSubDealer ? $data['SubdealerCd'] : '');
	if (isset($data['pswChange'])) {
		$stmt		= " UPDATE " . self::DTUserM . " SET UserName = '%s', Descript = '%s', Password ='%s' ,UserType=%s, SectorCd='%s', CustomerCd='%s', SubdealerCd='%s', ActiveFlag=%s, PhoneFlag=%s ,lastUpdate_by ='%s' ,lastUpdate_dateTime = '%s' WHERE UserName='%s'";
		$inputArr	= array(addslashes($data['UserName']), addslashes($data['Descript']), trim(md5($data['Password'])), (int)$data['UserType'], $data['SectorCd'], $CustomerCd, $SubdealerCd, (int)$data['ActiveFlag'],(int) $data['PhoneFlag'], $_SESSION['UserName'],$TransDateTime, $data['oldUserName']);
	} else {
		$stmt		= " UPDATE " . self::DTUserM . " SET UserName = '%s', Descript = '%s', UserType=%s, SectorCd='%s', CustomerCd='%s', SubdealerCd='%s', ActiveFlag=%s, PhoneFlag=%s, SemiActiveReason=%s ,lastUpdate_by ='%s' ,lastUpdate_dateTime = '%s' WHERE UserName='%s'";
		$inputArr	= array(addslashes($data['UserName']), addslashes($data['Descript']), (int)$data['UserType'], $data['SectorCd'], $CustomerCd, $SubdealerCd, (int)$data['ActiveFlag'],(int) $data['PhoneFlag'], $data['SemiActiveReason'], $_SESSION['UserName'],$TransDateTime, $data['oldUserName']);
	}
	$sql				= vsprintf($stmt,$inputArr);
	$returnData		= $this->execUpdateQuery($sql);
	return $returnData;
}

public function removeUser($userRemoveList) {
	$TransDateTime 	= date('Y-m-d H:i:s');
	$sql = "UPDATE " . self::DTUserM . " SET ActiveFlag=3, lastUpdate_by ='".$_SESSION['UserName']."' ,lastUpdate_dateTime = '".$TransDateTime."'  WHERE UserName IN (" . $userRemoveList . ")";
	$returnData = $this->execUpdateQuery($sql);
	return $returnData;
}

public function InActiveUser($CustomerCd) {
	$TransDateTime 	= date('Y-m-d H:i:s');
	$sql = "UPDATE " . self::DTUserM . " SET ActiveFlag=1 ,lastUpdate_by ='".$_SESSION['UserName']."' ,lastUpdate_dateTime = '".$TransDateTime."' WHERE CustomerCd = '".$CustomerCd."'";
	$returnData = $this->execUpdateQuery($sql);
	return $returnData;
}

public function DisableCustomerItemRateType($CustomerCd) {
	$sql = "delete FROM so_customer_m_item_rate_type WHERE CustomerCd  = $CustomerCd ";
	$returnData = $this->execUpdateQuery($sql);
	return $returnData;
}

public function changeUserPsw($data) {
	$sql		= "SELECT A.Password FROM " . self::DTUserM . " A WHERE A.UserName='" . $_SESSION['UserName'] . "'";
	$returnData = $this->execSelectQuery($sql);
	if ($returnData[0]['Password']==md5(trim($_POST['OldPsw']))) {
		$stmt		= "UPDATE " . self::DTUserM . " SET Password ='%s'WHERE UserName='%s'";
		$inputArr	= array(trim(md5($data['NewPsw'])), $_SESSION['UserName']);
		$sql		= vsprintf($stmt,$inputArr);
		$returnMsg	= $this->execUpdateQuery($sql);
	   return $returnMsg;
	} else
		return "Sorry. Unmatched Old-Password. Password not changed.";
}

//	get___List, get___, insert___ (or insert___Header, insert___Sub), update___ (or update___Header, update___Sub), isExist___


// Item Master ---------------------------------------------------------------------------------------------------------------------------------
public function getItemList($search = null) {
	$searchCnd	= (isset($search)) ? " WHERE A.Descript like '". $search . "%'" : "";
	$sql		= "SELECT  A.*,IFNULL(E.ShortDesc,A.CompanyCd) AS Company FROM so_item_m A LEFT OUTER JOIN so_company_m E ON A.CompanyCd=E.CompanyCd " .$searchCnd. " ORDER BY A.CompanyCd DESC, A.ItemCtgCd, A.Descript";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function insertItem($data) {
// Spl code for updating UOM (available with Value=related ItCtg) & UOMType (not avilable))
	$sql		= "SELECT  UOM,UOMType FROM so_item_ctg_m WHERE ItemCtgCd='".$data['ItemCtgCd']."'";
	$returnData = $this->execSelectQuery($sql);
	$UOM		= $returnData[0]["UOM"];
	$UOMType	= $returnData[0]["UOMType"];
	$IsforSubDealer = (isset($data['IsforSubDealer']) ? $data['IsforSubDealer'] : 0);

	$stmt = " INSERT INTO so_item_m (CompanyCd, ItemCd, Descript, ShortDescript, ItemCtgCd, UOM, UOMType, QtyPerBox, KgPerUOM, DispOrder, DefInCustomerItemRate, EquiItemCd, GroupDesc, MainGroupDesc, TokenNoPrefix, AcceptDailyStock, IsActive, IsforSubDealer, AcceptForTarget, RestrictForSale,	 MaxPORestrictedQty, SaleRateMH,SaleRateMP, SaleRateGJ, SaleRateRJ, SaleRateOther, Division, DistChannel)
				VALUES(%s, '%s', '%s', '%s', '%s', '%s', '%s', %s, %s, %s, %s, '%s', '%s', '%s', '%s', %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s);";
	$inputArr	= array((int)($data['CompanyCd']), addslashes($data['ItemCd']), addslashes(trim($data['Descript'])), addslashes(trim($data['ShortDescript'])), trim($data['ItemCtgCd'])
					,$UOM, $UOMType, (float)$data['QtyPerBox'], (float)$data['KgPerUOM'], (int)$data['DispOrder'], (int)$data['DefInCustomerItemRate'], $data['EquiItemCd']
					,$data['GroupDesc'], $data['MainGroupDesc'], $data['TokenNoPrefix'], (int)$data['AcceptDailyStock'], (int)$data['IsActive'], (int)$IsforSubDealer, (int)$data['AcceptForTarget'], (int)$data['RestrictForSale'], (float)$data['MaxPORestrictedQty']
					, (float)$data['SaleRateMH'], (float)$data['SaleRateMP'], (float)$data['SaleRateGJ'], (float)$data['SaleRateRJ'], (float)$data['SaleRateOther']
					, (int)$data['Division'], (int)$data['DistChannel']);
	$sql        = vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}

public function updateItem($data) {
// Spl code for updating UOM (available with Value=related ItCtg) & UOMType (not available))
	$sql		= "SELECT UOM,UOMType FROM so_item_ctg_m WHERE ItemCtgCd='".$data['ItemCtgCd']."'";
	$returnData = $this->execSelectQuery($sql);
	$UOM		= $returnData[0]["UOM"];
	$UOMType	= $returnData[0]["UOMType"];
	$IsforSubDealer = (isset($data['IsforSubDealer']) ? $data['IsforSubDealer'] : 0);

	$stmt		= " UPDATE so_item_m SET Descript = '%s', ShortDescript = '%s', ItemCtgCd ='%s' ,UOM='%s', UOMType='%s', QtyPerBox=%s, KgPerUOM=%s
						, DispOrder=%s, DefInCustomerItemRate=%s, EquiItemCd='%s', GroupDesc='%s', MainGroupDesc='%s', TokenNoPrefix='%s', AcceptDailyStock=%s, IsActive=%s, IsforSubDealer=%s, AcceptForTarget=%s, RestrictForSale=%s,  MaxPORestrictedQty='%s'
						,   SaleRateMH=%s, SaleRateMP=%s,   SaleRateGJ=%s, SaleRateRJ=%s, SaleRateOther=%s
						, Division=%s, DistChannel=%s WHERE CompanyCd=%s AND ItemCd='%s'";
	$inputArr	= array(addslashes(trim($data['Descript'])), addslashes(trim($data['ShortDescript'])), trim($data['ItemCtgCd'])
					,$UOM, $UOMType, (float)$data['QtyPerBox'], (float)$data['KgPerUOM'], (int)$data['DispOrder'], (int)$data['DefInCustomerItemRate'], $data['EquiItemCd']
					,$data['GroupDesc'], $data['MainGroupDesc'], $data['TokenNoPrefix'], (int)$data['AcceptDailyStock'], (int)$data['IsActive'], (int)$IsforSubDealer, (int)$data['AcceptForTarget'], (int)$data['RestrictForSale'], (float)$data['MaxPORestrictedQty']
					, (float)$data['SaleRateMH'], (float)$data['SaleRateMP'], (float)$data['SaleRateGJ'], (float)$data['SaleRateRJ'], (float)$data['SaleRateOther']
					,  (int)$data['Division'], (int)$data['DistChannel'], $data['oldCompanyCd'], $data['oldItemCd']);
	$sql		= vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}

public function updateCustomerItemPO($data) {
	$stmt		= "UPDATE so_customer_m_item_rate_type SET MaxPORestrictedQty=%s  WHERE ItemCd='%s'";
	$inputArr	= array((float)$data['MaxPORestrictedQty'], trim($data['oldItemCd']));
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function getItemHeader($companyCd,$mcode) {
	$stmt		= "SELECT * FROM so_item_m WHERE CompanyCd='%s' AND ItemCd='%s' ";
	$inputArr 	=  array($companyCd,$mcode);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function isExistItemCode($mcode) {
	$sql			= "SELECT * FROM so_item_m WHERE ItemCd='".$mcode."'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function deleteItem($ItemCd) {

	$sql = "delete FROM so_item_m WHERE ItemCd IN (".$ItemCd .")";
	$failMsg  = $this->execUpdateQuery($sql);
	return $failMsg;
}

// ItemTargetGroup Master ---------------------------------------------------------------------------------------------------------------------------------
public function getItemTargetGroupList() {
	$sql		= "SELECT  A.*,IFNULL(E.ShortDesc,A.CompanyCd) AS Company FROM so_item_targetgroup_m A LEFT OUTER JOIN so_company_m E ON A.CompanyCd=E.CompanyCd  ORDER BY A.DispOrder, A.Descript";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function insertItemTargetGroup($data) {
	$stmt = " INSERT INTO so_item_targetgroup_m (CompanyCd, ItemTargetGroupCd, Descript, UOM, UOMType, DispOrder, IsActive)
				VALUES(%s, %s, '%s', '%s', '%s', %s, %s);";
	$inputArr	= array((int)($data['CompanyCd']), (int)($data['ItemTargetGroupCd']), addslashes(trim($data['Descript']))
					,$data['UOM'], $data['UOMType'], (int)$data['DispOrder'], (int)$data['IsActive']);
	$sql        = vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}

public function updateItemTargetGroup($data) {
	$stmt		= " UPDATE so_item_targetgroup_m SET Descript = '%s', UOM='%s', UOMType='%s', DispOrder=%s, IsActive=%s WHERE ItemTargetGroupCd='%s'";
	$inputArr	= array(addslashes(trim($data['Descript'])), $data['UOM'], $data['UOMType'],  (int)$data['DispOrder'], (int)$data['IsActive'], $data['oldItemTargetGroupCd']);
	$sql		= vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}

public function getItemTargetGroupHeader($mcode) {
	$stmt		= "SELECT * FROM so_item_targetgroup_m WHERE ItemTargetGroupCd='%s' ";
	$inputArr 	=  array($mcode);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function isExistItemTargetGroupCode($mcode) {
	$sql			= "SELECT * FROM so_item_targetgroup_m WHERE ItemTargetGroupCd='".$mcode."'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

// Customer Master ---------------------------------------------------------------------------------------------------------------------------------------
public function getCustomerList($search = null, $searchValState= null ) {
	$searchCnd = " WHERE SectorCd='{$_SESSION['SectorCd']}' " . ((isset($search)) ? " AND A.Descript like '". $search . "%'" : "").((isset($searchValState)) ? " AND A.StateCd like '". $searchValState . "%'" : "");
	$sql		= "SELECT A.*,IFNULL(B.Descript,A.StateCd) AS State FROM so_customer_m A LEFT OUTER JOIN so_state_m B ON A.StateCd=B.StateCd " . $searchCnd . " ORDER BY A.IsActive DESC, B.DispOrder, A.CustomerCtgCd, A.Descript";

	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}


public function insertCustomerData($data) {
/*	if ($data['MaxDailyStockDate']=='' || $data['MaxDailyStockDate']=='00-00-0000')
		$MaxDailyStockDateTime='';
	else
		$MaxDailyStockDateTime = $this->convertDate($data['MaxDailyStockDate'], TRUE, 1) . ' ' . $data['MaxDailyStockTime'];*/
	$IsMainCustomer=0;
	if($data['CustomerCd'] == $data['AssociateFrom']){ $IsMainCustomer=1; }
	$stmt = " INSERT INTO so_customer_m 
	(CustomerCd,Descript,SectorCd,UserName,Address,City,StateCd,TelNo,EMailId,CustomerCtgCd,TaxType,IsInState,VATNo,CSTNo,PAN, 
	MaxContractDays,MaxMonthlyTargetDate, Division,DistChannel,IsActive,IsRE11MustInPO,DailyStockOrderExpl, DailyStockOrderAED, 
	HasSubdealer,HasDailyStock, DailyStockCheckDays, AllowCompanyVan,DummyVanAllowPO
	,BankName,BankBranch,BankAccountNo,IFSCCode, IsMainCustomer,AssociateFrom, AlertforTarget, AlertTargetDays, AlertforCreatePO, 
	AlertCreatePODays, AcceptStockBatchDatewise, CheckPhoneReport, DispPhoneReport)
				VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s',  '%s',  '%s', '%s', '%s', '%s', '%s', '%s', %s, '%s', %s, %s, %s, 
				%s, %s, %s, %s, %s, %s, %s, %s,'%s','%s','%s','%s', '%s', '%s', '%s', '%s', '%s', '%s', %s, %s, %s);";
	$inputArr   = array(trim($data['CustomerCd']), addslashes(trim($data['Descript'])), $data['SectorCd'], trim($data['UserName']), addslashes(trim($data['Address'])), trim($data['City'])
					, $data['StateCd'], trim($data['TelNo']), trim($data['EMailId']), $data['CustomerCtgCd'], trim($data['TaxType']), $data['IsInState']
					, $data['VATNo'], $data['CSTNo'], $data['PAN'], (int)$data['MaxContractDays'], $this->convertDate($data['MaxMonthlyTargetDate'],TRUE, 1)
					, (int)$data['Division'], (int)$data['DistChannel'], (int)$data['IsActive'], (int)$data['IsRE11MustInPO'], (int)$data['DailyStockOrderExpl'], (int)$data['DailyStockOrderAED']
					, (int)$data['HasSubdealer'], (int)$data['HasDailyStock'], (int)$data['DailyStockCheckDays']
					,(int)$data['AllowCompanyVan'] ,(int)$data['DummyVanAllowPO']
					, $data['BankName'], $data['BankBranch'], $data['BankAccountNo'], $data['IFSCCode'], $IsMainCustomer, $data['AssociateFrom'], $data['AlertforTarget'], $data['AlertTargetDays'], $data['AlertforCreatePO'], $data['AlertCreatePODays'], $data['AcceptStockBatchDatewise'], $data['CheckPhoneReport'], $data['DispPhoneReport'] );
	$sql        = vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}

public function updateCustomerData($data) {
/*	if ($data['MaxDailyStockDate']=='' || $data['MaxDailyStockDate']=='00-00-0000')
		$MaxDailyStockDateTime='';
	else
		$MaxDailyStockDateTime = $this->convertDate($data['MaxDailyStockDate'],TRUE, 1) . ' ' . $data['MaxDailyStockTime'];*/
	if($data['AlertforTarget'] == $data['OldAlertforTarget'] &&  $data['AlertTargetDays'] == $data['OldAlertTargetDays'] ){
	$AlertTargetUpdateDate= $data['OldAlertTargetUpdateDate'];
	}
	else{
		$AlertTargetUpdateDate = date('Y-m-d');
	}
	if($data['AlertforCreatePO'] == $data['OldAlertforCreatePO'] &&  $data['AlertCreatePODays'] == $data['oldAlertCreatePODays'] ){
	$AlertCreatePOUpdateDate= $data['OldAlertCreatePOUpdateDate'];
	}
	else{
		$AlertCreatePOUpdateDate = date('Y-m-d');
	}
	
	$IsMainCustomer=0;
	if($data['CustomerCd'] == $data['AssociateFrom']){ $IsMainCustomer=1; }
	$stmt		= " UPDATE so_customer_m SET Descript = '%s', SectorCd='%s', UserName='%s', Address = '%s', City ='%s' ,StateCd='%s', TelNo='%s', EMailId='%s', CustomerCtgCd='%s'
					,TaxType='%s', IsInState='%s', VATNo='%s', CSTNo='%s', PAN='%s', MaxContractDays=%s, MaxMonthlyTargetDate='%s'
					, Division=%s, DistChannel=%s, IsActive=%s, IsRE11MustInPO=%s, DailyStockOrderExpl=%s, DailyStockOrderAED=%s
					, HasSubdealer=%s, HasDailyStock=%s, DailyStockCheckDays=%s, AllowCompanyVan=%s
					, DummyVanAllowPO=%s, BankName='%s', BankBranch='%s', BankAccountNo='%s', IFSCCode='%s'
					, IsMainCustomer='%s', AssociateFrom='%s', AlertforTarget='%s', AlertTargetDays='%s', AlertTargetUpdateDate='%s'
					, AlertforCreatePO='%s', AlertCreatePODays='%s', AlertCreatePOUpdateDate='%s', AcceptStockBatchDatewise ='%s', CheckPhoneReport='%s', DispPhoneReport='%s' WHERE CustomerCd='%s'";
	$inputArr	= array(addslashes(trim($data['Descript'])), $data['SectorCd'], trim($data['UserName']), addslashes(trim($data['Address'])), trim($data['City'])
					, $data['StateCd'], trim($data['TelNo']), trim($data['EMailId']), $data['CustomerCtgCd'], trim($data['TaxType']), $data['IsInState']
					, $data['VATNo'], $data['CSTNo'], $data['PAN']
					, (int)$data['MaxContractDays'], $this->convertDate($data['MaxMonthlyTargetDate'],TRUE, 1)
					, (int)$data['Division'], (int)$data['DistChannel'], (int)$data['IsActive'], (int)$data['IsRE11MustInPO'], (int)$data['DailyStockOrderExpl']
					, (int)$data['DailyStockOrderAED'], (int)$data['HasSubdealer'], (int)$data['HasDailyStock'], (int)$data['DailyStockCheckDays'], (int)$data['AllowCompanyVan'], (int)$data['DummyVanAllowPO']
					, $data['BankName'], $data['BankBranch'], $data['BankAccountNo'], $data['IFSCCode'], $IsMainCustomer, $data['AssociateFrom'], $data['AlertforTarget'], $data['AlertTargetDays'], $AlertTargetUpdateDate, $data['AlertforCreatePO'], $data['AlertCreatePODays'], $AlertCreatePOUpdateDate, $data['AcceptStockBatchDatewise'],  $data['CheckPhoneReport'], $data['DispPhoneReport'], $data['oldCustomerCd']);
	$sql		= vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}

public function updateCustomerBankData($BankName, $BankBranch, $BankAccountNo, $IFSCCode, $oldCustomerCd) {
	$stmt		= " UPDATE so_customer_m SET  BankName='%s', BankBranch='%s', BankAccountNo='%s', IFSCCode='%s' WHERE CustomerCd='%s'";
	$inputArr	= array($BankName, $BankBranch, $BankAccountNo, $IFSCCode, $oldCustomerCd);
	$sql		= vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}

public function UpdaeCustomerTarVsAchvAlertsenddate($oldCustomerCd, $AlertSendDate) {
	$stmt		= " UPDATE so_customer_m SET  AlertTargetUpdateDate='%s' WHERE CustomerCd='%s'";
	$inputArr	= array($AlertSendDate, $oldCustomerCd);
	$sql		= vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}


public function getCustomer($ccode) {
	$stmt		= "SELECT * FROM so_customer_m WHERE CustomerCd='%s' ";
	$inputArr	= array($ccode);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getCustomerItemRateType($ccode = NULL) {
	$stmt		= "SELECT A.ItemCd, C.ShortDesc AS Company,  A.ItemRateType, IFNULL(B.Descript,A.ItemCd) AS Descript, 0 AS Order1
				, IFNULL(B.DispOrder,0) AS DispOrder,A.MinStockLevel, A.MaxPORestrictedQty, A.StartDate, A.EndDate, A.DateRestrictQty
				, A.StatusR_N, A.IsSubdealerItem, A.IsSuperActive, A.SuperActiveEndDate, IFNULL(B.UOM,'') AS UOM, A.BasicRate
					FROM so_customer_m_item_rate_type A LEFT OUTER JOIN so_item_m B ON A.ItemCd=B.ItemCd LEFT OUTER JOIN so_company_m AS C ON B.CompanyCd = C.CompanyCd WHERE "
			 		. (isset($ccode) ?  "A.CustomerCd='%s'" : "1<>1")
					. " UNION ALL "
				. " SELECT A.ItemCd, A.companyCd, ' ' AS ItemRateType, A.Descript, 1 AS Order1, DispOrder, 0 AS MinStockLevel, 0 As MaxPORestrictedQty
				, '00-00-0000' AS StartDate, '00-00-0000' AS EndDate, 0 AS DateRestrictQty, 'Regular' AS StatusR_N,  0 AS IsSubdealerItem
				, 0 AS IsSuperActive, '00-00-0000' AS SuperActiveEndDate, A.UOM, 0 AS BasicRate FROM so_item_m A WHERE " 
					. "!EXISTS(
							SELECT * FROM so_customer_m_item_rate_type B WHERE " . (isset($ccode) ?  "B.CustomerCd='%s'" : "1<>1") . " AND A.ItemCd=B.ItemCd"
					 . ") ORDER BY 4, 5, 3";
	$inputArr	= array($ccode, $ccode);
	$sql		= vsprintf($stmt,$inputArr);

	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getCustomerItemRateTypeInsertQuery() {
	return ("INSERT INTO so_customer_m_item_rate_type (CustomerCd, ItemCd, MinStockLevel, MaxPORestrictedQty,StartDate,EndDate,DateRestrictQty,StatusR_N, ItemRateType, IsSubdealerItem, IsSuperActive,SuperActiveEndDate, BasicRate)
				VALUES ('%s', '%s', %s, '%s', '%s','%s', '%s', '%s', '%s', %s, %s,'%s', %s);");
}

public function getCustomerItemRateTypeUpdateQuery() {
	return ("UPDATE so_customer_m_item_rate_type SET MinStockLevel=%s, MaxPORestrictedQty='%s', StartDate='%s', EndDate='%s', DateRestrictQty='%s', StatusR_N='%s',  ItemRateType='%s', IsSubdealerItem=%s, IsSuperActive=%s, SuperActiveEndDate='%s', BasicRate=%s WHERE CustomerCd='%s' AND ItemCd='%s' ");
}

public function getCustomerItemRateTypeDeleteQuery() {
	return ("DELETE FROM so_customer_m_item_rate_type WHERE CustomerCd='%s' AND ItemCd='%s'");
}

public function insertCustomerItemRateTypeData($data) {
	$returnData = array();
	$queryInsert	= $this->getCustomerItemRateTypeInsertQuery();
	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
	$IsSubdealerItem = (int)isset($data['IsSubdealerItem1_'.$curRowNo]);
	$IsSuperActive = (int)isset($data['IsSuperActive1_'.$curRowNo]);
	$StartDate = $this->convertDate($data['StartDate1_'.$curRowNo], TRUE, 1);
	$EndDate = 	$this->convertDate($data['EndDate1_'.$curRowNo], TRUE, 1);
	$SuperActiveEndDate = 	$this->convertDate($data['SuperActiveEndDate1_'.$curRowNo], TRUE, 1);
	if (trim($data['ItemRateType1_'.$curRowNo])=='' && $IsSubdealerItem==0 && $IsSuperActive==0 && (int)$data['MinStockLevel1_'.$curRowNo]==0 && (float)$data['BasicRate1_'.$curRowNo]==0) {
		continue;
	}
	$inputArr	= array($data['CustomerCd'], $data['ItemCd1_'.$curRowNo], $data['MinStockLevel1_'.$curRowNo], $data['MaxPORestrictedQty1_'.$curRowNo]
	, $StartDate, $EndDate, $data['DateRestrictQty1_'.$curRowNo], $data['StatusR_N1_'.$curRowNo], trim($data['ItemRateType1_'.$curRowNo])
	, $IsSubdealerItem, $IsSuperActive, $SuperActiveEndDate, (float)$data['BasicRate1_'.$curRowNo]);
	$sql		= vsprintf($queryInsert,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	if ($returnData) return $returnData;
	}
	return $returnData;
}

public function updateCustomerItemRateTypeData($data) {
	$queryInsert	= $this->getCustomerItemRateTypeInsertQuery();
	$queryUpdate	= $this->getCustomerItemRateTypeUpdateQuery();
	$queryDelete	= $this->getCustomerItemRateTypeDeleteQuery();
	$returnData		= '';
	for ($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		$IsSubdealerItem = (int)isset($data['IsSubdealerItem1_'.$curRowNo]);
		$IsSuperActive = (int)isset($data['IsSuperActive1_'.$curRowNo]);
		if (trim($data['ItemRateType1_'.$curRowNo])=='' && $IsSubdealerItem==0 && $IsSuperActive==0 && (int)$data['MinStockLevel1_'.$curRowNo]==0 && (float)$data['BasicRate1_'.$curRowNo]==0) {
			$inputArr	= array();
			$inputArr	= array($data['CustomerCd'], $data['ItemCd1_'.$curRowNo]);
			$sql		= vsprintf($queryDelete,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		} else {
			$queryCheck	= "SELECT COUNT(*) AS Count FROM so_customer_m_item_rate_type WHERE CustomerCd='%s' AND ItemCd='%s'";
			$inputArr	= array();
			$inputArr	= array($data['CustomerCd'], $data['ItemCd1_'.$curRowNo]);
			$sql		= vsprintf($queryCheck, $inputArr);
			$returnData	= $this->execSelectQuery($sql);
			if ($returnData[0]['Count']==0) {
				$inputArr	= array();
				$StartDate = $this->convertDate($data['StartDate1_'.$curRowNo], TRUE, 1);
				$EndDate = 	$this->convertDate($data['EndDate1_'.$curRowNo], TRUE, 1);
				$SuperActiveEndDate = 	$this->convertDate($data['SuperActiveEndDate1_'.$curRowNo], TRUE, 1);
				$inputArr	= array($data['CustomerCd'], $data['ItemCd1_'.$curRowNo], (int)$data['MinStockLevel1_'.$curRowNo], (int)$data['MaxPORestrictedQty1_'.$curRowNo],$StartDate, $EndDate, $data['DateRestrictQty1_'.$curRowNo], $data['StatusR_N1_'.$curRowNo], trim($data['ItemRateType1_'.$curRowNo]), $IsSubdealerItem, $IsSuperActive, $SuperActiveEndDate, (float)$data['BasicRate1_'.$curRowNo]);
				$sql		= vsprintf($queryInsert,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
			} else {
				$inputArr	= array();
				$StartDate = $this->convertDate($data['StartDate1_'.$curRowNo], TRUE, 1);
				$EndDate = 	$this->convertDate($data['EndDate1_'.$curRowNo], TRUE, 1);
				$SuperActiveEndDate  = 	$this->convertDate($data['SuperActiveEndDate1_'.$curRowNo], TRUE, 1);
				$inputArr	= array((int)$data['MinStockLevel1_'.$curRowNo], (int)$data['MaxPORestrictedQty1_'.$curRowNo], $StartDate, $EndDate, $data['DateRestrictQty1_'.$curRowNo], $data['StatusR_N1_'.$curRowNo], trim($data['ItemRateType1_'.$curRowNo]), $IsSubdealerItem, $IsSuperActive, $SuperActiveEndDate, (float)$data['BasicRate1_'.$curRowNo], $data['CustomerCd'], $data['ItemCd1_'.$curRowNo]);
				$sql		= vsprintf($queryUpdate,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
			}
			if ($returnData) return $returnData;
		}
	}
	return $returnData;
}

public function isExistCustomerCode($ccode) {
	$sql			= "SELECT * FROM so_customer_m WHERE CustomerCd='".$ccode."'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}
///==================Password Update ================\


public function passwordValidation(){
	$sql		= "SELECT A.lastUpdate_dateTime, PassRenewalDays FROM " . self::DTUserM . " A WHERE A.UserName='" . $_SESSION['UserName'] . "'";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function updatepasswordValidation($NewPassword,$UserName){
		$sql		= "SELECT A.Password FROM " . self::DTUserM . " A WHERE A.UserName='" . $UserName. "'";
		$returnData	= $this->execSelectQuery($sql);
		if ($returnData[0]['Password']==md5(trim($_POST['OldPassword']))) {
			$currentDateTime = date('Y-m-d H:i:s');
			$stmt		= "UPDATE " . self::DTUserM . " SET Password ='%s', lastUpdate_dateTime = '%s', lastUpdate_by='%s' WHERE UserName='%s'";
			$inputArr	= array(trim(md5($NewPassword)), $currentDateTime, $UserName, $UserName);
			$sql		= vsprintf($stmt,$inputArr);
			$returnMsg	= $this->execUpdateQuery($sql);
			//return $returnMsg;
			$data = array("status" => "success", "message" => "Password Change Successfully");
		}else{
			//return "Old password not match ";
		$data = array("status" => "error","message" => "Old password not match");
		}
		return $data;
		
}

		
// Subdealer Master ---------------------------------------------------------------------------------------------------------------------------------------
public function getSubdealerList($search = null, $searchValState = null, $filtercond= null) {
	$searchCnd	= " WHERE  " . ((isset($search)) ? " A.Descript like '". $search . "%'" : "1") .((isset($searchValState)) ? " And A.StateCd like '". $searchValState . "%'" : "");
	$searchCnd .= ((isset($filtercond) && $filtercond !='') ? " AND ".$filtercond ."" : "" );
	
	$sql		= "SELECT A.*,IFNULL(B.Descript,A.StateCd) AS State FROM so_subdealer_m A LEFT OUTER JOIN so_state_m B ON A.StateCd=B.StateCd "	. $searchCnd . " ORDER BY A.IsActive DESC, B.DispOrder, A.Descript";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function insertSubdealer($data) {
	$stmt = " INSERT INTO so_subdealer_m (SubdealerCd,SubdealerCtgCd, Descript,Address,City,StateCd,TelNo,EMailId,PAN,ContactPerson1,TelNo1,ContactPerson2
	,TelNo2,PartnerName1,PartnerName2,BankName,BankAcNo,BankIFSC,BankAddress,IsLoyality,IsActive,AllowTrgt,AssociatedDealerCd,Reason,StatusR_N)
				VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s',  '%s',  '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %s
				, %s, %s, '%s', '%s', '%s');";
	$inputArr   = array($data['SubdealerCd'], $data['SubdealerCtgCd'], addslashes(trim($data['Descript'])), addslashes(trim($data['Address']))
					, trim($data['City']), trim($data['StateCd'])
					,  trim($data['TelNo']), trim($data['EMailId']), $data['PAN'], trim($data['ContactPerson1']), trim($data['TelNo1'])
					, trim($data['ContactPerson2']), trim($data['TelNo2']), trim($data['PartnerName1']), trim($data['PartnerName2'])
					, trim($data['BankName']), trim($data['BankAcNo']), trim($data['BankIFSC']), trim($data['BankAddress'])
					, (int)$data['IsLoyality'], (int)$data['IsActive'], (int) $data['AllowTrgt'], $data['AssociatedDealerCd'], $data['Reason'], $data['StatusR_N']);
	$sql        = vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}

public function updateSubdealer($data) {
	$stmt		= " UPDATE so_subdealer_m SET SubdealerCd='%s', SubdealerCtgCd='%s', Descript = '%s', Address = '%s', City ='%s' ,StateCd='%s', TelNo='%s', EMailId='%s', PAN='%s'
					,ContactPerson1='%s', TelNo1='%s',ContactPerson2='%s', TelNo2='%s', PartnerName1='%s', PartnerName2='%s'
					,BankName='%s', BankAcNo='%s', BankIFSC='%s', BankAddress='%s', IsLoyality=%s, IsActive=%s, AllowTrgt=%s, AssociatedDealerCd='%s', Reason='%s', StatusR_N='%s' WHERE IdSubdealer=%s";
	$inputArr	= array($data['SubdealerCd'], $data['SubdealerCtgCd'], addslashes(trim($data['Descript'])), addslashes(trim($data['Address']))
					, trim($data['City']),  $data['StateCd'], trim($data['TelNo']), trim($data['EMailId']), $data['PAN']
					, trim($data['ContactPerson1']), trim($data['TelNo1']), trim($data['ContactPerson2']), trim($data['TelNo2'])
					, trim($data['PartnerName1']), trim($data['PartnerName2'])
					, trim($data['BankName']), trim($data['BankAcNo']), trim($data['BankIFSC']), trim($data['BankAddress'])
					, (int)$data['IsLoyality'], (int)$data['IsActive'], (int) $data['AllowTrgt'], $data['AssociatedDealerCd'], $data['Reason'], $data['StatusR_N'], (int)$data['oldIdSubdealer']);
	$sql		= vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}

public function insertSubdealerDealer($data) {
	$returnData = array();
	$queryInsert	= $this->objDBQuery->getSubdealerDealerInsertQuery();
	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
	if (!isset($data['CustomerCd1_'.$curRowNo]) || trim($data['CustomerCd1_'.$curRowNo])=='') {
		continue;
	}	
	//$inputArr	= array((int)$data['IdSubdealer'], $data['CustomerCd1_'.$curRowNo], $this->convertDate($data['RegnDate1_'.$curRowNo], TRUE, 1));
	$inputArr	= array((int)$data['IdSubdealer'], $data['CustomerCd1_'.$curRowNo], $this->convertDate($data['RegnDate1_'.$curRowNo], TRUE, 1),$data['Relation_'.$curRowNo]);
	$sql		= vsprintf($queryInsert,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	if ($returnData) return $returnData;
	}
	return $returnData;
}

public function getDealerSubdealerRelationMDisp(){
		$sql		= "SELECT RelationId,Descript  FROM  so_firm_relation_m ";
		$returnData = $this->execSelectQuery($sql);
		return $returnData;	
	}

public function updateSubdealerDealer($data) {
	$queryInsert	= $this->objDBQuery->getSubdealerDealerInsertQuery();
	$queryUpdate	= $this->objDBQuery->getSubdealerDealerUpdateQuery();
	$queryDelete	= $this->objDBQuery->getSubdealerDealerDeleteQuery();
	$returnData		= '';
	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		if (!isset($data['CustomerCd1_'.$curRowNo])) {
			continue;
		}	
		$UniqueId = (int)$data['UniqueId1_'.$curRowNo];
		if ( trim($data['CustomerCd1_'.$curRowNo])=='') {
			if ($UniqueId>0) {
				$inputArr	= array();
				$inputArr	= array($UniqueId);
				$sql		= vsprintf($queryDelete, $inputArr);
				$returnData	= $this->execUpdateQuery($sql);
				if ($returnData) return $returnData;
			}
		} else {
			if ($UniqueId>0) {
				//$inputArr	= array((int)$data['oldIdSubdealer'], $data['CustomerCd1_'.$curRowNo], $this->convertDate($data['RegnDate1_'.$curRowNo], TRUE, 1), $UniqueId);
				$inputArr	= array((int)$data['oldIdSubdealer'], $data['CustomerCd1_'.$curRowNo], $this->convertDate($data['RegnDate1_'.$curRowNo], TRUE, 1),$data['Relation_'.$curRowNo], $UniqueId);
				$sql		= vsprintf($queryUpdate,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
			} else {
				//$inputArr	= array((int)$data['oldIdSubdealer'], $data['CustomerCd1_'.$curRowNo], $this->convertDate($data['RegnDate1_'.$curRowNo], TRUE, 1));
				$inputArr	= array((int)$data['oldIdSubdealer'], $data['CustomerCd1_'.$curRowNo], $this->convertDate($data['RegnDate1_'.$curRowNo], TRUE, 1),$data['Relation_'.$curRowNo]);
				$sql		= vsprintf($queryInsert,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
			}
			if ($returnData) return $returnData;
		}
	}
	return $returnData;
}


public function getSubdealer($ccode) {
	$stmt		= "SELECT * FROM so_subdealer_m WHERE IdSubdealer=%s ";
	$inputArr	= array($ccode);
	$sql		= vsprintf($stmt, $inputArr);
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getSubdealerDealer($ccode = NULL) {
	$stmt		= "SELECT A.* FROM so_subdealer_m_dealer A LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd"
			 		. " WHERE " . (isset($ccode) ?  " A.IdSubdealer=%s " : "1<>1"). " ORDER BY B.Descript";
	$inputArr	= array($ccode);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}
///////  Subdealer Magazine Master --------------------------------------------------------------------------------------------------

public function getSubdealerMagazineList($search = null, $searchValState = null) {
	$searchCnd	= " WHERE " .(isset($search) ? " (B.Descript like '". $search . "%' OR A.Descript like '". $search . "%' OR A.LicDocKey like '". $search . "%')" : "1") . ((isset($searchValState)) ? " And A.StateCd like '". $searchValState . "%'" : "");
	$sql		= "SELECT A.MagazineCd,A.Descript,A.LicDocKey,A.IdSubdealer, A.OccupierName, DATE_FORMAT(A.LicExpiryDate,'%d-%m-%Y') AS LicExpiryDate
					,xf_Proper(IFNULL(B.Descript,A.IdSubdealer)) AS Subdealer, A.StateCd, IFNULL(C.Descript,A.StateCd) AS State  FROM 
					so_subdealer_magazine_m A LEFT OUTER JOIN so_subdealer_m B ON A.IdSubdealer=B.IdSubdealer JOIN so_state_m C ON  A.StateCd = C.StateCd 
					" .$searchCnd . " ORDER BY A.IsActive DESC,B.Descript,A.MagazineCd";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function insertSubdealerMagazine($data) {
	$stmt = "INSERT INTO so_subdealer_magazine_m (IdSubdealer,MagazineLicNo,Place,Descript,MagazineDetail
				,LicDocKey, OccupierName, LicExpiryDate,Taluka,District,StateCd,VanTurnAroundDays,IsActive)
			VALUES ('%s', '%s', '%s', '%s', '%s',  '%s',  '%s', '%s', '%s', '%s', '%s', '%s', '%s');";
	$inputArr   = array($data['IdSubdealer'], addslashes(trim($data['MagazineLicNo']))
	, addslashes(trim($data['Place'])), addslashes(trim($data['Descript'])), addslashes(trim($data['MagazineDetail'])), trim($data['LicDocKey']), $data['OccupierName']				
	, $this->convertDate($data['LicExpiryDate'], True, 1), trim($data['Taluka']), trim($data['District']), $data['StateCd'], trim($data['VanTurnAroundDays'])
					, trim($data['IsActive']));
	$sql        = vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}

public function insertSubdealerMagazineCapacity($data) {
	$returnData = array();
	$queryInsert	= "INSERT INTO so_subdealer_magazine_capacity (IdSubdealer, MagazineCd, ItemCtgCd,Capacity,RotationCapacity)
			VALUES ('%s', '%s', '%s', '%s', '%s');";
	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
	if (!isset($data['ItemCtgCd1_'.$curRowNo]) || trim($data['ItemCtgCd1_'.$curRowNo])=='') {
		continue;
	}	
	$inputArr	= array((int)$data['IdSubdealer'], $data['MagazineCd'],  $data['ItemCtgCd1_'.$curRowNo], $data['Capacity1_'.$curRowNo], $data['RotationCapacity1_'.$curRowNo] );
	$sql		= vsprintf($queryInsert,$inputArr);                     
	$returnData	= $this->execUpdateQuery($sql);
	if ($returnData) return $returnData;
	}
	return $returnData;
}


public function updateSubdealerMagazine($data) {
	$stmt		= " UPDATE so_subdealer_magazine_m SET MagazineLicNo='%s', Place = '%s', Descript = '%s', MagazineDetail ='%s'
					,LicDocKey='%s', OccupierName='%s', LicExpiryDate='%s', Taluka='%s', District='%s',StateCd='%s', VanTurnAroundDays='%s',IsActive='%s'
					WHERE IdSubdealer='%s' and MagazineCd='%s'";
	$inputArr	= array($data['MagazineLicNo'], addslashes(trim($data['Place'])), addslashes(trim($data['Descript'])), trim($data['MagazineDetail'])
					, $data['LicDocKey'], $data['OccupierName'], $this->convertDate($data['LicExpiryDate'], True, 1), trim($data['Taluka']), $data['District']
					, trim($data['StateCd']), trim($data['VanTurnAroundDays']), trim($data['IsActive']), trim($data['IdSubdealer'])
					, trim($data['oldMagazineCd']));
	$sql		= vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}


public function updateSubdealerMagazineCapacity($data) {
	$queryInsert	= $this->objDBQuery->getSubdealerMagazineCapacityInsertQuery();
	$queryUpdate	= $this->objDBQuery->getSubdealerMagazineCapacityUpdateQuery();
	$queryDelete	= $this->objDBQuery->getSubdealerMagazineCapacityDeleteQuery();
	$returnData		= '';
	$sql		= '';
	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		$sql=$data['ItemCtgCd1_'.$curRowNo];
		if (!isset($data['ItemCtgCd1_'.$curRowNo])) {
			continue;
		}	
		
		$UniqueId = (int)$data['UniqueId1_'.$curRowNo];
		$sql=$UniqueId;
		if ( trim($data['ItemCtgCd1_'.$curRowNo])=='') {
			if ($UniqueId>0) {
				$inputArr	= array();
				$inputArr	= array($UniqueId);
				$sql		= vsprintf($queryDelete, $inputArr);
				$returnData	= $this->execUpdateQuery($sql);
				if ($returnData) return $returnData;
			}
		} else {
			if ($UniqueId>0) {
				$inputArr	= array($data['ItemCtgCd1_'.$curRowNo], $data['Capacity1_'.$curRowNo], $data['RotationCapacity1_'.$curRowNo] , $UniqueId);
				$sql		= vsprintf($queryUpdate,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
			} else {
				$inputArr	= array((int)$data['oldIdSubdealer'], $data['oldMagazineCd'], $data['ItemCtgCd1_'.$curRowNo], $data['Capacity1_'.$curRowNo], $data['RotationCapacity1_'.$curRowNo],  );
				$sql		= vsprintf($queryInsert,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
			}
			if ($returnData) return $returnData;
		}
	}
	return $returnData;
}

public function getSubdealerMagazine($ccode) {
	$stmt		= "SELECT * FROM so_subdealer_magazine_m WHERE MagazineCd=%s ";
	$inputArr	= array($ccode);
	$sql		= vsprintf($stmt, $inputArr);
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getSubdealerMagazineCapacity($ccode = NULL) {
	$stmt		= "SELECT A.* FROM so_subdealer_magazine_capacity A LEFT OUTER JOIN so_item_ctg_m B ON A.ItemCtgCd=B.ItemCtgCd"
			 		. " WHERE " . (isset($ccode) ?  " A.MagazineCd=%s " : "1<>1"). " ORDER BY B.Descript";
	$inputArr	= array($ccode);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

///=================================================

// Subdealer Bank Details ===============================================================================

public function SubdealerBankDetails($data){
	$stmt = "Update so_subdealer_m SET BankName = '%s',BankAcNo = '%s',BankIFSC='%s',BankAddress = '%s' WHERE IdSubdealer = '%s'";
	$inputArr	= array($data['BankName'],$data['BankAcNo'],$data['BankIFSC'],$data['BankAddress'],$data['SubdealerCd']);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function SubdealerBankDetails_PDF($IdSubdealer, $uploadData){
	$target_path = 'upload/SubdealerBankDetails/';
	$filename	 ='ChequeDetails_'.$IdSubdealer.'.pdf' ;
	$target_path = $target_path.$filename; 
	if(move_uploaded_file($_FILES['BankCheque']['tmp_name'], $target_path)) {
		$sql = "update so_subdealer_m SET ChequeUpload = '".$filename."' where IdSubdealer =".$IdSubdealer;
		$result = $this->execUpdateQuery($sql);
	}
}

public function getSubdealerBankDetails($IdSubdealer){
	$sql = "SELECT BankName,BankAcNo,BankIFSC,BankAddress,ChequeUpload,IsBankDetailsApproved FROM so_subdealer_m WHERE IdSubdealer =".$IdSubdealer;
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function SubdealerBankDetailsList(){
	$sql = "SELECT IdSubdealer,Descript,BankName,BankAcNo,BankIFSC,BankAddress,ChequeUpload,IsBankDetailsApproved FROM so_subdealer_m WHERE BankAcNo <> '' AND IsBankDetailsApproved=0";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function approveBankDetails($IdSubdealer){
	$sql 	= "UPDATE so_subdealer_m SET IsBankDetailsApproved = 1  WHERE IdSubdealer IN($IdSubdealer)";
	$returnData = $this->execUpdateQuery($sql);
	return $returnData;	
}
//=======================================================================



// Subdealer Item Master----------------------------------------------------------------------------------------------------------------------------------------------
public function getSubdealerItemList($search = null, $searchValState = null) {
	$searchCnd	= " WHERE  " . ((isset($search)) ? " A.Descript like '". $search . "%'" : "1");
	$sql		= "SELECT A.*, IFNULL(B.Descript,A.StateCd) AS State FROM so_subdealer_m A  LEFT OUTER JOIN so_state_m B ON A.StateCd=B.StateCd "	. $searchCnd . "  AND IdSubdealer IN (select DISTINCT(IdSubdealer) from so_subdealer_item) ORDER BY A.IsActive DESC, B.DispOrder, A.Descript";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function createSubdealerItemList($search = null, $searchValState = null) {
	$searchCnd	= " WHERE  " . ((isset($search)) ? " A.Descript like '". $search . "%'" : "1");
	$sql		= "SELECT A.*, IFNULL(B.Descript,A.StateCd) AS State FROM so_subdealer_m A  LEFT OUTER JOIN so_state_m B ON A.StateCd=B.StateCd "	. $searchCnd . "  AND IdSubdealer NOT IN (select DISTINCT(IdSubdealer) from so_subdealer_item) ORDER BY A.IsActive DESC, B.DispOrder, A.Descript";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function isExistSubdealerItem($mcode) {
	$sql			= "SELECT  * FROM so_subdealer_item WHERE IdSubdealer='".$mcode."'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function getSubdealerDealerItem($ccode) {
	$stmt		= "select Distinct(A.ItemCd), B.ShortDescript from so_customer_m_item_rate_type A JOIN so_item_m B on A.ItemCd = B.ItemCd
				where A.CustomerCd IN (SELECT A.CustomerCd FROM so_subdealer_m_dealer A LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd 
				WHERE  A.IdSubdealer='$ccode') AND IsSubdealerItem=1 Order BY DailyStockRepOrder";
	$inputArr	= array($ccode);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getSubdealerSaleItemRestInsertQuery() {
	$sql = "INSERT INTO so_subdealer_item(IdSubdealer, CustomerCd, ItemCd, IsForSale)"
		. " VALUES ('%s', '%s', %s, %s);";
	return $sql ;
}

public function getSubdealerSaleItemRestUpdateQuery() {
	$sql	= "UPDATE so_subdealer_item SET IsForSale=%s WHERE IdSubdealer='%s' AND CustomerCd='%s'  AND ItemCd='%s'";
	return $sql ;
}

public function getSubdealerSaleItemRestDeleteQuery() {
	$sql	= "DELETE FROM so_subdealer_item WHERE IdSubdealer ='%s'  AND CustomerCd=%s AND  ItemCd='%s'";
	return $sql ;
}


public function insertSubdealerItem($data) {
	$queryInsert	= $this->getSubdealerSaleItemRestInsertQuery();

	$ItemArr = explode(',', $data['ItemCdStrForSaleRest']);	// 20000118,20000119,20000120,20000121
	$ItemCount = count($ItemArr);
	$returnData		= '';

	$IdSubdealer	= $data['IdSubdealer'];

	for ($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		$CustomerCd	= (int)$data['CustomerCd1_'.$curRowNo];
		for ($curItemCdIndex=0; $curItemCdIndex<$ItemCount; $curItemCdIndex++) {
			$ItemCd = $ItemArr[$curItemCdIndex];
			$IsForSale = (int)$data[$ItemCd.'_'.$curRowNo];	// $data['200001183_1']
			if ($CustomerCd>0 && $ItemCd>0 && $IsForSale>0) {
				$inputArr	= array($IdSubdealer, $CustomerCd, $ItemCd,  $IsForSale);
				$sql		= vsprintf($queryInsert, $inputArr);
				$returnData	= $this->execUpdateQuery($sql);
				if ($returnData) return $returnData;
			}
		}
	}
return $returnData;
}

public function getSubdealerDealerItemRest($IdSubdealer, $CustomerCd, $ItemCd=Null) {
	$searchCnd	= " AND " . ($ItemCd!='' && (isset($ItemCd) ) ? " ItemCd = '". $ItemCd . "'" : "1");
	$stmt		= "select IsForSale, ItemCd from so_subdealer_item WHERE  IdSubdealer='%s' and CustomerCd='%s' ". $searchCnd . "";
	$inputArr	= array($IdSubdealer, $CustomerCd, $ItemCd);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}


public function updateSubdealerItem($data) {
	$queryInsert	= $this->getSubdealerSaleItemRestInsertQuery();
	$queryUpdate	= $this->getSubdealerSaleItemRestUpdateQuery();
	$queryDelete	= $this->getSubdealerSaleItemRestDeleteQuery();

	$ItemArr = explode(',', $data['ItemCdStrForSaleRest']);
	$ItemCount = count($ItemArr);
	$returnData		= '';
	
	$IdSubdealer = (int)$data['IdSubdealer'];
	
	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		$CustomerCd = (int)$data['CustomerCd1_'.$curRowNo];
		for ($curItemCdIndex=0; $curItemCdIndex<$ItemCount; $curItemCdIndex++) {
			$ItemCd = $ItemArr[$curItemCdIndex];
			$IsForSale = (int)$data[$ItemCd.'_'.$curRowNo];	// $data['200001183_1']
			if ($CustomerCd<=0 || $IsForSale<=0 || $ItemCd<=0) {
				$inputArr	= array();
				$inputArr	= array($IdSubdealer, $CustomerCd, $ItemCd);
				$sql		= vsprintf($queryDelete, $inputArr);
				$returnData	= $this->execUpdateQuery($sql);
				if ($returnData) return $returnData;
			} else {
				$queryCheck	= "SELECT COUNT(*) AS Count FROM so_subdealer_item WHERE IdSubdealer='%s' AND CustomerCd='%s' AND ItemCd='%s'";
				$inputArr	= array();
				$inputArr	= array($IdSubdealer, $CustomerCd, $ItemCd);
				$sql		= vsprintf($queryCheck,$inputArr);
				$returnData	= $this->execSelectQuery($sql);
				if ($returnData[0]['Count']==0) {
					$inputArr	= array();
					$inputArr	= array($IdSubdealer, $CustomerCd, $ItemCd, $IsForSale);
					$sql		= vsprintf($queryInsert,$inputArr);
					$returnData	= $this->execUpdateQuery($sql);
				} else {
					$inputArr	= array();
					$inputArr	= array($IsForSale, $IdSubdealer, $CustomerCd, $ItemCd);
					$sql		= vsprintf($queryUpdate,$inputArr);
					$returnData	= $this->execUpdateQuery($sql);
				}
				if ($returnData) return $returnData;
			}
		}
	}
	return $returnData;
}

// Magazine Master ---------------------------------------------------------------------------------------------------------------------------------------
public function getMagazineList($search = null) {
	$searchCnd	= " WHERE B.SectorCd='{$_SESSION['SectorCd']}' " . (isset($search) ? " AND (B.Descript like '". $search . "%' OR A.Descript like '". $search . "%' OR A.LicDocKey like '". $search . "%')" : "");
	$sql		= "SELECT A.MagazineCd,A.Descript,A.LicDocKey,A.CustomerCd,DATE_FORMAT(A.LicExpiryDate,'%d-%m-%Y') AS LicExpiryDate
					,xf_Proper(IFNULL(B.Descript,A.CustomerCd)) AS Customer FROM so_magazine_m A LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd" .$searchCnd
					. " ORDER BY A.IsActive DESC,B.Descript,A.MagazineCd";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function isExistMagazineCode($mcode) {
	$sql			= "SELECT  * FROM so_magazine_m WHERE MagazineCd='".$mcode."'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function insertMagazineData($data) {
	$sql 		= " INSERT INTO so_magazine_m (MagazineCd,CustomerCd,MagazineLicNo,Descript,MagazineDetail,LicDocKey,LicExpiryDate,Place,Taluka,District,StateCd,VanTurnAroundDays,IsActive)
			VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %s, %s);";
	$inputArr	= array(trim($data['MagazineCd']),trim($data['CustomerCd']),trim($data['MagazineLicNo']),addslashes(trim($data['Descript']))
		, addslashes(trim($data['MagazineDetail'])), $data['LicDocKey'], $this->convertDate($data['LicExpiryDate'], TRUE, 1)
		, addslashes(trim($data['Place'])), addslashes(trim($data['Taluka'])), addslashes(trim($data['District'])), $data['StateCd'], (int)$data['VanTurnAroundDays'], (int)$data['IsActive']);
	$sql		= vsprintf($sql,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function updateMagazineData($data) {
	$sql		= " UPDATE so_magazine_m set MagazineLicNo = '%s', Descript ='%s', MagazineDetail='%s', LicDockey='%s', LicExpiryDate='%s', Place='%s', Taluka='%s', District='%s', StateCd='%s', VanTurnAroundDays=%s, IsActive=%s WHERE MagazineCd='%s'";
	$inputArr	= array(addslashes(trim($data['MagazineLicNo'])), addslashes(trim($data['Descript'])), addslashes(trim($data['MagazineDetail'])), $data['LicDocKey'], $this->convertDate($data['LicExpiryDate'], TRUE, 1)
		, addslashes(trim($data['Place'])), addslashes(trim($data['Taluka'])), addslashes(trim($data['District'])), $data['StateCd'], (int)$data['VanTurnAroundDays'], (int)$data['IsActive'], $data['oldMagazineCd']);
	$sql  = vsprintf($sql,$inputArr);
	$returnData = $this->execUpdateQuery($sql);
	return $returnData;
}

public function magazineEditData($mcode) {
	$sql		= "SELECT  * FROM so_magazine_m WHERE MagazineCd='%s' ";
	$inputArr 	=  array($mcode);
	$sql		= vsprintf($sql,$inputArr);
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

// Magazine Capacity ----------------------------------------------------------------------------------------------------------------------------------	
	public function getMagazineCapacityList($search = null) {
		$searchCnd	= " WHERE D.SectorCd='{$_SESSION['SectorCd']}' " . (isset($search) ? " AND D.Descript like '". $search . "%'" : "");
		$sql	= "SELECT A.*,IFNULL(B.Descript,A.MagazineCd) AS Magazine,IFNULL(D.Descript,A.CustomerCd) AS Customer,IFNULL(C.Descript,A.ItemCtgCd) AS ItemCtg FROM so_magazine_capacity A LEFT OUTER JOIN so_magazine_m B ON A.MagazineCd=B.MagazineCd "
			. " LEFT OUTER JOIN so_item_ctg_m C ON A.ItemCtgCd=C.ItemCtgCd LEFT OUTER JOIN so_customer_m D ON A.CustomerCd=D.CustomerCd" .$searchCnd. " ORDER BY D.Descript,C.ItemCtgCd;";
		$returnData		= $this->execSelectQuery($sql);
		return $returnData;	
	}

	public function isExistMagazineCapacity($CustomerCd, $MagazineCd, $ItemCtgCd) {
		$sql			= "SELECT * FROM so_magazine_capacity WHERE CustomerCd='".$CustomerCd."' AND  MagazineCd='".$MagazineCd."' AND  ItemCtgCd='".$ItemCtgCd."'";
		$queryResult	= $this->execSelectQuery($sql);
		$rowCount		= count($queryResult);
		return $rowCount;
	}

	public function insertMagazineCapacity($data) {
		$sql		= $this->objDBQuery->getMagazineCapacityInsertQuery();
		$inputArr	= array(trim($data['CustomerCd']),trim($data['MagazineCd']),trim($data['ItemCtgCd']),trim($data['Capacity']),trim($data['RotationCapacity']));
		$sql		= vsprintf($sql,$inputArr);
		$returnData = $this->execUpdateQuery($sql);
		return $returnData;
	}
	
	public function updateMagazineCapacity($data) {
		$sql		= $this->objDBQuery->getMagazineCapacityUpdateQuery();
		$inputArr	= array((float)$data['Capacity'], (float)$data['RotationCapacity'], $data['oldMagazineCd'], $data['oldItemCtgCd']);
		$sql		= vsprintf($sql,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
		return $returnData;
	}
	
	public function getMagazineCapacityHeader($MagazineCd, $ItemCtgCd) {
		$sql		= $this->objDBQuery->getMagazineCapacityHeaderQuery(); 
		$inputArr 	= array($MagazineCd, $ItemCtgCd);
		$sql		= vsprintf($sql,$inputArr);
		$returnData = $this->execSelectQuery($sql);
		return $returnData;
	}

// Vehicle Master ---------------------------------------------------------------------------------------------------------------------------------------
public function isExistVehicleCode($mcode, $UniqueId = 0) {
	$sql			= "SELECT * FROM so_vehicle_m WHERE VehicleNo='".$mcode."' AND UniqueId<>".$UniqueId ;
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function getVehicleList($search = null) {
	$searchCnd	= ((isset($search)) ? " WHERE (A.VehicleNo LIKE '$search%' OR B.Descript LIKE '$search%')" : "") ;
	$sql		= "SELECT A.VehicleNo,A.CustomerCd,IFNULL(B.Descript,A.CustomerCd) AS Customer,A.Capacity,DATE_FORMAT(A.LicValidUptoDate,'%d-%m-%Y') AS LicValidUptoDate, A.IsActive"
					. " FROM so_vehicle_m A LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd" .$searchCnd. " ORDER BY A.IsActive, B.Descript,A.VehicleNo";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function isDocKeyExist($dockey, $UniqueId = 0){
	$sql			= "SELECT * FROM so_vehicle_m WHERE DocKey = '$dockey'  AND UniqueId <>".$UniqueId;
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}


public function insertVehicleData($data) {
	$sql = " INSERT INTO so_vehicle_m (VehicleNo,Descript,CustomerCd,Transporter,Capacity,LicenseNo,LicValidUptoDate,IsDummyCompanyVan,DocKey,IsActive)
			VALUES('%s', '%s', '%s', '%s', %s, '%s', '%s', %s, '%s','%s');";
	$inputArr	= array(trim($data['VehicleNo']),addslashes(trim($data['Descript'])),trim($data['CustomerCd']),trim($data['Transporter'])
		,(float)$data['Capacity'],trim($data['LicenseNo']),$this->convertDate($data['LicValidUptoDate'], TRUE, 1), (int)$data['IsDummyCompanyVan'],trim($data['dockey']), (int)$data['IsActive']);
	$sql		= vsprintf($sql,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function updateVehicleData($data) {
	$sql	= " UPDATE so_vehicle_m set VehicleNo = '%s', Descript = '%s', CustomerCd = '%s', Transporter = '%s', Capacity = %s, LicenseNo = '%s', LicValidUptoDate = '%s', IsDummyCompanyVan=%s, IsActive=%s ,DocKey ='%s' WHERE UniqueId='%s'";
	$inputArr	= array(trim($data['VehicleNo']),addslashes(trim($data['Descript'])),trim($data['CustomerCd']),trim($data['Transporter'])
		,(float)$data['Capacity'],trim($data['LicenseNo']),$this->convertDate($data['LicValidUptoDate'], TRUE, 1),(int)$data['IsDummyCompanyVan'], (int)$data['IsActive'],trim($data['dockey']),$data['UniqueId']);
	$sql  = vsprintf($sql,$inputArr);
	$returnData = $this->execUpdateQuery($sql);
	return $returnData;
}
public function VehicleEditData($mcode) {
	$sql		= "SELECT  * FROM so_vehicle_m WHERE VehicleNo='%s' ";
	$inputArr 	=  array($mcode);
	$sql		= vsprintf($sql,$inputArr);
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}
/*
public function getVehiclePOCapacity($VehicleNo, $IdExpDet) {
	$sql		= "SELECT  sum(TotBox) as TotBox    FROM so_expdet WHERE VehicleNo='%s' and IdExpDet <> '$IdExpDet' and StatusCd IN ('U', 'W', 'A','E')";
	$inputArr 	=  array($VehicleNo, $IdExpDet);
	$sql		= vsprintf($sql,$inputArr);
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}
*/


public function getVehiclePOCapacity($VehicleNo, $IdExpDet) {
	$sql	= "SELECT  IFNULL(sum(TotBox),0) as TotBox  FROM so_expdet WHERE VehicleNo='%s' and IdExpDet <> '$IdExpDet' and StatusCd IN ('U', 'W', 'A')";
	$inputArr 	=  array($VehicleNo, $IdExpDet);
	$sql		= vsprintf($sql,$inputArr);
	$returnData1	= $this->execSelectQuery($sql);
	
	if($VehicleNo == 'DUMMY' && $_SESSION['IsCustomer']){
		$CustomerCd = $_SESSION['CustomerCd'];
		$sql2 = "SELECT count(VehicleNo) AS Totdummy,B.DummyVanAllowPO, SUM(IsClubedPO) as IsClubedPO FROM so_expdet A INNER JOIN so_customer_m B ON A.CustomerCd = B.CustomerCd WHERE A.CustomerCd ='".$CustomerCd."' AND A.VehicleNo ='DUMMY' AND StatusCd IN ('W','U')";
		$result2 = $this->execSelectQuery($sql2);
		if($result2[0]['IsClubedPO'] == NULL ) { $IsClubedPO = 0;  }
		else{ $IsClubedPO = $result2[0]['IsClubedPO']; }
		if($result2[0]['DummyVanAllowPO'] !=0){
			if($result2[0]['Totdummy'] >= $result2[0]['DummyVanAllowPO']){
				$returnData2 = array(array("status" => "exceed", "IsClubedPO" =>$IsClubedPO )); 
			}else{
				$returnData2 = array(array("status" => "under", "IsClubedPO" => $IsClubedPO)); 
			}
		}
		else{
			$returnData2 = array(array("status" => "under", "IsClubedPO" => $IsClubedPO)); 
		}
		$returnData = array_merge($returnData1,$returnData2);
	}else{
		$returnData = $returnData1;
	}
	return $returnData ;
}

public function getPORestrictionQty($StartDate, $EndDate, $ItemCd, $CustomerCd, $IdExpDet) {
	$sql		= "SELECT  sum(B.TotBox) as TotBox  FROM so_expdet_magazine_item A JOIN so_expdet B on A.IdExpdet = B.IdExpDet WHERE A.IdExpDet <> '$IdExpDet' and  A.ItemCd='%s' and B.CustomerCd='%s' AND StatusCd <>'T' AND B.DateTime Between '%s' AND '%s'";
	$inputArr 	=  array($ItemCd, $CustomerCd, $StartDate, $EndDate);
	$sql		= vsprintf($sql,$inputArr);
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

// Customer Item Rate ------------------------------------------------------------------------------------------------------------------------------------	
public function getCustomerSuperactiveEndDate($search = NULL) {
	$CurrentDate = date('Y-m-d');
	$sql	= "SELECT * FROM so_customer_m_item_rate_type where SuperActiveEndDate < '$CurrentDate'";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getCustomerTargetVsAchvAlert() {
	$sql	= "SELECT * FROM so_customer_m where AlertforTarget = '1'";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function updateCustomerSuperactiveEndDatelist($CustomerCd, $ItemCd, $SuperActiveEndDate) {
	$stmt		= "UPDATE so_customer_m_item_rate_type SET  IsSuperActive=%s  WHERE CustomerCd='%s' AND ItemCd='%s'";
	$inputArr	= array(0,$CustomerCd,$ItemCd);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	$this->sendEMailRateChange();
	return $returnData;
}

public function getCustomerItemRateList($search = NULL) {
	$searchCnd	= (isset($search)) ? " WHERE B.Descript like '". $search . "%'" : "";
	$sql	= "SELECT A.*,IFNULL(B.Descript,A.CustomerCd) AS Customer,IFNULL(C.Descript,A.ItemCd) AS Item,IFNULL(E.ShortDesc,A.CompanyCd) AS Company FROM so_customer_item_rate A LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd "
		. " LEFT OUTER JOIN so_item_m C ON A.ItemCd=C.ItemCd LEFT OUTER JOIN so_company_m E ON A.CompanyCd=E.CompanyCd " .$searchCnd. " ORDER BY B.Descript, A.CustomerCd, C.ItemCtgCd;";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function isExistCustomerItemRate($CustomerCd, $CompanyCd, $ItemCd) {
	$sql			= "SELECT * FROM so_customer_item_rate WHERE CustomerCd='".$CustomerCd."' AND  CompanyCd=".(int)$CompanyCd." AND ItemCd='".$ItemCd."'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function insertCustomerItemRate($data) {
	$stmt		= " INSERT INTO so_customer_item_rate (CustomerCd,CompanyCd,ItemCd,Rate,SaleRate,MinStockLevel) VALUES('%s', '%s', '%s', %s, %s, %s);";
	$inputArr	= array(trim($data['CustomerCd']),(int)($data['CompanyCd']),trim($data['ItemCd']),(float)($data['Rate']),(float)($data['SaleRate']),(int)($data['MinStockLevel']));
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	$this->sendEMailRateChange();
	return $returnData;
}

public function updateCustomerItemRate($data) {
	$stmt		= "UPDATE so_customer_item_rate SET Rate=%s, SaleRate=%s, MinStockLevel=%s  WHERE CustomerCd='%s' AND CompanyCd='%s' AND ItemCd='%s'";
	$inputArr	= array((float)$data['Rate'],(float)$data['SaleRate'],(int)($data['MinStockLevel']),trim($data['oldCustomerCd']),trim($data['oldCompanyCd']),trim($data['oldItemCd']));
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	$this->sendEMailRateChange();
	return $returnData;
}

public function UpdateGaurdPhotoUpload($IdExpDet, $VerificationStatus) {
	$stmt		= "UPDATE so_expdet SET ForGuardPhotoVerify=%s WHERE IdExpDet='%s'";
	$inputArr	= array( $VerificationStatus, $IdExpDet);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function getTransNoSCM($IdExpDet) {
	$stmt		= "SELECT GateTranNo FROM scm_solar_sc.vm_gate_tran_customer WHERE PONo='%s' and IsGateIn=0 and  (GateCd='1' or GateCd='11')";
	$inputArr 	= array($IdExpDet);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getCustomerItemRateHeader($CustomerCd, $CompanyCd, $ItemCd) {
	$stmt		= "SELECT * FROM so_customer_item_rate WHERE CustomerCd='%s' AND CompanyCd='%s' AND ItemCd='%s'";
	$inputArr 	= array($CustomerCd, $CompanyCd, $ItemCd);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getMagazineOfCustomer($data) {
	$stmt	= "SELECT MagazineCd,Descript FROM so_magazine_m WHERE CustomerCd='%s' " 
		. ($data['ShowAll'] ? "" : " AND IsActive=1") . " AND DATEDIFF(LicExpiryDate, '%s')>2";	// assuming min 2 days from PO to Load
	$inputArr 	= array($data["CustomerCd"], date('Y-m-d'));
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function sendEMailRateChange() {		// defunct
	$templateArr = $this->getEMailTemplate(4);
	$sql = "SELECT A.*, B.EMailId, IFNULL(C.Descript,A.ItemCd) AS Descript FROM so_customer_item_rate A INNER JOIN so_customer_m B"
		. " ON A.CustomerCd=B.CustomerCd LEFT OUTER JOIN so_item_m C ON A.CompanyCd=C.CompanyCd AND A.ItemCd=C.ItemCd"
		. " WHERE A.Rate>=0 AND A.RateOld>=0 AND A.Rate<>A.RateOld ORDER BY A.CustomerCd";

	$eMailDetailArr = $this->execSelectQuery($sql);
	$eMailDetailRowCount = count($eMailDetailArr);
	$curRow=0;
	while ($curRow < $eMailDetailRowCount) {
		$curCustomer = $eMailDetailArr[$curRow]['CustomerCd'];
		$curEMailId = $eMailDetailArr[$curRow]['EMailId'];
		$Dim2Arr = array();
		$Dim2ArrCurRow = 0;
		while ($curRow < $eMailDetailRowCount && $curCustomer == $eMailDetailArr[$curRow]['CustomerCd']) {
			$Dim2Arr[$Dim2ArrCurRow] = array($eMailDetailArr[$curRow]['Descript']);
			$Dim2ArrCurRow++;
			$curRow++;
		}
		$eMailBody = $this->strPositSubstitute($templateArr['Body'], NULL, $Dim2Arr);
		$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
		$objSolarMailer = new solarMailer();
		$success = $objSolarMailer->sendSolarMail($curEMailId, $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
		if ($success) {
			$sql = "UPDATE so_customer_item_rate SET RateOld = Rate WHERE CustomerCd='" . $curCustomer . "'";
			$this->execSelectQuery($sql);
		}
	}
}

public function sendEMailItemRateChange($eMailDetailArr) {
	$templateArr = $this->getEMailTemplate(14);
	$eMailDetailRowCount = count($eMailDetailArr);
	$curRow=0;
	while ($curRow < $eMailDetailRowCount) {
		$curCustomer = $eMailDetailArr[$curRow]['CustomerCd'];
		$curEMailId = $eMailDetailArr[$curRow]['EMailId'];
		//$curEMailId = 'websupport@solargroup.com';
		$Dim2Arr = array();
		$Dim2ArrCurRow = 0;
		while ($curRow < $eMailDetailRowCount  && $curCustomer == $eMailDetailArr[$curRow]['CustomerCd']) {
			$Dim2Arr[$Dim2ArrCurRow] = array($eMailDetailArr[$curRow]['Descript'], $eMailDetailArr[$curRow]['DespatchMode']
											, $eMailDetailArr[$curRow]['DisplayRate'], $eMailDetailArr[$curRow]['UOM']);
			$Dim2ArrCurRow++;
			$curRow++;
		}
		$eMailBody = $this->strPositSubstitute($templateArr['Body'], NULL, $Dim2Arr);
		$eMailBody = str_replace(array('\r','\n','\t'),array("\r","\n","\t"), $eMailBody);
		$objSolarMailer = new solarMailer();
		$objSolarMailer->sendSolarMail($curEMailId, $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	}
}



public function sendEMailAccesCtgRateChange() {
switch (3) {
	case 3:
		$Emailtemplate	= 13;
		//$TableName		= 'so_expdet';
	//	$TransId		= 'IdExpDet';
	//	$Date			= 'DateTime';
		break;
	}
	
	$templateArr = $this->getEMailTemplate($Emailtemplate);
	$sql = "SELECT A.$TransId AS IdExpDet, DATE_FORMAT(A.$Date,'%d-%m-%Y') AS Date, B.EMailId, B.IsActive FROM $TableName A INNER JOIN so_customer_m B
		ON A.CustomerCd=B.CustomerCd WHERE A.$TransId IN ($IdExpDet)";
	
	$eMailDetailArr = $this->execSelectQuery($sql);
	if($eMailDetailArr[0]['IsActive']){
		$EmailId= $eMailDetailArr[0]['EMailId'];
		//$EmailId= 'websupport@solaregroup.com';
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($IdExpDet, $RE11No, $RE11Date));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($EmailId, $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	}
}

// Sales Contract ------------------------------------------------------------------------------------------------------------------------------------	
public function getSalesContractList($search) {
	$searchCnd	= (isset($search)) ? " WHERE B.Descript like '". $search . "%'" : " WHERE 1=1";
	$searchCnd	.= ($_SESSION['IsCustomer']) ? " AND A.CustomerCd='" .$_SESSION['CustomerCd']. "'" : "";
	switch ($_SESSION['StatusFilter']) {
	case 0:
		break;
	case 1:
		$searchCnd	.= " AND A.StatusCd='U'";
		break;
	case 2:
		$searchCnd	.= " AND A.StatusCd='A'";
		break;
	case 3:
		$searchCnd	.= " AND A.StatusCd='P'";
		break;
	case 4:
		$searchCnd	.= " AND A.StatusCd='C'";
		break;
	default:
		$searchCnd	.= " AND A.StatusCd IN ('D','T')";
		break;
	}
	$sql	= "SELECT A.IdContract, IF(A.DespatchMode='F','F.O.R.','X-Factory') AS DespatchMode, DATE_FORMAT(A.Date,'%d-%m-%Y') AS Date"
		. ",IFNULL(B.Descript,A.CustomerCd) AS Customer,IFNULL(C.Descript,A.StatusCd) AS Status,IFNULL(E.ShortDesc,A.CompanyCd) AS Company FROM so_sales_contract A"
		. " LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd" 
		. " LEFT OUTER JOIN so_company_m E ON A.CompanyCd=E.CompanyCd" 
		. " LEFT OUTER JOIN so_status_m C ON A.StatusCd=C.StatusCd" .$searchCnd. " ORDER BY A.DespatchMode DESC, A.IdContract DESC";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getSalesContractHeader($IdContract) {
	$stmt		= $this->objDBQuery->getContractHeaderDataQuery();
	$inputArr 	= array($IdContract);
	$sql		= vsprintf($stmt, $inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getContractCustomerItemRate($CustomerCd, $CompanyCd, $excludeDefCustomer, $IdContract, $StatusCd, $DespatchModeFOR) {
// Return complete details of Item available to specified Customer + Company. Optionally return Items of Default Customer also. This along with specified ContractNo details
// getContractCustomerItemRate paras: IN CustomerCd CHAR(10), IN CompanyCd INT, IN AlterCustomer CHAR(10), IN IdContract INT, IN StatusCd CHAR(1)
	$AlterCustomer	= (($excludeDefCustomer) ? "" : self::DEFCUSTOMERCD);
	$inputArr 		= array($CustomerCd, (int)$CompanyCd, $AlterCustomer, (int)$IdContract, $StatusCd, $DespatchModeFOR);
	$paraString		= vsprintf("'%s',%s,'%s',%s,'%s', %s",$inputArr);
	$sql			= "call sp_getContractCustomerItemRate(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}

public function uploadSalesContractPaymentRefFile($CustomerCd) {	// Defunct
// Store uiploaded file in ./upload/CustomerCd folder with Name as .Extension
	$returnFileName = "";
//		if ((($_FILES["PaymentRefImageFileName"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "application/msword") || ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"))) {
	if (TRUE && isset($_FILES["PaymentRefImageFileName"]["name"]) && $_FILES["PaymentRefImageFileName"]["error"] == 0) {
		$extension = substr(strrchr($_FILES["PaymentRefImageFileName"]["name"], '.'), 1);
		$fileNameDir = trim($CustomerCd);
		if(!is_dir('upload/'.$fileNameDir)){
			mkdir('upload/'.$fileNameDir);
			chmod('upload/'.$fileNameDir,777);
		}
		$returnFileName = "upload/".$fileNameDir.'/'.time().'.'.$extension;
		move_uploaded_file($_FILES["PaymentRefImageFileName"]["tmp_name"], $returnFileName);
	}
	return $returnFileName;
}

public function insertSalesContract($data) {
	$stmt		= $this->objDBQuery->getSalesContractInsertQuery();
/* ColumnNames : IdContract, CustomerCd, CompanyCd, Date, DespatchMode, DateFrom, DateUpto, ItemAmt, HnFAmt, ExcDuty, EduCessAmt, SHSECessAmt
	, TransportCost, TaxAmt, TotAmt, PaymentDate, PaymentAmt, BalPaymentDate, ApprovedByUserName, ApprovalDateTime, StatusCd
	, Remark, TransUserName, TransDateTime
*/		$inputArr	= array($data['CustomerCd'], (int)$data['CompanyCd'], $this->convertDate($data['Date'], TRUE, 3), $data['DespatchMode'], $this->convertDate($data['DateFrom'],TRUE,1)
		, $this->convertDate($data['DateUpto'],TRUE,1), (float)$data['ItemAmt'], (float)$data['HnFAmt'], (float)$data['ExcDuty'], (float)$data['EduCessAmt'], (float)$data['SHSECessAmt']
		, (float)$data['TransportCost'], (float)$data['TaxAmt'], (float)$data['TotAmt'], $this->convertDate($data['PaymentDate'],TRUE,1), (float)$data['PaymentAmt']
		, $this->convertDate($data['BalPaymentDate'],TRUE,1)
		, $data['StatusCd'], $data['Remark'], $_SESSION['UserName'], date('Y-m-d H:i:s'));
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function updateSalesContract($data) {
	$stmt		= $this->objDBQuery->getSalesContractUpdateQuery();
	$inputArr	= array($this->convertDate($data['DateUpto'],TRUE,1), (float)$data['ItemAmt'], (float)$data['HnFAmt'], (float)$data['ExcDuty'], (float)$data['EduCessAmt'], (float)$data['SHSECessAmt']
		, (float)$data['TransportCost'], (float)$data['TaxAmt'], (float)$data['TotAmt'], $this->convertDate($data['PaymentDate'],TRUE,1), (float)$data['PaymentAmt']
		, $this->convertDate($data['BalPaymentDate'],TRUE,1)
		, $data['StatusCd'], $data['Remark'], $_SESSION['UserName'], date('Y-m-d H:i:s'), $data['IdContract']);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function insertSalesContractItem($data) {
	$queryInsert	= $this->objDBQuery->getSalesContractItemInsertQuery();
/* ColumnNames: IdContract, CustomerCd, CompanyCd, ItemCd, OrderBox, OrderQty, ApprovedBox, ApprovedQty, Rate, ItemAmt, HnFAmt, ExcDuty, EduCessAmt
, SHSECessAmt, TransportCost, TaxAmt, TotAmt, DespatchedBox, DespatchedQty
*/		for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		if (!isset($data['ItemCd1_'.$curRowNo]) || trim($data['ItemCd1_'.$curRowNo])=='' || (float)$data['OrderQty1_'.$curRowNo]<=0) {
			continue;
		}	
		$dataItem = array();
		$dataItem = array('ItemCd'=>$data['ItemCd1_'.$curRowNo], 'OrderBox'=>$data['OrderBox1_'.$curRowNo], 'OrderQty'=>$data['OrderQty1_'.$curRowNo]
				, 'Rate'=>$data['Rate1_'.$curRowNo]
				, 'ItemAmt'=>$data['ItemAmt1_'.$curRowNo], 'HnFAmt'=>$data['HnFAmt1_'.$curRowNo], 'ExcDuty'=>$data['ExcDuty1_'.$curRowNo], 'EduCessAmt'=>$data['EduCessAmt1_'.$curRowNo]
				, 'SHSECessAmt'=>$data['SHSECessAmt1_'.$curRowNo], 'TransportCost'=>$data['TransportCost1_'.$curRowNo], 'TaxAmt'=>$data['TaxAmt1_'.$curRowNo]
				, 'TotAmt'=>$data['TotAmt1_'.$curRowNo]);
		$inputArr	= array();
		$inputArr	= array($data['IdContract'], $data['CustomerCd'], (int)$data['CompanyCd'], $dataItem['ItemCd'], (float)$dataItem['OrderBox']
					, (float)$dataItem['OrderQty'], (float)$dataItem['Rate'], (float)$dataItem['ItemAmt'], (float)$dataItem['HnFAmt'], (float)$dataItem['ExcDuty']
					, (float)$dataItem['EduCessAmt'], (float)$dataItem['SHSECessAmt'], (float)$dataItem['TransportCost']
					, (float)$dataItem['TaxAmt'], (float)$dataItem['TotAmt']);
		$sql		= vsprintf($queryInsert,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
		if ($returnData) return $returnData;
	}
	return $returnData;
}

public function updateSalesContractItem($data) {
	$queryInsert	= $this->objDBQuery->getSalesContractItemInsertQuery();
	$queryUpdate	= $this->objDBQuery->getSalesContractItemUpdateQuery();
	$queryDelete	= $this->objDBQuery->getSalesContractItemDeleteQuery();
	$returnData		= '';
	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		if (!isset($data['ItemCd1_'.$curRowNo]) || trim($data['ItemCd1_'.$curRowNo])=='') {
			continue;
		}	
		if ((float)$data['OrderQty1_'.$curRowNo]<=0) {
			$inputArr	= array();
			$inputArr	= array($data['IdContract'], $data['ItemCd1_'.$curRowNo]);
			$sql		= vsprintf($queryDelete,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		} else {
			$dataItem = array();
			$dataItem = array('ItemCd'=>$data['ItemCd1_'.$curRowNo],'OrderBox'=>$data['OrderBox1_'.$curRowNo], 'OrderQty'=>$data['OrderQty1_'.$curRowNo]
					, 'Rate'=>$data['Rate1_'.$curRowNo]
					, 'ItemAmt'=>$data['ItemAmt1_'.$curRowNo], 'HnFAmt'=>$data['HnFAmt1_'.$curRowNo], 'ExcDuty'=>$data['ExcDuty1_'.$curRowNo], 'EduCessAmt'=>$data['EduCessAmt1_'.$curRowNo]
					, 'SHSECessAmt'=>$data['SHSECessAmt1_'.$curRowNo], 'TransportCost'=>$data['TransportCost1_'.$curRowNo], 'TaxAmt'=>$data['TaxAmt1_'.$curRowNo]
					, 'TotAmt'=>$data['TotAmt1_'.$curRowNo]);
			$queryCheck	= "SELECT COUNT(*) AS Count FROM so_sales_contract_item WHERE IdContract=%s AND ItemCd='%s'";
			$inputArr	= array();
			$inputArr	= array($data['IdContract'], $data['ItemCd1_'.$curRowNo]);
			$sql		= vsprintf($queryCheck,$inputArr);
			$returnData	= $this->execSelectQuery($sql);
			if ($returnData[0]['Count']==0) {
				$inputArr	= array();
				$inputArr	= array($data['IdContract'], $data['CustomerCd'], (int)$data['CompanyCd'], $dataItem['ItemCd'], (float)$dataItem['OrderBox']
							, (float)$dataItem['OrderQty'], (float)$dataItem['Rate'], (float)$dataItem['ItemAmt'], (float)$dataItem['HnFAmt'], (float)$dataItem['ExcDuty']
							, (float)$dataItem['EduCessAmt'], (float)$dataItem['SHSECessAmt'], (float)$dataItem['TransportCost']
							, (float)$dataItem['TaxAmt'], (float)$dataItem['TotAmt']);
				$sql		= vsprintf($queryInsert,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
			} else {
				$inputArr	= array();
				$inputArr	= array((float)$dataItem['OrderBox']
							, (float)$dataItem['OrderQty'], (float)$dataItem['Rate'], (float)$dataItem['ItemAmt'], (float)$dataItem['HnFAmt'], (float)$dataItem['ExcDuty']
							, (float)$dataItem['EduCessAmt'], (float)$dataItem['SHSECessAmt'], (float)$dataItem['TransportCost']
							, (float)$dataItem['TaxAmt'], (float)$dataItem['TotAmt'], 'IdContract'=>$data['IdContract'], $dataItem['ItemCd']);
				$sql		= vsprintf($queryUpdate,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
			}
			if ($returnData) return $returnData;
		}
	}
	return $returnData;
}

public function approveSalesContract($approveDocList, $isApproved) {
	$stmt		= "UPDATE so_sales_contract SET StatusCd='%s', ApprovedByUserName='%s', ApprovalDateTime='%s' WHERE IdContract IN (%s)";
	if ($isApproved)
		$inputArr 	= array('A', $_SESSION['UserName'], date('Y-m-d H:i:s'), $approveDocList);
	else
		$inputArr 	= array('U', '', '', $approveDocList);
	$sql		= vsprintf($stmt,$inputArr);
	$this->execUpdateQuery($sql);

	if ($isApproved) {
		$sql	= "call sp_updateSalesContractTokenNoPrefix('$approveDocList');";
		$this->execUpdateQuery($sql);
		$this->sendEMailContractApproval($approveDocList);
	}

	return;
}

public function sendEMailContractApproval($approveDocList) {
	$templateArr = $this->getEMailTemplate(1);
	$sql = "SELECT A.IdContract, DATE_FORMAT(A.Date,'%d-%m-%Y') AS Date, B.EMailId FROM so_sales_contract A INNER JOIN so_customer_m B"
		. " ON A.CustomerCd=B.CustomerCd WHERE A.IdContract IN ($approveDocList)";
	$eMailDetailArr = $this->execSelectQuery($sql);
	foreach ($eMailDetailArr as $eMailDetailRow) {
		$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($eMailDetailRow['IdContract'], $eMailDetailRow['Date']));
		$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
		$objSolarMailer = new solarMailer();
		$objSolarMailer->sendSolarMail($eMailDetailRow['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	}
}

public function sendEMailContractRTGSDetail($data, &$alertMsg) {
	$arrCompanyMDisp	= $this->getCompanyMDisp($data['CompanyCd']);
	$sql = "SELECT A.EMailId FROM so_customer_m A WHERE A.CustomerCd='" . $data['CustomerCd'] . "'";
	$eMailDetailArr = $this->execSelectQuery($sql);
	$templateArr = $this->getEMailTemplate(21);
	$alertMsg = $this->strPositSubstitute($templateArr['Body'], array($data['IdContract'], $arrCompanyMDisp[0]['RTGSCompanyAc']
		, $data['CustomerCd'], $arrCompanyMDisp[0]['RTGSContractPrefix'], $data['IdContract'], $arrCompanyMDisp[0]['RTGSBankAddress'], $arrCompanyMDisp[0]['RTGSBankIFSCCd']));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $alertMsg);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
}

// PO ------------------------------------------------------------------------------------------------------------------------------------	
public function getPOList($search) {
	$searchCnd	= (isset($search)) ? " WHERE B.Descript like '". $search . "%'" : " WHERE 1=1";
	$searchCnd	.= ($_SESSION['IsCustomer']) ? " AND A.CustomerCd='" .$_SESSION['CustomerCd']. "'" : "";
	switch ($_SESSION['StatusFilter']) {
	case 0:
		break;
	case 1:
		$searchCnd	.= " AND A.StatusCd='U'";
		break;
	case 2:
		$searchCnd	.= " AND A.StatusCd='A'";
		break;
	case 4:
		$searchCnd	.= " AND A.StatusCd='C'";
		break;
	default:
		$searchCnd	.= " AND A.StatusCd IN ('D','T')";
		break;
	}
	$sql	= "SELECT A.IdPO, A.DespatchMode, DATE_FORMAT(A.Date,'%d-%m-%Y') AS Date, A.ContractNo, A.VehicleNo, CONCAT(TRIM(A.TokenNoPrefix),'/',A.TokenNo%100) AS TokenNoFull"
		. ",IFNULL(B.Descript,A.CustomerCd) AS Customer,IFNULL(C.Descript,A.StatusCd) AS Status,IFNULL(D.Descript,A.MagazineCd) AS Magazine,IFNULL(E.ShortDesc,A.CompanyCd) AS Company FROM so_po A"
		. " LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd" 
		. " LEFT OUTER JOIN so_status_m C ON A.StatusCd=C.StatusCd" 
		. " LEFT OUTER JOIN so_company_m E ON A.CompanyCd=E.CompanyCd" 
		. " LEFT OUTER JOIN so_magazine_m D ON A.MagazineCd=D.MagazineCd".$searchCnd. " ORDER BY A.DespatchMode DESC,A.IdPO DESC";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getPOHeader($IdPO) {
	$stmt		= $this->objDBQuery->getPOHeaderDataQuery(); 
	$inputArr 	= array($IdPO);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getPOPendingContract($CustomerCd) {
	$inputArr 		= array($CustomerCd);
	$paraString		= vsprintf("'%s'",$inputArr);
	$sql			= "call sp_getPOPendingContract(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getPOVehicleMDisp($CustomerCd, $Date, $DespatchModeFOR, $IsAccessory) {
	$inputArr 		= array($CustomerCd, $this->convertDate($Date, TRUE), $DespatchModeFOR, $IsAccessory);
	$paraString		= vsprintf("'%s','%s', %s, %s", $inputArr);
	$sql			= "call sp_getPOVehicleMDisp(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getPOCustomerItemRate($ContractNo, $IdPO, $StatusCd) {
// Return complete details of Item available from given Contract, along with specified PO details
// getPOCustomerItemRate paras: IN ContractNo INT, IN IdPO INT, IN StatusCd CHAR(1)
	$inputArr 		= array((int)$ContractNo, (int)$IdPO, $StatusCd);
	$paraString		= vsprintf("%s,%s,'%s'",$inputArr);
	$sql			= "call sp_getPOCustomerItemRate(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}

public function insertPO($data) {
	$stmt		= $this->objDBQuery->getPOInsertQuery();
	$inputArr	= array($data['CustomerCd'], (int)$data['CompanyCd'], $this->convertDate($data['Date'],TRUE,3), (int)$data['ContractNo'], $data['DespatchMode']
		, $data['MagazineCd'], $data['RE11No'], $this->convertDate($data['RE11Date'],TRUE), $data['VehicleNo'], $this->convertDate($data['ExpVehicleArrDate'],TRUE)
		, (float)$data['ItemAmt'], (float)$data['HnFAmt'], (float)$data['ExcDuty'], (float)$data['EduCessAmt'], (float)$data['SHSECessAmt']
		, (float)$data['TransportCost'], (float)$data['TaxAmt'], (float)$data['TotAmt'], $this->convertDate($data['RE11ReceiptDate'],TRUE)
		, $data['StatusCd'], $data['Remark'], $data['ItemCtgCd'], $data['SAPSONo'], $this->convertDate($data['SAPSODate'],TRUE), $_SESSION['UserName'], date('Y-m-d H:i:s'));
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function updatePO($data) {
	$oriDataArr = $this->getPOHeader($data['IdPO']);
	$stmt		= $this->objDBQuery->getPOUpdateQuery();
	$inputArr	= array($data['MagazineCd'], $data['RE11No'], $this->convertDate($data['RE11Date'],TRUE), $data['VehicleNo'], $this->convertDate($data['ExpVehicleArrDate'],TRUE), (float)$data['ItemAmt'], (float)$data['HnFAmt'], (float)$data['ExcDuty'], (float)$data['EduCessAmt']
		, (float)$data['SHSECessAmt'], (float)$data['TransportCost'], (float)$data['TaxAmt'], (float)$data['TotAmt'],  $this->convertDate($data['RE11ReceiptDate'],TRUE)
		, $data['StatusCd'], $data['Remark'], $data['ItemCtgCd'], $data['SAPSONo'], $this->convertDate($data['SAPSODate'],TRUE), $_SESSION['UserName'], date('Y-m-d H:i:s'), $data['IdPO']);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	
	if ($data['RE11ReceiptDate']!='' && $oriDataArr[0]['RE11ReceiptDate']=='0000-00-00')
		$this->sendEMailRE11Receipt($data['IdPO'], 1);
	return $returnData;
}

public function insertPOItem($data) {
	$queryInsert	= $this->objDBQuery->getPOItemInsertQuery();
/* ColumnNames: IdPO, CustomerCd, CompanyCd, ContractNo, ItemCd, OrderBox, OrderQty, ApprovedBox, ApprovedQty, Rate, ItemAmt, HnFAmt, ExcDuty, EduCessAmt
, SHSECessAmt, TransportCost, TaxAmt, TotAmt, DespatchedBox, DespatchedQty
*/		$returnData	= '';
	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		if (!isset($data['ItemCd1_'.$curRowNo]) || trim($data['ItemCd1_'.$curRowNo])=='' || (float)$data['OrderQty1_'.$curRowNo]<=0) {
			continue;
		}	
		$dataItem = array();
		$dataItem = array('ItemCd'=>$data['ItemCd1_'.$curRowNo], 'OrderBox'=>$data['OrderBox1_'.$curRowNo], 'OrderQty'=>$data['OrderQty1_'.$curRowNo]
				, 'Rate'=>$data['Rate1_'.$curRowNo]
				, 'ItemAmt'=>$data['ItemAmt1_'.$curRowNo], 'HnFAmt'=>$data['HnFAmt1_'.$curRowNo], 'ExcDuty'=>$data['ExcDuty1_'.$curRowNo], 'EduCessAmt'=>$data['EduCessAmt1_'.$curRowNo]
				, 'SHSECessAmt'=>$data['SHSECessAmt1_'.$curRowNo], 'TransportCost'=>$data['TransportCost1_'.$curRowNo], 'TaxAmt'=>$data['TaxAmt1_'.$curRowNo]
				, 'TotAmt'=>$data['TotAmt1_'.$curRowNo]);
		$inputArr	= array();
		$inputArr	= array($data['IdPO'], $data['CustomerCd'], (int)$data['CompanyCd'], $data['ContractNo'], $dataItem['ItemCd'], (float)$dataItem['OrderBox']
					, (float)$dataItem['OrderQty'], (float)$dataItem['Rate'], (float)$dataItem['ItemAmt'], (float)$dataItem['HnFAmt'], (float)$dataItem['ExcDuty']
					, (float)$dataItem['EduCessAmt'], (float)$dataItem['SHSECessAmt'], (float)$dataItem['TransportCost']
					, (float)$dataItem['TaxAmt'], (float)$dataItem['TotAmt']);
		$sql		= vsprintf($queryInsert,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
		if ($returnData) return $returnData;
	}
	return $returnData;
}

public function updatePOItem($data) {
	$queryInsert	= $this->objDBQuery->getPOItemInsertQuery();
	$queryUpdate	= $this->objDBQuery->getPOItemUpdateQuery();
	$queryDelete	= $this->objDBQuery->getPOItemDeleteQuery();
	$returnData		= '';
	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		if (!isset($data['ItemCd1_'.$curRowNo]) || trim($data['ItemCd1_'.$curRowNo])=='') {
			continue;
		}	
		if ((float)$data['OrderQty1_'.$curRowNo]<=0) {
			$inputArr	= array();
			$inputArr	= array($data['IdPO'], $data['ItemCd1_'.$curRowNo]);
			$sql		= vsprintf($queryDelete,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		} else {
			$dataItem = array();
			$dataItem = array('ItemCd'=>$data['ItemCd1_'.$curRowNo],'OrderBox'=>$data['OrderBox1_'.$curRowNo], 'OrderQty'=>$data['OrderQty1_'.$curRowNo]
					, 'Rate'=>$data['Rate1_'.$curRowNo]
					, 'ItemAmt'=>$data['ItemAmt1_'.$curRowNo], 'HnFAmt'=>$data['HnFAmt1_'.$curRowNo], 'ExcDuty'=>$data['ExcDuty1_'.$curRowNo], 'EduCessAmt'=>$data['EduCessAmt1_'.$curRowNo]
					, 'SHSECessAmt'=>$data['SHSECessAmt1_'.$curRowNo], 'TransportCost'=>$data['TransportCost1_'.$curRowNo], 'TaxAmt'=>$data['TaxAmt1_'.$curRowNo]
					, 'TotAmt'=>$data['TotAmt1_'.$curRowNo]);
			$queryCheck	= "SELECT COUNT(*) AS Count FROM so_po_item WHERE IdPO=%s AND ItemCd='%s'";
			$inputArr	= array();
			$inputArr	= array($data['IdPO'], $data['ItemCd1_'.$curRowNo]);
			$sql		= vsprintf($queryCheck,$inputArr);
			$returnData	= $this->execSelectQuery($sql);
			if ($returnData[0]['Count']==0) {
				$inputArr	= array();
				$inputArr	= array($data['IdPO'], $data['CustomerCd'], (int)$data['CompanyCd'], $data['ContractNo'], $dataItem['ItemCd'], (float)$dataItem['OrderBox']
							, (float)$dataItem['OrderQty'], (float)$dataItem['Rate'], (float)$dataItem['ItemAmt'], (float)$dataItem['HnFAmt'], (float)$dataItem['ExcDuty']
							, (float)$dataItem['EduCessAmt'], (float)$dataItem['SHSECessAmt'], (float)$dataItem['TransportCost']
							, (float)$dataItem['TaxAmt'], (float)$dataItem['TotAmt']);
				$sql		= vsprintf($queryInsert,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
			} else {
				$inputArr	= array();
				$inputArr	= array((float)$dataItem['OrderBox']
							, (float)$dataItem['OrderQty'], (float)$dataItem['Rate'], (float)$dataItem['ItemAmt'], (float)$dataItem['HnFAmt'], (float)$dataItem['ExcDuty']
							, (float)$dataItem['EduCessAmt'], (float)$dataItem['SHSECessAmt'], (float)$dataItem['TransportCost']
							, (float)$dataItem['TaxAmt'], (float)$dataItem['TotAmt'], 'IdPO'=>$data['IdPO'], $dataItem['ItemCd']);
				$sql		= vsprintf($queryUpdate,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
			}
			if ($returnData) return $returnData;
		}
	}
	return $returnData;
}

public function updateSalesContractStatus($ContractNo) {
	$sql = 'SELECT COUNT(*) AS ExcptionRows FROM so_sales_contract_item WHERE IdContract=' . $ContractNo . ' AND DespatchedQty>OrderQty;';
	$returnData 	= $this->execSelectQuery($sql);
if ($returnData[0]['ExcptionRows']==0) {
		$sql			= "call sp_updateSalesContractStatus(" . $ContractNo. ")";
		$returnData 	= $this->execSelectQuery($sql);
		return '';
	} else return 'Despatch Quantity getting more that Order Quantity. Record not saved. Try again.';
}

public function approvePO($approveDocList, $isApproved, &$TokenNoAr=NULL) {
	$stmt		= "UPDATE so_po SET StatusCd='%s', ApprovedByUserName='%s', ApprovalDateTime='%s' WHERE IdPO IN (%s)";
	if ($isApproved)
		$inputArr 	= array('A', $_SESSION['UserName'], date('Y-m-d H:i:s'), $approveDocList);
	else
		$inputArr 	= array('U', '', '', $approveDocList);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execUpdateQuery($sql);

	if ($isApproved) {
		$sql	= "call sp_updatePOTokenNo('$approveDocList', 0);";
		$TokenNoAr	= $this->execSelectQuery($sql);

// make SAP Upload File for just Approved POs
// OrderType, SalesOrg, DistChannel, Division, CustomerCd, MagazineCd, IdPO AS PONumber, Date AS PODate, ItemCd, OrderQty, Plant, VehicleNo, RE11No
// 		, RE11Date, Rate, ItemAmt, HnFAmt, ExcDuty, EduCessAmt, SHSECessAmt, TransportCost, TaxAmt, TotAmt, ContractNo, ContractDate, CotractQty, ContractTotRate, ContractTotAmt.	Dates in DD-MM-YYYY Format
		$stmt		= "call sp_getPO2SAPUpload('$approveDocList')";
		$returnData	= $this->execSelectQuery($stmt);
		$this->sendEMailPOAccessApproval($approveDocList, 1);
	} else {
		$sql	= "call sp_updatePOTokenNo('$approveDocList', 1);";
		$this->execUpdateQuery($sql);
	}
	return $returnData;
}
//// ============diff Amt==================

public function diffAmt($StartDate,$EndDate,$Company,$CustomerCd,$diffCond,$reasonStatus){
	$sDate 	= date('Y-m-d', strtotime($StartDate));
	$eDate 	= date('Y-m-d', strtotime($EndDate));
	$cond	= 1;
	$reasonStat = 1;
	if(($StartDate !='' ) && ($EndDate !='')) {
		$searchCnd	= "AND B.SAPInvDate BETWEEN '$sDate' AND '$eDate'";
	}
	else{
		$searchCnd  = "AND B.SAPInvDate >= DATE_SUB(CURDATE(), INTERVAL 15 DAY)";
	}
	if($Company != ''){
		$searchCnd  = $searchCnd." AND  A.CompanyCd = ".$Company;
	}
	if($CustomerCd != ''){
		$searchCnd  = $searchCnd." AND  A.CustomerCd = ".$CustomerCd;
	}
	if($diffCond == '0' ){
		$cond 		= "   DIFFAMT = 0.00";
	}
	if(($diffCond == '1' ) || ($diffCond == '' )){
		$cond  		= "   DIFFAMT <> 0.00";		
	}
	if($reasonStatus == 1){
		$reasonStat = "  A.Reason <> 'null'";
	}
	if($reasonStatus == 0){
		$reasonStat = " A.Reason IS NULL";
	}
	if($reasonStatus == ''){
		$reasonStat = 1;
	}
	$sql  = "SELECT * FROM (
	SELECT A.IdExpDet,A.TotAmt,A.CustomerCd,IFNULL(C.Descript,A.CustomerCd)AS Customer,SUM(B.SAPTotInvAmt) AS SAPTotInvAmt, (SUM(B.SAPTotInvAmt) - A.TotAmt) AS DIFFAMT,DATE_FORMAT(A.DateTime, '%d-%m-%Y') AS PODate,DATE_FORMAT(B.SAPInvDate , '%d-%m-%Y')AS SAPInvDate,A.IsDiffFileGenrated,IFNULL(D.ShortDesc,A.CompanyCd) AS Company ,B.SAPInvNo,IF(A.DespatchMode='F','CompanyVan','X-Factory') AS DespatchModeDisp,E.Reason,E.Action  
	FROM so_expdet A 
	INNER JOIN so_expdet_magazine B ON A.IdExpDet = B.IdExpDet 
	LEFT JOIN so_customer_m C ON A.CustomerCd = C.CustomerCd
	LEFT JOIN so_company_m D ON A.CompanyCd=D.CompanyCd 
	LEFT JOIN so_diffamt_reason E ON A.IdExpDet=E.IdExpDet 
	WHERE A.StatusCd IN ('C', 'B') " .$searchCnd. "  GROUP BY A.IdExpDet ORDER BY A.CustomerCd DESC  ) A WHERE ".$cond." AND ".$reasonStat." 
	";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}


public function exportDiffAmt($IdExpDet){
	/*$sql  = "
	SELECT A.IdExpDet AS PONo, DATE_FORMAT(A.DateTime, '%d-%m-%Y') AS PODate,A.CustomerCd,IFNULL(C.Descript,A.CustomerCd)AS Customer,A.TotAmt AS TotalAmount ,SUM(B.SAPTotInvAmt) AS SAPTotInvAmt,DATE_FORMAT(B.SAPInvDate , '%d-%m-%Y')AS SAPInvDate, (SUM(B.SAPTotInvAmt) - A.TotAmt) AS AmountDiffernce,D.Reason FROM so_expdet A INNER JOIN so_expdet_magazine B ON A.IdExpDet = B.IdExpDet LEFT JOIN so_customer_m C ON A.CustomerCd = C.CustomerCd 
	LEFT JOIN so_diffamt_reason D ON A.IdExpDet = D.IdExpDet
	WHERE A.StatusCd='C' AND A.IdExpDet IN (" .$IdExpDet. ") GROUP BY A.IdExpDet ORDER BY `SAPTotInvAmt` DESC 
	";
	*/
	$curDate = date('d-m-Y');
	$sql= "SELECT 'P' as 'Parent Child Identifier', IF(A.CompanyCd = '1800','\'000255','\'000256') as 'Customer Code'
	, IF(A.CompanyCd = '1800','Solar Industries India Ltd','Economic Explosives Ltd') as 'Customer Name'
	, IF(A.CompanyCd = '1800','10374783693','10374784143') as 'Debit Account No', '' as 'Product Code'
	, '$curDate' AS 'Instrument Value Date',(A.TotAmt - SUM(B.SAPTotInvAmt)) AS Amount,IFNULL(C.Descript,A.CustomerCd)AS 'Beneficiary Name'
	, C.BankName as 'Beneficiary Bank Code', C.IFSCCode as 'Beneficiary Branch Code', CONCAT( '\'', C.BankAccountNo) as 'Credit Account No'
	, C.BankBranch as 'Beneficiary Add Line 1', '' as 'Beneficiary Add Line 2', '' as 'Beneficiary Add Line 3', '' as 'Beneficiary Add Line 4'
	, C.City  as City,C.StateCd as 'State Code', '' as 'Pin Code', CONCAT(C.EMailId, ';dd@solargroup.com') as 'Email Id', C.TelNo as Phone, A.CustomerCd as 'Customer Ref No'
	, CONCAT('CNN', A.IdExpDet)   as 'Remarks 1'
	, '' as 'Remarks 2', '' as 'ADDITIONAL FIELD 1', '' as 'ADDITIONAL FIELD 2', (A.TotAmt - SUM(B.SAPTotInvAmt)) AS 'ADDITIONAL FIELD 3' ,'0' AS 'ADDITIONAL FIELD 4'
	,(A.TotAmt - SUM(B.SAPTotInvAmt)) AS 'ADDITIONAL FIELD 5'
	FROM so_expdet A INNER JOIN so_expdet_magazine B ON A.IdExpDet = B.IdExpDet LEFT JOIN so_customer_m C ON A.CustomerCd = C.CustomerCd 
	LEFT JOIN so_diffamt_reason D ON A.IdExpDet = D.IdExpDet
	WHERE A.StatusCd IN ('C','B') AND A.IdExpDet IN (" .$IdExpDet. ") GROUP BY A.IdExpDet ORDER BY `SAPTotInvAmt` DESC ";
	
	$returnData = $this->execSelectQuery($sql,2);
	if($returnData){
	$sql1 = "
		UPDATE so_expdet SET IsDiffFileGenrated = '1' WHERE IdExpDet IN (" .$IdExpDet. ")";
		$updateData	= $this->execUpdateQuery($sql1);
	}
	$curDateTime = date('Y-m-d ');
	$fileName = './../wrk/diffamt_'.trim($curDateTime).'_'.trim(rand()).'.xls';
	$repTitle = str_repeat("\t",1) . " Differnce Ammount in Purchase Order ";
	$this->makeTabReport($returnData, 3, $fileName, -1, $repTitle, True, 0); 
	return  ;
}



public function insertDiffAmtReasonQuery(){
	$sql	= "INSERT INTO so_diffamt_reason(IdExpDet,Reason,Action ) VALUES ('%s', '%s', '%s')";
	return $sql ;	
}

public function updateDiffAmtReasonQuery(){
	$sql	= "UPDATE  so_diffamt_reason SET Reason = '%s',Action ='%s' WHERE IdExpDet =  '%s'";
	return $sql ;	
}
public function insertDiffAmtReason($data){
	
	$sql='';
	$queryInsert		= $this->insertDiffAmtReasonQuery();
	$queryUpdate        = $this->updateDiffAmtReasonQuery();
	$returnData			= '';
	for($curRowNo=1; $curRowNo<=$data['totRow']; $curRowNo++) {
		$IdExpDet		=	$data['IdExpDet_'.$curRowNo];	
		$Reason 		=	$data['Reason_'.$curRowNo];	
		$Action 		=	$data['Action_'.$curRowNo];	
		if (($Reason =='' ) ||($Action =='' )) 
		{
			continue;
		}	 
		$queryCheck		= "SELECT COUNT(*) AS Total FROM so_diffamt_reason WHERE IdExpDet='%s'";
		$inputArr		= array();
		$inputArr		= array($IdExpDet);
		$sql		= vsprintf($queryCheck,$inputArr);
		$returnData		= $this->execSelectQuery($sql);
		if ($returnData[0]['Total']==0) {
			$inputArr	= array();
			$inputArr	= array($IdExpDet,$Reason,$Action);
			$sql	= vsprintf($queryInsert,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		}else{
			$inputArr	= array();
			$inputArr	= array($Reason,$Action,$IdExpDet);
			$sql	= vsprintf($queryUpdate,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
		}
	}
return $returnData;
} 

///==============================End of Diff AMt ===================================================

// ExpDet Order -------------------------------------------------------------------------------------------------------------------------------------
public function getExpDetList($search, $SearchDateFrom, $SearchDateTo) {
	$date = date('Y-m-d');
	if($SearchDateFrom =='' && $SearchDateTo==''){
		$SearchDateFrom = date('Y-m-d H:i:s', strtotime("-40 days"));
		$SearchDateTo = date('Y-m-d H:i:s');
	}
	else{
		$SearchDateFrom = $this->convertDate($SearchDateFrom,TRUE,3);
		$SearchDateTo = $this->convertDate($SearchDateTo,TRUE,3);
	}
	
	$PoExpDate=  date('Y-m-d', strtotime("- 2 day", strtotime($date)));
	
	
	$POStatus = $this::$POStatus;
	$searchCnd	= ((isset($search)) ? " WHERE (A.VehicleNo LIKE '$search%' OR B.Descript LIKE '$search%')" : " WHERE 1=1") ;
	$searchCnd	.= ($_SESSION['IsCustomer']) ? " AND A.CustomerCd='" .$_SESSION['CustomerCd']. "'" : "";
	$searchCnd	.= ($_SESSION['HasCustomer']) ? " AND B.UserName='" .$_SESSION['UserName']. "'" : "";
	$searchCnd	.= " AND DateTime > '". $SearchDateFrom ."' AND  DateTime < '". $SearchDateTo ."'";
	$IsAdmin= $_SESSION['IsAdmin'];
	$IsCustomer= $_SESSION['IsCustomer'];
	if($IsAdmin){ $GuardVerifyStatus=1;
	}else if($IsCustomer){ $GuardVerifyStatus=0;
	}
	
	switch ($_SESSION['StatusFilter']%100) {
	case $POStatus['All']:
		//$searchCnd	.= " AND A.StatusCd IN ('U', 'W', 'A')";
		break;
	case $POStatus['Unapprove']:
		$searchCnd	.= " AND A.StatusCd = 'U'";
		break;
	case $POStatus['Held']:
		$searchCnd	.= " AND A.StatusCd IN ('H', 'G')";
		break;
	case $POStatus['Approve']:
		$searchCnd	.= " AND A.StatusCd='A'";
		break;
	case $POStatus['Ready']:
		$searchCnd	.= " AND A.StatusCd='E'";
		break;
	case $POStatus['Confirm']:
		$searchCnd	.= " AND A.StatusCd='N'";
		break;
	case $POStatus['Pending']:
		$searchCnd	.= " AND A.StatusCd='W'";
		break;
	case $POStatus['Complete']:
		$searchCnd	.= " AND A.StatusCd='C'";
		break;
	case $POStatus['GoodsReceipt']:
		$searchCnd	.= " AND A.StatusCd='B'";
		break;
	case $POStatus['GuardPhotoVerify']:
		$searchCnd	.= " AND A.StatusCd IN ('C','B') AND ForGuardPhotoVerify='$GuardVerifyStatus'";
		break;
	case $POStatus['Terminate']:
		$searchCnd	.= " AND A.StatusCd='T'";
		break;
	case $POStatus['Expired']:
		$searchCnd	.= " AND A.StatusCd='U' AND DATE_FORMAT(A.DateTime,'%Y-%m-%d') < '$PoExpDate' ";
		break;
	}
	$searchCnd	.= " AND B.SectorCd='{$_SESSION['SectorCd']}'";
	$sql	= "SELECT   A.IdExpDet, A.DespatchMode, IF(A.DespatchMode='F','FOR','EX') AS DespatchModeDisp,
			DATE_FORMAT(A.DateTime,'%d-%m-%Y') AS Date
		, A.VehicleNo, A.ExpVehicleArrDate, A.TotAmt, A.RE11ReceiptDate,TRIM(A.TokenNoPrefix) as TokenNoPrefix, A.TokenNo ,CONCAT(TRIM(A.TokenNoPrefix),'/',A.TokenNo%100) AS TokenNoFull, A.CustomerCd
		, xf_Proper(REPLACE(IFNULL(B.Descript,''),UPPER(IFNULL(B.City,'')),'')) AS Customer, xf_Proper(IFNULL(B.City,'')) AS City, A.IsClubedPO
		,F.IsMainCustomer,F.Id, F.PoNo, F.ApproveByOwner
		,IFNULL(C.ShortDescript,A.StatusCd) AS Status,IFNULL(E.ShortDesc,A.CompanyCd) AS Company, A.RE11CheckStatus, A.PaymentStatus, A.UTR
		,CAST(IFNULL(DATEDIFF(NOW(), A.DateTime),3) - 3 AS CHAR(5))  AS `TerminationDays`
		FROM so_expdet A
		LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd
		LEFT OUTER JOIN so_company_m E ON A.CompanyCd=E.CompanyCd 
		LEFT OUTER JOIN b2b_solar_sc.so_expdet_clubbed_van F ON A.IdExpDet=F.IdExpDet
		LEFT OUTER JOIN so_status_m C ON A.StatusCd=C.StatusCd" . $searchCnd . " ORDER BY C.Disporder, A.IdExpDet DESC ";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

/*public function get_RE11_n_PO_details($IdExpDet){
	$sql 	 = " SELECT A.RE11No,B.RE11Company, B.RE11Date, B.RE11Product, B.RE11MagazineLicNo, B.RE11Qty, B.RE11DigitalSign, B.RE11DigitalSignSingleSide,C.MagazineLicNo FROM so_expdet_magazine A LEFT JOIN so_expdet_re11_checklist B ON A.IdExpDet = B.IdExpDet LEFT JOIN so_magazine_m C ON A.MagazineCd = C.MagazineCd WHERE A.IdExpDet = '{$IdExpDet}' GROUP BY A.RE11No";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}
*/


public function getExpDetMagList($IdExpDet) {
		$sql	= "SELECT A.RE11No, A.RE11Date, A.RE11ExpiredMail, A.MagazineCd, B.StatusCd FROM so_expdet_magazine A JOIN so_expdet B ON A.IdExpDet = B.IdExpDet where A.IdExpDet='$IdExpDet'";
		$returnData 	= $this->execSelectQuery($sql);
		return $returnData;
}

public function XXXExpDetChkDailyStock($CustomerCd) {
	$arrCustomerMDisp = $this->getCustomerMDisp(0, $CustomerCd);
	$returnVal	= TRUE;
	if ((int)$arrCustomerMDisp[0]['HasDailyStock']==1) {
		$inputArr	= array($CustomerCd, $this->addDate(NULL, '0', FALSE), $this->addDate(NULL, '-1 day', FALSE));
		$sql	= "SELECT COUNT(*) AS DSCount FROM so_daily_stock WHERE CustomerCd='%s' AND Date IN ('%s', '%s')";
		$sql	= vsprintf($sql, $inputArr);
		$returnData 	= $this->execSelectQuery($sql);
		$returnVal	= ($returnData[0]['DSCount'] > 0);		// Return True only if DailyStock of Today or Yesterday is put
	}
	return $returnVal;
}

public function ExpDetChkDailyStock($CustomerCd) {
	$arrCustomerMDisp = $this->getCustomerMDisp(0, $CustomerCd);
	$returnVal	= TRUE;
	if ((int)$arrCustomerMDisp[0]['HasDailyStock']==1) {
		$arrOpenDate = $this->getDailyStockOpenDate($_SESSION['CustomerCd'], 0);
		$RowCount = count($arrOpenDate);
		$returnVal	= ($RowCount == 0);
	}
	return $returnVal;
}

public function insertExpDet($data) {
	if($_SESSION['SectorCd']=='E'){
		$stmt	= "INSERT INTO so_expdet (CustomerCd, CompanyCd, DateTime, DespatchMode, VehicleNo, ExpVehicleArrDate, TotAmt, PaymentDate, RE11StatusCd, RE11ReceiptDate
				, CourierName, CourierRef, RateContractRef, RateContractDate, StatusCd, Remark, IsCreatedByAdmin, TransUserName, TransDateTime, SAPRTGSDate, SAPRTGSAmt
				, DateValidUpto, TotBox, AvailableDate, ReadyRemark, TentativeDespDate, AvailableDateActual, VehicleReachedDate, VanChangeReason, CourierSentDate, IsFactoryIntimated
				, AvailableDateTo, TentativeDespDateTo ) 
			VALUES ('%s', %s, '%s', '%s', '%s',  '%s', %s, '%s', %s, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %s, '%s', '%s', '%s', %s, '%s', %s, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %s, '%s', '%s' )";
		$inputArr	= array($data['CustomerCd'], (int)$data['CompanyCd'], $this->convertDate($data['DateTime'],TRUE,3)
		, $data['DespatchMode'], $data['VehicleNo'],  $this->convertDate($data['ExpVehicleArrDate'],TRUE), (float)$data['TotAmt'], $this->convertDate($data['PaymentDate'],TRUE)
		, (int)$data['RE11StatusCd'], $this->convertDate($data['RE11ReceiptDate'],TRUE), $data['CourierName'], $data['CourierRef'], trim($data['RateContractRef'])
		, $this->convertDate($data['RateContractDate'],TRUE), $data['StatusCd']
		, $data['Remark'], (int)$data['IsCreatedByAdmin'], $_SESSION['UserName'], date('Y-m-d H:i:s')
		, $this->convertDate($data['SAPRTGSDate'],TRUE), (float)$data['SAPRTGSAmt'], $this->convertDate($data['DateValidUpto'],TRUE,3)
		, (int)$data['TotBox'], $this->convertDate($data['AvailableDate'],TRUE), $data['ReadyRemark'], $this->convertDate($data['TentativeDespDate'],TRUE)
		, $this->convertDate($data['AvailableDateActual'],TRUE), $this->convertDate($data['VehicleReachedDate'],TRUE), $data['VanChangeReason'], $this->convertDate($data['CourierSentDate'],TRUE), (int)$data['IsFactoryIntimated']
		, $this->convertDate($data['AvailableDateTo'],TRUE), $this->convertDate($data['TentativeDespDateTo'],TRUE));
	}
	else { 
		$stmt	= "INSERT INTO so_expdet (CustomerCd, CompanyCd, DateTime, DespatchMode, VehicleNo, IsClubedPO, SMSMobileNo, ExpVehicleArrDate, TotAmt, PaymentDate, RE11StatusCd, RE11ReceiptDate
				, CourierName, CourierRef, RateContractRef, RateContractDate, StatusCd, Remark, IsCreatedByAdmin, TransUserName, TransDateTime, SAPRTGSDate, SAPRTGSAmt
				, DateValidUpto, TotBox, AvailableDate, ReadyRemark, TentativeDespDate, AvailableDateActual, VehicleReachedDate, VanChangeReason, CourierSentDate, IsFactoryIntimated
				) 
			VALUES ('%s', %s, '%s', '%s', '%s', '%s', '%s', '%s', %s, '%s', %s, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %s, '%s', '%s', '%s', %s, '%s', %s, '%s', '%s', '%s', '%s', '%s', '%s', '%s', %s)";
		$inputArr	= array($data['CustomerCd'], (int)$data['CompanyCd'], $this->convertDate($data['DateTime'],TRUE,3)
		, $data['DespatchMode'], $data['VehicleNo'], $data['IsClubedVan'], $data['SMSMobileNo'], $this->convertDate($data['ExpVehicleArrDate'],TRUE), (float)$data['TotAmt'], $this->convertDate($data['PaymentDate'],TRUE)
		, (int)$data['RE11StatusCd'], $this->convertDate($data['RE11ReceiptDate'],TRUE), $data['CourierName'], $data['CourierRef'], trim($data['RateContractRef'])
		, $this->convertDate($data['RateContractDate'],TRUE), $data['StatusCd']
		, $data['Remark'], (int)$data['IsCreatedByAdmin'], $_SESSION['UserName'], date('Y-m-d H:i:s')
		, $this->convertDate($data['SAPRTGSDate'],TRUE), (float)$data['SAPRTGSAmt'], $this->convertDate($data['DateValidUpto'],TRUE,3)
		, (int)$data['TotBox'], $this->convertDate($data['AvailableDate'],TRUE), $data['ReadyRemark'], $this->convertDate($data['TentativeDespDate'],TRUE)
		, $this->convertDate($data['AvailableDateActual'],TRUE), $this->convertDate($data['VehicleReachedDate'],TRUE), $data['VanChangeReason'], $this->convertDate($data['CourierSentDate'],TRUE), (int)$data['IsFactoryIntimated']
		);
	}
	 $sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	$this->lastInsertTranNo	= $this->getInsertId();

	if (!$returnData && !$_SESSION['IsTradeSector']) {
		$lastInsertId = $this->lastInsertTranNo;
		$stmt	= "UPDATE so_expdet SET ItemAmt=%s, HnFAmt=%s, ExcDuty=%s, TransportCost=%s, TaxAmt=%s, RE11DelvDatePESO='%s' WHERE IdExpDet=%s";
		$inputArr	= array((float)$data['ItemAmt'], (float)$data['HnFAmt'], (float)$data['ExcDuty'], (float)$data['TransportCost'], (float)$data['TaxAmt']
						,$this->convertDate($data['RE11DelvDatePESO'],TRUE), $lastInsertId) ;
		$sql		= vsprintf($stmt,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
	}

	return $returnData;
}

public function updateExpDet($data) {
$oriDataArr = $this->getExpDetHeader($data['IdExpDet']);

if($_SESSION['SectorCd']=='E'){
$stmt	= "UPDATE so_expdet SET CustomerCd='%s', CompanyCd=%s, DateTime='%s', DespatchMode='%s', VehicleNo='%s', ExpVehicleArrDate='%s', TotAmt=%s, PaymentDate='%s', RE11StatusCd=%s
			, RE11ReceiptDate='%s', CourierName='%s', CourierRef='%s', RateContractRef='%s', RateContractDate='%s', ApprovedByUserName='%s', ApprovalDateTime='%s'
			, StatusCd='%s', Remark='%s', IsCreatedByAdmin=%s, TransUserName='%s', TransDateTime='%s', SAPRTGSDate='%s', SAPRTGSAmt=%s, DateValidUpto='%s'
			, TotBox=%s, AvailableDate='%s', ReadyRemark='%s', TentativeDespDate='%s', AvailableDateActual='%s', VehicleReachedDate='%s', VanChangeReason='%s'
			, CourierSentDate='%s', IsFactoryIntimated=%s,  AvailableDateTo='%s', TentativeDespDateTo='%s' WHERE IdExpDet=%s";
$inputArr	= array($data['CustomerCd'], (int)$data['CompanyCd'], $this->convertDate($data['DateTime'],TRUE,3)
	, $data['DespatchMode'], $data['VehicleNo'], $this->convertDate($data['ExpVehicleArrDate'],TRUE), (float)$data['TotAmt'], $this->convertDate($data['PaymentDate'],TRUE), (int)$data['RE11StatusCd']
	, $this->convertDate($data['RE11ReceiptDate'],TRUE), $data['CourierName'], $data['CourierRef'], trim($data['RateContractRef']), $this->convertDate($data['RateContractDate'],TRUE)
	, $data['ApprovedByUserName'], $this->convertDate($data['ApprovalDateTime'],TRUE,3), $data['StatusCd']
	, $data['Remark'], (int)$data['IsCreatedByAdmin'], $_SESSION['UserName'], date('Y-m-d H:i:s')
	, $this->convertDate($data['SAPRTGSDate'],TRUE), (float)$data['SAPRTGSAmt'], $this->convertDate($data['DateValidUpto'],TRUE,3)
	, (int)$data['TotBox'], $this->convertDate($data['AvailableDate'],TRUE), $data['ReadyRemark'], $this->convertDate($data['TentativeDespDate'],TRUE), $this->convertDate($data['AvailableDateActual'],TRUE)
	, $this->convertDate($data['VehicleReachedDate'],TRUE), $data['VanChangeReason'], $this->convertDate($data['CourierSentDate'],TRUE), (int)$data['IsFactoryIntimated']
	, $this->convertDate($data['AvailableDateTo'],TRUE), $this->convertDate($data['TentativeDespDateTo'],TRUE), (int)$data['oldIdExpDet']
	);
}
else{
	if($data['StatusCd'] == 'T'){
		$TerminatedBy = $_SESSION['UserName'];;
		$TerminatedDateTime = date('Y-m-d H:i:s');
	}else{
		$TerminatedBy = '';
		$TerminatedDateTime = '0000-00-00 00:00:00';
	}
$stmt	= "UPDATE so_expdet SET CustomerCd='%s', CompanyCd=%s, DateTime='%s', DespatchMode='%s', VehicleNo='%s', IsClubedPO='%s',  SMSMobileNo='%s', ExpVehicleArrDate='%s', TotAmt=%s, PaymentDate='%s', RE11StatusCd=%s
			, RE11ReceiptDate='%s', CourierName='%s', CourierRef='%s', RateContractRef='%s', RateContractDate='%s', ApprovedByUserName='%s', ApprovalDateTime='%s'
			, StatusCd='%s', PendingReason ='%s', TerminateReason ='%s', Remark='%s', IsCreatedByAdmin=%s, TransUserName='%s', TransDateTime='%s', SAPRTGSDate='%s', SAPRTGSAmt=%s, DateValidUpto='%s'
			, TotBox=%s, AvailableDate='%s', ReadyRemark='%s', TentativeDespDate='%s', AvailableDateActual='%s', VehicleReachedDate='%s', VanChangeReason='%s'
			, CourierSentDate='%s', IsFactoryIntimated=%s, TerminatedBy='%s',TerminatedDateTime ='%s' WHERE IdExpDet=%s";
$inputArr	= array($data['CustomerCd'], (int)$data['CompanyCd'], $this->convertDate($data['DateTime'],TRUE,3)
	, $data['DespatchMode'], $data['VehicleNo'], $data['IsClubedVan'], $data['SMSMobileNo'], $this->convertDate($data['ExpVehicleArrDate'],TRUE), (float)$data['TotAmt'], $this->convertDate($data['PaymentDate'],TRUE), (int)$data['RE11StatusCd']
	, $this->convertDate($data['RE11ReceiptDate'],TRUE), $data['CourierName'], $data['CourierRef'], trim($data['RateContractRef']), $this->convertDate($data['RateContractDate'],TRUE)
	, $data['ApprovedByUserName'], $this->convertDate($data['ApprovalDateTime'],TRUE,3), $data['StatusCd'], $data['PendingReason'], $data['TerminateReason']
	, $data['Remark'], (int)$data['IsCreatedByAdmin'], $_SESSION['UserName'], date('Y-m-d H:i:s')
	, $this->convertDate($data['SAPRTGSDate'],TRUE), (float)$data['SAPRTGSAmt'], $this->convertDate($data['DateValidUpto'],TRUE,3)
	, (int)$data['TotBox'], $this->convertDate($data['AvailableDate'],TRUE), $data['ReadyRemark'], $this->convertDate($data['TentativeDespDate'],TRUE), $this->convertDate($data['AvailableDateActual'],TRUE)
	, $this->convertDate($data['VehicleReachedDate'],TRUE), $data['VanChangeReason'], $this->convertDate($data['CourierSentDate'],TRUE)
	, (int)$data['IsFactoryIntimated'], $TerminatedBy, $TerminatedDateTime, (int)$data['oldIdExpDet']);
}
$sql		= vsprintf($stmt,$inputArr);
$returnData	= $this->execUpdateQuery($sql);

if (!$returnData && !$_SESSION['IsTradeSector']) {
	$lastInsertId = (int)$data['oldIdExpDet'];
	$stmt	= "UPDATE so_expdet SET ItemAmt=%s, HnFAmt=%s, ExcDuty=%s, TransportCost=%s, TaxAmt=%s, RE11DelvDatePESO='%s' WHERE IdExpDet=%s";
	$inputArr	= array((float)$data['ItemAmt'], (float)$data['HnFAmt'], (float)$data['ExcDuty'], (float)$data['TransportCost'], (float)$data['TaxAmt']
					, $this->convertDate($data['RE11DelvDatePESO'],TRUE), $lastInsertId) ;
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
}

if ($data['RE11ReceiptDate']!='' && $oriDataArr[0]['RE11ReceiptDate']=='0000-00-00'){
	$this->sendEMailRE11Receipt($data['IdExpDet'], 2);
	}
return $returnData;
}


public function updateVehicleReachedDate($IdExpDet) {
	$queryUpdate	= "UPDATE so_expdet SET VehicleReachedDate = '%s', StatusCd = '%s' WHERE IdExpDet=%s";
	$IdExpDet		= $IdExpDet;
	$VehicleReachedDate	= date('Y-m-d');
	$inputArr	= array($VehicleReachedDate, self::POStatusGoodsReceipt, $IdExpDet);
	$sql		= vsprintf($queryUpdate, $inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	if ($returnData) { return false; }
	else{ return true; }
	
}

public function sendSMSalert($IdExpdet, $TokenNoFull, $vehicleNo, $TelNo){
$uname = 'SIILJPRO'; //'SIILJPRP';
$password = 'S(ol)!ar';// 'E9W!f9Y~';
$info ='1';
$test = '0';
$from = 'iSOLAR';
$dest = $TelNo;  //'8793653028' //'919649569999'; //'918600993992';
$messages = "Dear Customer, Your PO No.".$IdExpdet." having Van No. ".$vehicleNo." has been approved with Token No. ".$TokenNoFull.". Thank You, Customer Service Department";
$data ="uname=".$uname."&pass=".$password."&msg=".$messages."&send=".$from."&dest=".$dest;
$ch = curl_init("http://api.unicel.in/SendSMS/sendmsg.php?");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);
curl_close($ch);
return $result;
}

public function getExpDetMagazineInsertQuery() {
	return ("INSERT INTO so_expdet_magazine (IdExpDet, MagazineCd, RE11No, RE11Date, TotAmt, SAPSONo, SAPSODate, SAPInvNo, SAPInvDate) 
			VALUES (%s, '%s', '%s', '%s', %s, '%s', '%s', '%s', '%s')");
}

/* public function getExpDetMagazineUpdateQuery() {
	return ("UPDATE so_expdet_magazine SET IdExpDet=%s, MagazineCd='%s', RE11No='%s', RE11Date='%s', TotAmt=%s
				, SAPSONo='%s', SAPSODate='%s', SAPInvNo='%s', SAPInvDate='%s' WHERE UniqueId=%s"); 
}
*/

 public function getExpDetMagazineUpdateQuery() {
	return ("UPDATE so_expdet_magazine SET  RE11No='%s', RE11Date='%s', TotAmt=%s
				, SAPSONo='%s', SAPSODate='%s', SAPInvNo='%s', SAPInvDate='%s' WHERE UniqueId=%s"); 
}


public function getExpDetMagazineDeleteQuery() {
	return ("DELETE FROM so_expdet_magazine WHERE UniqueId=%s");
}

public function insertExpDetMagazine($data) {
	$returnData 	= array();
	$queryInsert	= $this->getExpDetMagazineInsertQuery();

	for ($curSubNo=1; $curSubNo<=$data['LastSubNo']; $curSubNo++) {
		for ($curRowNo=1; $curRowNo<=$data['SubMagLastRowNo'.$curSubNo]; $curRowNo++) {		// actually only 1 row per MagazineSub
			$curSubRowNo = $curSubNo.'_'.$curRowNo;
			if (!isset($data['MagazineCd'.$curSubRowNo]) || trim($data['MagazineCd'.$curSubRowNo])=='') {
				continue;
			}	
			$inputArr	= array((int)$data['IdExpDet'], $data['MagazineCd'.$curSubRowNo], $data['RE11No'.$curSubRowNo]
				, $this->convertDate($data['RE11Date'.$curSubRowNo],TRUE), (float)$data['TotAmt'.$curSubRowNo]
				, $data['SAPSONo'.$curSubRowNo], $this->convertDate($data['SAPSODate'.$curSubRowNo],TRUE)
				, $data['SAPInvNo'.$curSubRowNo], $this->convertDate($data['SAPInvDate'.$curSubRowNo],TRUE));
			$sql		= vsprintf($queryInsert, $inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
			$UniqueIdMagazine = $this->getInsertId();
			if($_SESSION['SectorCd']=='T'){
				$target_path = 'upload/re11PDF/PO/';
				//$target_path = $target_path . basename( $_FILES['rellPDF'.$curSubRowNo]['name']); 
				$filename=$data['RE11No'.$curSubRowNo].'.pdf' ;
				$target_path = $target_path.$filename; 
				if(move_uploaded_file($_FILES['rellPDF'.$curSubRowNo]['tmp_name'], $target_path)) {
					$sqlquery = "update so_expdet_magazine SET RE11PDF = '".$filename."' where IdExpDet =".$data['IdExpDet'] . " and MagazineCd=".$data['MagazineCd'.$curSubRowNo];
					$resultoutput = $this->execUpdateQuery($sqlquery);
				}
			}
			$returnData = $this->insertExpDetMagazineItem($data, $curSubNo, $UniqueIdMagazine);
			if($_SESSION['SectorCd'] == 'T' && $data['StateCd'] = 'GJ' && $data['MultiPoPromoId'] != '0'){
				$returnData=	$this->updateMultiPOPromo($data, $curSubNo, $UniqueIdMagazine);
			}
			if ($returnData) return $returnData;
		}
	}
	return $returnData;
}


public function getExpDetMagazineItemInsertQuery() {
	return ("INSERT INTO so_expdet_magazine_item (UniqueIdMagazine, IdExpDet, MagazineCd, ItemCd, OrderBox, OrderQty, RE11Qty
				, Rate, BasicRate, Amount, DespatchedBox, DespatchedQty) 
			VALUES (%s, %s, '%s', '%s', %s, %s, %s, %s, %s, %s, %s, %s)");
}

public function getExpDetMagazineItemUpdateQuery() {
	return ("UPDATE so_expdet_magazine_item SET UniqueIdMagazine=%s, IdExpDet=%s, MagazineCd='%s', ItemCd='%s', OrderBox=%s, OrderQty=%s, RE11Qty=%s
		, Rate=%s, BasicRate=%s, Amount=%s, DespatchedBox=%s, DespatchedQty=%s WHERE UniqueId=%s"); 
}

public function getExpDetMagazineItemDeleteQuery() {
	return ("DELETE FROM so_expdet_magazine_item WHERE UniqueId=%s");
}


public function insertExpDetMagazineItem($data, $curSubNo, $UniqueIdMagazine) {
	$returnData 	= array();
	$queryInsert	= $this->getExpDetMagazineItemInsertQuery();

	for ($curRowNo=1; $curRowNo<=$data['SubItemLastRowNo'.$curSubNo]; $curRowNo++) {
		$curMagSubRowNo = $curSubNo.'_1';
		$curSubRowNo = $curSubNo.'B_'.$curRowNo;
		if (!isset($data['MagazineCd'.$curMagSubRowNo]) || trim($data['MagazineCd'.$curMagSubRowNo])==''
				|| trim($data['ItemCd'.$curSubRowNo])=='' || (float)$data['OrderQty'.$curSubRowNo]==0) {
			continue;
		}	
		$inputArr	= array($UniqueIdMagazine, (int)$data['IdExpDet'], $data['MagazineCd'.$curMagSubRowNo], $data['ItemCd'.$curSubRowNo]
			, (int)$data['OrderBox'.$curSubRowNo], (float)$data['OrderQty'.$curSubRowNo], (int)$data['RE11Qty'.$curSubRowNo]
			, (float)$data['Rate'.$curSubRowNo], (float)$data['BasicRate'.$curSubRowNo]
			, (float)$data['Amount'.$curSubRowNo], (int)$data['DespatchedBox'.$curSubRowNo], (float)$data['DespatchedQty'.$curSubRowNo]);
		$sql		= vsprintf($queryInsert, $inputArr);
		$returnData	= $this->execUpdateQuery($sql);

		if (!$returnData && !$_SESSION['IsTradeSector']) {
			$lastInsertId = $this->getInsertId();
			$stmt	= "UPDATE so_expdet_magazine_item SET HnFAmt=%s, ExcDuty=%s, TransportCost=%s, TaxAmt=%s WHERE UniqueId=%s";
			$inputArr	= array((float)$data['HnFAmt'.$curSubRowNo], (float)$data['ExcDuty'.$curSubRowNo]
							, (float)$data['TransportCost'.$curSubRowNo], (float)$data['TaxAmt'.$curSubRowNo], $lastInsertId);
			$sql		= vsprintf($stmt,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
		}

		if ($returnData) {
			return $returnData;
		}
	}
	return $returnData;
}

public function updateMultiPOPromo($data, $curSubNo){
	$returnData 	= array();
	$sql='';
	$queryUpdate  	= "UPDATE `so_customer_multi_po_restriction` SET `RemainingQty`='%s',`DeliverQty`='%s' WHERE `MultiPoRestId`='%s' AND `CustomerCd`='%s' AND `ItemCd`='%s'";
	for ($curRowNo=1; $curRowNo<=$data['SubItemLastRowNo'.$curSubNo]; $curRowNo++) {
		$curSubRowNo = $curSubNo.'B_'.$curRowNo;
		$inputArr	= array((int)$data['AfterUpdateRemainingMultiPOQty'.$curSubRowNo], (int)$data['UpdateDeliverQty'.$curSubRowNo], $data['MultiPoPromoId'], $data['CustomerCd'], $data['ItemCd'.$curSubRowNo]);
		$sql		= vsprintf($queryUpdate, $inputArr);
		$returnData	= $this->execUpdateQuery($sql);
	}
		$queryInsert  	= "INSERT INTO `so_customer_multi_po_restriction_trans`(`MultiPoRestId`, `IdExpDet`, `CustomerCd`) VALUES ('%s', '%s', '%s')";
		$inputArr1	= array($data['MultiPoPromoId'], (int)$data['IdExpDet'],  $data['CustomerCd']);
		$sql1		= vsprintf($queryInsert, $inputArr1);
		$returnData	= $this->execUpdateQuery($sql1);
	return $returnData;
}

public function updateExpDetRE11PDF($IdExpDet, $uploadData, $re11no){
	$target_path = 'upload/re11PDF/PO/';
	$filename=$re11no.'.pdf' ;
	$target_path = $target_path.$filename; 
	//$target_path = $target_path . basename( $_FILES['rellPDF']['name']); 
	if(move_uploaded_file($_FILES['rellPDF']['tmp_name'], $target_path)) {
		$sql = "update so_expdet_magazine SET RE11PDF = '".$filename."' where IdExpDet =".$IdExpDet;
		$result = $this->execUpdateQuery($sql);
	}
}

public function updateVanLoading_PDF($IdExpDet, $uploadData){
	$target_path_VanLoadingLetter = 'upload/VanLoadingLetter/';
	
	$filename_VanLoadingLetter=$IdExpDet.'_VanLoadingLetter.pdf' ;
	
	$target_path_VanLoadingLetter = $target_path_VanLoadingLetter.$filename_VanLoadingLetter; 
	
	if(move_uploaded_file($_FILES['VanLoadingLetter']['tmp_name'], $target_path_VanLoadingLetter)) {
		$sql = "update so_expdet SET VanLoadingPDF = '".$filename_VanLoadingLetter."' where IdExpDet =".$IdExpDet;
		$result = $this->execUpdateQuery($sql);
	}
}

public function updateDriverAuth_PDF($IdExpDet, $uploadData){
	$target_path_DriverAuthPDF = 'upload/DriverAuthPDF/';
	
	$filename_DriverAuthPDF=$IdExpDet.'_DriverAuth.pdf' ;
	
	$target_path_DriverAuthPDF = $target_path_DriverAuthPDF.$filename_DriverAuthPDF; 
	
	if(move_uploaded_file($_FILES['DriverAuthPDF']['tmp_name'], $target_path_DriverAuthPDF) ) {
		$sql = "update so_expdet SET DriverAuthPDF = '".$filename_DriverAuthPDF."' where IdExpDet =".$IdExpDet;
		$result = $this->execUpdateQuery($sql);
	}
}

public function update403FormPDF($IdExpDet, $uploadData){
	$target_path_403FormPDF = 'upload/Form403PDF/';
	
	$filename_403FormPDF=$IdExpDet.'_403Form.pdf' ;
	
	$target_path_403FormPDF = $target_path_403FormPDF.$filename_403FormPDF; 
	
	if(move_uploaded_file($_FILES['Form403PDF']['tmp_name'], $target_path_403FormPDF) ) {
		$sql = "update so_expdet SET Form403PDF = '".$filename_403FormPDF."' where IdExpDet =".$IdExpDet;
		$result = $this->execUpdateQuery($sql);
		if($result){
			$mailsendresult = $this->Form403PDFUploadMailSend($IdExpDet, 3);
		}
	}
}

public function updateExpDetRE11PDFTrade($IdExpDet, $magazineCd, $uploadData){
	
	$target_path = 'upload/re11PDF/PO/';
	$target_path = $target_path . basename( $_FILES['rellPDF']['name']); if(move_uploaded_file($_FILES['rellPDF']['tmp_name'], $target_path)) {
		$sql = "update so_expdet_magazine SET RE11PDF = '".basename( $_FILES['rellPDF']['name'])."' where IdExpDet =".$IdExpDet." and MagazineCd=".$MagazineCd;
		$result = $this->execUpdateQuery($sql);
	}
}

public function getExpDetRE11PDF($IdExpDet){
	$sql = "select RE11PDF from so_expdet_magazine where IdExpDet =".$IdExpDet;
	$result = $this->execSelectQuery($sql);
	return $result;
}

public function removeExpDetRE11PDF($IdExpDet, $filename){
	$target_path = '/public_html/B2B/upload/re11PDF/PO/';
	$target_path = $target_path.$filename; 
	unlink($target_path);
	$sql = "update so_expdet_magazine SET RE11PDF = '' where IdExpDet =".$IdExpDet;
	$result = $this->execUpdateQuery($sql);
	return $result;
}

public function removeExpDetvanloadingPDF($IdExpDet, $filename){
	$target_path = '/public_html/B2B/upload/VanLoadingLetter/';
	$target_path = $target_path.$filename; 
	unlink($target_path);
	$sql = "update so_expdet SET VanLoadingPDF = '', RemoveVanLoadingPDF = '1' where IdExpDet =".$IdExpDet;
	$result = $this->execUpdateQuery($sql);
	return $result;
}

public function removeExpDetDriverAuthPDF($IdExpDet, $filename){
	$target_path = '/public_html/B2B/upload/DriverAuthPDF/';
	$target_path = $target_path.$filename; 
	unlink($target_path);
	$sql = "update so_expdet SET DriverAuthPDF = '', RemoveDriverAuthPDF = '1' where IdExpDet =".$IdExpDet;
	$result = $this->execUpdateQuery($sql);
	return $result;
}

public function removeExpDet403FormPDF($IdExpDet, $filename){
	$target_path = '/public_html/B2B/upload/Form403PDF/';
	$target_path = $target_path.$filename; 
	unlink($target_path);
	$sql = "update so_expdet SET Form403PDF = '' where IdExpDet =".$IdExpDet;
	$result = $this->execUpdateQuery($sql);
	return $result;
}

public function removeExpDetRE11PDFTrade($IdExpDet, $MagazineCd, $filename){
	$target_path = '/public_html/B2B/upload/re11PDF/PO/';
	$target_path = $target_path.$filename; 
	//unlink($target_path);
	$sql = "update so_expdet_magazine SET RE11PDF = '', RemoveRe11Pdf='1' where IdExpDet =".$IdExpDet." AND MagazineCd=".$MagazineCd;
	$result = $this->execUpdateQuery($sql);
	return $result;
}

public function updateExpDetMagazine($data) {
	$queryInsert	= $this->getExpDetMagazineInsertQuery();
	$queryUpdate	= $this->getExpDetMagazineUpdateQuery();
	$queryDelete	= $this->getExpDetMagazineDeleteQuery();
	$returnData		= array();
	for ($curSubNo=1; $curSubNo<=$data['LastSubNo']; $curSubNo++) {
		for ($curRowNo=1; $curRowNo<=$data['SubMagLastRowNo'.$curSubNo]; $curRowNo++) {
			$curSubRowNo = $curSubNo.'_'.$curRowNo;
			if (!isset($data['MagazineCd'.$curSubRowNo]) || trim($data['MagazineCd'.$curSubRowNo])=='') {
				continue;
			}	

			$UniqueId = (int)$data['UniqueId'.$curSubRowNo];
			$UniqueIdMagazine = $UniqueId;
			if (trim($data['MagazineCd'.$curSubRowNo])=='') {
				if ($UniqueId>0) {		// This won't happen, as Magazine is locked in edit. Hence no processing of magazine_item also
					$inputArr	= array();
					$inputArr	= array($UniqueId);
					$sql		= vsprintf($queryDelete, $inputArr);
					$returnData	= $this->execUpdateQuery($sql);
					if ($returnData) return $returnData;
				}
			} else {
				if ($UniqueId > 0) {
					if ((float)$data['TotAmt'.$curSubRowNo]==0) {	// changed All Item Quantity to 0, for nullifying the Magazine
						$inputArr	= array();
						$inputArr	= array($UniqueId);
						$sql		= vsprintf($queryDelete, $inputArr);
						$returnData	= $this->execUpdateQuery($sql);
					} else {
						/*$inputArr	= array((int)$data['IdExpDet'], $data['MagazineCd'.$curSubRowNo], $data['RE11No'.$curSubRowNo]
							, $this->convertDate($data['RE11Date'.$curSubRowNo],TRUE), (float)$data['TotAmt'.$curSubRowNo]
							, $data['SAPSONo'.$curSubRowNo], $this->convertDate($data['SAPSODate'.$curSubRowNo],TRUE)
							, $data['SAPInvNo'.$curSubRowNo], $this->convertDate($data['SAPInvDate'.$curSubRowNo],TRUE), $UniqueId); */
						
						$inputArr	= array( $data['RE11No'.$curSubRowNo]
							, $this->convertDate($data['RE11Date'.$curSubRowNo],TRUE), (float)$data['TotAmt'.$curSubRowNo]
							, $data['SAPSONo'.$curSubRowNo], $this->convertDate($data['SAPSODate'.$curSubRowNo],TRUE)
							, $data['SAPInvNo'.$curSubRowNo], $this->convertDate($data['SAPInvDate'.$curSubRowNo],TRUE), $UniqueId); 
							
						$sql		= vsprintf($queryUpdate,$inputArr);
						$returnData	= $this->execUpdateQuery($sql);
						$UniqueIdMagazine = $UniqueId;
						if (!empty($data['SAPSONo'.$curSubRowNo])) {
							$IdExpDet = (int)$data['oldIdExpDet'];
							
							$sql = "UPDATE scm_solar_sc.vm_gate_tran_customer SET SAPSONo='{$data['SAPSONo'.$curSubRowNo]}' WHERE PONo=$IdExpDet AND RE11No='{$data['RE11No'.$curSubRowNo]}'";
							$this->execUpdateQuery($sql);
						}
						if($_SESSION['SectorCd']=='T' ){
							$filename=$data['RE11No'.$curSubRowNo].'.pdf';
							$target_path = 'upload/re11PDF/PO/';
							$target_path = $target_path . $filename; 
							if(move_uploaded_file($_FILES['rellPDF'.$curSubRowNo]['tmp_name'], $target_path)) {
								$sqlquery = "update so_expdet_magazine SET RE11PDF = '".$filename."', RE11ExpiredMail = 0, RemoveRe11Pdf = 0  where IdExpDet =".$data['IdExpDet'] . " and MagazineCd='".$data['MagazineCd'.$curSubRowNo]."'";
								$resultoutput = $this->execUpdateQuery($sqlquery);
								if( ($data['StatusCd']=='A' || $data['StatusCd']=='W')  && $data['RE11ExpiredMail'.$curSubRowNo]=='1'  ){
									$RE11List	= $this->Re11PDFExpireMailSend($IdExpDet, '3', $data['RE11No'.$curSubRowNo], $this->convertDate($data['RE11Date'.$curSubRowNo], TRUE));
								}
								if($data['RemoveRe11Pdf'.$curSubRowNo]=='1'  ){
									$RE11List	= $this->Re11PDFReUploadMailSend($data['IdExpDet'], '3', $data['RE11No'.$curSubRowNo], $this->convertDate($data['RE11Date'.$curSubRowNo], TRUE));
								}
							}
						}
					}					
				} else {
					$inputArr	= array((int)$data['IdExpDet'], $data['MagazineCd'.$curSubRowNo], $data['RE11No'.$curSubRowNo]
						, $this->convertDate($data['RE11Date'.$curSubRowNo],TRUE), (float)$data['TotAmt'.$curSubRowNo]
						, $data['SAPSONo'.$curSubRowNo], $this->convertDate($data['SAPSODate'.$curSubRowNo],TRUE)
						, $data['SAPInvNo'.$curSubRowNo], $this->convertDate($data['SAPInvDate'.$curSubRowNo],TRUE));
					$sql		= vsprintf($queryInsert,$inputArr);
					$returnData	= $this->execUpdateQuery($sql);
					$UniqueIdMagazine = $this->getInsertId();
				}
				if ($returnData) return $returnData;

				$this->updateExpDetMagazineItem($data, $curSubNo, $UniqueIdMagazine);
				if ($returnData) return $returnData;
			}
		}
	}
	return $returnData;
}
public function updateExpDetMagazineItem($data, $curSubNo, $UniqueIdMagazine) {
	$queryInsert	= $this->getExpDetMagazineItemInsertQuery();
	$queryUpdate	= $this->getExpDetMagazineItemUpdateQuery();
	$queryDelete	= $this->getExpDetMagazineItemDeleteQuery();
	$returnData		= array();

	for ($curRowNo=1; $curRowNo<=$data['SubItemLastRowNo'.$curSubNo]; $curRowNo++) {
		$curMagSubRowNo = $curSubNo.'_1';
		$curSubRowNo = $curSubNo.'B_'.$curRowNo;
		if (!isset($data['MagazineCd'.$curMagSubRowNo]) || trim($data['MagazineCd'.$curMagSubRowNo])=='') {
			continue;
		}	

		$UniqueId	= (int)$data['UniqueId'.$curSubRowNo];
		if (trim($data['ItemCd'.$curSubRowNo])=='' || (float)$data['OrderQty'.$curSubRowNo]==0) {
			if ($UniqueId>0) {
				$inputArr	= array();
				$inputArr	= array($UniqueId);
				$sql		= vsprintf($queryDelete, $inputArr);
				$returnData	= $this->execUpdateQuery($sql);
				if ($returnData) return $returnData;
			}
		} else {
			if ($UniqueId>0) {
				$inputArr	= array($UniqueIdMagazine, (int)$data['IdExpDet'], $data['MagazineCd'.$curMagSubRowNo], $data['ItemCd'.$curSubRowNo]
					, (int)$data['OrderBox'.$curSubRowNo], (float)$data['OrderQty'.$curSubRowNo], (int)$data['RE11Qty'.$curSubRowNo]
					, (float)$data['Rate'.$curSubRowNo], (float)$data['BasicRate'.$curSubRowNo]
					, (float)$data['Amount'.$curSubRowNo], (int)$data['DespatchedBox'.$curSubRowNo], (float)$data['DespatchedQty'.$curSubRowNo], $UniqueId);
				$sql		= vsprintf($queryUpdate,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);

				if (!$returnData && !$_SESSION['IsTradeSector']) {
					$lastInsertId = $UniqueId;
					$stmt	= "UPDATE so_expdet_magazine_item SET HnFAmt=%s, ExcDuty=%s, TransportCost=%s, TaxAmt=%s WHERE UniqueId=%s";
					$inputArr	= array((float)$data['HnFAmt'.$curSubRowNo], (float)$data['ExcDuty'.$curSubRowNo]
									, (float)$data['TransportCost'.$curSubRowNo], (float)$data['TaxAmt'.$curSubRowNo], $lastInsertId);
					$sql		= vsprintf($stmt,$inputArr);
					$returnData	= $this->execUpdateQuery($sql);
				}
			} else {
				$inputArr	= array($UniqueIdMagazine, (int)$data['IdExpDet'], $data['MagazineCd'.$curMagSubRowNo], $data['ItemCd'.$curSubRowNo]
					, (int)$data['OrderBox'.$curSubRowNo], (float)$data['OrderQty'.$curSubRowNo], (int)$data['RE11Qty'.$curSubRowNo]
					, (float)$data['Rate'.$curSubRowNo], (float)$data['BasicRate'.$curSubRowNo]
					, (float)$data['Amount'.$curSubRowNo], (int)$data['DespatchedBox'.$curSubRowNo], (float)$data['DespatchedQty'.$curSubRowNo]);
				$sql		= vsprintf($queryInsert,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);

				if (!$returnData && !$_SESSION['IsTradeSector']) {
					$lastInsertId = $this->getInsertId();
					$stmt	= "UPDATE so_expdet_magazine_item SET HnFAmt=%s, ExcDuty=%s, TransportCost=%s, TaxAmt=%s WHERE UniqueId=%s";
					$inputArr	= array((float)$data['HnFAmt'.$curSubRowNo], (float)$data['ExcDuty'.$curSubRowNo]
									, (float)$data['TransportCost'.$curSubRowNo], (float)$data['TaxAmt'.$curSubRowNo], $lastInsertId);
					$sql		= vsprintf($stmt,$inputArr);
					$returnData	= $this->execUpdateQuery($sql);
				}
			}
			if ($returnData) return $returnData;
		}
	}
	return $returnData;
}

/*public function getExpDetHeader($IdExpDet) {
	$stmt	= "SELECT A.*,CONCAT(TRIM(A.TokenNoPrefix),IF(A.TokenNo=0,'',CONCAT('/',A.TokenNo%%100))) AS TokenNoFull FROM so_expdet A WHERE A.IdExpDet=%s";
	$inputArr 	= array($IdExpDet);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}
*/
public function getExpDetHeader($IdExpDet) {
	$stmt	= "SELECT A.*,CONCAT(TRIM(A.TokenNoPrefix),IF(A.TokenNo=0,'',CONCAT('/',A.TokenNo%%100))) AS TokenNoFull, B.IsMainCustomer,B.PoNo FROM
	so_expdet A LEFT JOIN b2b_solar_sc.so_expdet_clubbed_van B ON  A.IdExpDet = B.IdExpDet  WHERE A.IdExpDet=%s";
	$inputArr 	= array($IdExpDet);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}


public function updtExpDetRTGSDetailRemark($IdExpDet, &$alertMsg) {
	if ($_SESSION['IsTradeSector']) {
		$stmt		= 'UPDATE so_expdet SET Remark=CONCAT("%s", "\r\n", TRIM(Remark)) WHERE IdExpDet=%s;';
		$inputArr	= array($alertMsg, $IdExpDet);
		$sql		= vsprintf($stmt,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
		$alertMsg = "Purchase Order No. allocated to you is: $IdExpDet" . '\r\n\r\n' . $alertMsg;
	} else {
		$alertMsg = "Purchase Order No. allocated to you is: $IdExpDet";
	}
}

public function getExpDetMagazine($IdExpDet) {
	//$stmt	= "SELECT A.* FROM so_expdet_magazine A join so_expdet_magazine_item B ON A.UniqueId = B.UniqueIdMagazine WHERE A.IdExpDet=%s";
	$stmt	= "SELECT A.* FROM so_expdet_magazine A WHERE A.IdExpDet=%s";
	$inputArr 	= array($IdExpDet);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}
//======================Clubbed Van PO Case =====================================================

public function getExpDetClubVehicleList($CompanyCd) {
	$sql	= "SELECT Distinct(VehicleNo) as VehicleNo FROM so_expdet where StatusCd IN ('W', 'U', 'A', 'E') and CompanyCd='$CompanyCd' GROUP BY VehicleNo HAVING COUNT(`VehicleNo`) > 1
				UNION  
				SELECT Distinct(VehicleNo) as VehicleNo FROM so_accessory A JOIN so_accessory_item B ON A.IdAccessory = B.IdAccessory JOIN
				so_accessory_ctg_m C ON B.AccessoryCtgCd = C.AccessoryCtgCd
				Where  StatusCd IN ('W', 'U', 'A', 'E')  and C.CompanyCd='$CompanyCd' GROUP BY VehicleNo HAVING COUNT(`VehicleNo`) > 1 ";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getExpDetClubPO($VehicleNo, $CompanyCd) {
	/*$sql	= "SELECT  A.IdExpDet, xf_Proper(REPLACE(IFNULL(B.Descript,''),UPPER(IFNULL(B.City,'')),'')) AS Customer, xf_Proper(IFNULL(B.City,'')) AS City
		,IFNULL(C.Descript,A.StatusCd) AS Status FROM so_expdet A 
		LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd
		LEFT OUTER JOIN so_company_m E ON A.CompanyCd=E.CompanyCd 
		LEFT OUTER JOIN so_status_m C ON A.StatusCd=C.StatusCd where A.StatusCd IN ('W','U', 'A','E') and VehicleNo='$VehicleNo' Order BY A.IdExpdet";
	*/
	$sql = "SELECT  A.IdExpDet as Id, '0' as FromPO, xf_Proper(REPLACE(IFNULL(B.Descript,''),UPPER(IFNULL(B.City,'')),'')) AS Customer, xf_Proper(IFNULL(B.City,'')) AS City
		,IFNULL(C.Descript,A.StatusCd) AS Status FROM so_expdet A 
		LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd
		LEFT OUTER JOIN so_status_m C ON A.StatusCd=C.StatusCd
		where A.StatusCd IN ('W','U', 'A','E') and VehicleNo='$VehicleNo' and A.CompanyCd ='$CompanyCd'
UNION
SELECT  A.IdAccessory as Id, '1' as FromPO, xf_Proper(REPLACE(IFNULL(B.Descript,''),UPPER(IFNULL(B.City,'')),'')) AS Customer, xf_Proper(IFNULL(B.City,'')) AS City
		,IFNULL(C.Descript,A.StatusCd) AS Status FROM so_accessory A 
		LEFT OUTER JOIN so_accessory_item D ON A.IdAccessory=D.IdAccessory
		LEFT OUTER JOIN so_accessory_ctg_m E ON D.AccessoryCtgCd=E.AccessoryCtgCd
		LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd
		LEFT OUTER JOIN so_status_m C ON A.StatusCd=C.StatusCd where A.StatusCd IN ('W','U', 'A','E') and VehicleNo='$VehicleNo' and E.CompanyCd='$CompanyCd' ";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}



public function getClubedVanCustomer($PONo){
	$sql = "SELECT A.Id, A.IdExpDet, C.VehicleNo, D.Capacity, A.IsMainCustomer, A.CustomerCd, IFNULL(B.Descript,A.CustomerCd) AS Customer ,A.IsMainCustomer, A.PoNo, A.ApproveByOwner
	, A.ApproveByAdmin, DATE_FORMAT(A.TransDateTime,'%d-%m-%Y') AS date, C.TotBox, IFNULL(E.ShortDescript,C.StatusCd) AS Status, C.RE11CheckStatus, C.PaymentStatus  FROM so_expdet_clubbed_van A INNER JOIN so_customer_m B 
	ON A.CustomerCd = B.CustomerCd 	INNER JOIN so_expdet C ON A.IdExpDet =C.IdExpDet INNER JOIN so_vehicle_m D ON  C.VehicleNo= D.VehicleNo INNER JOIN so_status_m E ON C.StatusCd= E.StatusCd WHERE PONo ='".$PONo."' and ApproveByOwner IN (0,1) Order By  A.IsMainCustomer DESC";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function acceptClubedVanPOByOwner($IdExpDet,$AcceptValue){
	$sql = " UPDATE so_expdet_clubbed_van SET ApproveByOwner = '".$AcceptValue."', ApproveUserName = '".$_SESSION['UserName']."', ApprovedDateTime = '".date('Y-m-d  H:i:s')."' WHERE IdExpDet = '".$IdExpDet."'";
	$result = $this->execUpdateQuery($sql);
	$rowAffected = $this->objDBQuery->objDBConnect->affected_rows;
	$returnMsg = ($AcceptValue == 1)?"Clubbed van PO is Accepted":"Clubbed van PO is Deny";
	if($rowAffected >0){
		$msg = array("Status" =>"Success","Message"=>$returnMsg);
	}else{
		$msg = array("Status" =>"Error","Message"=>" Error in updating \n Please contact system administrator");
	}
	return $msg;
}


public function getclubedVanData($IdExpDet){
	$sql = "SELECT * FROM so_expdet_clubbed_van WHERE IdExpDet='".$IdExpDet."'";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function checkMainClubedPOExist($value){
	 $sql = " SELECT COUNT(A.IdExpDet) AS Total  FROM so_expdet_clubbed_van A JOIN so_expdet B ON A.IdExpdet = B.IdExpdet WHERE A.IdExpDet = '".$value."' AND A.IsMainCustomer='1' AND  B.StatusCd IN ('U', 'W', 'A')";
	$result = $this->execSelectQuery($sql);
	if($result[0]['Total'] <= 0){
		$msg = array("Status"=>"Error","Message"=>"This Customer PO not created ! Please try another");
		return $msg;
	}else{
		return true;
	}
	
}

public function insertClubedVanPOQuery(){
	$sql = "INSERT INTO so_expdet_clubbed_van(IdExpDet, CustomerCd, IsMainCustomer, PoNo, TransUserName) VALUES ('%s','%s','%s','%s','%s')";
	return $sql;
}

public function insertClubedVanPO($data){
	$queryInsert = $this->insertClubedVanPOQuery();
	if($data['ClubedVanCustomerType'] == 1){
		$data['CustomerPONo'] = $data['IdExpDet'];
	}
	$inputArr = array($data['IdExpDet'],$data['CustomerCd'],$data['ClubedVanCustomerType'],$data['CustomerPONo'],$_SESSION['UserName']);
	$sql = vsprintf($queryInsert,$inputArr);
	$returnData = $this->execUpdateQuery($sql);
}


public function updateClubedVanPO($data){
	$queryCheck = "SELECT * FROM so_expdet_clubbed_van WHERE IdExpDet='".$data['oldIdExpDet']."'";
	$result =$this->execSelectQuery($queryCheck);
	if(count($result)<=0){
		$queryInsert = $this->insertClubedVanPOQuery();
		if($data['ClubedVanCustomerType'] == 1){
		$data['CustomerPONo'] = $data['oldIdExpDet'];
	}
		$inputArr = array($data['oldIdExpDet'],$data['CustomerCd'],$data['ClubedVanCustomerType'],$data['CustomerPONo'],$_SESSION['UserName']);
		$sql = vsprintf($queryInsert,$inputArr);
		$returnData = $this->execUpdateQuery($sql);
	}else{
		if($data['ClubedVanCustomerType'] == 1){
			$data['CustomerPONo'] = $data['oldIdExpDet'];
		}
		$sql = "UPDATE so_expdet_clubbed_van SET IsMainCustomer = '".$data['ClubedVanCustomerType']."',  PoNo= '".$data['CustomerPONo']."' WHERE IdExpDet ='".$data['oldIdExpDet']."'";
		$returnData = $this->execUpdateQuery($sql);
	}
}



public function checkMainCustomerVehicle($VehicleNo, $IdExpdet){
	$CustomerCd = $_SESSION['CustomerCd'];
	$sql = " SELECT A.* FROM so_expdet A INNER JOIN so_expdet_clubbed_van B  ON A.IdExpDet = B.IdExpDet WHERE A.CustomerCd ='".$CustomerCd."' AND VehicleNo = '".$VehicleNo."' AND B.IsMainCustomer = 1 AND A.IsClubedPO = 1 AND A.StatusCd IN ('U','W')";
	$result = $this->execSelectQuery($sql);
	if(count($result)<=0){
		$msg = array("Status"=>"Success","Message"=>"");
	}else{
		$msg = array("Status"=>"Error","Message"=>"This Vehicle is Already Serviced");
	} 
	return $msg;
}


public function clubedVanFinalAprove($Id){
	$sql = " SELECT * FROM so_expdet_clubbed_van WHERE PONO = (SELECT PONo FROM so_expdet_clubbed_van WHERE Id = '".$Id."') and ApproveByOwner!= '2'";
	$result = $this->execSelectQuery($sql);
	$approveDocList= '';
	foreach($result as $value){
		$approveDocList .= $value['IdExpDet'].",";
	}
	$approveDocList = rtrim($approveDocList, ",");
	$query = " SELECT * FROM so_expdet WHERE IdExpdet IN ($approveDocList) AND StatusCd ='A' and TokenNoPrefix = ''";
	$result1 = $this->execSelectQuery($query);
	 if(count($result)==1){
		$msg = array("Status"=>"Error","Message"=>"Missing Sub PO Details, Can't Allocate Token No");
	}
	else if(count($result1) == count($result)){
		$msg = array("Status"=>"Success","Message"=>" Clubbed Van PO is Approved");
			
			$stmt	= "SELECT MAX(TokenNo) as TokenNo FROM so_expdet";
			$returnData	= $this->execSelectQuery($stmt);
			
			$TokenNo = $returnData[0]['TokenNo']+1;
			$TokenNoPrefix ='CLB';
			
			$stmt		= "UPDATE so_expdet SET TokenNoPrefix='%s', TokenNo='%s' WHERE IdExpDet IN (%s)";
			$inputArr 	= array($TokenNoPrefix, $TokenNo, $approveDocList);
			$sql		= vsprintf($stmt,$inputArr);
			$this->execUpdateQuery($sql);
			if ($_SESSION['IsTradeSector']) {
				//$emailBody = $this->sendEMailPOAccessApproval($approveDocList, 2);
			}
				/*$stmt="SELECT A.IdExpDet, CONCAT(TRIM(A.TokenNoPrefix),IF(A.TokenNo=0,'',CONCAT('/',A.TokenNo%%100))) AS TokenNoFull FROM so_expdet A WHERE A.IdExpDet IN (%s)";	
				$inputArr 	= array($approveDocList);
				$sql		= vsprintf($stmt,$inputArr);
				$TokenNoAr = $this->execSelectQuery($sql);
				*/
		
	}else{
		$msg = array("Status"=>"Error","Message"=>"All accepted Clubbed Van PO is not Approved OR Token no is already Allocated ");
	}
	return $msg;
}


//===================== End of Clubbed Van PO =======================================================//
//==================================Customer UTR No Update
public function UpdatePOUTR($IdExpDet,$List){
		$stmt = " UPDATE so_expdet SET UTR = '%s' WHERE IdExpDet = '%s'";
		$inputArr = array($List,$IdExpDet);
		$sql = vsprintf($stmt,$inputArr);
		$returnData = $this->execUpdateQuery($sql);
		$arrUTR = explode(",", $List);
		$msg='';
		for( $i=0; $i<count($arrUTR); $i++){
			$UTR = $arrUTR[$i];
			
			$stmt = "select CNN_NO as CNNNO, REMITTER_CODE as RemitterCode, REMITTER_NAME as RemitterName, Id as Id, VALUE_DATE as ValueDate   from so_expdet_customer_bank_payment where UTR ='%s'  and Flag !='1'";
			$inputArr = array(trim($UTR),$IdExpDet);
			$sql = vsprintf($stmt,$inputArr);
			$returnData1 = $this->execSelectQuery($sql);
			if(count($returnData1) > 0){
				$returnData1[0]['CNNNO'] ='CNN'.$IdExpDet;
				$returnData2 = $this->updateCustomerBankPayment($returnData1[0]);
				//print_r($returnData2);
			}
		}
		if($returnData){
			$msg = array("Status"=>"Error","Message"=>"Error in  Updating UTR");
		}
		else{
			$msg = array("Status"=>"Success","Message"=>"UTR Updated Successfully");
		}
		return $msg;
}



public function checkUTRCondition($UTRvalue,$IdExpDet){
	$msg 		= '';
	$query1 	= " SELECT * FROM so_expdet WHERE UTR REGEXP '^{$UTRvalue}[,]|[,]{$UTRvalue}[,]|[,]{$UTRvalue}$|^{$UTRvalue}$' AND UTR<>'' AND IdExpDet <> '".$IdExpDet."'";
	$result1 	= $this->execSelectQuery($query1);
	if(count($result1)>0){
		$msg = array('Status'=>'3');
	}else{
		$query 		= " SELECT CustomerCd FROM so_expdet WHERE IdExpDet = '".$IdExpDet."'";
		$result 	= $this->execSelectQuery($query);
		$customerCd = $result[0]['CustomerCd'];
		$sql 		= " SELECT * FROM so_expdet_customer_bank_payment WHERE (CNN_NO = CONCAT('CNN',$IdExpDet)  OR REMITTER_CODE = CONCAT('$customerCd','CNN','$IdExpDet'))";  
		$returnData	= $this->execSelectQuery($sql);
		if(!empty($returnData)){
			$utr = array();
			foreach($returnData as $key=>$value){
				array_push($utr,$value['UTR']);
			}
			if(!in_array($UTRvalue,$utr)){
				$msg = array('Status'=>'2');
			}
		}
	}
	return $msg;
}

public function getUTRFromExpDet($IdExpDet){
	$sql 		= "SELECT UTR FROM so_expdet WHERE IdExpDet = '".$IdExpDet."'";
	$returnData =  $this->execSelectQuery($sql);
	return  $returnData;
}
//=======================End of Customer UTR No===========================


/*********************** Update backup table so_expdet_backup **************************************/
function POLastViewedBY($IdExpDet){
	$sql 		= "SELECT CustomerCd FROM so_expdet WHERE IdExpDet=".$IdExpDet;
	$returnData	= $this->execSelectQuery($sql);
	$CustomerCd = $returnData[0]['CustomerCd'];
	$TransUserName	= $_SESSION['UserName'] ;
	$curdatetime= date('Y-m-d H:i:s');
	$sql 	 	= "INSERT INTO so_po_view (CustomerCd,IdExpDet,TransUserName,TransDateTime) values (".$CustomerCd.",".$IdExpDet.",'".$TransUserName."','".$curdatetime."')";
	$returnData	= $this->execUpdateQuery($sql);
}
function insertExpDetBackup($IdExpDet){
	$sql 	 	= "INSERT INTO so_expdet_backup SELECT NULL, so_expdet.* FROM so_expdet WHERE IdExpDet = ".$IdExpDet; 
	$returnData	= $this->execUpdateQuery($sql);
	$lastInsertTranNo	= $this->getInsertId();
}

function insertExpDetMagzinBackup($IdExpDet,$lastExpDetBackupId){
	$sql 	 	= "INSERT INTO so_expdet_magazine_backup ( ExpdetMagzinBackupId,	ExpDetBackupId,UniqueId,IdExpDet,MagazineCd,ItemCtgCd,RE11No,RE11PDF ,	RE11Date ,	RE11ExpiredMail,RemoveRe11Pdf,TotAmt,SAPPONo,SAPSONo,SAPSODate,SAPInvNo,SAPInvDate,SAPTotInvAmt) 
	SELECT NULL,".$lastExpDetBackupId.", UniqueId,IdExpDet,MagazineCd,ItemCtgCd,RE11No,RE11PDF ,	RE11Date ,	RE11ExpiredMail,RemoveRe11Pdf,TotAmt,SAPPONo,SAPSONo,SAPSODate,SAPInvNo,SAPInvDate,SAPTotInvAmt FROM so_expdet_magazine WHERE IdExpDet = ".$IdExpDet; 
	$returnData	= $this->execUpdateQuery($sql);
	$lastInsertTranNo	= $this->getInsertId();
}

function insertExpDetMagzinItemBackup($IdExpDet,$lastExpDetMagzineBackupId){
	$sql 	 	= "INSERT INTO so_expdet_magazine_item_backup ( ExpDetMagzinItemBackupId,ExpdetMagzinBackupId,UniqueId,UniqueIdMagazine,IdExpDet ,MagazineCd,ItemCd ,OrderBox,OrderQty ,RE11Qty,BasicRate,Rate,Amount,SAPInvAmount,DespatchedBox,DespatchedQty ) 
	SELECT NULL,".$lastExpDetMagzineBackupId.",UniqueId,UniqueIdMagazine,IdExpDet,MagazineCd,ItemCd ,OrderBox ,OrderQty,RE11Qty,BasicRate,Rate,Amount,SAPInvAmount,DespatchedBox,DespatchedQty FROM so_expdet_magazine_item WHERE IdExpDet = ".$IdExpDet; 
	$returnData	= $this->execUpdateQuery($sql);
}

function POTracking(){
	$sql = "SELECT A.*,B.ExpDetBackupId FROM so_po_view A INNER JOIN so_expdet B  ON A.IdExpDet = B.IdExpDet 
	ORDER BY A.TransDateTime DESC";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}
/*********************** End Update backup table so_expdet_backup *********************************/

/////==================================  PO Item Promotion  =====================    

public function getCustomerItem($CustomerCd) {
	$stmt	= "SELECT A.ItemCd, B.Descript AS ItemDes   FROM so_customer_m_item_rate_type A join so_item_m B ON A.ItemCd = B.ItemCd WHERE A.CustomerCd='%s'";
	$inputArr 	= array($CustomerCd);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getPOPromoQuantityList(){
	$searchCnd	= (isset($search)) ? " WHERE B.Descript like '". $search . "%'" : " WHERE 1=1";
	$searchCnd	.= ($_SESSION['IsCustomer']) ? " AND A.CustomerCd='" .$_SESSION['CustomerCd']. "'" : "";
	$sql	= "SELECT A.CustomerCd, IFNULL(B.Descript,A.CustomerCd) AS Customer,A.CustVehicleCapacity, DATE_FORMAT(A.StartDate,'%d-%m-%Y') AS StartDate,DATE_FORMAT(A.EndDate,'%d-%m-%Y') AS EndDate FROM so_customer_po_promoqty A 
	LEFT OUTER JOIN so_customer_m B 
	ON A.CustomerCd=B.CustomerCd 
	GROUP BY A.CustVehicleCapacity,A.CustomerCd order by A.CustomerCd " ;
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function isExistPOPromoRestriction($CustomerCd){
	$sql = "SELECT PromoGroupId FROM so_customer_po_promoqty WHERE CustomerCd = '".$CustomerCd."'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
	
}

public function isExistPOPromoItemRestrict($data){
		 $sql = "SELECT * FROM so_customer_po_promoqty WHERE CustomerCd = '".$data['CustomerCdInput']."' AND CustVehicleCapacity = '".$data['vehicleCapacity']."' ";
		$queryResult	= $this->execSelectQuery($sql);
		$rowCount		= count($queryResult);
		return $rowCount;
}

public function insertPOPromoItemRestrictQuery() {
	$sql	= "INSERT INTO so_customer_po_promoqty(PromoGroupId,CustomerCd,CustVehicleCapacity, ItemCd, StartDate, EndDate, Quantity, IsBaseItem, IsCompulsoryItem) 
				VALUES ('%s', '%s', '%s', '%s', '%s', '%s','%s', '%s', '%s')";
	return $sql ;
}

public function updatePOPromoItemRestrictQuery(){
	$sql	= "UPDATE so_customer_po_promoqty SET  StartDate='%s',EndDate='%s', Quantity = '%s', IsBaseItem='%s', IsCompulsoryItem='%s' WHERE CustomerCd='%s' AND ItemCd = '%s' AND CustVehicleCapacity='%s'";
	return $sql ;
}

public function deletePOPromoItemRestrictQuery() {
	$sql	= "DELETE FROM so_customer_po_promoqty WHERE CustomerCd='%s'  AND ItemCd='%s' AND CustVehicleCapacity='%s'";
	return $sql ;
}

public function insertPOPromoItemRestrict($data){
	$queryInsert	= $this->insertPOPromoItemRestrictQuery();
	$returnData		= '';

	$CustomerCd	= $data['CustomerCdInput'];
	$vehicleCapacity = $data['vehicleCapacity'];
	
	for($curRowNo=1; $curRowNo<=$data['LastRowNo1']; $curRowNo++) {
		if (!isset($data['BaseQuantityItemCd_'.$curRowNo])) continue;
		$PromoGroupId           = 1;
		$ItemCd				= $data['BaseQuantityItemCd_'.$curRowNo];
		$StartDate			= $this->convertDate($data['BaseQuantitySD_'.$curRowNo],TRUE,1);
		$EndDate			= $this->convertDate($data['BaseQuantityED_'.$curRowNo],TRUE,1);;
		$BaseQuantity		= $data['BaseQuantity_'.$curRowNo];
		$IsCheck			= isset($data['BaseQuantityCheck_'.$curRowNo]) ? 1 : 0;
		$IsCompulsoryItem   = isset($data['BaseQuantityCompItem_'.$curRowNo]) ? 1 : 0;
		if (trim($ItemCd)=='' || ($BaseQuantity<=0 )) {
			continue;
		}	
		$inputArr	= array();
		$inputArr	= array($PromoGroupId,$CustomerCd,$vehicleCapacity, $ItemCd, $StartDate,$EndDate,$BaseQuantity,$IsCheck,$IsCompulsoryItem);
		$sql		= vsprintf($queryInsert,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
		if ($returnData) return $returnData;
	}
return $returnData;
	
}

public function getPOPromoQuantityHeader($CustomerCd,$vehicleCapacity) {
	$sql = "SELECT A2.CustomerCd, A2.PromoGroupId, A2.CustVehicleCapacity, B2.ItemCd,IFNULL(B2.Descript,A2.ItemCd)AS ItemDes
		, IFNULL(DATE_FORMAT(A2.StartDate, '%d-%m-%Y'), '') AS StartDate, IFNULL(DATE_FORMAT(A2.EndDate, '%d-%m-%Y'), '') AS EndDate
		, IFNULL(A2.Quantity, '') AS Quantity, IFNULL(A2.IsBaseItem, '') AS IsBaseItem, IFNULL(A2.IsCompulsoryItem, '') AS IsCompulsoryItem
		FROM
			(SELECT B.CustomerCd, B.PromoGroupId, B.CustVehicleCapacity, A.ItemCd, B.StartDate, B.EndDate, B.Quantity, B.IsBaseItem
			, B.IsCompulsoryItem 
			FROM 
				(SELECT ItemCd FROM so_customer_m_item_rate_type WHERE CustomerCd='".$CustomerCd."') A
			LEFT JOIN 
			( SELECT CustomerCd, PromoGroupId, CustVehicleCapacity, ItemCd, StartDate, EndDate, Quantity, IsBaseItem, IsCompulsoryItem 
			FROM so_customer_po_promoqty  WHERE CustomerCd='".$CustomerCd."' AND `CustVehicleCapacity` = '".$vehicleCapacity."' 
			) B 
		ON A.ItemCd = B.ItemCd)A2 
		JOIN so_item_m B2 ON A2.ItemCd = B2.ItemCd Order By A2.CustVehicleCapacity DESC "; 
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function updatePOPromoItemRestrict($data){
	$queryInsert		= $this->insertPOPromoItemRestrictQuery();
	$queryUpdate		= $this->updatePOPromoItemRestrictQuery();
	$queryDelete		= $this->deletePOPromoItemRestrictQuery();
	$CustomerCd			= $data['CustomerCd'];
	$vehicleCapacity	= $data['vehicleCapacity'];
	for($curRowNo=1; $curRowNo<=$data['LastRowNo1']; $curRowNo++) {
		$PromoGroupId       = 1;
		$ItemCd      		= $data['BaseQuantityItemCd_'.$curRowNo];
		$StartDate			= $this->convertDate($data['BaseQuantitySD_'.$curRowNo],TRUE,1);
		$EndDate			= $this->convertDate($data['BaseQuantityED_'.$curRowNo],TRUE,1);;
		$BaseQuantity		= $data['BaseQuantity_'.$curRowNo];
		$IsBaseQty      	= isset($data['BaseQuantityCheck_'.$curRowNo]) ? 1 : 0;
		$IsCompulsoryItem   = isset($data['BaseQuantityCompItem_'.$curRowNo]) ? 1 : 0;
		$IsCheck			= isset($data['BaseQuantityCheck_'.$curRowNo]) ? 1 : 0;	
		if (trim($ItemCd)=='' || ($BaseQuantity<=0 )) {
			$inputArr	= array();
			$inputArr	= array($CustomerCd, $ItemCd,$vehicleCapacity);
			$sql		= vsprintf($queryDelete, $inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		}else{
		 $queryCheck	= "SELECT COUNT(*) AS Total FROM so_customer_po_promoqty WHERE CustomerCd='%s' AND ItemCd='%s'  AND CustVehicleCapacity='%s' ";
				$inputArr	= array();
				$inputArr	= array($CustomerCd,$ItemCd,$vehicleCapacity);
			 	$sql		= vsprintf($queryCheck,$inputArr);
				$returnData	= $this->execSelectQuery($sql);
				if ($returnData[0]['Total']==0) {
					$inputArr	= array();
					$inputArr	= array($PromoGroupId,$CustomerCd,$vehicleCapacity, $ItemCd, $StartDate,$EndDate,$BaseQuantity,$IsCheck,$IsCompulsoryItem);
				 	$sql		= vsprintf($queryInsert,$inputArr);
					$returnData	= $this->execUpdateQuery($sql);
				} else {
					$inputArr	= array();
					$inputArr	= array( $StartDate,$EndDate,$BaseQuantity,$IsBaseQty,$IsCompulsoryItem,$CustomerCd,$ItemCd,$vehicleCapacity);
					$sql		= vsprintf($queryUpdate,$inputArr);
					$returnData	= $this->execUpdateQuery($sql);
				}
				if ($returnData) return $returnData;
		}
	}
	return $returnData;
}



//============================================end PO Item Promotion ===================

////====================== Multi PO promo ============================

public function getCustomerMultiPoRestrictionList(){
	$promo = $this->checkMultiPOPromoExpiry();
	$searchCnd	= (isset($search)) ? " WHERE B.Descript like '". $search . "%'" : " WHERE 1=1";
	$searchCnd	.= ($_SESSION['IsCustomer']) ? " AND A.CustomerCd='" .$_SESSION['CustomerCd']. "'" : "";

	$sql	= "SELECT A.CustomerCd, IFNULL(B.Descript,A.CustomerCd) AS Customer, A.VehicleCapacity,DATE_FORMAT(A.StartDate,'%d-%m-%Y') AS StartDate,DATE_FORMAT(A.EndDate,'%d-%m-%Y') AS EndDate FROM so_customer_multi_po_restriction A 
	LEFT OUTER JOIN so_customer_m B 
	ON A.CustomerCd=B.CustomerCd WHERE A.IsActive = '0' GROUP BY A.VehicleCapacity,A.CustomerCd order by A.CustomerCd " ;
		
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function isExistCustomerMultiPoRestriction($data){
	$sql = "SELECT * FROM so_customer_multi_po_restriction WHERE CustomerCd = '".$data['CustomerCdInput']."' AND  IsActive = '0' ";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
	
}

public function insertCustomerMultiPoRestrictionQuery() {
	$sql	= "INSERT INTO so_customer_multi_po_restriction(MultiPoRestId,CustomerCd,VehicleCapacity,ItemCd,StartDate,EndDate,
	MultiPoQty,RemainingQty, IsBaseProduct,IsCompulsoryProduct,IsActive) VALUES ('%s', '%s','%s', '%s', '%s', '%s', '%s','%s', '%s', '%s', '%s')";
	return $sql ;
}

public function multiPOId($CustomerCd,$vehicleCapacity){
	$query = "SELECT MultiPORestId FROM so_customer_multi_po_restriction WHERE CustomerCd = '".$CustomerCd."' AND vehicleCapacity='".$vehicleCapacity."' AND IsActive='1'  ORDER BY MultiPORestId DESC LIMIT 1  ";
	$returnData = $this->execSelectQuery($query);
	return $returnData;
	
}

public function insertCustomerMultiPoRestriction($data){
	$queryInsert	= $this->insertCustomerMultiPoRestrictionQuery();
	$returnData		= '';
	$CustomerCd	= $data['CustomerCdInput'];
	$vehicleCapacity = $data['vehicleCapacity'];
	$ID = array();
	$ID  = $this->multiPOId($CustomerCd,$vehicleCapacity);
	if(!isset($ID[0] )){
			$MultiPoRestId  = 1;
		}else{
			$MultiPoRestId      = $ID[0]['MultiPORestId'] + 1 ;
		}
	for($curRowNo=1; $curRowNo<=$data['LastRowNo1']; $curRowNo++) {
		if (!isset($data['MultiPOItemCd_'.$curRowNo])) continue;
		
		$ItemCd				= $data['MultiPOItemCd_'.$curRowNo];
		$StartDate			= $this->convertDate($data['MultiPOSD_'.$curRowNo],TRUE,1);
		$EndDate			= $this->convertDate($data['MultiPOED_'.$curRowNo],TRUE,1);
		$MultiPOBaseItem 	= isset($data['MultiPOBaseItem_'.$curRowNo]) ? 1 : 0;
		$MultiPONoAllow		= $data['MultiPONoAllow_'.$curRowNo];
		$MultiPONoRemains 	= $data['MultiPONoRemains_'.$curRowNo];
		$MultiPONoQty		= $data['MultiPONoQty_'.$curRowNo];
		$MultiPORemainsQty	= $data['MultiPONoQty_'.$curRowNo];
		$MultiPODeliverQty	= $data['MultiPODeliverQty_'.$curRowNo];
		$MultiPOCompulsoryItem = isset($data['MultiPOCompulsoryItem_'.$curRowNo]) ? 1 : 0;
		$IsActive			= 0;
		$RestrictionFlag	= 0;
		if (trim($ItemCd)=='' || ($MultiPONoQty<=0 ) && ($MultiPOCompulsoryItem == 0)) {
			continue;
		}	
		$inputArr	= array();
	
		$inputArr	= array($MultiPoRestId,$CustomerCd,$vehicleCapacity, $ItemCd, $StartDate,$EndDate,$MultiPONoQty,$MultiPORemainsQty,$MultiPOBaseItem,$MultiPOCompulsoryItem,$IsActive);
		$sql		= vsprintf($queryInsert,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
		if ($returnData) return $returnData;
	}
return $returnData;
	
}

public function getCustomerMultiPoResrtictionHeader($CustomerCd,$vehCap) {
	$sql = "SELECT A.CustomerCd, A.MultiPoRestId, A.VehicleCapacity,  A.ItemCd,IFNULL(B.Descript,A.ItemCd) AS ItemDes
				, IFNULL(DATE_FORMAT(A.StartDate, '%d-%m-%Y'), '') AS StartDate, IFNULL(DATE_FORMAT(A.EndDate, '%d-%m-%Y'), '') AS EndDate
				, IFNULL(A.MaxPoAllow,'') AS MaxPoAllow,	IFNULL(A.RemainsPO,'') AS RemainsPO , IFNULL(A.MultiPOQty,'') AS MultiPOQty
				,IFNULL(A.IsBaseProduct,'') AS  IsBaseProduct,A.IsCompulsoryProduct,A.IsActive,A.RemainingQty, A.DeliverQty
				FROM
					(SELECT A2.ItemCd,B2.CustomerCd, B2.MultiPoRestId, B2.VehicleCapacity,  B2.StartDate, B2.EndDate,B2.MaxPoAllow, B2.RemainsPO,B2.MultiPOQty,B2.IsBaseProduct,B2.IsCompulsoryProduct,B2.IsActive,B2.RemainingQty, B2.DeliverQty 
					FROM
						(SELECT ItemCd
						FROM so_customer_m_item_rate_type 
						WHERE CustomerCd='".$CustomerCd."' 
						)A2
					LEFT JOIN
						(SELECT B.CustomerCd, B.MultiPoRestId, VehicleCapacity,ItemCd,StartDate, EndDate,MaxPoAllow, RemainsPO,MultiPOQty,IsBaseProduct,IsCompulsoryProduct,IsActive,RemainingQty, DeliverQty
						FROM so_customer_multi_po_restriction B
						WHERE B.CustomerCd='".$CustomerCd."' AND VehicleCapacity = '".$vehCap."' AND IsActive='0'
						)B2
					ON A2.ItemCd = B2.ItemCd 
					)A	
				JOIN 
				so_item_m B ON A.ItemCd = B.ItemCd"; 
	$returnData	= $this->execSelectQuery($sql);
	return $returnData; 
}


public function updateCustomerMultiPoRestrictionQuery(){
	$sql	= "UPDATE so_customer_multi_po_restriction SET VehicleCapacity = '%s', StartDate = '%s', EndDate = '%s', MultiPoQty = '%s',RemainingQty = '%s', IsBaseProduct = '%s', 	IsCompulsoryProduct = '%s',IsActive = '%s'  WHERE CustomerCd='%s' AND ItemCd = '%s' and MultiPoRestId='%s'";
	return $sql ;
}

public function deleteCustomerMultiPoRestrictionQuery() {
	$sql	= "DELETE FROM so_customer_multi_po_restriction WHERE CustomerCd='%s'  AND ItemCd='%s' and MultiPoRestId='%s'";
	return $sql ;
}

public function updateCustomerMultiPoRestriction($data){
	//print_r($data);
	//exit();
	$queryInsert		= $this->insertCustomerMultiPoRestrictionQuery();
	$queryUpdate		= $this->updateCustomerMultiPoRestrictionQuery();
	$queryDelete		= $this->deleteCustomerMultiPoRestrictionQuery();

	$CustomerCd			= $data['CustomerCd'];
	$vehicleCapacity	= $data['vehicleCapacity'];
	
	for($curRowNo=1; $curRowNo<=$data['LastRowNo1']; $curRowNo++) {
		$IsActive           = isset($data['Isactive']) ? $data['Isactive'] : 0;
		$MultiPoRestId      = $data['MultiPoRestId_'.$curRowNo];
		$ItemCd				= $data['MultiPOItemCd_'.$curRowNo];
		$StartDate			= $this->convertDate($data['MultiPOSD_'.$curRowNo],TRUE,1);
		$EndDate			= $this->convertDate($data['MultiPOED_'.$curRowNo],TRUE,1);
		$MultiPOBaseItem 	= isset($data['MultiPOBaseItem_'.$curRowNo]) ? 1 : 0;
	//	$MultiPONoAllow		= $data['MultiPONoAllow_'.$curRowNo];  
	//	$MultiPONoRemains 	= $data['MultiPONoRemains_'.$curRowNo]; 
		$MultiPONoQty		= $data['MultiPONoQty_'.$curRowNo];
		$MultiPORemainsQty	= $data['MultiPONoQty_'.$curRowNo];
		$MultiPOCompulsoryItem = isset($data['MultiPOCompulsoryItem_'.$curRowNo]) ? 1 : 0;
		$RestrictionFlag	= 0;
		if (trim($ItemCd)=='' || ($MultiPONoQty<=0 )  && ($MultiPOCompulsoryItem == 0)) {
			
			$inputArr	= array();
			$inputArr	= array($CustomerCd, $ItemCd, $MultiPoRestId);
			$sql		= vsprintf($queryDelete, $inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		}else{
		 $queryCheck	= "SELECT COUNT(*) AS Total FROM so_customer_multi_po_restriction WHERE CustomerCd='%s' AND ItemCd='%s' and MultiPoRestId='%s' ";
				$inputArr	= array();
				$inputArr	= array($CustomerCd,$ItemCd, $MultiPoRestId);
			 	$sql		= vsprintf($queryCheck,$inputArr);
				$returnData	= $this->execSelectQuery($sql);
				if ($returnData[0]['Total']==0) {
					$inputArr	= array();
					$inputArr	= array($MultiPoRestId,$CustomerCd,$vehicleCapacity, $ItemCd, $StartDate,$EndDate,$MultiPONoQty, $MultiPORemainsQty,$MultiPOBaseItem,$MultiPOCompulsoryItem,$IsActive);
				 	$sql		= vsprintf($queryInsert,$inputArr);
					$returnData	= $this->execUpdateQuery($sql);
				} else {
					$inputArr	= array();
					$inputArr	= array($vehicleCapacity,  $StartDate,$EndDate,$MultiPONoQty,$MultiPORemainsQty,$MultiPOBaseItem,$MultiPOCompulsoryItem,$IsActive,$CustomerCd,$ItemCd,$MultiPoRestId);
					$sql		= vsprintf($queryUpdate,$inputArr);
					
					$returnData	= $this->execUpdateQuery($sql);
				}
				if ($returnData) return $returnData;
		}
	}
	return $returnData;
}


public function checkMultiPOPromoExpiry(){
	$sql = "SELECT B.IdExpDet,A.CustomerCd,A.MultiPoRestId FROM 
			(SELECT CustomerCd,MultiPoRestId FROM so_customer_multi_po_restriction  
				WHERE IsActive = '0'
				GROUP BY CustomerCd , MultiPoRestId 
				HAVING SUM(RemainingQty) = 0
			)A
			INNER JOIN   so_expdet B 
			ON A.CustomerCd = B.CustomerCd
			WHERE B.StatusCd ='A' ";
	$returnData	= $this->execSelectQuery($sql);
	
	if(is_array($returnData)){
		foreach($returnData as $key => $value){
			$MultiPoRestId 	= 	(int) $value['MultiPoRestId'];
			$IdExpDet 		= 	$value['IdExpDet'] ;
			$CustomerCd 	=  	$value['CustomerCd'] ;
			
			$query  = "SELECT * FROM so_customer_multi_po_restriction_trans WHERE   MultiPoRestId = '".$MultiPoRestId."' AND IdExpDet = '".$IdExpDet."' AND CustomerCd = '".$CustomerCd."'";
			$queryResult	= $this->execSelectQuery($query);
			$rowCount		= count($queryResult);
			
			if($rowCount == 0){
				$sql = "INSERT INTO so_customer_multi_po_restriction_trans (MultiPoRestId, IdExpDet,CustomerCd) values ('$MultiPoRestId ', '$IdExpDet', '$CustomerCd')";
				$result	= $this->execUpdateQuery($sql);
			}
		}
	}

}

/// =-=========================================End of Multi PO PromoGroupId===================
//================================ Dealer Subdealer  AED Allocation ========================
public function getDealerSubdealerAEDAllocationList(){
	$searchCnd	 = (isset($search)) ? " WHERE B.Descript like '". $search . "%'" : " WHERE 1=1";
	$searchCnd	.= ($_SESSION['IsCustomer']) ? " AND A.CustomerCd='" .$_SESSION['CustomerCd']. "'" : "";

	$sql	= "SELECT A.AEDAllotment_Id, A.CustomerCd,A.Year,A.Month AS Month, IFNULL(B.Descript,A.CustomerCd) AS Customer,A.TransUserName,A.TransDateTime FROM so_aedallotment_dealer A LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd GROUP BY A.AEDAllotment_Id, A.Year,A.Month,A.CustomerCd order by A.CustomerCd DESC" ;
		
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
	//print_r($returnData);
}



public function getDealerSubdealerDetails($CustomerCd) {
	$searchCnd = " WHERE A.CustomerCd='$CustomerCd' ";
	$sql		= "SELECT A.*, B.Descript AS SubdealerName, B.EMailId AS SubdealerEmail, B.TelNo AS SubdealerTelNo, C.Descript AS DealerName
	, C.EMailId AS DealerEmail, C.TelNo AS DealerTelNo, C.City AS DealerCity 
	FROM so_subdealer_m_dealer A LEFT OUTER JOIN so_subdealer_m B ON A.IdSubdealer=B.IdSubdealer LEFT OUTER JOIN so_customer_m C ON A.CustomerCd = C.CustomerCd " . $searchCnd . " ORDER BY B.Descript";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}


public function getDealerSubdealerReserveStock($CustomerCd) {
	$sql		= "SELECT A.* FROM so_aedallotment_dealer A where CustomerCd ='$CustomerCd' ORDER BY `AEDAllotment_Id` DESC Limit 1";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function isExistDealerSubdealerAEDAllocation($data){
	$CurDate = date('Y-m-d');
	$DFY  =  $this->convertDate($CurDate , TRUE,1);
	$Year = $this->getTargetYear($DFY);
	 $sql = "SELECT * FROM so_aedallotment_dealer WHERE CustomerCd = '".$data['CustomerCdInput']."' AND	Year = '".$Year."' AND Month = '".$data['MonthInput']."'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function getDealerSubdealerAEDAllocation($CustomerCd, $Year, $Month, $AEDAllotment_Id ){
	$sql = "SELECT A.*, B.*, C.Descript as subdealer_Name, D.Descript as Dealer_Name FROM so_aedallotment_dealer A 
	JOIN so_aedallotment_subdealer B ON A.AEDAllotment_Id = B.AEDAllotment_Id JOIN so_subdealer_m C ON B.SubdealerCd = C.IdSubdealer
	JOIN so_customer_m D ON A.CustomerCd = D.CustomerCd WHERE A.CustomerCd = '".$CustomerCd."' AND A.Year ='".$Year."' AND A.Month = '".$Month."' AND A.AEDAllotment_Id = '".$AEDAllotment_Id."'";
	$resultData	= $this->execSelectQuery($sql);
	return $resultData;
}


public function insertDealerAEDAllocationQuery() {
	$sql	= "INSERT INTO so_aedallotment_dealer (Year, Month, Date, CustomerCd, CustomerEmailId,CustomerMobileNo
	,Customer_SupremeAED15_Date, Customer_SupremeAED15_Qty, Customer_SupremeAED15US_Date, Customer_SupremeAED15US_Qty, Customer_SupremeAED18_Date
	, Customer_SupremeAED18_Qty, Customer_SupremeAED30_Date, Customer_SupremeAED30_Qty, Customer_SolarAED15_Date, Customer_SolarAED15_Qty
	, Customer_SolarAED18_Date, Customer_SolarAED18_Qty, Customer_SolarAED30_Date, Customer_SolarAED30_Qty, Customer_SupremeAED15_ReserveQty_open
	, Customer_SupremeAED15US_ReserveQty_open, Customer_SupremeAED18_ReserveQty_open, Customer_SupremeAED30_ReserveQty_open
	, Customer_SolarAED15_ReserveQty_open, Customer_SolarAED18_ReserveQty_open, Customer_SolarAED30_ReserveQty_open, TransUserName )  
	VALUES ('%s', '%s','%s', '%s','%s', '%s','%s', '%s', '%s','%s', '%s', '%s', '%s', '%s', '%s','%s', '%s',  '%s', '%s' , '%s', '%s', '%s', '%s', '%s', '%s'
	, '%s', '%s', '%s')";
	return $sql ;	
}

public function insertDealerAEDAllocation($data){
	$sql='';
	$queryInsert					= $this->insertDealerAEDAllocationQuery();
	$returnData						= '';
	$Year							= $data['Year'];
	$MonthInput						= $data['MonthInput'];
	$date 							= $this->convertDate($data['curDate'],TRUE,1); 
	$CustomerCd						= $data['CustomerCdInput'];
	$Customer_Name					= $data['Customer_Name'];
	$Customer_Email					= $data['Customer_Email'];
	$Customer_MobileNo				= $data['Customer_MobileNo'];
	$Customer_SupremeAED15_Date		= $this->convertDate($data['Customer_SupremeAED15_Date'], TRUE, 1); 
	$Customer_SupremeAED15_Qty		= $data['Customer_SupremeAED15_Qty']; 
	$Customer_SupremeAED15US_Date	= $this->convertDate($data['Customer_SupremeAED15US_Date'], TRUE, 1); 
	$Customer_SupremeAED15US_Qty	= $data['Customer_SupremeAED15US_Qty']; 
	$Customer_SupremeAED18_Date		= $this->convertDate($data['Customer_SupremeAED18_Date'], TRUE, 1); 
	$Customer_SupremeAED18_Qty		= $data['Customer_SupremeAED18_Qty']; 
	$Customer_SupremeAED30_Date		= $this->convertDate($data['Customer_SupremeAED30_Date'], TRUE, 1); 
	$Customer_SupremeAED30_Qty		= $data['Customer_SupremeAED30_Qty']; 
	$Customer_SolarAED15_Date		= $this->convertDate($data['Customer_SolarAED15_Date'], TRUE, 1); 
	$Customer_SolarAED15_Qty 		= $data['Customer_SolarAED15_Qty']; 
	$Customer_SolarAED18_Date		= $this->convertDate($data['Customer_SolarAED18_Date'], TRUE, 1); 
	$Customer_SolarAED18_Qty 		= $data['Customer_SolarAED18_Qty']; 
	$Customer_SolarAED30_Date		= $this->convertDate($data['Customer_SolarAED30_Date'], TRUE, 1); 
	$Customer_SolarAED30_Qty 		= $data['Customer_SolarAED30_Qty']; 
	
	$Customer_SupremeAED15_ReserveQty_Open 		= $data['Customer_SupremeAED15_ReserveQty_Open']; 
	$Customer_SupremeAED15US_ReserveQty_Open 	= $data['Customer_SupremeAED15US_ReserveQty_Open']; 
	$Customer_SupremeAED18_ReserveQty_Open 		= $data['Customer_SupremeAED18_ReserveQty_Open']; 
	$Customer_SupremeAED30_ReserveQty_Open 		= $data['Customer_SupremeAED30_ReserveQty_Open']; 
	$Customer_SolarAED15_ReserveQty_Open 		= $data['Customer_SolarAED15_ReserveQty_Open']; 
	$Customer_SolarAED18_ReserveQty_Open 		= $data['Customer_SolarAED18_ReserveQty_Open']; 
	$Customer_SolarAED30_ReserveQty_Open 		= $data['Customer_SolarAED30_ReserveQty_Open']; 
	
	
		$TransUserName				= 		$_SESSION['UserName'] ;
		if( ($Customer_SupremeAED15_Qty<=0 ) && ($Customer_SupremeAED15US_Qty<= 0) && ($Customer_SupremeAED18_Qty<=0 ) && ($Customer_SupremeAED30_Qty<= 0)
			&& ($Customer_SolarAED15_Qty<=0 ) && ($Customer_SolarAED18_Qty<= 0) && ($Customer_SolarAED30_Qty<=0 ) 
			&& ($Customer_SupremeAED15_ReserveQty_Open<=0 ) && ($Customer_SupremeAED15US_ReserveQty_Open <= 0) && ($Customer_SupremeAED18_ReserveQty_Open <= 0 ) 
			&& ($Customer_SupremeAED30_ReserveQty_Open<= 0) && ($Customer_SolarAED15_ReserveQty_Open<=0 ) && ($Customer_SolarAED18_ReserveQty_Open <= 0) 
			&& ($Customer_SolarAED30_ReserveQty_Open<=0 ) )
		{
			//continue;
		}	
		$inputArr	= array();
		$inputArr	= array($Year, $MonthInput,$date,$CustomerCd, $Customer_Email,$Customer_MobileNo, $Customer_SupremeAED15_Date,$Customer_SupremeAED15_Qty
		, $Customer_SupremeAED15US_Date, $Customer_SupremeAED15US_Qty, $Customer_SupremeAED18_Date, $Customer_SupremeAED18_Qty, $Customer_SupremeAED30_Date
		, $Customer_SupremeAED30_Qty, $Customer_SolarAED15_Date, $Customer_SolarAED15_Qty, $Customer_SolarAED18_Date, $Customer_SolarAED18_Qty, $Customer_SolarAED30_Date
		, $Customer_SolarAED30_Qty, $Customer_SupremeAED15_ReserveQty_Open, $Customer_SupremeAED15US_ReserveQty_Open, $Customer_SupremeAED18_ReserveQty_Open
		, $Customer_SupremeAED30_ReserveQty_Open, $Customer_SolarAED15_ReserveQty_Open, $Customer_SolarAED18_ReserveQty_Open, $Customer_SolarAED30_ReserveQty_Open, $TransUserName);
		$sql		= vsprintf($queryInsert,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
		//$return = $this->SMSAlertSubdealerAEDAllocation($Customer_Name, $data['SubDealer_SupremeAED_Date_'.$curRowNo], $SubDealer_SupremeAED_Qty, $data['SubDealer_SolarAED_Date_'.$curRowNo], $SubDealer_SolarAED_Qty, $Subdealer_MobileNo);
		//if ($returnData) return $returnData;
		$this->lastInsertTranNo	= $this->getInsertId();
	return $returnData;
}


public function insertSubdealerAEDAllocationQuery() {
	$sql	= "INSERT INTO so_aedallotment_subdealer(AEDAllotment_Id, CustomerCd, SubdealerCd, SubdealerMobileNo, SubdealerEmailId, Subdealer_SupremeAED15_Date, Subdealer_SupremeAED15_Qty
	, Subdealer_SupremeAED15US_Date, Subdealer_SupremeAED15US_Qty, Subdealer_SupremeAED18_Date, Subdealer_SupremeAED18_Qty, Subdealer_SupremeAED30_Date
	, Subdealer_SupremeAED30_Qty, Subdealer_SolarAED15_Date, Subdealer_SolarAED15_Qty, Subdealer_SolarAED18_Date, Subdealer_SolarAED18_Qty
	, Subdealer_SolarAED30_Date, Subdealer_SolarAED30_Qty )  
	VALUES ('%s', '%s', '%s', '%s', '%s','%s', '%s','%s', '%s', '%s','%s', '%s', '%s', '%s', '%s', '%s','%s', '%s',  '%s')";
	return $sql ;	
}

public function updateDealerAEDAllocationReserveStockClosingQuery() {
	$sql	= "UPDATE so_aedallotment_dealer SET  Customer_SupremeAED15_ReserveQty_Close ='%s', Customer_SupremeAED15US_ReserveQty_Close = '%s'
	, Customer_SupremeAED18_ReserveQty_Close ='%s', Customer_SupremeAED30_ReserveQty_Close = '%s' 
	, Customer_SolarAED15_ReserveQty_Close = '%s', Customer_SolarAED18_ReserveQty_Close ='%s', Customer_SolarAED30_ReserveQty_Close ='%s'  
	WHERE CustomerCd='%s' AND Date = '%s' AND AEDAllotment_Id='%s'";  
	
	return $sql ;	
}

public function insertSubdealerAEDAllocation($data){
	$sql='';
	$queryInsert						= $this->insertSubdealerAEDAllocationQuery();
	$queryUpdate						= $this->updateDealerAEDAllocationReserveStockClosingQuery();
	$returnData							= '';
		$CustomerCd						= $data['CustomerCdInput'];
		$Customer_Name					= $data['Customer_Name'];
		$date 							= $this->convertDate($data['curDate'],TRUE,1); 
		$AEDAllotment_Id				=	$data['AEDAllotment_Id'];	
		
		$Subdealer_SupremeAED15_TotalQty = $Subdealer_SupremeAED15US_TotalQty = $Subdealer_SupremeAED18_TotalQty = $Subdealer_SupremeAED30_TotalQty=0;
		$Subdealer_SolarAED15_TotalQty = $Subdealer_SolarAED18_TotalQty= $Subdealer_SolarAED30_TotalQty=0;
		
	for($curRowNo=1; $curRowNo<=$data['LastRowNo1']; $curRowNo++) {
		
		$SubdealerCd 					=	$data['SubdealerCd_'.$curRowNo];	
		$Subdealer_Name 				=	$data['Subdealer_Name_'.$curRowNo];	
		$Subdealer_MobileNo				= 	$data['Subdealer_MobileNo_'.$curRowNo];	
		$Subdealer_Email				= 	$data['Subdealer_Email_'.$curRowNo];
		$Subdealer_SupremeAED15_Date	= 	$this->convertDate($data['SubDealer_SupremeAED15_Date_'.$curRowNo],TRUE,1);	
		$Subdealer_SupremeAED15_Qty 	= 	$data['SubDealer_SupremeAED15_Qty_'.$curRowNo];
		$Subdealer_SupremeAED15US_Date	= 	$this->convertDate($data['SubDealer_SupremeAED15US_Date_'.$curRowNo],TRUE,1);	
		$Subdealer_SupremeAED15US_Qty 	= 	$data['SubDealer_SupremeAED15US_Qty_'.$curRowNo];
		$Subdealer_SupremeAED18_Date	= 	$this->convertDate($data['SubDealer_SupremeAED18_Date_'.$curRowNo],TRUE,1);	
		$Subdealer_SupremeAED18_Qty 	= 	$data['SubDealer_SupremeAED18_Qty_'.$curRowNo];
		$Subdealer_SupremeAED30_Date	= 	$this->convertDate($data['SubDealer_SupremeAED30_Date_'.$curRowNo],TRUE,1);	
		$Subdealer_SupremeAED30_Qty 	= 	$data['SubDealer_SupremeAED30_Qty_'.$curRowNo];
		$Subdealer_SolarAED15_Date	 	=  	$this->convertDate($data['SubDealer_SolarAED15_Date_'.$curRowNo],TRUE,1);
		$Subdealer_SolarAED15_Qty 		= 	$data['SubDealer_SolarAED15_Qty_'.$curRowNo];	
		$Subdealer_SolarAED18_Date 		=  	$this->convertDate($data['SubDealer_SolarAED18_Date_'.$curRowNo],TRUE,1);
		$Subdealer_SolarAED18_Qty	 	= 	$data['SubDealer_SolarAED18_Qty_'.$curRowNo];	
		$Subdealer_SolarAED30_Date	 	=  	$this->convertDate($data['SubDealer_SolarAED30_Date_'.$curRowNo],TRUE,1);
		$Subdealer_SolarAED30_Qty 		= 	$data['SubDealer_SolarAED30_Qty_'.$curRowNo];	
		$TransUserName					= 	$_SESSION['UserName'] ;
		

		$Subdealer_SupremeAED15_TotalQty = $Subdealer_SupremeAED15_TotalQty + $Subdealer_SupremeAED15_Qty;
		$Subdealer_SupremeAED15US_TotalQty = $Subdealer_SupremeAED15US_TotalQty + $Subdealer_SupremeAED15US_Qty;
		$Subdealer_SupremeAED18_TotalQty = $Subdealer_SupremeAED18_TotalQty + $Subdealer_SupremeAED18_Qty;
		$Subdealer_SupremeAED30_TotalQty =$Subdealer_SupremeAED30_TotalQty + $Subdealer_SupremeAED30_Qty;
		$Subdealer_SolarAED15_TotalQty = $Subdealer_SolarAED15_TotalQty + $Subdealer_SolarAED15_Qty;
		$Subdealer_SolarAED18_TotalQty = $Subdealer_SolarAED18_TotalQty + $Subdealer_SolarAED18_Qty;
		$Subdealer_SolarAED30_TotalQty = $Subdealer_SolarAED30_TotalQty + $Subdealer_SolarAED30_Qty;
		
		if (($Subdealer_SupremeAED15_Qty<=0 ) && ($Subdealer_SupremeAED15US_Qty<= 0) && ($Subdealer_SupremeAED18_Qty<=0) && ($Subdealer_SupremeAED30_Qty<=0)
			&& ($Subdealer_SolarAED15_Qty<=0) && ($Subdealer_SolarAED18_Qty<=0) && ($Subdealer_SolarAED30_Qty<=0) ) 
		{
			continue;
		}	
		$inputArr	= array();
		$inputArr	= array($AEDAllotment_Id, $CustomerCd, $SubdealerCd, $Subdealer_MobileNo, $Subdealer_Email, $Subdealer_SupremeAED15_Date, $Subdealer_SupremeAED15_Qty
		, $Subdealer_SupremeAED15US_Date, $Subdealer_SupremeAED15US_Qty, $Subdealer_SupremeAED18_Date, $Subdealer_SupremeAED18_Qty
		, $Subdealer_SupremeAED30_Date, $Subdealer_SupremeAED30_Qty, $Subdealer_SolarAED15_Date, $Subdealer_SolarAED15_Qty, $Subdealer_SolarAED18_Date
		, $Subdealer_SolarAED18_Qty, $Subdealer_SolarAED30_Date, $Subdealer_SolarAED30_Qty);
		$sql		= vsprintf($queryInsert,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
	/*	
		$return1 = $this->SMSAlertSubdealerSupremeAEDAllocation($Customer_Name, $Subdealer_Name, $data['SubDealer_SupremeAED15_Date_'.$curRowNo], $Subdealer_SupremeAED15_Qty
		, $data['SubDealer_SupremeAED15US_Date_'.$curRowNo], $Subdealer_SupremeAED15US_Qty, $data['SubDealer_SupremeAED18_Date_'.$curRowNo]
		, $Subdealer_SupremeAED18_Qty, $data['SubDealer_SupremeAED30_Date_'.$curRowNo], $Subdealer_SupremeAED30_Qty, $Subdealer_MobileNo);
		
		$return2 = $this->SMSAlertSubdealerSolarAEDAllocation($Customer_Name, $Subdealer_Name, $data['SubDealer_SolarAED15_Date_'.$curRowNo], $Subdealer_SolarAED15_Qty
		, $data['SubDealer_SolarAED18_Date_'.$curRowNo], $Subdealer_SolarAED18_Qty, $data['SubDealer_SolarAED30_Date_'.$curRowNo]
		, $Subdealer_SolarAED30_Qty, $Subdealer_MobileNo);
	*/ 
		if ($returnData) return $returnData;
	}
		
		$Customer_SupremeAED15_TotalQty 		= $data['Customer_SupremeAED15_TotalQty']; 
		$Customer_SupremeAED15US_TotalQty 		= $data['Customer_SupremeAED15US_TotalQty']; 
		$Customer_SupremeAED18_TotalQty 		= $data['Customer_SupremeAED18_TotalQty']; 
		$Customer_SupremeAED30_TotalQty 		= $data['Customer_SupremeAED30_TotalQty']; 
		$Customer_SolarAED15_TotalQty 		= $data['Customer_SolarAED15_TotalQty']; 
		$Customer_SolarAED18_TotalQty 		= $data['Customer_SolarAED18_TotalQty']; 
		$Customer_SolarAED30_TotalQty 		= $data['Customer_SolarAED30_TotalQty']; 
		
		/*$Customer_SupremeAED15US_ReserveQty_Open 	= $data['Customer_SupremeAED15US_ReserveQty_Open']; 
		$Customer_SupremeAED18_ReserveQty_Open 		= $data['Customer_SupremeAED18_ReserveQty_Open']; 
		$Customer_SupremeAED30_ReserveQty_Open 		= $data['Customer_SupremeAED30_ReserveQty_Open']; 
		$Customer_SolarAED15_ReserveQty_Open 		= $data['Customer_SolarAED15_ReserveQty_Open']; 
		$Customer_SolarAED18_ReserveQty_Open 		= $data['Customer_SolarAED18_ReserveQty_Open']; 
		$Customer_SolarAED30_ReserveQty_Open 		= $data['Customer_SolarAED30_ReserveQty_Open']; 
	*/
		$Customer_SupremeAED15_ReserveQty_Close 	= $Customer_SupremeAED15_TotalQty - $Subdealer_SupremeAED15_TotalQty;
		$Customer_SupremeAED15US_ReserveQty_Close   = $Customer_SupremeAED15US_TotalQty - $Subdealer_SupremeAED15US_TotalQty;
		$Customer_SupremeAED18_ReserveQty_Close 	= $Customer_SupremeAED18_TotalQty - $Subdealer_SupremeAED18_TotalQty;
		$Customer_SupremeAED30_ReserveQty_Close 	= $Customer_SupremeAED30_TotalQty - $Subdealer_SupremeAED30_TotalQty;
		$Customer_SolarAED15_ReserveQty_Close 		= $Customer_SolarAED15_TotalQty - $Subdealer_SolarAED15_TotalQty;
		$Customer_SolarAED18_ReserveQty_Close 		= $Customer_SolarAED18_TotalQty - $Subdealer_SolarAED18_TotalQty;
		$Customer_SolarAED30_ReserveQty_Close 		= $Customer_SolarAED30_TotalQty - $Subdealer_SolarAED30_TotalQty;
		
	$inputArr	= array($Customer_SupremeAED15_ReserveQty_Close, $Customer_SupremeAED15US_ReserveQty_Close, $Customer_SupremeAED18_ReserveQty_Close
		, $Customer_SupremeAED30_ReserveQty_Close, $Customer_SolarAED15_ReserveQty_Close, $Customer_SolarAED18_ReserveQty_Close
		, $Customer_SolarAED30_ReserveQty_Close, $CustomerCd, $date,$AEDAllotment_Id );
		$sql		= vsprintf($queryUpdate,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
return $returnData;
}


public function SMSAlertSubdealerSupremeAEDAllocation($Customer_Name, $Subdealer_Name, $Subdealer_SupremeAED15_Date, $Subdealer_SupremeAED15_Qty, $SubDealer_SupremeAED15US_Date
, $Subdealer_SupremeAED15US_Qty, $Subdealer_SupremeAED18_Date, $Subdealer_SupremeAED18_Qty, $Subdealer_SupremeAED30_Date, $Subdealer_SupremeAED30_Qty,
 $Subdealer_MobileNo){
$uname = 'SIILJPRO'; //'SIILJPRP';
$password = 'S(ol)!ar';// 'E9W!f9Y~';
$info ='1';
$test = '0';
$from = 'iSOLAR';
//$dest =  '9406547095,8793653028'; //'8793653028'; // 9649569999// // //'8600993992';
$dest =  $Subdealer_MobileNo.', 09422460039 ';
if(($Subdealer_SupremeAED15_Date == $SubDealer_SupremeAED15US_Date) && ($SubDealer_SupremeAED15US_Date ==$Subdealer_SupremeAED18_Date) && ($Subdealer_SupremeAED18_Date ==$Subdealer_SupremeAED30_Date) ){
//if(1){
	
$messages = "Dear ". str_replace("&", "and", $Subdealer_Name) .", As per update received from M/s ". str_replace("&", "and", $Customer_Name) ." they have allocated you ";
if($Subdealer_SupremeAED15_Qty!=0) {
	$messages .= $Subdealer_SupremeAED15_Qty." Nos Supreme AED 1.5, ";
}
if($Subdealer_SupremeAED15US_Qty!=0) {
	$messages .= $Subdealer_SupremeAED15US_Qty." Nos Supreme AED 1.5US, ";
}
if($Subdealer_SupremeAED18_Qty!=0) {
	$messages .= $Subdealer_SupremeAED18_Qty." Nos Supreme AED 1.8, ";
}
if($Subdealer_SupremeAED30_Qty!=0) {
	$messages .= $Subdealer_SupremeAED30_Qty." Nos Supreme AED 3.0";
}
 $messages .=" on date ".$Subdealer_SupremeAED15_Date." to you. Please ignore if details already received from them. Thank You, Customer Service Department" ;
}

else{
$messages = "Dear ". str_replace("&", "and", $Subdealer_Name) .", As per update received from M/s ". str_replace("&", "and", $Customer_Name) ." they have allocated you ";
if($Subdealer_SupremeAED15_Qty!=0) {
	$messages .= $Subdealer_SupremeAED15_Qty." Nos Supreme AED 1.5 on date " .$Subdealer_SupremeAED15_Date;
}
if($Subdealer_SupremeAED15US_Qty!=0) {
	$messages .= $Subdealer_SupremeAED15US_Qty." Nos Supreme AED 1.5US on date ". $SubDealer_SupremeAED15US_Date. " ";
}
if($Subdealer_SupremeAED18_Qty!=0) {
	$messages .= $Subdealer_SupremeAED18_Qty." Nos Supreme AED 1.8 on date ". $Subdealer_SupremeAED18_Date. " ";
}
if($Subdealer_SupremeAED30_Qty!=0) {
	$messages .= $Subdealer_SupremeAED30_Qty." Nos Supreme AED 3.0 on date ".$Subdealer_SupremeAED30_Date. " ";
}
 $messages .=" to you. Please ignore if details already received from them. Thank You, Customer Service Department" ;
}

$data ="uname=".$uname."&pass=".$password."&msg=".$messages."&send=".$from."&dest=".$dest;
$ch = curl_init("http://api.unicel.in/SendSMS/sendmsg.php?");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);
curl_close($ch);
return $messages;
}


public function SMSAlertSubdealerSolarAEDAllocation($Customer_Name, $Subdealer_Name, $Subdealer_SolarAED15_Date, $Subdealer_SolarAED15_Qty, $Subdealer_SolarAED18_Date
		, $Subdealer_SolarAED18_Qty, $Subdealer_SolarAED30_Date, $Subdealer_SolarAED30_Qty, $Subdealer_MobileNo){
$uname = 'SIILJPRO'; //'SIILJPRP';
$password = 'S(ol)!ar';// 'E9W!f9Y~';
$info ='1';
$test = '0';
$from = 'iSOLAR';
//$dest =  '8793653028,9406547095'; //'8793653028'; // 9649569999// // //'8600993992';
$dest =  $Subdealer_MobileNo.', 09422460039';
//if($Subdealer_SolarAED15_Date == $Subdealer_SolarAED18_Date == $Subdealer_SolarAED30_Date){
	 
if(($Subdealer_SolarAED15_Date == $Subdealer_SolarAED18_Date) && ($Subdealer_SolarAED18_Date ==$Subdealer_SolarAED30_Date)){
$messages = "Dear ". str_replace("&", "and", $Subdealer_Name) .", As per update received from M/s ". str_replace("&", "and", $Customer_Name) ." they have allocated you ";
if($Subdealer_SolarAED15_Qty!=0) {
	$messages .= $Subdealer_SolarAED15_Qty." Nos Solar AED 1.5, ";
}
if($Subdealer_SolarAED18_Qty!=0) {
	$messages .= $Subdealer_SolarAED18_Qty." Nos Solar AED 1.8, ";
}
if($Subdealer_SolarAED30_Qty!=0) {
	$messages .= $Subdealer_SolarAED30_Qty." Nos Solar AED 1.8, ";
}
 $messages .=" on date ".$Subdealer_SolarAED15_Date." to you. Please ignore if details already received from them. Thank You, Customer Service Department" ;
}

else{
$messages = "Dear ". str_replace("&", "and", $Subdealer_Name) .", As per update received from M/s ". str_replace("&", "and", $Customer_Name) ." they have allocated you ";
if($Subdealer_SolarAED15_Qty!=0) {
	$messages .= $Subdealer_SolarAED15_Qty." Nos Solar AED 1.5 on date ". $Subdealer_SolarAED15_Date;
}
if($Subdealer_SolarAED18_Qty!=0) {
	$messages .= $Subdealer_SolarAED18_Qty." Nos Solar AED 1.8 on date ". $Subdealer_SolarAED18_Date. " ";
}
if($Subdealer_SolarAED30_Qty!=0) {
	$messages .= $Subdealer_SolarAED30_Qty." Nos Solar AED 1.8 on date ". $Subdealer_SolarAED30_Date. " ";
}
 $messages .=" to you. Please ignore if details already received from them. Thank You, Customer Service Department" ;
}


$data ="uname=".$uname."&pass=".$password."&msg=".$messages."&send=".$from."&dest=".$dest;
$ch = curl_init("http://api.unicel.in/SendSMS/sendmsg.php?");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);
curl_close($ch);
return $messages;
}


public function sendEMailDealerSubdealerAEDAllocation($data) {
	$templateArr = $this->getEMailTemplate(55);
	$eMailDetailRowCount = count($data);
	$curRow=0;
		$CustomerCd		= $data['CustomerCdInput'];
		$Customer_Name	= $data['Customer_Name'];
		$curEMailId	= $data['Dealer_Email'];
		//$curEMailId = 'websupport@solargroup.com';
		$Dim2Arr = array();
		$Dim2ArrCurRow = 0;
		for($curRowNo=1; $curRowNo<=$data['LastRowNo1']; $curRowNo++) {
			$Dim2Arr[$Dim2ArrCurRow] = array($data['subdealer_Name_'.$curRowNo], $data['SubDealer_SupremeAED_Date_'.$curRowNo], $data['SubDealer_SupremeAED_Qty_'.$curRowNo]
										, $data['SubDealer_SolarAED_Date_'.$curRowNo], $data['SubDealer_SolarAED_Qty_'.$curRowNo]);
		$Dim2ArrCurRow++;
		}
		$eMailBody = $this->strPositSubstitute($templateArr['Body'], NULL, $Dim2Arr);
		$eMailBody = str_replace(array('\r','\n','\t'),array("\r","\n","\t"), $eMailBody);
		$EmailIdCC = $templateArr['EMailIdCC'];
		//$EmailIdCC = '';
		$objSolarMailer = new solarMailer();
		$objSolarMailer->sendSolarMail($curEMailId, $templateArr['Subject'], $eMailBody, $EmailIdCC);
		return $eMailBody;
}

/*
public function getDealerSubDealerAEDAllocationHeader($CustomerCd,$month,$year){
	$sql = "SELECT A.*, B.*, D.Descript as Subdealer_Name, D.EMailId as Subdealer_Email, D.TelNo1 as Subdealer_TelNo, E.CustomerCd, E.Descript  as Customer_Name
	, E.EMailId as Customer_Mail, E.TelNo as Customer_TelNo   
	FROM so_AEDallotment_dealer A JOIN  so_AEDallotment_subdealer B ON A.AEDAllotment_Id = B.AEDAllotment_Id  
	JOIN so_subdealer_m_dealer C ON B.CustomerCd  = C.CustomerCd  
	JOIN  so_subdealer_m D 	ON B.SubDealerCd  = D.IdSubdealer 
	JOIN so_customer_m E	ON A.CustomerCd=E.CustomerCd 
	WHERE A.CustomerCd='".$CustomerCd."' AND A.Month = '".$month."' AND A.Year='".$year."'";
	$returnData	= $this->execSelectQuery($sql);
	//return $returnData;
	print_r($returnData);
}
*/


public function getDealerSubDealerAEDAllocationHeader($CustomerCd,$month,$year, $AEDAllotment_Id){
	 $sql = "
		SELECT A.*,IFNULL(B.Descript,A.CustomerCd) AS DealerName,B.City AS DealerCity,IFNULL(C.Descript,A.IdSubdealer) AS SubdealerName,B.TelNo AS DealerTelNo ,B.EmailId AS DealerEmail ,C.TelNo AS SubdealerTelNo, C.Descript AS SubdealerName, C.EMailId AS SubdealerEmail FROM 
			(SELECT A1.CustomerCd AS CustCd,A1.IdSubdealer,B1.* FROM 
			(SELECT * FROM so_subdealer_m_dealer WHERE CustomerCd = '".$CustomerCd."')A1
			LEFT OUTER JOIN 
				(SELECT A.Year, A.Month, A.Date ,A.Customer_SupremeAED15_Date,A.Customer_SupremeAED15_Qty, A.Customer_SupremeAED15US_Date,A.Customer_SupremeAED15US_Qty,
				A.Customer_SupremeAED18_Date,A.Customer_SupremeAED18_Qty,A.Customer_SupremeAED30_Date,
				A.Customer_SupremeAED30_Qty,
				A.Customer_SolarAED15_Date,A.Customer_SolarAED15_Qty, A.Customer_SolarAED18_Date,A.Customer_SolarAED18_Qty,
				A.Customer_SolarAED30_Date,A.Customer_SolarAED30_Qty,
				
				A.Customer_SupremeAED15_ReserveQty_Open, A.Customer_SupremeAED15US_ReserveQty_Open, A.Customer_SupremeAED18_ReserveQty_Open, 
				A.Customer_SupremeAED30_ReserveQty_Open,	A.Customer_SolarAED15_ReserveQty_Open ,A.Customer_SolarAED18_ReserveQty_Open, A.Customer_SolarAED30_ReserveQty_Open,
				
				A.Customer_SupremeAED15_ReserveQty_Close, A.Customer_SupremeAED15US_ReserveQty_Close, A.Customer_SupremeAED18_ReserveQty_Close, 
				A.Customer_SupremeAED30_ReserveQty_Close,	A.Customer_SolarAED15_ReserveQty_Close ,A.Customer_SolarAED18_ReserveQty_Close, A.Customer_SolarAED30_ReserveQty_Close,
				
				B.* FROM so_aedallotment_dealer A 
				LEFT OUTER  JOIN so_aedallotment_subdealer B ON A.AEDAllotment_Id = B.AEDAllotment_Id
				WHERE A.CustomerCd='".$CustomerCd."' AND A.Month = '$month' AND A.AEDAllotment_Id= '$AEDAllotment_Id')B1
			ON A1.IdSubdealer = B1.SubdealerCd)A 
		LEFT JOIN so_customer_m B ON A.CustCd = B.CustomerCd
		LEFT JOIN  so_subdealer_m C ON A.IdSubdealer = C.IdSubdealer	 Order By C.Descript			
		";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
	//print_r($returnData);
}

public function updateDealerAEDAllocationQuery() {
	$sql	= "UPDATE so_aedallotment_dealer SET Customer_SupremeAED15_Date = '%s', Customer_SupremeAED15_Qty = '%s', Customer_SupremeAED15US_Date = '%s'
	, Customer_SupremeAED15US_Qty = '%s', Customer_SupremeAED18_Date = '%s', Customer_SupremeAED18_Qty = '%s', Customer_SupremeAED30_Date ='%s'
	, Customer_SupremeAED30_Qty ='%s', Customer_SolarAED15_Date = '%s', Customer_SolarAED15_Qty ='%s', Customer_SolarAED18_Date = '%s'
	, Customer_SolarAED18_Qty = '%s', Customer_SolarAED30_Date ='%s', Customer_SolarAED30_Qty ='%s'  
	WHERE CustomerCd='%s' AND Date = '%s' AND AEDAllotment_Id='%s' ";  
	
	return $sql ;	
}

public function updateSubdealerAEDAllocationQuery() {
	$sql	= "UPDATE  so_aedallotment_subdealer SET  Subdealer_SupremeAED15_Date = '%s' , Subdealer_SupremeAED15_Qty = '%s'
	, Subdealer_SupremeAED15US_Date  = '%s', Subdealer_SupremeAED15US_Qty = '%s', Subdealer_SupremeAED18_Date = '%s', Subdealer_SupremeAED18_Qty = '%s'
	,  Subdealer_SupremeAED30_Date = '%s', Subdealer_SupremeAED30_Qty = '%s' , Subdealer_SolarAED15_Date = '%s', Subdealer_SolarAED15_Qty = '%s' 
	, Subdealer_SolarAED18_Date = '%s' , Subdealer_SolarAED18_Qty = '%s', Subdealer_SolarAED30_Date = '%s', Subdealer_SolarAED30_Qty = '%s' 
	WHERE  CustomerCd='%s' AND AEDAllotment_Id = '%s' AND SubdealerCd = '%s' ";
	return $sql ;	
}


public function deleteSubDealerAEDAllocationQuery() {
	$sql	= "DELETE FROM `so_aedallotment_subdealer` WHERE `CustomerCd` = %s AND `SubdealerCd` ='%s' AND `AEDAllotment_Id` = %s ";
	return $sql ;
}
public function updateDealerAEDAllocation($data){
	$sql='';
	$queryInsert					= $this->insertDealerAEDAllocationQuery();
	$queryUpdate					= $this->updateDealerAEDAllocationQuery();
	$returnData						= '';
	
	$date 							= $this->convertDate($data['curDate'],TRUE,1); 
	$CustomerCd						= $data['CustomerCdInput'];
	$Customer_Name					= $data['Customer_Name'];
	$AEDAllotment_Id					= $data['AEDAllotment_Id'];
	$Customer_SupremeAED15_Date		= $this->convertDate($data['Customer_SupremeAED15_Date'], TRUE, 1); 
	$Customer_SupremeAED15_Qty		= $data['Customer_SupremeAED15_Qty']; 
	$Customer_SupremeAED15US_Date	= $this->convertDate($data['Customer_SupremeAED15US_Date'], TRUE, 1); 
	$Customer_SupremeAED15US_Qty	= $data['Customer_SupremeAED15US_Qty']; 
	$Customer_SupremeAED18_Date		= $this->convertDate($data['Customer_SupremeAED18_Date'], TRUE, 1); 
	$Customer_SupremeAED18_Qty		= $data['Customer_SupremeAED18_Qty']; 
	$Customer_SupremeAED30_Date		= $this->convertDate($data['Customer_SupremeAED30_Date'], TRUE, 1); 
	$Customer_SupremeAED30_Qty		= $data['Customer_SupremeAED30_Qty']; 
	$Customer_SolarAED15_Date		= $this->convertDate($data['Customer_SolarAED15_Date'], TRUE, 1); 
	$Customer_SolarAED15_Qty 		= $data['Customer_SolarAED15_Qty']; 
	$Customer_SolarAED18_Date		= $this->convertDate($data['Customer_SolarAED18_Date'], TRUE, 1); 
	$Customer_SolarAED18_Qty 		= $data['Customer_SolarAED18_Qty']; 
	$Customer_SolarAED30_Date		= $this->convertDate($data['Customer_SolarAED30_Date'], TRUE, 1); 
	$Customer_SolarAED30_Qty 		= $data['Customer_SolarAED30_Qty']; 
//	echo $Customer_SupremeAED15_Qty;
		if(($Customer_SupremeAED15_Qty<=0 ) && ($Customer_SupremeAED15US_Qty<= 0) && ($Customer_SupremeAED18_Qty<=0 ) && ($Customer_SupremeAED30_Qty<= 0)
		   && ($Customer_SolarAED15_Qty<=0 ) && ($Customer_SolarAED18_Qty<= 0) && ($Customer_SolarAED30_Qty<=0 ))
		{
			//continue;
		}	
		$queryCheck	= "SELECT COUNT(*) AS Count FROM so_aedallotment_dealer WHERE CustomerCd='%s' AND Date='%s'";
		$inputArr	= array();
		$inputArr	= array($CustomerCd,$date );
		$sql		= vsprintf($queryCheck,$inputArr);
		$returnData	= $this->execSelectQuery($sql);
		if ($returnData[0]['Count']==0) {
			$inputArr	= array();
			$inputArr	= array($Year, $MonthInput,$date,$CustomerCd, $Customer_Email,$Customer_MobileNo, $Customer_SupremeAED15_Date,$Customer_SupremeAED15_Qty
			, $Customer_SupremeAED15US_Date, $Customer_SupremeAED15US_Qty, $Customer_SupremeAED18_Date, $Customer_SupremeAED18_Qty, $Customer_SupremeAED30_Date
			, $Customer_SupremeAED30_Qty, $Customer_SolarAED15_Date, $Customer_SolarAED15_Qty, $Customer_SolarAED18_Date, $Customer_SolarAED18_Qty, $Customer_SolarAED30_Date
			, $Customer_SolarAED30_Qty, $TransUserName);
			$sql		= vsprintf($queryInsert,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
		}else{
			$inputArr	= array($Customer_SupremeAED15_Date,$Customer_SupremeAED15_Qty
			, $Customer_SupremeAED15US_Date, $Customer_SupremeAED15US_Qty, $Customer_SupremeAED18_Date, $Customer_SupremeAED18_Qty, $Customer_SupremeAED30_Date
			, $Customer_SupremeAED30_Qty, $Customer_SolarAED15_Date, $Customer_SolarAED15_Qty, $Customer_SolarAED18_Date, $Customer_SolarAED18_Qty, $Customer_SolarAED30_Date
			, $Customer_SolarAED30_Qty,$CustomerCd,$date,$AEDAllotment_Id);
			$sql= vsprintf($queryUpdate,$inputArr);	
			$returnData	= $this->execUpdateQuery($sql);
		}
	return $returnData;
}



public function updateSubdealerAEDAllocation($data){
	//print_r($data);
	$sql='';
	$queryInsert						= $this->insertSubdealerAEDAllocationQuery();
	$queryUpdate						= $this->updateSubdealerAEDAllocationQuery();
	$queryDelete						= $this->deleteSubdealerAEDAllocationQuery();
	$returnData							= '';
	$CustomerCd						= $data['CustomerCdInput'];
	for($curRowNo=1; $curRowNo<=$data['LastRowNo1']; $curRowNo++) {
		$AEDAllotment_Id				=	$data['AEDAllotment_Id'];	
		$SubdealerCd 					=	$data['SubdealerCd_'.$curRowNo];	
		$Subdealer_MobileNo				= 	$data['Subdealer_MobileNo_'.$curRowNo];	
		$Subdealer_Email				= 	$data['Subdealer_Email_'.$curRowNo];
		$Subdealer_SupremeAED15_Date	= 	$this->convertDate($data['SubDealer_SupremeAED15_Date_'.$curRowNo],TRUE,1);	
		$Subdealer_SupremeAED15_Qty 	= 	$data['SubDealer_SupremeAED15_Qty_'.$curRowNo];
		$Subdealer_SupremeAED15US_Date	= 	$this->convertDate($data['SubDealer_SupremeAED15US_Date_'.$curRowNo],TRUE,1);	
		$Subdealer_SupremeAED15US_Qty 	= 	$data['SubDealer_SupremeAED15US_Qty_'.$curRowNo];
		$Subdealer_SupremeAED18_Date	= 	$this->convertDate($data['SubDealer_SupremeAED18_Date_'.$curRowNo],TRUE,1);	
		$Subdealer_SupremeAED18_Qty 	= 	$data['SubDealer_SupremeAED18_Qty_'.$curRowNo];
		$Subdealer_SupremeAED30_Date	= 	$this->convertDate($data['SubDealer_SupremeAED30_Date_'.$curRowNo],TRUE,1);	
		$Subdealer_SupremeAED30_Qty 	= 	$data['SubDealer_SupremeAED30_Qty_'.$curRowNo];
		$Subdealer_SolarAED15_Date 		=  	$this->convertDate($data['SubDealer_SolarAED15_Date_'.$curRowNo],TRUE,1);
		$Subdealer_SolarAED15_Qty 		= 	$data['SubDealer_SolarAED15_Qty_'.$curRowNo];	
		$Subdealer_SolarAED18_Date 		=  	$this->convertDate($data['SubDealer_SolarAED18_Date_'.$curRowNo],TRUE,1);
		$Subdealer_SolarAED18_Qty 		= 	$data['SubDealer_SolarAED18_Qty_'.$curRowNo];	
		$Subdealer_SolarAED30_Date 		=  	$this->convertDate($data['SubDealer_SolarAED30_Date_'.$curRowNo],TRUE,1);
		$Subdealer_SolarAED30_Qty 		= 	$data['SubDealer_SolarAED30_Qty_'.$curRowNo];	
		
		if (($Subdealer_SupremeAED15_Qty==0)&&($Subdealer_SupremeAED15US_Qty==0)&&($Subdealer_SupremeAED18_Qty==0)&&($Subdealer_SupremeAED30_Qty==0)&&($Subdealer_SolarAED15_Qty==0)&&($Subdealer_SolarAED18_Qty==0)&&($Subdealer_SolarAED30_Qty==0))
		{	
			$inputArr	= array();
			$inputArr	= array($CustomerCd,$SubdealerCd ,$AEDAllotment_Id );
			 $sql		= vsprintf($queryDelete,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		}
			
		$queryCheck	= "SELECT COUNT(*) AS Count FROM so_aedallotment_subdealer WHERE CustomerCd='%s' AND SubdealerCd='%s' AND AEDAllotment_Id = '%s'";
		$inputArr	= array();
		$inputArr	= array($CustomerCd,$SubdealerCd ,$AEDAllotment_Id );
		$sql		= vsprintf($queryCheck,$inputArr);
		$returnData	= $this->execSelectQuery($sql);
		$returnData[0]['Count'];
		if ($returnData[0]['Count']==0) {
			if (($Subdealer_SupremeAED15_Qty<=0)&&($Subdealer_SupremeAED15US_Qty<=0)&&($Subdealer_SupremeAED18_Qty<=0)&&($Subdealer_SupremeAED30_Qty<=0)&&($Subdealer_SolarAED15_Qty<=0)&&($Subdealer_SolarAED18_Qty<=0)&&($Subdealer_SolarAED30_Qty<=0))
			{	
				continue;
			}
			$inputArr	= array();
			$inputArr	= array($AEDAllotment_Id, $CustomerCd, $SubdealerCd, $Subdealer_MobileNo, $Subdealer_Email, $Subdealer_SupremeAED15_Date, $Subdealer_SupremeAED15_Qty
			, $Subdealer_SupremeAED15US_Date, $Subdealer_SupremeAED15US_Qty, $Subdealer_SupremeAED18_Date, $Subdealer_SupremeAED18_Qty, $Subdealer_SupremeAED30_Date, $Subdealer_SupremeAED30_Qty, $Subdealer_SolarAED15_Date, $Subdealer_SolarAED15_Qty, $Subdealer_SolarAED18_Date
			,$Subdealer_SolarAED18_Qty, $Subdealer_SolarAED30_Date, $Subdealer_SolarAED30_Qty);
			$sql		= vsprintf($queryInsert,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
		}else{
			$inputArr	= array();
			$inputArr	= array($Subdealer_SupremeAED15_Date, $Subdealer_SupremeAED15_Qty
			,$Subdealer_SupremeAED15US_Date, $Subdealer_SupremeAED15US_Qty, $Subdealer_SupremeAED18_Date, $Subdealer_SupremeAED18_Qty, $Subdealer_SupremeAED30_Date, $Subdealer_SupremeAED30_Qty, $Subdealer_SolarAED15_Date, $Subdealer_SolarAED15_Qty, $Subdealer_SolarAED18_Date
			, $Subdealer_SolarAED18_Qty, $Subdealer_SolarAED30_Date, $Subdealer_SolarAED30_Qty,$CustomerCd, $AEDAllotment_Id, $SubdealerCd);
			$sql		= vsprintf($queryUpdate,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
		}
		if ($returnData) return $returnData;
	}
return $sql;
}

//====================================End of Dealer Subdealer AED Allocation ========================
public function getFlagRE11PDF($CustomerCd) {
	$stmt	= "SELECT A.* FROM so_customer_m A WHERE A.CustomerCd=%s";
	$inputArr 	= array($CustomerCd);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}


public function IsExistMultiPOPromo($CustomerCd) {
	$CurDate = date('Y-m-d');
	$stmt	= "SELECT *  FROM `so_customer_multi_po_restriction` WHERE `CustomerCd` = '%s'  AND `IsActive` = '%s'  AND StartDate <= '%s' AND EndDate >='%s' ";
	$inputArr 	= array($CustomerCd, 0, $CurDate, $CurDate);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getMultiPOPromotionItemQuantity ($CustomerCd, $VehicleCapacity, $ItemCd) {
	$CurDate = date('Y-m-d');
	$stmt	= "SELECT *  FROM `so_customer_multi_po_restriction` WHERE `CustomerCd` = '%s'  AND `ItemCd` = '%s' AND StartDate <= '%s' AND EndDate >='%s' ";
	$inputArr 	= array($CustomerCd, $ItemCd, $CurDate, $CurDate);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getPromotionItemQuantity($CustomerCd, $VehicleCapacity, $ItemCd) {
	$CurDate = date('Y-m-d');
	$stmt	= "SELECT *  FROM `so_customer_po_promoqty` WHERE `CustomerCd` = '%s' AND `CustVehicleCapacity` = '%s' AND `ItemCd` = '%s' AND StartDate <= '%s' AND EndDate >='%s' ";
	$inputArr 	= array($CustomerCd, $VehicleCapacity, $ItemCd, $CurDate, $CurDate);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getExpDetSubItemNew($IsTradeSector, $CustomerCd, $MagazineCd, $CompanyCd, $DespatchMode, $IsCustomer) {

	$inputArr 		= array($CustomerCd, $MagazineCd, $CompanyCd, $DespatchMode, $IsCustomer);
	$paraString		= vsprintf("'%s', '%s', %s, '%s', %s", $inputArr);
	if ($IsTradeSector) {
		$sql			= "call sp_getExpDetSubItemNew(". $paraString. ")";
	} else if($CompanyCd == '1110' || $CompanyCd == '1821'){
		$sql			= "call sp_getExpDetSubItemNewExport(". $paraString. ")";	
	}else {
		$sql			= "call sp_getExpDetSubItemNewNonTrade(". $paraString. ")";
	}
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getExpDetSubItemEdit($IsTradeSector, $IdExpDet, $UniqueIdMagazine, $StatusCd, $IsCustomer) {
	$inputArr 		= array($IdExpDet, $UniqueIdMagazine, $StatusCd, $IsCustomer);
	$paraString		= vsprintf("%s, %s, '%s', %s", $inputArr);
	if ($IsTradeSector) {
		$sql			= "call sp_getExpDetSubItemEdit(". $paraString. ")";
	} else {
		$sql			= "call sp_getExpDetSubItemEditNonTrade(". $paraString. ")";
	}

	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function approveExpDet($approveDocList, $isApproved, &$TokenNoAr=NULL, $IsClubedPO=NULL) {
	$stmt		= "UPDATE so_expdet SET StatusCd='%s', ApprovedByUserName='%s', ApprovalDateTime='%s' WHERE IdExpDet IN (%s)";
	if ($isApproved) {
		$inputArr 	= array('A', $_SESSION['UserName'], date('Y-m-d H:i:s'), $approveDocList);
	} else {
		$inputArr 	= array('U', '', '', $approveDocList);
	}
	$sql		= vsprintf($stmt,$inputArr);
	$this->execUpdateQuery($sql);
	if ($isApproved) {
		if($IsClubedPO){
			//exit;	
			/*
			$stmt	= "SELECT MAX(TokenNo) as TokenNo FROM so_expdet";
			$returnData	= $this->execSelectQuery($stmt);
			$TokenNo = $returnData[0]['TokenNo'];
			$TokenNoPrefix ='CLB';
			*/
			$stmt		= "UPDATE so_expdet SET StatusCd='%s', ApprovedByUserName='%s' WHERE IdExpDet IN (%s)";
			$inputArr 	= array('A', $_SESSION['UserName'], $approveDocList);
			$sql		= vsprintf($stmt,$inputArr);
			$this->execUpdateQuery($sql);
			if ($_SESSION['IsTradeSector']) {
				$emailBody = $this->sendEMailPOAccessApproval($approveDocList, 2);
			}
			/*
				$stmt="SELECT A.IdExpDet, CONCAT(TRIM(A.TokenNoPrefix),IF(A.TokenNo=0,'',CONCAT('/',A.TokenNo%%100))) AS TokenNoFull FROM so_expdet A WHERE A.IdExpDet IN (%s)";	
				$inputArr 	= array($approveDocList);
				$sql		= vsprintf($stmt,$inputArr);
				$TokenNoAr = $this->execSelectQuery($sql);
			*/
		}
		else{
			$sql	= "call sp_updateExpDetTokenNo('{$_SESSION['SectorCd']}', '$approveDocList', 0);";
			$TokenNoAr	= $this->execSelectQuery($sql);
			if ($_SESSION['IsTradeSector']) {
				$emailBody = $this->sendEMailPOAccessApproval($approveDocList, 2);
			}
		}
	} else {
		$sql	= "call sp_updateExpDetTokenNo('{$_SESSION['SectorCd']}', '$approveDocList', 1);";
		$this->execUpdateQuery($sql);
	}
	return $emailBody;
}

public function treminateExpDet($terminateDocList) {
	$POStatusTerminate = self::POStatusTerminate;
	$curdatetime= date('Y-m-d H:i:s');
	$stmt		= "UPDATE so_expdet SET StatusCd='%s', TransDateTime='%s' WHERE IdExpDet IN (%s)";
	$inputArr 	= array($POStatusTerminate, $curdatetime,  $terminateDocList);
	$sql		= vsprintf($stmt, $inputArr);
	$this->execUpdateQuery($sql);

	//$this->sendEMailPOAccessApproval($approveDocList, 3);
	return;
}



public function getTerminatePOLog($IdExpDet){
	$sql 	= "SELECT * FROM so_expdet_termination_log WHERE IdExpDet = '".$IdExpDet."'";
	$result = $this->execSelectQuery($sql);
	return $result;
}

public function updateTerminateToAppUnapp($data){
	$sql 	= "UPDATE so_expdet_termination_log SET AppUnappReason = '".$data['terminateToAppUnapp']."' WHERE IdExpDet='".$data['oldIdExpDet']."' ";
	$returnData = $this->execUpdateQuery($sql);
}


public function SendMailDueRTGSExpDet($IdExpDet, $Status) {
	switch ($Status) {
	case 1:
		$Emailtemplate	= 48;
		$TableName		= 'so_expdet';
		$TransId		= 'IdExpDet';
		$Date			= 'DateTime';
		break;
	}
	
	$templateArr = $this->getEMailTemplate($Emailtemplate);
	$sql = "SELECT A.$TransId AS IdExpDet, DATE_FORMAT(A.$Date,'%d-%m-%Y') AS Date, B.EMailId FROM $TableName A INNER JOIN so_customer_m B
		ON A.CustomerCd=B.CustomerCd WHERE A.$TransId IN ($IdExpDet)";
	
	$eMailDetailArr = $this->execSelectQuery($sql);
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($IdExpDet, $eMailDetailArr[0]['Date']));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	
}

public function SendMailDueRTGSIdAccessory($IdAccessory, $Status) {
	switch ($Status) {
	case 1:
		$Emailtemplate	= 56;
		$TableName		= 'so_accessory';
		$TransId		= 'IdAccessory';
		$Date			= 'Date';
		break;
	}
	
	$templateArr = $this->getEMailTemplate($Emailtemplate);
	$sql = "SELECT A.$TransId AS IdAccessory, DATE_FORMAT(A.$Date,'%d-%m-%Y') AS Date, B.EMailId FROM $TableName A INNER JOIN so_customer_m B
		ON A.CustomerCd=B.CustomerCd WHERE A.$TransId IN ($IdAccessory)";
	
	$eMailDetailArr = $this->execSelectQuery($sql);
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($IdAccessory, $eMailDetailArr[0]['Date']));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	
}


public function confirmExpDet($approveDocList) {
	$POStatusConfirm = self::POStatusConfirm;
	$stmt		= "UPDATE so_expdet SET StatusCd='%s' WHERE IdExpDet IN (%s)";
	$inputArr 	= array($POStatusConfirm, $approveDocList);
	$sql		= vsprintf($stmt, $inputArr);
	$this->execUpdateQuery($sql);

	$this->sendEMailPOAccessApproval($approveDocList, 3);
	return;
}

public function uploadExpDet2SAP($approveDocList, $StatusCd) {
// We only put the file in upload/po2sap folder. SAP thro an utility, would read & update in SAP & then move it to upload/Backup folder
	$IsClubMagVan	= 0;			// $_SESSION['IsTradeSector'] ? 0 : 1;
	$stmt		= "call sp_getExpDet2SAPUpload('$approveDocList', '$StatusCd', $IsClubMagVan)";	// ReturnData of SAP Upload File for just Approved POs
	
	$approvePOArr	= $this->execSelectQuery($stmt);

	$fileFolder = '/home/solarexplosives/solar_sap/po2sap/' . $_SESSION['Sector'] . '/';
	$row = 0;
	$rowTotal	= count($approvePOArr);
	$IsError	= FALSE;
	while ($row<$rowTotal) {
		$curPONumber = $approvePOArr[$row]['PONumber'];
		if ($approvePOArr[$row]['OrderType']=='Z5') {		// so_customer_m.IsDepot
			$fileName = "ExpDet".trim($curPONumber).'.txt';		
		} else {
			$fileName = "ExpDetPO".(int)$curPONumber.'.txt';
		}
		$folderFileName = $fileFolder.$fileName;
		$handle = fopen($folderFileName,'wb');
		if (!$handle) {
			$IsError	= TRUE;
			//break;
		}

		while ($row<$rowTotal && $curPONumber == $approvePOArr[$row]['PONumber']) {
			if ($approvePOArr[$row]['OrderType']=='Z5') {		// so_customer_m.IsDepot
// PONumber, OrderType, Plant, RE11No, RE11Date, VehicleNo, ItemCd, OrderQty, CustomerCd,  MagazineCd, RateContractRef, RateContractDate, OrderBox, AvailableDate
				$curRow = $approvePOArr[$row];
				$curRec = $curRow['PONumber'] . "\t" . $curRow['OrderType'] . "\t" . $curRow['Plant'] . "\t" . $curRow['RE11No'] 
					. "\t" . $curRow['RE11Date'] . "\t" . $curRow['VehicleNo'] . "\t" . $curRow['ItemCd'] . "\t" . $curRow['OrderQty'] 
					. "\t" . $curRow['CustomerCd'] . "\t" . $curRow['MagazineCd'] . "\t" . $curRow['RateContractRef'] 
					. "\t" . $curRow['RateContractDate'] . "\t" . $curRow['OrderBox'] . "\t" . $curRow['AvailableDate'] . "\r\n";
			} else {
// PONumber, UniqueIdMagazine, ItemCd, PODate, CustomerCd,  MagazineCd, OrderQty, VehicleNo, RE11No, RE11Date, Plant, OrderType, SalesOrg, DistChannel, Division, RateContractRef, RateContractDate, OrderBox, AvailableDate
				$curRec = trim(implode("\t", $approvePOArr[$row]))."\r\n";
			}
			$handlefwrite =  fwrite($handle, $curRec);
			if (!$handlefwrite) {
			$IsError	= TRUE;
			break;
		}
			$row++;
		}
		fclose($handle);
	}
	return $IsError;
}

public function getPODateValidUpto($SectorCd) {
	$inputArr 		= array(date('Y-m-d'), $SectorCd, 1);
	$paraString		= vsprintf("'%s', '%s', %s",$inputArr);
	$DBNameTrade	= $this::DBNameTrade;
	$sql			= "call $DBNameTrade.sp_getPODateValidUpto(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData[0]['DateValidUpto'];
}

public function sendEMailExpDetRTGSDetail($data, &$alertMsgDisp, &$alertMsgStore) {
	$arrCompanyMDisp	= $this->getCompanyMDisp($data['CompanyCd']);
	$sql = "SELECT A.EMailId FROM so_customer_m A WHERE A.CustomerCd='" . $data['CustomerCd'] . "'";
	$eMailDetailArr = $this->execSelectQuery($sql);
	$templateArr = $this->getEMailTemplate(22);
	$alertMsg = $this->strPositSubstitute($templateArr['Body'], array($data['IdExpDet'], $data['DateValidUpto']));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $alertMsg);
	//echo $eMailBody;
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	$templateArr = $this->getEMailTemplate(25);
	$alertMsgDisp = $this->strPositSubstitute($templateArr['Body'], array($arrCompanyMDisp[0]['RTGSCompanyAc']
		, $data['CustomerCd'], $arrCompanyMDisp[0]['RTGSContractPrefix'], $data['IdExpDet'], $arrCompanyMDisp[0]['RTGSBankAddress'], $arrCompanyMDisp[0]['RTGSBankIFSCCd'], $data['TotAmt']));

	$templateArr = $this->getEMailTemplate(26);
	$alertMsgStore = $this->strPositSubstitute($templateArr['Body'], array($arrCompanyMDisp[0]['RTGSCompanyAc']
		, $data['CustomerCd'], $arrCompanyMDisp[0]['RTGSContractPrefix'], $data['IdExpDet']));
}

public function sendEMailExpDetByAdmin($data, &$alertMsgDisp, &$alertMsgStore) {
	$arrCompanyMDisp	= $this->getCompanyMDisp($data['CompanyCd']);
	$sql = "SELECT A.EMailId FROM so_customer_m A WHERE A.CustomerCd='" . $data['CustomerCd'] . "'";
	$eMailDetailArr = $this->execSelectQuery($sql);
	$templateArr = $this->getEMailTemplate(31);
	$Dim1Arr = array($data['IdExpDet'], substr( $this->convertDate($data['DateTime'], FALSE),0,10), $data['DateValidUpto']);
	$sql = "SELECT B.Descript AS Item, A.OrderBox, A.OrderQty, B.UOM FROM so_expdet_magazine_item A INNER JOIN so_item_m B
				ON A.ItemCd=B.ItemCd WHERE A.IdExpDet={$data['IdExpDet']}";
	$ItemDetailArr = $this->execSelectQuery($sql);
	$ItemDetailRowCount = count($ItemDetailArr);
	$Dim2Arr = array();
	for ($curRow=0; $curRow < $ItemDetailRowCount; $curRow++) {
		$Dim2Arr[$curRow] = array($ItemDetailArr[$curRow]['Item'], $ItemDetailArr[$curRow]['OrderBox']
											, $ItemDetailArr[$curRow]['OrderQty'], $ItemDetailArr[$curRow]['UOM']);
		}
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], $Dim1Arr, $Dim2Arr);
	$eMailBody = str_replace(array('\r','\n','\t'),array("\r","\n","\t"), $eMailBody);
	
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);

	$templateArr = $this->getEMailTemplate(25);
	$alertMsgDisp = $this->strPositSubstitute($templateArr['Body'], array($arrCompanyMDisp[0]['RTGSCompanyAc']
		, $data['CustomerCd'], $arrCompanyMDisp[0]['RTGSContractPrefix'], $data['IdExpDet'], $arrCompanyMDisp[0]['RTGSBankAddress'], $arrCompanyMDisp[0]['RTGSBankIFSCCd'], $data['TotAmt'], $data['DateDisp']));

	$templateArr = $this->getEMailTemplate(26);
	$alertMsgStore = $this->strPositSubstitute($templateArr['Body'], array($arrCompanyMDisp[0]['RTGSCompanyAc']
		, $data['CustomerCd'], $arrCompanyMDisp[0]['RTGSContractPrefix'], $data['IdExpDet']));
}

public function sendEMailExpDetTerminate($data) {
	$sql = "SELECT A.EMailId FROM so_customer_m A WHERE A.CustomerCd='" . $data['CustomerCd'] . "'";
	$eMailDetailArr = $this->execSelectQuery($sql);
	$templateArr = $this->getEMailTemplate(34);
	$TerminateReason = array('1' => 'Payment Not Recieved', '2'=>'Order Cancelled By Customer', '3'=>'Order Cancelled By Company'
		, 4 =>'Duplicate PO Create', 5 =>'Wrong Qty',  6=>'Wrong Company', 7=> 'Wrong Despatch Mode' );
	$TerminateReasonCd=$data['TerminateReason'];
	$alertMsg = $this->strPositSubstitute($templateArr['Body'], array($data['IdExpDet'], substr($data['DateTime'],0,10), $TerminateReason[$TerminateReasonCd]));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $alertMsg);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
}

public function sendEMailExpDetPending($data) {
	$sql = "SELECT A.EMailId FROM so_customer_m A WHERE A.CustomerCd='" . $data['CustomerCd'] . "'";
	$eMailDetailArr = $this->execSelectQuery($sql);
	$templateArr = $this->getEMailTemplate(49);
	$PendingReason = array('1' => 'WrongRE11 No', '2'=>'Digital sign missing / single side sign', '3'=>'Corrupt Re-11', 4 =>'Missing van no', 
	5 =>'Holded by customer',  6=>'Route map not available', 7=> 'Van provided already servicing PO' );
	$PendingReasonCd=$data['PendingReason'];
	$alertMsg = $this->strPositSubstitute($templateArr['Body'], array($data['IdExpDet'], substr($data['DateTime'],0,10), $PendingReason[$PendingReasonCd]));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $alertMsg);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
}

public function sendEMailExpDetPendingCustomer($data) {
	$sql = "SELECT A.EMailId, Descript FROM so_customer_m A WHERE A.CustomerCd='" . $data['CustomerCd'] . "'";
	$eMailDetailArr = $this->execSelectQuery($sql);
	$templateArr = $this->getEMailTemplate(57);
	$alertMsg = $this->strPositSubstitute($templateArr['Body'], array($eMailDetailArr[0]['Descript'], $data['IdExpDet'], substr( $this->convertDate($data['DateTime'], FALSE),0,10), $data['VehicleNoInput']));
	echo $eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $alertMsg);
	$objSolarMailer = new solarMailer();
//	$EmailId =$eMailDetailArr[0]['EMailId']; 
	$EmailId= 'solartrade@solargroup.com';
	//$EmailId= 'websupport@solargroup.com';
	$objSolarMailer->sendSolarMail($EmailId, $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	//return $eMailBody;
}

public function Utility_Update_VehicleReachedDate() {
/*	UPDATE so_expdet A INNER JOIN so_expdet_magazine B ON A.IdExpDet=B.IdExpDet SET A.VehicleReachedDate='2014-01-25' WHERE 
	A.VehicleReachedDate='0000-00-00' AND B.SAPInvDate!='0000-00-00' AND B.SAPInvDate<='2014-22-01';
*/
}
//Export Accesssory---------------------------------------------------------------------------
public function getExportAccessory($AccessoryCd = null, $AccessoryCtgCd=null) {
	$searchCnd = (isset($AccessoryCd)) ? " WHERE A.AccessoryCd = '". $AccessoryCd . "' AND  A.AccessoryCtgCd = '". $AccessoryCtgCd . "'" : "";
	$sql		= "SELECT A.AccessoryCd, A.Descript, A.AccessoryCtgCd, B.Descript AS AccessoryCtg, B.CompanyCd, A.Length, A.DelayTime, A.LDSNo, A.DelayNo, A.RelayTime, A.QtyPerBox, A.UOM, B.Division, B.DistChannel, A.IsActive FROM so_accessory_m AS A LEFT OUTER JOIN so_accessory_ctg_m AS B ON A.AccessoryCtgCd = B.AccessoryCtgCd ".$searchCnd;

	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getAccessoryCtgList($PlantCd) {
	$sql		= "SELECT AccessoryCtgCd, Descript, CompanyCd, UOM FROM so_accessory_ctg_m where CompanyCd='$PlantCd' ORDER BY AccessoryCtgCd";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getAccessoryCtgMDisp() {
	$sql		= "SELECT AccessoryCtgCd, Descript, CompanyCd, UOM FROM so_accessory_ctg_m ORDER BY AccessoryCtgCd";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}


public function getExportAccessoryList($search) {
	$searchCnd	= (isset($search)) ? " WHERE A.Descript like '". $search . "%'" : " WHERE 1=1";
	$sql	= "SELECT  A.*, B.AccessoryCtgCd, B.CompanyCd, B.Descript as AcceessoryCtgName from so_accessory_m A JOIN so_accessory_ctg_m B ON A.AccessoryCtgCd= B.AccessoryCtgCd".$searchCnd." ORDER BY A.AccessoryCd DESC";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getExportAccessoryHeaderDataQuery() {
	$sql	= "SELECT A.*,CONCAT(TRIM(A.TokenNoPrefix),IF(A.TokenNo=0,'',CONCAT('/',A.TokenNo%%100))) AS TokenNoFull FROM so_accessory A WHERE A.IdAccessory=%s";
	return $sql;
}

public function insertExportAccessory($data) {
// Spl code for updating UOM (available with Value=related AccCtg) & UOMType (not avilable))
	$sql		= "SELECT  UOM, UOMType FROM so_accessory_ctg_m WHERE AccessoryCtgCd='".$data['AccessoryCtgCd']."'";
	$returnData = $this->execSelectQuery($sql);
	$UOM		= $returnData[0]["UOM"];
	$UOMType	= $returnData[0]["UOMType"];

	$stmt = " INSERT INTO so_accessory_m (AccessoryCd, Descript, AccessoryCtgCd, Length, DelayTime, LDSNo, DelayNo, RelayTime, QtyPerBox, UOM, UOMType, IsActive)
				VALUES(%s, '%s', '%s', '%s', '%s', '%s', '%s', %s, %s, '%s', '%s', %s);";
	$inputArr	= array((int)($data['AccessoryCd']), addslashes($data['Descript']), trim($data['AccessoryCtgCd']), $data['Length'], $data['DelayTime'], $data['LDSNo'], $data['DelayNo'], $data['RelayTime'], (float)$data['QtyPerBox'], $UOM, $UOMType, $data['IsActive']);
	$sql        = vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	if($data['PlantCd']=='1821' || $data['PlantCd']=='1810' ){
		$AccessoryCtgCd=$data['AccessoryCtgCd']-100;
	}
	else{
		$AccessoryCtgCd=$data['AccessoryCtgCd']+100;
	}
	$stmt1 = " INSERT INTO so_accessory_m (AccessoryCd, Descript, AccessoryCtgCd, Length, DelayTime, LDSNo, DelayNo, RelayTime, QtyPerBox, UOM, UOMType, IsActive)
				VALUES(%s, '%s', '%s', '%s', '%s', '%s', '%s', %s, %s, '%s', '%s', %s);";
	$inputArr1	= array((int)($data['AccessoryCd']), addslashes($data['Descript']), trim($AccessoryCtgCd), $data['Length'], $data['DelayTime'], $data['LDSNo'], $data['DelayNo'], $data['RelayTime'], (float)$data['QtyPerBox'], $UOM, $UOMType, $data['IsActive']);
	$sql1        = vsprintf($stmt1,$inputArr1); 
	
	$failMsg	= $this->execUpdateQuery($sql1);
	return $failMsg;
}

public function updateExportAccessory($data) {
// Spl code for updating UOM (available with Value=related AccCtg) & UOMType (not available))
	$sql		= "SELECT  UOM, UOMType FROM so_accessory_ctg_m WHERE AccessoryCtgCd='".$data['AccessoryCtgCd']."'";
	$returnData = $this->execSelectQuery($sql);
	$UOM		= $returnData[0]["UOM"];
	$UOMType	= $returnData[0]["UOMType"];

	$stmt		= " UPDATE so_accessory_m SET Descript = '%s', AccessoryCtgCd ='%s' , Length='%s', DelayTime=%s, LDSNo='%s', DelayNo='%s', RelayTime='%s', QtyPerBox=%s, UOM='%s', UOMType='%s', IsActive=%s WHERE AccessoryCd='%s' and AccessoryCtgCd='%s' ";
	$inputArr	= array(addslashes($data['Descript']), trim($data['AccessoryCtgCd']), $data['Length'], $data['DelayTime'], $data['LDSNo'], $data['DelayNo'], $data['RelayTime'], (float)$data['QtyPerBox'], $UOM, $UOMType, $data['IsActive'], $data['oldAccessoryCd'],  trim($data['AccessoryCtgCd']));
	$sql		= vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}

public function isExistAccessoryCode($mcode, $PlantCd) {
	$sql			= "SELECT * FROM so_accessory_m WHERE AccessoryCd='".$mcode."' ";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function deleteExportAccessory($AccessoryCd) {

	$sql = "delete FROM so_accessory_m WHERE AccessoryCd IN (" . $AccessoryCd . ")";
	$failMsg  = $this->execUpdateQuery($sql);
	return $failMsg;
}

// Accessory ------------------------------------------------------------------------------------------------------------------------------------	
public function getAccessoryList($search) {
/* -1:Internal:InternalCall. 0:All 1:Unapprove:Unapproved(Allow mass Approval) 2:Approve:Approved 3:Pending 4:Complete:Completed/Despatched 
	5:Terminate:Terminated 6:Held 7:Ready(NonTrade:Allow mass Approval) 8:Confirm:Confirmed. Add +100 if want to allow New		*/

	$POStatus = $this::$POStatus;
	$POStatusPending		= self::POStatusPending;
	$POStatusReady		= self::POStatusReady;
	$POStatusConfirm	= self::POStatusConfirm;
	$POStatusDespatch	= self::POStatusDespatch;
	$AccessoryCtgCd	= (int)$_SESSION['Action2Val'];
	$searchCnd	= (isset($search)) ? " WHERE B.Descript like '". $search . "%'" : " WHERE 1=1";
	$searchCnd	.= ($_SESSION['IsCustomer']) ? " AND A.CustomerCd='" .$_SESSION['CustomerCd']. "'" : "";
	$searchCnd	.= ($_SESSION['HasCustomer']) ? " AND B.UserName='" .$_SESSION['UserName']. "'" : "";
	if ($AccessoryCtgCd != -1) {
		$searchCnd	.= " AND A.AccessoryCtgCd=$AccessoryCtgCd";
	}
	switch ($_SESSION['StatusFilter']%100) {
	case $POStatus['Unapprove']:
		$searchCnd .= " AND A.StatusCd='U'";
		break;
	case $POStatus['Pending']:
		$searchCnd	.= " AND A.StatusCd='$POStatusPending'";
		break;
	case $POStatus['Approve']:
		$searchCnd	.= " AND A.StatusCd='A'";
		break;
	case $POStatus['Ready']:
		$searchCnd	.= " AND A.StatusCd='$POStatusReady'";
		break;
	case $POStatus['Confirm']:
		$searchCnd	.= " AND A.StatusCd='$POStatusConfirm'";
		break;
	case $POStatus['Complete']:
		$searchCnd	.= " AND A.StatusCd='$POStatusDespatch'";
		break;
	case $POStatus['GoodsReceipt']:
		$searchCnd	.= " AND A.StatusCd='B'";
		break;
	case $POStatus['Terminate']:
		$searchCnd	.= " AND A.StatusCd='T'";
		break;
	}
	
	$searchCnd	.= " AND IFNULL(B.SectorCd,'{$_SESSION['SectorCd']}')='{$_SESSION['SectorCd']}'";
	$sql	= "SELECT A.IdAccessory, A.DespatchMode, DATE_FORMAT(A.Date,'%d-%m-%Y') AS Date, A.VehicleNo, A.ExpVehicleArrDate, A.RE11ReceiptDate"
		. ",IFNULL(B.Descript,A.CustomerCd) AS Customer,IFNULL(C.Descript,A.StatusCd) AS Status,IFNULL(D.Descript,A.MagazineCd) AS Magazine,IFNULL(E.Descript,A.AccessoryCtgCd) AS AccessoryCtg FROM so_accessory A"
		. " LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd" 
		. " LEFT OUTER JOIN so_status_m C ON A.StatusCd=C.StatusCd" 
		. " LEFT OUTER JOIN so_accessory_ctg_m E ON A.AccessoryCtgCd=E.AccessoryCtgCd" 
		. " LEFT OUTER JOIN so_magazine_m D ON A.MagazineCd=D.MagazineCd".$searchCnd. " ORDER BY A.IdAccessory DESC";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getAccessoryHeaderDataQuery() {
	$sql	= "SELECT A.*,CONCAT(TRIM(A.TokenNoPrefix),IF(A.TokenNo=0,'',CONCAT('/',A.TokenNo%%100))) AS TokenNoFull FROM so_accessory A WHERE A.IdAccessory=%s";
	return $sql;
}

public function getAccessoryInsertQuery() {
	if($_SESSION['SectorCd']=='E'){
	$sql	= "INSERT INTO so_accessory (CustomerCd, AccessoryCtgCd, Date,DespatchMode, MagazineCd, RE11No, RE11Date, VehicleNo, ExpVehicleArrDate, TotalMtr, Rate, ItemAmt, HnFAmt, ExcDuty
		, EduCessAmt, SHSECessAmt, TransportCost, TaxAmt, TotAmt, TotQty, TotBox, RateContractRef, RateContractDate, PaymentDate, RequireDate, AvailableDate, RE11ReceiptDate, StatusCd, Remark, SAPSONo, SAPSODate
		, TransUserName, TransDateTime, ReadyRemark, TentativeDespDate, AvailableDateActual, VehicleReachedDate, VanChangeReason, SAPInvNo, SAPInvDate, TentativeDespDateTo, AvailableDateTo)
		 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %s, %s, %s, %s, %s
			, %s, %s, %s, %s, %s, %s, %s, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');";
	}
	else{
	$sql	= "INSERT INTO so_accessory (CustomerCd, AccessoryCtgCd, Date,DespatchMode, MagazineCd, RE11No, RE11Date, VehicleNo, ExpVehicleArrDate, TotalMtr, Rate, ItemAmt, HnFAmt, ExcDuty
		, EduCessAmt, SHSECessAmt, TransportCost, TaxAmt, TotAmt, TotQty, TotBox, RateContractRef, RateContractDate, PaymentDate, RequireDate, AvailableDate, RE11ReceiptDate, StatusCd, Remark, SAPSONo, SAPSODate
		, TransUserName, TransDateTime, ReadyRemark, TentativeDespDate, AvailableDateActual, VehicleReachedDate, VanChangeReason, IsProductionIntimated, SAPInvNo, SAPInvDate)
		 VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %s, %s, %s, %s, %s
			, %s, %s, %s, %s, %s, %s, %s, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');";
	}
	return $sql ;
}

public function getAccessoryUpdateQuery() {
	if($_SESSION['SectorCd']=='E'){
	$sql	= "UPDATE so_accessory SET DespatchMode='%s', MagazineCd='%s', RE11No='%s', RE11Date='%s', VehicleNo='%s', ExpVehicleArrDate='%s', TotalMtr=%s, Rate=%s, ItemAmt=%s, HnFAmt=%s, ExcDuty=%s, EduCessAmt=%s"
		. ", SHSECessAmt=%s, TransportCost=%s, TaxAmt=%s, TotAmt=%s, TotQty=%s, TotBox=%s, RateContractRef='%s', RateContractDate='%s', PaymentDate='%s', RequireDate='%s', AvailableDate='%s', RE11ReceiptDate='%s'"
		. ", StatusCd='%s', Remark='%s', SAPSONo='%s', SAPSODate='%s', TransUserName='%s', TransDateTime='%s', ReadyRemark='%s', TentativeDespDate='%s', AvailableDateActual='%s', VehicleReachedDate='%s'"
		. ", VanChangeReason='%s', SAPInvNo='%s', SAPInvDate='%s', TentativeDespDateTo='%s', AvailableDateTo='%s' WHERE IdAccessory=%s";
	}else{	
	$sql	= "UPDATE so_accessory SET DespatchMode='%s', MagazineCd='%s', RE11No='%s', RE11Date='%s', VehicleNo='%s', ExpVehicleArrDate='%s', TotalMtr=%s, Rate=%s, ItemAmt=%s, HnFAmt=%s, ExcDuty=%s, EduCessAmt=%s"
		. ", SHSECessAmt=%s, TransportCost=%s, TaxAmt=%s, TotAmt=%s, TotQty=%s, TotBox=%s, RateContractRef='%s', RateContractDate='%s', PaymentDate='%s', RequireDate='%s', AvailableDate='%s', RE11ReceiptDate='%s'"
		. ", StatusCd='%s', Remark='%s', SAPSONo='%s', SAPSODate='%s', TransUserName='%s', TransDateTime='%s', ReadyRemark='%s', TentativeDespDate='%s', AvailableDateActual='%s', VehicleReachedDate='%s'"
		. ", VanChangeReason='%s', IsProductionIntimated='%s', SAPInvNo='%s', SAPInvDate='%s' WHERE IdAccessory=%s";
	}
	return $sql ;
}

public function insertAccessory($data) {
	$stmt		= $this->getAccessoryInsertQuery();
	if($_SESSION['SectorCd']=='E'){
	$inputArr	= array($data['CustomerCd'], $data['AccessoryCtgCd'], $this->convertDate($data['Date'],TRUE,3), $data['DespatchMode']
		, $data['MagazineCd'], $data['RE11No'], $this->convertDate($data['RE11Date'],TRUE), $data['VehicleNo'], $this->convertDate($data['ExpVehicleArrDate'],TRUE)
		, (int)$data['TotalMtr'], (float)$data['Rate'], (float)$data['ItemAmt'], (float)$data['HnFAmt'], (float)$data['ExcDuty'], (float)$data['EduCessAmt'], (float)$data['SHSECessAmt']
		, (float)$data['TransportCost'], (float)$data['TaxAmt'], (float)$data['TotAmt'], (int)$data['TotQty'], (int)$data['TotBox'], trim($data['RateContractRef']), $this->convertDate($data['RateContractDate'],TRUE), $this->convertDate($data['PaymentDate'],TRUE), $this->convertDate($data['RequireDate'],TRUE), $this->convertDate($data['AvailableDate'],TRUE), $this->convertDate($data['RE11ReceiptDate'],TRUE)
		, $data['StatusCd'], $data['Remark'], $data['SAPSONo'], $this->convertDate($data['SAPSODate'],TRUE), $_SESSION['UserName'], date('Y-m-d H:i:s')
		, $data['ReadyRemark'], $this->convertDate($data['TentativeDespDate'],TRUE), $this->convertDate($data['AvailableDateActual'],TRUE)
		, $this->convertDate($data['VehicleReachedDate'],TRUE), $data['VanChangeReason'], $data['SAPInvNo'], $this->convertDate($data['SAPInvDate'],TRUE)
		, $this->convertDate($data['TentativeDespDateTo'],TRUE), $this->convertDate($data['AvailableDateTo'],TRUE)
		);
	}else{
	$inputArr	= array($data['CustomerCd'], $data['AccessoryCtgCd'], $this->convertDate($data['Date'],TRUE,3), $data['DespatchMode']
		, $data['MagazineCd'], $data['RE11No'], $this->convertDate($data['RE11Date'],TRUE), $data['VehicleNo'], $this->convertDate($data['ExpVehicleArrDate'],TRUE)
		, (int)$data['TotalMtr'], (float)$data['Rate'], (float)$data['ItemAmt'], (float)$data['HnFAmt'], (float)$data['ExcDuty'], (float)$data['EduCessAmt'], (float)$data['SHSECessAmt']
		, (float)$data['TransportCost'], (float)$data['TaxAmt'], (float)$data['TotAmt'], (int)$data['TotQty'], (int)$data['TotBox'], trim($data['RateContractRef']), $this->convertDate($data['RateContractDate'],TRUE), $this->convertDate($data['PaymentDate'],TRUE), $this->convertDate($data['RequireDate'],TRUE), $this->convertDate($data['AvailableDate'],TRUE), $this->convertDate($data['RE11ReceiptDate'],TRUE)
		, $data['StatusCd'], $data['Remark'], $data['SAPSONo'], $this->convertDate($data['SAPSODate'],TRUE), $_SESSION['UserName'], date('Y-m-d H:i:s')
		, $data['ReadyRemark'], $this->convertDate($data['TentativeDespDate'],TRUE), $this->convertDate($data['AvailableDateActual'],TRUE)
		, $this->convertDate($data['VehicleReachedDate'],TRUE), $data['VanChangeReason'], (int)$data['IsProductionIntimated'], $data['SAPInvNo'], $this->convertDate($data['SAPInvDate'],TRUE));
	}	
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function updateAccessoryRE11PDF($IdAccessory, $uploadData, $RE11No){
	$filename= $RE11No.'.pdf';
	$target_path = 'upload/re11PDF/Accessory/';
	$target_path = $target_path.$filename;
	//$target_path = $target_path . basename( $_FILES['rellPDF']['name']); 
	if(move_uploaded_file($_FILES['rellPDF']['tmp_name'], $target_path)) {
		$sql = "update so_accessory SET RE11PDF = '".$filename."' where IdAccessory =".$IdAccessory;
		$result = $this->execUpdateQuery($sql);
	}
}

public function removeAccessoryRE11PDF($IdAccessory, $filename){
	$target_path = '/var/zpanel/hostdata/solarexp/public_html/b2b_solarexplosives_com/upload/re11PDF/Accessory/';
	$target_path = $target_path.$filename; 
	unlink($target_path);
	$sql = "update so_accessory SET RE11PDF = '' where IdAccessory =".$IdAccessory;
	$result = $this->execUpdateQuery($sql);
	return $result;
}

public function getAccessoryRE11PDF($IdAccessory){
	$sql = "select RE11PDF from so_accessory where IdAccessory =".$IdAccessory;
	$result = $this->execSelectQuery($sql);
	return $result;
	
}

public function updateAccessory($data) {
	$oriDataArr = $this->getAccessoryHeader($data['IdAccessory']);
	$stmt		= $this->getAccessoryUpdateQuery();
	if($_SESSION['SectorCd']=='E'){
	$inputArr	= array($data['DespatchMode']
		, $data['MagazineCd'], $data['RE11No'], $this->convertDate($data['RE11Date'],TRUE), $data['VehicleNo'], $this->convertDate($data['ExpVehicleArrDate'],TRUE)
		, (int)$data['TotalMtr'], (float)$data['Rate'], (float)$data['ItemAmt'], (float)$data['HnFAmt'], (float)$data['ExcDuty'], (float)$data['EduCessAmt'], (float)$data['SHSECessAmt']
		, (float)$data['TransportCost'], (float)$data['TaxAmt'], (float)$data['TotAmt'], (int)$data['TotQty'], (int)$data['TotBox'], trim($data['RateContractRef']), $this->convertDate($data['RateContractDate'],TRUE), $this->convertDate($data['PaymentDate'],TRUE)
		, $this->convertDate($data['RequireDate'],TRUE), $this->convertDate($data['AvailableDate'],TRUE), $this->convertDate($data['RE11ReceiptDate'],TRUE)
		, $data['StatusCd'], $data['Remark'], $data['SAPSONo'], $this->convertDate($data['SAPSODate'],TRUE), $_SESSION['UserName'], date('Y-m-d H:i:s')
		, $data['ReadyRemark'], $this->convertDate($data['TentativeDespDate'],TRUE), $this->convertDate($data['AvailableDateActual'],TRUE)
		, $this->convertDate($data['VehicleReachedDate'],TRUE), $data['VanChangeReason'],  $data['SAPInvNo'], $this->convertDate($data['SAPInvDate'],TRUE)
		, $this->convertDate($data['TentativeDespDateTo'],TRUE), $this->convertDate($data['AvailableDateTo'],TRUE), $data['IdAccessory']);
	}
	else{
	$inputArr	= array($data['DespatchMode']
		, $data['MagazineCd'], $data['RE11No'], $this->convertDate($data['RE11Date'],TRUE), $data['VehicleNo'], $this->convertDate($data['ExpVehicleArrDate'],TRUE)
		, (int)$data['TotalMtr'], (float)$data['Rate'], (float)$data['ItemAmt'], (float)$data['HnFAmt'], (float)$data['ExcDuty'], (float)$data['EduCessAmt'], (float)$data['SHSECessAmt']
		, (float)$data['TransportCost'], (float)$data['TaxAmt'], (float)$data['TotAmt'], (int)$data['TotQty'], (int)$data['TotBox'], trim($data['RateContractRef']), $this->convertDate($data['RateContractDate'],TRUE), $this->convertDate($data['PaymentDate'],TRUE)
		, $this->convertDate($data['RequireDate'],TRUE), $this->convertDate($data['AvailableDate'],TRUE), $this->convertDate($data['RE11ReceiptDate'],TRUE)
		, $data['StatusCd'], $data['Remark'], $data['SAPSONo'], $this->convertDate($data['SAPSODate'],TRUE), $_SESSION['UserName'], date('Y-m-d H:i:s')
		, $data['ReadyRemark'], $this->convertDate($data['TentativeDespDate'],TRUE), $this->convertDate($data['AvailableDateActual'],TRUE)
		, $this->convertDate($data['VehicleReachedDate'],TRUE), $data['VanChangeReason'], (int)$data['IsProductionIntimated'], $data['SAPInvNo'], $this->convertDate($data['SAPInvDate'],TRUE), $data['IdAccessory']);
	}
	
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);

	if ($data['RE11ReceiptDate']!='' && $oriDataArr[0]['RE11ReceiptDate']=='0000-00-00')
		$this->sendEMailRE11Receipt($data['IdAccessory'], 3);
	return $returnData;
}

public function getAccessoryItemInsertQuery() {
	$sql	= "INSERT INTO so_accessory_item (IdAccessory, CustomerCd, AccessoryCtgCd, AccessoryCd, OrderBox, OrderQty)"
			. " VALUES (%s, '%s', '%s', '%s', %s, %s)";
	return $sql ;
}

public function getAccessoryItemUpdateQuery() {
	$sql	= "UPDATE so_accessory_item SET CustomerCd='%s', AccessoryCtgCd='%s', AccessoryCd=%s, OrderBox=%s, OrderQty=%s WHERE UniqueId=%s";
	return $sql ;
}

public function getAccessoryItemDeleteQuery() {
	$sql	= "DELETE FROM so_accessory_item WHERE UniqueId=%s";
	return $sql ;
}

public function insertAccessoryItem($data) {
	$returnData = array();
	$queryInsert	= $this->getAccessoryItemInsertQuery();

	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
	if (!isset($data['AccessoryCd1_'.$curRowNo]) || trim($data['AccessoryCd1_'.$curRowNo])=='' || (int)$data['OrderQty1_'.$curRowNo]<=0) {
		continue;
	}	
	$inputArr	= array($data['IdAccessory'], $data['CustomerCd'], $data['AccessoryCtgCd'], $data['AccessoryCd1_'.$curRowNo]
					, (int)$data['OrderBox1_'.$curRowNo], (int)$data['OrderQty1_'.$curRowNo]);
	$sql		= vsprintf($queryInsert, $inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	if ($returnData) return $returnData;
	}
	return $returnData;
}

public function updateAccessoryItem($data) {
	$queryInsert	= $this->getAccessoryItemInsertQuery();
	$queryUpdate	= $this->getAccessoryItemUpdateQuery();
	$queryDelete	= $this->getAccessoryItemDeleteQuery();
	$returnData		= array();
	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		if (!isset($data['AccessoryCd1_'.$curRowNo])) {
			continue;
		}	

		$UniqueId = (int)$data['UniqueId1_'.$curRowNo];
		if (trim($data['AccessoryCd1_'.$curRowNo])=='' || (int)$data['OrderQty1_'.$curRowNo]<=0) {
			if ($UniqueId>0) {
				$inputArr	= array();
				$inputArr	= array($UniqueId);
				$sql		= vsprintf($queryDelete, $inputArr);
				$returnData	= $this->execUpdateQuery($sql);
				if ($returnData) return $returnData;
			}
		} else {
			if ($UniqueId>0) {
				$inputArr	= array($data['CustomerCd'], $data['AccessoryCtgCd'], $data['AccessoryCd1_'.$curRowNo]
								, (int)$data['OrderBox1_'.$curRowNo], (int)$data['OrderQty1_'.$curRowNo], $UniqueId);
				$sql		= vsprintf($queryUpdate,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
			} else {
				$inputArr	= array($data['IdAccessory'], $data['CustomerCd'], $data['AccessoryCtgCd'], $data['AccessoryCd1_'.$curRowNo]
								, (int)$data['OrderBox1_'.$curRowNo], (int)$data['OrderQty1_'.$curRowNo]);
				$sql		= vsprintf($queryInsert,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
			}
			if ($returnData) return $returnData;
		}
	}
	return $returnData;
}

public function getAccessoryHeader($IdAccessory) {
	$stmt		= $this->getAccessoryHeaderDataQuery(); 
	$inputArr 	= array($IdAccessory);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getAccessoryPropertyList($AccessoryCtgCd, $PropertyNo, $Property) {
	$sql = "SELECT DISTINCT $Property AS Property$PropertyNo FROM so_accessory_m WHERE AccessoryCtgCd=$AccessoryCtgCd ORDER BY CAST($Property AS DECIMAL(6,2))";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

/*public function getAccessoryMDisp($AccessoryCtgCd) {
	$sql = "SELECT * FROM so_accessory_m WHERE AccessoryCtgCd=$AccessoryCtgCd";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}*/

public function getAccessoryMDisp($AccessoryCtgCd, $PropertyName1, $PropertyName2) {
	$sql = "SELECT AccessoryCd, Descript, $PropertyName1 AS Property1" . ($PropertyName2=='' ? '' : ", $PropertyName2 AS Property2") 
		. ", QtyPerBox, UOM FROM so_accessory_m WHERE AccessoryCtgCd=$AccessoryCtgCd";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getAccessoryVehicleMDisp($CustomerCd, $Date, $DespatchModeFOR) {
	$inputArr 		= array($CustomerCd, $this->convertDate($Date, TRUE), $DespatchModeFOR);
	$paraString		= vsprintf("'%s','%s', %s",$inputArr);
	$sql			= "call sp_getPOVehicleMDisp(" . $paraString. ")";		// VehicleM same for PO & Accessory
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getAccessoryCustDetail($CustomerCd, $AccessoryCtgCd) {
	$stmt		= "SELECT A.IsInState, A.TaxType,IFNULL(B.DespatchMode,'X') AS DespatchMode, IFNULL(B.FromQty,0) AS FromQty, IFNULL(B.Rate,0.0000) AS Rate"
		. " FROM so_customer_m A LEFT OUTER JOIN so_accessory_ctg_rate B ON A.IsInState=B.IsInState AND B.AccessoryCtgCd=%s"
		. " WHERE A.CustomerCd='%s' ORDER BY B.DespatchMode, B.FromQty DESC";
	$inputArr 	= array($AccessoryCtgCd, $CustomerCd);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getAccessoryDirectSub($IdAccessory, $StatusCd, $AccessoryCtgCd) {
	$inputArr 		= array($IdAccessory, $StatusCd, $AccessoryCtgCd);
	$paraString		= vsprintf("%s, '%s','%s'", $inputArr);
	$sql			= "call sp_getAccessoryDirectSub(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getAccessoryIndirectSub($IdAccessory, $AccessoryCtgCd, $PropertyName1, $PropertyName2) {
	$sql = "SELECT A.*, B.$PropertyName1 AS Property1" . ($PropertyName2=='' ? '' : ", B.$PropertyName2 AS Property2") 
		. ", B.Descript, B.QtyPerBox, B.UOM FROM so_accessory_item A LEFT OUTER JOIN so_accessory_m B 
		ON A.AccessoryCd=B.AccessoryCd WHERE A.IdAccessory=$IdAccessory  AND B.AccessoryCtgCd = $AccessoryCtgCd ORDER BY A.UniqueId";

	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}


public function getSolarAEDComVanPlan() {
	$sql = "SELECT A.*, B.Descript, C.MagazineCd, C.RE11No, C.RE11Date, C.SAPSONo, C.SAPSODate FROM so_expdet A JOIN so_customer_m B on A.CustomerCd= B.CustomerCd JOIN 
	so_expdet_magazine C on A.IdExpdet= C.IdExpdet JOIN so_expdet_magazine_item D on A.IdExpDet=D.IdExpDet and C.MagazineCd=D.MagazineCd 
	WHERE A.CompanyCd='1800' and A.DespatchMode='F' and  A.StatusCd IN ('U', 'W', 'A') and D.ItemCd IN ('20000120','20000121', '20005315') group By C.MagazineCd, A.IdExpdet Order BY VehicleNo, IdExpdet DESC";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getEconomicAEDComVanPlan() {
	$sql = "SELECT distinct(A.IdExpdet) As PONo,  A.*, B.Descript, C.MagazineCd, C.RE11No, C.RE11Date, C.SAPSONo, C.SAPSODate FROM so_expdet A JOIN so_customer_m B on A.CustomerCd= B.CustomerCd JOIN 
	so_expdet_magazine C on A.IdExpdet= C.IdExpdet JOIN so_expdet_magazine_item D on A.IdExpDet=D.IdExpDet and C.MagazineCd=D.MagazineCd 
	WHERE A.CompanyCd='1100' and A.DespatchMode='F' and  A.StatusCd IN ('U', 'W', 'A', 'P') and D.ItemCd IN ('20001340','20001341', '20002672', '20009157', '20009607', '20009608', '20005568')  
	Order BY VehicleNo, IdExpdet DESC";
	$returnData = $this->execSelectQuery($sql);              
	return $returnData;
}

public function getEconomicAccessoryComVanPlan() {
	$sql = "SELECT Distinct(A.IdAccessory) As IdAccessory, A.CustomerCd, A.AccessoryCtgCd, A.Date, A.DespatchMode, A.VehicleNo, A.StatusCd,  A.RE11No, A.RE11Date, A.SAPSONo, A.SAPSODate, B.Descript
 FROM so_accessory A JOIN so_customer_m B on A.CustomerCd= B.CustomerCd  WHERE  A.DespatchMode='F' and  A.StatusCd IN ('U', 'P', 'A', 'W') and  A.AccessoryCtgCd IN ('3', '4', '5', '7')
ORDER BY VehicleNo, IdAccessory DESC";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function approveAccessory($approveDocList, $isApproved, &$TokenNoAr=NULL) {
	$stmt		= "UPDATE so_accessory SET StatusCd='%s', ApprovedByUserName='%s', ApprovalDateTime='%s' WHERE IdAccessory IN (%s)";
	if ($isApproved) {
		$inputArr 	= array('A', $_SESSION['UserName'], date('Y-m-d H:i:s'), $approveDocList);
	} else {
		$inputArr 	= array('U', '', '', $approveDocList);
	}
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execUpdateQuery($sql);

	if ($isApproved) {
		$sql	= "call sp_updateAccessoryTokenNo('{$_SESSION['SectorCd']}', '$approveDocList', 0);";
		$TokenNoAr	= $this->execSelectQuery($sql);
		if ($_SESSION['IsTradeSector']) {
			$this->sendEMailPOAccessApproval($approveDocList, 4);
		}
	} else {
		$sql	= "call sp_updateAccessoryTokenNo('{$_SESSION['SectorCd']}', '$approveDocList', 1);";
		$this->execUpdateQuery($sql);
	}
	return $returnData;
}

public function confirmAccessory($approveDocList) {
	$POStatusConfirm = self::POStatusConfirm;
	$stmt		= "UPDATE so_accessory SET StatusCd='%s' WHERE IdAccessory IN (%s)";
	$inputArr 	= array($POStatusConfirm, $approveDocList);
	$sql		= vsprintf($stmt, $inputArr);
	$this->execUpdateQuery($sql);

	$this->sendEMailPOAccessApproval($approveDocList, 5);
	return $returnData;
}

public function uploadAccessory2SAP($approveDocList, $StatusCd) {
// We only put the file in upload/po2sap folder. SAP thro an utility, would read & update in SAP & then move it to upload/Backup folder
	$IsClubMagVan	= $_SESSION['IsTradeSector'] ? 0 : 1;
	$stmt		= "call sp_getAccessory2SAPUpload('$approveDocList', '$StatusCd', $IsClubMagVan)";
	$reportData	= $this->execSelectQuery($stmt);


	$fileFolder = '/home/solarexplosives/solar_sap/po2sap/' . $_SESSION['Sector'] . '/';
	$row = 0;
	$rowTotal = count($reportData);

	$IsError	= FALSE;
	while ($row<$rowTotal) {
		$curAccessoryNumber = $reportData[$row]['AccessoryNumber'];
		if ($reportData[$row]['OrderType']=='Z5') {			// so_customer_m.IsDepot
			$fileName = "Accessory".trim($curAccessoryNumber).'.txt';		
		} else {
			$fileName = "Accessory".$curAccessoryNumber.'.txt';
		}
		$folderFileName = $fileFolder.$fileName;
		$handle = fopen($folderFileName,'wb');
		if (!$handle) {
			$IsError	= TRUE;
			break;
		}

		while ($row<$rowTotal && $curAccessoryNumber == $reportData[$row]['AccessoryNumber']) {
			if ($reportData[$row]['OrderType']=='Z5') {				// so_customer_m.IsDepot
// AccessoryNumber, OrderType, Plant, RE11No, RE11Date, VehicleNo, AccessoryCd, OrderQty, CustomerCd,  MagazineCd, RateContractRef, RateContractDate, OrderBox, AvailableDate
				$curRow = $reportData[$row];
				$curRec = $curRow['AccessoryNumber'] . "\t" . $curRow['OrderType'] . "\t" . $curRow['Plant'] . "\t" . $curRow['RE11No'] 
					. "\t" . $curRow['RE11Date'] . "\t" . $curRow['VehicleNo'] . "\t" . $curRow['AccessoryCd'] . "\t" . $curRow['OrderQty'] 
					. "\t" . $curRow['CustomerCd'] . "\t" . $curRow['MagazineCd'] . "\t" . $curRow['RateContractRef'] 
					. "\t" . $curRow['RateContractDate'] . "\t" . $curRow['OrderBox'] . "\t" . $curRow['AvailableDate'] . "\r\n";
			} else {
// OrderType, SalesOrg, DistChannel, Division, CustomerCd, MagazineCd, AccessoryNumber, AccessoryDate, AccessoryCd, OrderQty, Plant, VehicleNo, RE11No, RE11Date, RateContractRef, RateContractDate, OrderBox, AvailableDate
				$curRec = trim(implode("\t", $reportData[$row]))."\r\n";
			}
		
			fwrite($handle, $curRec);
			$row++;
		}
		fclose($handle);
	}
	return $IsError;
}

public function sendEMailAccessorySubmit($data) {
	$sql = "SELECT A.Descript FROM so_customer_m A WHERE A.CustomerCd='" . $data['CustomerCd'] . "'";
	$CustNameArr = $this->execSelectQuery($sql);
	$eMailDetailArr[0]['EMailId'] = 'm.bhalerao@solargroup.com';
	$templateArr = $this->getEMailTemplate(35);
	$alertMsg = $this->strPositSubstitute($templateArr['Body'], array($data['IdAccessory'], substr($data['Date'],0,10), $CustNameArr[0]['Descript']));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $alertMsg);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
}

	
public function sendEMailAccessorySubmit2Customer($data) {
	$sql = "SELECT B.CompanyCd FROM so_accessory A INNER JOIN so_accessory_ctg_m B
				ON A.AccessoryCtgCd=B.AccessoryCtgCd WHERE A.IdAccessory={$data['IdAccessory']}";
	$CompanyCdArrArr = $this->execSelectQuery($sql);
	$arrCompanyMDisp	= $this->getCompanyMDisp($CompanyCdArrArr[0]['CompanyCd']);

	$sql = "SELECT A.EMailId FROM so_customer_m A WHERE A.CustomerCd='" . $data['CustomerCd'] . "'";
	$eMailDetailArr = $this->execSelectQuery($sql);
	$templateArr = $this->getEMailTemplate(38);
	$Dim1Arr = array($data['IdAccessory'], substr($data['Date'],0,10));
	$sql = "SELECT B.Descript AS Item, A.OrderBox, A.OrderQty, B.UOM FROM so_accessory_item A INNER JOIN so_accessory_m B ON A.AccessoryCd=B.AccessoryCd WHERE A.IdAccessory={$data['IdAccessory']}";
	$ItemDetailArr = $this->execSelectQuery($sql);
	$ItemDetailRowCount = count($ItemDetailArr);
	$Dim2Arr = array();
	for ($curRow=0; $curRow < $ItemDetailRowCount; $curRow++) {
		$Dim2Arr[$curRow] = array($ItemDetailArr[$curRow]['Item'], $ItemDetailArr[$curRow]['OrderBox']
											, $ItemDetailArr[$curRow]['OrderQty'], $ItemDetailArr[$curRow]['UOM']);
		}
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], $Dim1Arr, $Dim2Arr);
	$eMailBody = str_replace(array('\r','\n','\t'),array("\r","\n","\t"), $eMailBody);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
//echo $eMailBody;
	//$templateArr = $this->getEMailTemplate(38);
}

public function sendEMailAccessoryReady($data) {
	$sql = "SELECT A.CompanyCd FROM so_accessory_ctg_m A INNER JOIN so_accessory B ON A.AccessoryCtgCd=B.AccessoryCtgCd WHERE B.IdAccessory={$data['IdAccessory']}";

	$CompanyCdArr = $this->execSelectQuery($sql);
	$arrCompanyMDisp	= $this->getCompanyMDisp($CompanyCdArr[0]['CompanyCd']);
	$sql = "SELECT A.EMailId FROM so_customer_m A WHERE A.CustomerCd='" . $data['CustomerCd'] . "'";
	$eMailDetailArr = $this->execSelectQuery($sql);
	if ($data['DespatchMode']=='X') {
		$dayMargin = 1;
		$templateArr = $this->getEMailTemplate(32);

		$alertMsg = $this->strPositSubstitute($templateArr['Body'], array($data['IdAccessory'], $arrCompanyMDisp[0]['Descript']	, $this->addDate(null, $dayMargin)));

		$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $alertMsg);
	} else {
		$templateArr = $this->getEMailTemplate(33);
		$alertMsg = $this->strPositSubstitute($templateArr['Body'], array($data['IdAccessory']));
		$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $alertMsg);
	}
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
}

	
// Dealer Despatch Plan. Defunct -------------------------------------------------------------------------------------------------------------
public function getDespPlanList($search) {
	$searchCnd	= (isset($search)) ? " WHERE B.Descript like '". $search . "%'" : " WHERE 1=1";
	$searchCnd	.= ($_SESSION['IsCustomer']) ? " AND A.CustomerCd='" .$_SESSION['CustomerCd']. "'" : "";
	$sql	= "SELECT A.CustomerCd, IFNULL(B.Descript,A.CustomerCd) AS Customer, DATE_FORMAT(A.Date,'%d-%m-%Y') AS Date"
		. ", IFNULL(C.Descript,A.StatusCd) AS Status FROM so_desp_plan A"
		. " LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd" 
		. " LEFT OUTER JOIN so_status_m C ON A.StatusCd=C.StatusCd" 
		.$searchCnd. " ORDER BY A.Date DESC,B.Descript";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function isExistDespPlan($CustomerCd, $Date) {
	$sql			= "SELECT * FROM so_desp_plan WHERE CustomerCd='".$CustomerCd."' AND Date='".$this->convertDate($Date,TRUE)."'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function insertDespPlan($data) {
	$sql = " INSERT INTO so_desp_plan (CustomerCd, Date, StatusCd, Remark, TransUserName, TransDateTime)
		VALUES('%s', '%s', '%s', '%s', '%s', '%s');";
	$inputArr	= array($data['CustomerCd'], $this->convertDate($data['Date'],TRUE,1), $data['StatusCd']
			, $data['Remark'], $_SESSION['UserName'], date('Y-m-d H:i:s'));
	$sql		= vsprintf($sql,$inputArr);
	$returnData = $this->execUpdateQuery($sql);
	return $returnData;
}

public function getDespPlanHeader($CustomerCd, $Date) {
	$sql		= "SELECT * FROM so_desp_plan WHERE CustomerCd='".$CustomerCd."' AND Date='".$this->convertDate($Date,TRUE)."'";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function updateDespPlan($data) {
	$stmt		= "UPDATE so_desp_plan SET StatusCd='%s', Remark='%s', TransUserName='%s', TransDateTime='%s'"
					. " WHERE CustomerCd='%s' AND Date='%s'";
	$inputArr	= array($data['StatusCd'], $data['Remark'], $_SESSION['UserName'], date('Y-m-d H:i:s'), $data['oldCustomerCd'], $this->convertDate($data['oldDate'],TRUE));
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

// Daily Stock, Sale & DespatchPlan --------------------------------------------------------------------------------------------------------------------
public function getNonRcptPO($CustomerCd) {
	$inputArr	= array($CustomerCd);
	$paraString		= vsprintf("'%s'", $inputArr);
	$sql			= "call sp_getNonRcptPO(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}

public function updateNonRcptPO($data) {
	$queryUpdate	= "UPDATE so_expdet SET VehicleReachedDate = '%s', StatusCd = '%s' WHERE IdExpDet=%s";
	for($curRowNo=1; $curRowNo<=$data['LastRowNo1']; $curRowNo++) {
		$IdExpDet		= (int)$data['IdExpDet1_'.$curRowNo];
		$VehicleReachedDate	= $data['VehicleReachedDate1_'.$curRowNo];
		if (trim($VehicleReachedDate)=='') {
			continue;
		}	
		$VehicleReachedDate	= $this->convertDate($VehicleReachedDate,TRUE,1);
		$inputArr	= array($VehicleReachedDate, self::POStatusGoodsReceipt, $IdExpDet);
		$sql		= vsprintf($queryUpdate, $inputArr);
		$returnData	= $this->execUpdateQuery($sql);
	}
}

public function getDailyStockOpenDate($CustomerCd, $FromDailyStock) {
	$inputArr	= array($CustomerCd, ($FromDailyStock ? self::MinDailyStockAddTime : '23:59:59'));
	$paraString		= vsprintf("'%s', '%s'", $inputArr);
	$sql			= "call sp_getDailyStockOpenDate(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getDailyStockList($search, $ListForMY) {
	$DTSAnsi	= preg_replace('/(\d{2})[-\/](\d{4})/', "$2-$1", $ListForMY) . '-01';
	$DTEAnsi	= $this->addDate($this->addDate($DTSAnsi, '+1 month', FALSE), '-1 day', FALSE);
	$searchCnd	= (isset($search)) ? " WHERE B.Descript like '". $search . "%'" : " WHERE 1=1";
	$searchCnd	.= ($_SESSION['IsCustomer']) ? " AND A.CustomerCd='" .$_SESSION['CustomerCd']. "'" : "";
	switch ($_SESSION['StatusFilter']) {
	case 0:
		break;
	case 2:
		$searchCnd	.= " AND A.StatusCd='A'";
		break;
	default:		// 1
		$searchCnd	.= " AND A.StatusCd='U'";
		break;
	}
	$sql	= "SELECT A.CustomerCd, IFNULL(B.Descript,A.CustomerCd) AS Customer, DATE_FORMAT(A.Date,'%d-%m-%Y') AS Date"
		. ", IFNULL(C.Descript,A.StatusCd) AS Status FROM so_daily_stock A"
		. " LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd" 
		. " LEFT OUTER JOIN so_status_m C ON A.StatusCd=C.StatusCd" 
		.$searchCnd. " AND DATE_FORMAT(A.Date,'%Y-%m-%d') BETWEEN '$DTSAnsi' AND '$DTEAnsi' ORDER BY A.Date DESC,B.Descript";

	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function isExistDailyStock($CustomerCd, $Date, $IsDateANSI=FALSE) {
	$sql			= "SELECT * FROM so_daily_stock WHERE CustomerCd='".$CustomerCd."' AND Date='".($IsDateANSI ? $Date : $this->convertDate($Date,TRUE,1)) ."'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function AllowDailyStockDates($CustomerCd) {
	$sql			= "SELECT * FROM so_daily_stock WHERE CustomerCd='".$CustomerCd."' AND Date='".($IsDateANSI ? $Date : $this->convertDate($Date,TRUE,1)) ."'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function insertDailyStock($data) {
	$sql = " INSERT INTO so_daily_stock (CustomerCd, Date, CreateDateTime, StatusCd, Remark, TransUserName, TransDateTime)
		VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s');";
	$rr = $this->convertDate($data['CreateDateTime'],TRUE,3);
	$inputArr	= array($data['CustomerCd'], $this->convertDate($data['Date'],TRUE,1), date('Y-m-d H:i:s'), $data['StatusCd']
			, $data['Remark'], $_SESSION['UserName'], date('Y-m-d H:i:s'));
	$sql		= vsprintf($sql,$inputArr);
	$returnData = $this->execUpdateQuery($sql);
	return $returnData;
}

public function getDailyStockHeader($CustomerCd, $Date) {
	$sql		= "SELECT * FROM so_daily_stock WHERE CustomerCd='".$CustomerCd."' AND Date='".$this->convertDate($Date,TRUE,1)."'";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function updateDailyStock($data) {
	if ($_SESSION['IsCustomer']) {
		$stmt		= "UPDATE so_daily_stock SET StatusCd='%s', Remark='%s', TransUserName='%s', TransDateTime='%s'"
						. " WHERE CustomerCd='%s' AND Date='%s'";
		$inputArr	= array($data['StatusCd'], $data['Remark'], $_SESSION['UserName'], date('Y-m-d H:i:s'), $data['oldCustomerCd'], $this->convertDate($data['oldDate'],TRUE,1));
	} else {
		$stmt		= "UPDATE so_daily_stock SET StatusCd='%s', Remark='%s'"
						. " WHERE CustomerCd='%s' AND Date='%s'";
		$inputArr	= array($data['StatusCd'], $data['Remark'], $data['oldCustomerCd'], $this->convertDate($data['oldDate'],TRUE,1));
	}
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

// DailyStockItem (Grid-1) ------------------------------------------------------
public function getDailyStockItemInsertQuery() {
	$sql	= "INSERT INTO so_daily_stock_item (CustomerCd, Date, ItemCd, OpStockQty, TDReceiptQty, TDSaleQty, TDOwnUseQty, ClStockSaleQty
					, ClStockOwnUseQty, ArrivalQty, PendingQty, DespPlanQty, OwnUsePlanQty, DaysLast, TDOtherReceiptQty) 
				VALUES ('%s', '%s', '%s', %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)";
	return $sql ;
}

public function getDailyStockItemUpdateQuery() {
	$sql	= "UPDATE so_daily_stock_item SET OpStockQty=%s, TDReceiptQty=%s, TDSaleQty=%s, TDOwnUseQty=%s
					, ClStockSaleQty=%s, ClStockOwnUseQty=%s, ArrivalQty=%s, PendingQty=%s, DespPlanQty=%s, OwnUsePlanQty=%s, DaysLast=%s, TDOtherReceiptQty=%s
					WHERE CustomerCd='%s' AND Date='%s' AND ItemCd='%s'";
	return $sql ;
}

public function getDailyStockItemDeleteQuery() {
	$sql	= "DELETE FROM so_daily_stock_item WHERE CustomerCd='%s' AND Date='%s' AND ItemCd='%s'";
	return $sql ;
}

public function insertDailyStockItem($data) {
	$queryInsert	= $this->getDailyStockItemInsertQuery();
	$returnData		= '';

	$CustomerCd	= $data['CustomerCd'];
	$Date = $this->convertDate($data['Date'],TRUE,1);
	for($curRowNo=1; $curRowNo<=$data['LastRowNo1']; $curRowNo++) {
		if (!isset($data['ItemCd1_'.$curRowNo])) continue;

		$ItemCd			= $data['ItemCd1_'.$curRowNo];
		$OpStockQty		= (int)$data['OpStockQty1_'.$curRowNo];
		$TDReceiptQty	= (int)$data['TDReceiptQty1_'.$curRowNo];
		$TDOtherReceiptQty	= (int)$data['TDOtherReceiptQty1_'.$curRowNo];
		$TDSaleQty		= (int)$data['TDSaleQty1_'.$curRowNo];
		$TDOwnUseQty	= (int)$data['TDOwnUseQty1_'.$curRowNo];
		$ClStockSaleQty	= (int)@$data['ClStockSaleQty1_'.$curRowNo];
		$ClStockOwnUseQty= (int)@$data['ClStockOwnUseQty1_'.$curRowNo];
		$ArrivalQty		= (int)$data['ArrivalQty1_'.$curRowNo];
		$PendingQty		= (int)$data['PendingQty1_'.$curRowNo];
		$DespPlanQty	= (int)$data['DespPlanQty1_'.$curRowNo];
		$OwnUsePlanQty	= (int)$data['OwnUsePlanQty1_'.$curRowNo];
		$DaysLast		= (int)$data['DaysLast1_'.$curRowNo];
		if (trim($ItemCd)=='' || ($OpStockQty<=0 && $TDReceiptQty<=0 && $TDOtherReceiptQty<=0 && $TDSaleQty<=0 && $TDOwnUseQty<=0 && $ClStockSaleQty<=0 && $ClStockOwnUseQty<=0 
									&& $ArrivalQty<=0 && $PendingQty<=0 && $DespPlanQty<=0 && $OwnUsePlanQty<=0 && $DaysLast<=0)) {
			continue;
		}	
		$inputArr	= array();
		$inputArr	= array($CustomerCd, $Date, $ItemCd, $OpStockQty, $TDReceiptQty, $TDSaleQty, $TDOwnUseQty, $ClStockSaleQty
						, $ClStockOwnUseQty, $ArrivalQty, $PendingQty, $DespPlanQty, $OwnUsePlanQty, $DaysLast, $TDOtherReceiptQty);
		$sql		= vsprintf($queryInsert,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
		if ($returnData) return $returnData;
	}
return $returnData;
}

public function updateDailyStockItem($data) {
	$queryInsert	= $this->getDailyStockItemInsertQuery();
	$queryUpdate	= $this->getDailyStockItemUpdateQuery();
	$queryDelete	= $this->getDailyStockItemDeleteQuery();
	$returnData		= '';

	$CustomerCd	= $data['CustomerCd'];
	$Date = $this->convertDate($data['Date'], TRUE, 1);
	for($curRowNo=1; $curRowNo<=$data['LastRowNo1']; $curRowNo++) {
		if (!isset($data['ItemCd1_'.$curRowNo])) continue;

		$ItemCd			= $data['ItemCd1_'.$curRowNo];
		$OpStockQty		= (int)$data['OpStockQty1_'.$curRowNo];
		$TDReceiptQty	= (int)$data['TDReceiptQty1_'.$curRowNo];
		$TDOtherReceiptQty	= (int)$data['TDOtherReceiptQty1_'.$curRowNo];
		$TDSaleQty		= (int)$data['TDSaleQty1_'.$curRowNo];
		$TDOwnUseQty	= (int)$data['TDOwnUseQty1_'.$curRowNo];
		$ClStockSaleQty	= (int)$data['ClStockSaleQty1_'.$curRowNo];
		$ClStockOwnUseQty= (int)$data['ClStockOwnUseQty1_'.$curRowNo];
		$ArrivalQty		= (int)$data['ArrivalQty1_'.$curRowNo];
		$PendingQty		= (int)$data['PendingQty1_'.$curRowNo];
		$DespPlanQty	= (int)$data['DespPlanQty1_'.$curRowNo];
		$OwnUsePlanQty	= (int)$data['OwnUsePlanQty1_'.$curRowNo];
		$DaysLast		= (int)$data['DaysLast1_'.$curRowNo];
		if (trim($ItemCd)=='') {
			continue;
		}	

		if ($OpStockQty<=0 && $TDReceiptQty<=0 && $TDOtherReceiptQty<=0 && $TDSaleQty<=0 && $TDOwnUseQty<=0 && $ClStockSaleQty<=0 && $ClStockOwnUseQty<=0 
									&& $ArrivalQty<=0 && $PendingQty<=0 && $DespPlanQty<=0 && $OwnUsePlanQty<=0 && $DaysLast<=0) {
			$inputArr	= array();
			$inputArr	= array($CustomerCd, $Date, $ItemCd);
			$sql		= vsprintf($queryDelete, $inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		} else {
			$queryCheck	= "SELECT COUNT(*) AS Count FROM so_daily_stock_item WHERE CustomerCd='%s' AND Date='%s' AND ItemCd='%s'";
			$inputArr	= array();
			$inputArr	= array($CustomerCd, $Date, $ItemCd);
			$sql		= vsprintf($queryCheck,$inputArr);
			$returnData	= $this->execSelectQuery($sql);
			if ($returnData[0]['Count']==0) {
				$inputArr	= array();
				$inputArr	= array($CustomerCd, $Date, $ItemCd, $OpStockQty, $TDReceiptQty, $TDSaleQty, $TDOwnUseQty, $ClStockSaleQty
								, $ClStockOwnUseQty, $ArrivalQty, $PendingQty, $DespPlanQty, $OwnUsePlanQty, $DaysLast, $TDOtherReceiptQty);
				$sql		= vsprintf($queryInsert,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
			} else {
				$inputArr	= array();
				$inputArr	= array($OpStockQty, $TDReceiptQty, $TDSaleQty, $TDOwnUseQty, $ClStockSaleQty, $ClStockOwnUseQty, $ArrivalQty, $PendingQty
								, $DespPlanQty, $OwnUsePlanQty, $DaysLast, $TDOtherReceiptQty, $CustomerCd, $Date, $ItemCd);
				$sql		= vsprintf($queryUpdate,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
			}
			if ($returnData) return $returnData;
		}
	}
	return $returnData;
}
////////===========================Route Change Request===========================================================

public function getrouterequest($CustomerCd, $searchVal) {
	$searchCnd='';
	$GroupBy = " group By A.RequestId ";
	if($CustomerCd!='' ){
		$searchCnd	= " Where  A.CustomerCd=".$CustomerCd."";
		
	}
	if($searchVal!=''){
		$searchCnd	.= " And  A.RequestId = '".$searchVal."'";
		$GroupBy ='';
	}
	
	$sql	= "SELECT A.Id, A.RequestId, A.CustomerCd, A.RouteSeqNo, A.District, A.StateCd, A.District, A.Status
		,	IFNULL(B.Descript,'A.CustomerCd') AS Customer, A.CreatedDateTime, Rdays from so_ai_route_request A
		LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd
		".$searchCnd . $GroupBy."   Order By A.Id";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function insertRouteChangeRequest($data) {
	$sql	= "SELECT max(RequestId) as RequestId from so_ai_route_request Order By Id";
	$returnData = $this->execSelectQuery($sql);
	$RequestId = sprintf('%08d',$returnData[0]['RequestId']+1);
	$LastSubNo=$data['LastSubNo'];
	for($i=1; $i<=$LastSubNo; $i++){
		$sql = " INSERT INTO so_ai_route_request ( RequestId, CustomerCd, RouteSeqNo, District, StateCd, Status, CreatedBy, CreatedDateTime)
		VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');";
		$RouteSeqNo= $i;
		$District= $data['District_'.$i];
		//	$EmailId= $data['EmailId_'.$i];
		$inputArr	= array($RequestId, $data['CustomerCd'], $RouteSeqNo, addslashes($District), $data['StateCd_'.$i], 'U',  $_SESSION['UserName'] , date('Y-m-d H:i:s') );	
		$sql		= vsprintf($sql, $inputArr);
		if(($District )!=''){
			$returnData1 = $this->execUpdateQuery($sql);
		}
	}
	return $returnData1;
}

public function updateRouteChangeRequest($data) {
	$sql = " Update so_ai_route_request SET Status='%s', AcceptedBy='%s', AcceptedDateTime='%s' where RequestId ='%s' and CustomerCd ='%s'";
	$inputArr	= array('A', $_SESSION['UserName'], date('Y-m-d H:i:s'), $data['RequestId'], $data['oldCustomerCd'] );
	$sql		= vsprintf($sql,$inputArr);
	$returnData1= $this->execUpdateQuery($sql);
	return $returnData1;
}


public function SendMailRouteRequestReq($RequestId, $Status) {
	switch ($Status) {
	case 1:
		$Emailtemplate	= 60;
		$TableName		= 'so_ai_route_request';
		$TransId		= 'RequestId';
		$Date			= 'CreatedDateTime';
		break;
		
	}
	$templateArr = $this->getEMailTemplate($Emailtemplate);
	$sql = "SELECT B.Descript as Customer, A.$TransId AS RequestId, DATE_FORMAT(A.$Date,'%d-%m-%Y %H:%i:%s') AS Date, B.EMailId FROM $TableName A INNER JOIN 
	so_customer_m B	ON A.CustomerCd=B.CustomerCd WHERE A.$TransId IN ($RequestId)";
	$eMailDetailArr = $this->execSelectQuery($sql);
	
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($eMailDetailArr[0]['Customer'], $RequestId ));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
}	

public function SendMailRouteRequestAcc($RequestId, $Status) {
	switch ($Status) {
	case 2:
		$Emailtemplate	= 61;
		$TableName		= 'so_ai_route_request';
		$TransId		= 'RequestId';
		$Date			= 'CreatedDateTime';
		$Date1			= 'AcceptedDateTime';
		break;
	}
	
	$templateArr = $this->getEMailTemplate($Emailtemplate);
	$sql = "SELECT B.Descript as Customer, A.$TransId AS RequestId, DATE_FORMAT(A.$Date,'%d-%m-%Y %H:%i:%s') AS Date,  
	DATE_FORMAT(A.$Date1,'%d-%m-%Y %H:%i:%s') AS Date1, B.EMailId FROM $TableName A INNER JOIN 
	so_customer_m B	ON A.CustomerCd=B.CustomerCd WHERE A.$TransId IN ($RequestId)";
	$eMailDetailArr = $this->execSelectQuery($sql);
	
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($eMailDetailArr[0]['Customer'], $eMailDetailArr[0]['Date'],
	$eMailDetailArr[0]['Date1'] ));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	
}

//=========================================== Selling rate ==================//

public function getSellingRateItem() {
	$sql			= "select * from so_selling_rate_item ";
	$reportData		= $this->execSelectQuery($sql);
	return $reportData;
}

public function StatewiseSellingRateEmailList(){
	$sql 		= "SELECT * FROM so_selling_rate GROUP BY UniqueId";
	$reportData	= $this->execSelectQuery($sql);
	return $reportData;
}

public function insertStatewiseSellingRateQuery(){
	$sql = "INSERT INTO so_selling_rate(UniqueId,ProductId,Descript,State,Rate,TransUserName,TransDateTime) VALUES('%s','%s','%s','%s','%s','%s','%s')";
	return $sql;
}
public function insertStatewiseSellingRate($data){
	$sql='';
	$queryInsert		= $this->insertStatewiseSellingRateQuery();
	$returnData			= '';
	$stateName			= json_decode($data['StateName']);
	$totItem			= $data['TotItem'];
	$transUsername		= $_SESSION['UserName'];
	$transDateTime		=	date('Y-m-d H:i:s');
	$sqlid = "SELECT MAX(UniqueId) As maxid FROM so_selling_rate";
	$returnData0 = $this->execSelectQuery($sqlid);
	$UniqueId = $returnData0[0]['maxid']+1;
	

	for($curRowNo=1;$curRowNo<=$totItem;$curRowNo++){
		$ItemCd = $data['itemCd_'.$curRowNo];
		$sql = "SELECT ProductId,ProductName FROM so_selling_rate_item WHERE ItemCd like '%".$ItemCd."%'";
		$returnData1 = $this->execSelectQuery($sql);
		$ProductCd = $returnData1[0]['ProductId'];
		$Descript = $returnData1[0]['ProductName'];
			foreach($stateName as $state){
				$stateCd 	= $state;
				$rate 		= $data[$state.'_'.$curRowNo];
				if(($rate<=0 )){
				continue;
			}
				$inputArr	= array();
				$inputArr	= array($UniqueId,$ItemCd,$Descript,$stateCd,$rate,$transUsername,$transDateTime);
				$sql		= vsprintf($queryInsert,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
				if ($returnData) return $returnData;
			}
	}
	//$this->lastInsertTranNo	= $this->getInsertId();
	return $returnData;
}

public function insertStatewiseSellingRateEmailSMSQuery(){
	$sql = "INSERT INTO so_selling_rate_email_sms(SellingRateId,StateCd,DealerEmail,DealerSMS,SubdealerEmail,SubdealerSMS) VALUES('%s','%s','%s','%s','%s','%s')";
	return $sql;
}

public function insertStatewiseSellingRateEmailSMS($data){
	$sql='';
	$returnData			= '';
	$queryInsert		= $this->insertStatewiseSellingRateEmailSMSQuery();
	$stateName			= json_decode($data['StateName']);
	//$SellingRateId 		= $data['SellingRateId'];
	$sqlid 				= "SELECT MAX(UniqueId) As maxid FROM so_selling_rate";
	$returnData0 		= $this->execSelectQuery($sqlid);
	$UniqueId 			= $returnData0[0]['maxid'];
	
	foreach($stateName as $state){
		$stateCd 			= $state;
		$DealerEmail 		= isset($data[$state.'_delaerEmail'])? 1:0;
		$DealerSMS			= isset($data[$state.'_delaerSMS'])? 1:0;
		$SubdealerEmail 	= isset($data[$state.'_SubdelaerEmail'])? 1:0;
		$SubdealerSMS 		= isset($data[$state.'_SubdelaerSMS'])? 1:0;
		
		$inputArr	= array();
		$inputArr	= array($UniqueId,$stateCd,$DealerEmail,$DealerSMS,$SubdealerEmail,$SubdealerSMS);
		$sql		= vsprintf($queryInsert,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
		if ($returnData) return $returnData;
	}
	return $returnData;
}

public function getStatewiseSellingRateHeader($id){
	$sql = "SELECT A1.ProductId,A1.ProductName,B1.UniqueId,B1.MH,B1.MP,B1.GJ,B1.RJ,B1.OS, B1.RateLaunched, A1.ShowDecimal  FROM 
			(SELECT * FROM so_selling_rate_item ) A1 
			LEFT OUTER JOIN 
			( SELECT A.UniqueId,A.ProductId,max(case when A.State='MH' then A.Rate end) MH,max(case when A.State='MP' then A.Rate end) MP,max(case when A.State='GJ' then A.Rate end) GJ,max(case when A.State='RJ' then A.Rate end) RJ,	max(case when A.State='OS' then A.Rate end) OS, A.RateLaunched FROM  so_selling_rate A  WHERE A.UniqueId = '$id' GROUP BY A.ProductId)B1
			ON A1.ProductId = B1.ProductId";
	$reportData	= $this->execSelectQuery($sql);
	return $reportData;
}

public function getStatewiseSellingRateEmailSMSHeader($id){
	$sql = "SELECT * FROM so_selling_rate_email_sms WHERE SellingRateId = $id ";
	$reportData	= $this->execSelectQuery($sql);
	return $reportData;
}
public function updateStatewiseSellingRateQuery(){
	$sql	= "UPDATE so_selling_rate SET Rate = '%s' WHERE  ProductId = '%s' AND  State = '%s' AND UniqueId ='%s'";  
	return $sql ;	
}

public function updateStatewiseSellingRate($data){
	$sql='';
	$queryUpdate		= $this->updateStatewiseSellingRateQuery();
	$queryInsert		= $this->insertStatewiseSellingRateQuery();
	$returnData			= '';
	$UniqueId			= $data['UniqueId'];
	$totItem			= $data['TotItem'];
	$stateName			= json_decode($data['StateName']);
	$transUsername		= $_SESSION['UserName'];
	$transDateTime		=	date('Y-m-d H:i:s');
	for($curRowNo=1;$curRowNo<=$totItem;$curRowNo++){
		$ItemCd 		= $data['itemCd_'.$curRowNo];
		$sql 			= "SELECT ProductId,ProductName FROM so_selling_rate_item WHERE ItemCd like '%".$ItemCd."%'";
		$returnData1 	= $this->execSelectQuery($sql);
		$ProductCd 		= $returnData1[0]['ProductId'];
		$Descript 		= $returnData1[0]['ProductName'];
		foreach($stateName as $state){
			$stateCd 	= $state;
			$rate 		= $data[$state.'_'.$curRowNo];
			if($rate<=0){
				continue;
			}
			$queryCheck	= "SELECT COUNT(*) AS Count FROM so_selling_rate WHERE ProductId = '%s' AND  State = '%s' AND UniqueId ='%s'";
			$inputArr	= array();
			$inputArr	= array($ItemCd,$stateCd,$UniqueId);
			$sql	= vsprintf($queryCheck,$inputArr);
			$returnData	= $this->execSelectQuery($sql);
			if($returnData[0]['Count']==0){
				$inputArr	= array();
				$inputArr	= array($UniqueId,$ItemCd,$Descript,$stateCd,$rate,$transUsername,$transDateTime);
				$sql		= vsprintf($queryInsert,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
				if ($returnData) return $returnData;
			}else{
				$inputArr	= array();
				$inputArr	= array($rate,$ItemCd,$stateCd,$UniqueId);
				$sql		= vsprintf($queryUpdate,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
				if ($returnData) return $returnData;
			}
		}
	}
}

public function updateStatewiseSellingRateEmailSMSQuery(){
	$sql	= "UPDATE so_selling_rate_email_sms SET DealerEmail='%s',DealerSMS='%s',SubdealerEmail='%s',SubdealerSMS='%s' WHERE  SellingRateId = '%s' AND StateCd = '%s'";  
	return $sql ;
}

public function updateStatewiseSellingRateEmailSMS($data){
	$sql='';
	$returnData			= '';
	$queryInsert		= $this->insertStatewiseSellingRateEmailSMSQuery();
	$queryUpdate		= $this->updateStatewiseSellingRateEmailSMSQuery();
	$stateName			= json_decode($data['StateName']);
	$UniqueId			= $data['UniqueId']; 
	foreach($stateName as $state){
		$stateCd 			= $state;
		$DealerEmail 		= isset($data[$state.'_delaerEmail'])? 1:0;
		$DealerSMS			= isset($data[$state.'_delaerSMS'])? 1:0;
		$SubdealerEmail 	= isset($data[$state.'_SubdelaerEmail'])? 1:0;
		$SubdealerSMS 		= isset($data[$state.'_SubdelaerSMS'])? 1:0;
		
		$inputArr	= array();
		$inputArr	= array($DealerEmail,$DealerSMS,$SubdealerEmail,$SubdealerSMS,$UniqueId,$stateCd);
		$sql	= vsprintf($queryUpdate,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
		if ($returnData) return $returnData;
	}
	return $returnData;
}



public function UpdateRateLaunched($UniqueId){
	$sql	= "UPDATE so_selling_rate SET RateLaunched='%s' WHERE  UniqueId = '%s' ";  
	$inputArr	= array();
	$inputArr	= array(1,$UniqueId);
	$sql	= vsprintf($sql,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function getSellingRate_EmailSMSOrgDealer($StateCd,$SellingRateId ) {
	 $sql = "select A.UniqueId, A.State, A.rate, A.ProductId, B.DealerEmail, B.DealerSMS, C.ProductName, C.ShowDecimal, C.Base_of_Price from  so_selling_rate A JOIN 
	so_selling_rate_email_sms B ON A.UniqueId = B.SellingRateId and A.State =B.StateCd	JOIN so_selling_rate_item C 
	ON A.ProductId = C.ProductId where  A.State = '$StateCd' and A.UniqueId = '$SellingRateId' order By C.ProductId";
	$reportData		= $this->execSelectQuery($sql);
	return $reportData;
}


public function LaunchDealerPriceEmail($reportData, $CustomerName, $EMailId) {
	$templateArr = $this->getEMailTemplate(62); // Body not in use: EmialID CC is Used 
	$curRow=1;
	//$curEMailId = 'websupport@solargroup.com;rahul@solargroup.com;solartrade@solargroup.com';
//	$EMailIdBCC ='b2b.solarexplosives@gmail.com';
	
	$curEMailId = $EMailId;
	$EMailIdBCC = 'solartrade@solargroup.com;websupport@solargroup.com';
	$eMailDetailRowCount = count($reportData);
	$eMailBody = "<BR/>M/s ".$CustomerName.".<br/><br/> Kindly Note Guidance / Best Price for <b>Solar Products</b> as follows :";
	$eMailBody .= "<br/><br/><table width='60%' cellspacing='1' cellpadding='5' border='1' style='border-collapse:collapse; font-size:12px;' >";
	$eMailBody .= "<tr style='background-color:#b3ccff'>
					<th>S.no</th>
					<th>Item</th>
					<th>Best Price </th>
					<th>Base of Price </th>
				</tr>";
	foreach ($reportData as $data) {
			$ShowDecimal = $data['ShowDecimal'];
			$rate = ($ShowDecimal) ?  sprintf('%.2f', $data['rate']) : $data['rate'];
			if($rate == '0.00' || $rate == '0'  ){ $rate = ''; }
			
			$eMailBody .= "<tr>";
			$eMailBody .= "<td align='center' width='5%'>".$curRow."</td>";
			$eMailBody .= "<td width='35%'>".$data['ProductName']."</td>";
			$eMailBody .= "<td width='10%' style='color:red;' align='center'>₹ " .$rate."</td>";
			$eMailBody .= "<td align='center' width='10%' align='right'>".$data['Base_of_Price']."</td>";
			$eMailBody .= "</tr>";
			$curRow++;
		}
		$eMailBody .= "</table><br/>";
		$eMailBody .= "<p style='color: red'>Note : 1. Pricing as per your discretion, above prices are for reference only.<br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
		2. Ensure your B2B and Magazine stock data have no variation.</p><br/>";
		$eMailBody .= "Thank You <br/> Customer Service Department<br/>";
		$objSolarMailer = new solarMailer();
		$objSolarMailer->IsHTML(true);  
		
		$returnData = $objSolarMailer->sendSolarMail($curEMailId, $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC'], $EMailIdBCC, True);
			
	return $returnData;
}


public function LaunchDealerPriceSMS($data, $CustomerName, $TelNo){
	$uname = 'SIILJPRO'; //'SIILJPRP';
	$password = 'S(ol)!ar';// 'E9W!f9Y~';
	$info ='1';
	$test = '0';
	$from = 'iSOLAR';
	//$dest =  '8793653028';   //'9765933450'; // $TelNo;  //'8793653028' //'919649569999'; //'918600993992';
	$dest =  $TelNo.', 9829586470';
	$messages = "M/s ".str_replace("&", "and", $CustomerName).", Guidance / Best Price for Solar Products as follows : ";
	
	$curRow=0;
	$dataCount = count($data);
	$Month = date('M');
	while ($curRow < $dataCount) {

	$ShowDecimal = $data[$curRow]['ShowDecimal'];
			$rate = ($ShowDecimal) ?  sprintf('%.2f', $data[$curRow]['rate']) : $data[$curRow]['rate'];
			if($rate == '0.00' || $rate == '0'  ){ $rate = ''; }
		$messages .= ' '. $data[$curRow]['ProductName'] .' Rs. ' . $rate .' '.$data[$curRow]['Base_of_Price'].', ';
		$curRow++;
	}
	$messages .='Pricing as per your discretion, above price are for reference only.';
	$messages .='Thank You, Solar Industries India Ltd';
	$data ="uname=".$uname."&pass=".$password."&msg=".$messages."&form=".$from."&dest=".$dest;
	$ch = curl_init("http://api.unicel.in/SendSMS/sendmsg.php?");
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	$result = curl_exec($ch);
	curl_close($ch);
return $messages;
}


public function getSellingRate_EmailSMSOrgSubDealer($StateCd,$SellingRateId ) {
	 $sql = "select A.UniqueId, A.State, A.rate, A.ProductId, B.SubDealerEmail, B.SubDealerSMS, C.ProductName, C.Base_of_Price, C.ShowDecimal from  so_selling_rate A JOIN 
	so_selling_rate_email_sms B ON A.UniqueId = B.SellingRateId and A.State =B.StateCd	JOIN so_selling_rate_item C 
	ON A.ProductId = C.ProductId where  A.State = '$StateCd' and A.UniqueId = '$SellingRateId' Order By C.ProductId  ";
	$reportData		= $this->execSelectQuery($sql);
	return $reportData;
}

public function LaunchSubDealerPriceEmail($reportData, $SubdealerName, $EMailId) {
	$templateArr = $this->getEMailTemplate(62); // Body not in use: EmialID CC is Used 
	$curRow=1;
//	$EMailIdBCC ='';
	//$curEMailId = 'websupport@solargroup.com';
	
	$curEMailId = $EMailId;
	$EMailIdBCC = 'solartrade@solargroup.com';
	$eMailDetailRowCount = count($reportData);
	$eMailBody = "<BR/>M/s ".$SubdealerName.".<br/><br/> Kindly Note Guidance / Best Buy Price for <b> Solar Products</b> as follows :";
	$eMailBody .= "<br/><br/><table width='60%' cellspacing='1' cellpadding='5' border='1' style='border-collapse:collapse; font-size:12px;' >";
	$eMailBody .= "<tr style='background-color:#b3ccff'>
					<th>S.no</th>
					<th>Item</th>
					<th>Best Buy Price </th>
					<th>Base of Price </th>
				</tr>";
	foreach ($reportData as $data) {
			$ShowDecimal = $data['ShowDecimal'];
			$rate = ($ShowDecimal) ?  sprintf('%.2f', $data['rate']) : $data['rate'];
			if($rate == '0.00' || $rate == '0'  ){ $rate = ''; }
			
			$eMailBody .= "<tr>";
			$eMailBody .= "<td align='center' width='5%'>".$curRow."</td>";
			$eMailBody .= "<td width='35%'>".$data['ProductName']."</td>";
			$eMailBody .= "<td width='10%' style='color:red;' align='right'> &#8377 ". $rate."</td>";
			$eMailBody .= "<td align='center' width='10%' align='right'>".$data['Base_of_Price']."</td>";
			$eMailBody .= "</tr>";
			$curRow++;
		}
		$eMailBody .= "</table><br/>";
		$eMailBody .= "<p style='color: red'>Note : Please submit your todays magazine stock in your B2B account.</p><br/>";
		$eMailBody .= "Thank You <br/> Customer Service Department<br/>";
		$objSolarMailer = new solarMailer();
		$objSolarMailer->IsHTML(true);  
			$returnData = $objSolarMailer->sendSolarMail($curEMailId, $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC'], $EMailIdBCC, True);
		return $returnData;
}


public function LaunchSubDealerPriceSMS($data, $SubdealerName, $StateCd, $TelNo){
	$uname = 'SIILJPRO'; //'SIILJPRP';
	$password = 'S(ol)!ar';// 'E9W!f9Y~';
	$info ='1';
	$test = '0';
	$from = 'iSOLAR';
//	$dest =  '9422460040,9406547095,9649569999'; //'9983960042';   //'9765933450'; // $TelNo;  //'8793653028' //'919649569999'; //'918600993992';
	$dest =  $TelNo.', 9983960042';
	$messages = "M/s ".str_replace("&", "and", $SubdealerName)."-". $StateCd . ", Guidance / Best Buy Price for Solar Products as follows : ";
	
	$curRow=0;
	$dataCount = count($data);
	$Month = date('M');
	while ($curRow < $dataCount) {
			$ShowDecimal = $data[$curRow]['ShowDecimal'];
			$rate = ($ShowDecimal) ?  sprintf('%.2f', $data[$curRow]['rate']) : $data[$curRow]['rate'];
			if($rate == '0.00' || $rate == '0'  ){ $rate = ''; }
		
		$messages .= ' '. $data[$curRow]['ProductName'] .' Rs. ' . $rate.' '.$data[$curRow]['Base_of_Price'].', ';
		$curRow++;
	}
	$messages .=' Please submit your todays magazine stock in your B2B account. Thank You, Solar Industries India Ltd';
	$data ="uname=".$uname."&pass=".$password."&msg=".$messages."&send=".$from."&dest=".$dest;
	$ch = curl_init("http://api.unicel.in/SendSMS/sendmsg.php?");
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	$result = curl_exec($ch);
	curl_close($ch);
return $messages;
}



/////////////////////////////////////////////-------------------Intimation ----------------------------------//

public function getExpDetListApprovedmagazine($search) {
	$POStatus = $this::$POStatus;
	$searchCnd	= ((isset($search)) ? " And  (E.Descript LIKE '$search%')" : " ") ;
	$sql	= "SELECT D.Descript, A.MagazineCd, A.IdExpDet, A.UTR, B.CustomerCd, IFNULL(E.Descript,B.CustomerCd) AS Customer, E.City,IF(B.DespatchMode='F','CompanyVan','X-Factory') AS DespatchModeDisp
		, B.CompanyCd, B.ExpVehicleArrDate, B.RE11ReceiptDate, DATE_FORMAT(B.DateTime,'%d-%m-%Y') AS Date, B.VehicleNo, B.TotAmt
		, IFNULL(F.ShortDesc,B.CompanyCd) AS Company, IFNULL(D.Descript,B.StatusCd) AS Status, B.VehicleNo from so_expdet_magazine A
		LEFT OUTER JOIN so_expdet B ON A.IdExpDet=B.IdExpDet
		LEFT OUTER JOIN  so_magazine_m C ON A.MagazineCd=C.MagazineCd	
		LEFT OUTER JOIN so_status_m D ON B.StatusCd=D.StatusCd
		LEFT OUTER JOIN so_customer_m E ON B.CustomerCd=E.CustomerCd
		LEFT OUTER JOIN so_company_m F ON B.CompanyCd=F.CompanyCd where  A.ForAdvIntimation=0 AND B.StatusCd <> 'T' ".$searchCnd." ORDER BY B.IdExpDet DESC";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getIntimationList() {
	$sql	= "SELECT A.TransId, D.RE11No, D.RE11Date, D.RE11PDF, A.IntimationSeq, A.IntimationNo, DATE_FORMAT(A.IntimationDate, '%d-%m-%Y') as IntimationDate, A.PONo, A.PODate, B.CustomerCd, IFNULL(B.Descript,B.CustomerCd) AS Customer, C.MagazineCd, IFNULL(C.Descript,C.MagazineCd) AS Magazine
		FROM so_ai_trans A LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd LEFT OUTER JOIN  so_magazine_m C 
		ON A.MagazineCd=C.MagazineCd JOIN so_expdet_magazine D ON A.PONo=D.IdExpdet and A.MagazineCd=D.MagazineCd  GROUP BY A.IntimationNo order by A.IntimationSeq DESC";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getpodetails($IdExpDet, $MagazineCd) {
	$searchCnd	= " Where A.IdExpDet=".$IdExpDet." and E.MagazineCd=".$MagazineCd." and F.MagazineCd=".$MagazineCd. " and F.IdExpDet=".$IdExpDet."";
	$searchCnd	.= " AND B.SectorCd='T'";
	$sql	= "SELECT A.DateTime, B.CustomerCd, B.StateCd, E.RE11No, DATE_FORMAT(E.RE11Date,'%d-%m-%Y') AS RE11Date, G.Descript as magdescript, G.Place, G.Taluka
		, G.District, G.StateCd, E.MagazineCd, B.Address, D.CompanyAddress, A.IdExpDet, A.DespatchMode, SUM(F.OrderBox) AS TotBox
		, IF(A.DespatchMode='F','CompanyVan','X-Factory') AS DespatchModeDisp, DATE_FORMAT(A.DateTime,'%d-%m-%Y') AS Date
		, A.VehicleNo, A.ExpVehicleArrDate, A.TotAmt, A.RE11ReceiptDate, CONCAT(TRIM(A.TokenNoPrefix),'/',A.TokenNo%100) AS TokenNoFull
		,xf_Proper(REPLACE(IFNULL(B.Descript,''),UPPER(IFNULL(B.City,'')),'')) AS Customer, xf_Proper(IFNULL(B.City,'')) AS City
		,IFNULL(C.Descript,A.StatusCd) AS Status,IFNULL(D.ShortDesc,A.CompanyCd) AS Company, IFNULL(D.Descript,A.CompanyCd) AS CompanyName,  E.For_RM_PO_Route FROM so_expdet A
		LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd
		LEFT OUTER JOIN so_status_m C ON A.StatusCd=C.StatusCd
		LEFT OUTER JOIN so_company_m D ON A.CompanyCd= D.CompanyCd 
		LEFT OUTER JOIN  so_expdet_magazine E ON A.IdExpDet=E.IdExpDet
		LEFT OUTER JOIN  so_expdet_magazine_item F ON A.IdExpDet=E.IdExpDet and E.MagazineCd= F.MagazineCd
		LEFT OUTER JOIN  so_magazine_m G ON E.MagazineCd=G.MagazineCd
		" . $searchCnd . " ORDER BY A.IdExpDet DESC";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getroutemaster($CustomerCd, $MagazineCd, $searchVal) {
	$searchCnd='';
	if($CustomerCd!=''  && $MagazineCd!=''){
		$searchCnd	= " Where  A.MagazineCd=".$MagazineCd." and A.CustomerCd=".$CustomerCd."";
	}
	if($searchVal!=''){
		$searchCnd	= " Where  B.Descript like '%".$searchVal."%'";
	}
	$sql	= "SELECT A.Id, A.MagazineCd, A.CustomerCd, A.RouteSeqNo, A.District, A.StateCd, A.District, A.EmailId, A.CCEmailId, A.CCOfficeAdd1
		, A.CCOfficeAdd2, A.Rdays, IFNULL(B.Descript,B.CustomerCd) AS Customer,
		IFNULL(C.Descript,'C.MagazineCd') as Magazine from so_ai_route_m A
		LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd
		LEFT OUTER JOIN  so_magazine_m C ON A.MagazineCd=C.MagazineCd
		".$searchCnd."  Order By B.CustomerCd, A.MagazineCd, A.RouteSeqNo, B.StateCd ";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}


public function getAdvanceintimationRoute($CustomerCd, $MagazineCd, $searchVal) {
	$searchCnd='';
	if($CustomerCd!=''  && $MagazineCd!=''){
		$searchCnd	= " Where  A.MagazineCd=".$MagazineCd." and A.CustomerCd=".$CustomerCd."";
	}
	if($searchVal!=''){
		$searchCnd	= " Where  B.Descript like '%".$searchVal."%'";
	}
	$sql	= "SELECT A.PONo, A.MagazineCd, A.CustomerCd, A.RouteSeqNo, A.District, A.StateCd, A.District, A.EmailId, A.CCEmailId, A.CCOfficeAdd1
		, A.CCOfficeAdd2, A.DistrictReachedDate, xf_Proper(REPLACE(IFNULL(B.Descript,''),UPPER(IFNULL(B.City,'')),'')) AS Customer,
		IFNULL(C.Descript,'C.MagazineCd') as Magazine from so_ai_trans_route A
		LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd
		LEFT OUTER JOIN  so_magazine_m C ON A.MagazineCd=C.MagazineCd
		".$searchCnd."  Order By A.TransRouteId";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getPOroutemaster($CustomerCd, $IdExpDet, $searchVal) {
	$searchCnd='';
	if($CustomerCd!=''  && $IdExpDet!=''){
		$searchCnd	= " Where  A.PONo=".$IdExpDet." and A.CustomerCd=".$CustomerCd."";
	}
	if($searchVal!=''){
		$searchCnd	= " Where  B.Descript like '%".$searchVal."%'";
	}
	$sql	= "SELECT A.PONo, A.MagazineCd, A.CustomerCd, A.RouteSeqNo, A.District, A.StateCd, A.District, A.EmailId, A.CCEmailId, A.CCOfficeAdd1
		, A.CCOfficeAdd2, A.Rdays, xf_Proper(REPLACE(IFNULL(B.Descript,''),UPPER(IFNULL(B.City,'')),'')) AS Customer,
		IFNULL(C.Descript,'C.MagazineCd') as Magazine from so_ai_po_route A
		LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd
		LEFT OUTER JOIN  so_magazine_m C ON A.MagazineCd=C.MagazineCd
		".$searchCnd."  Order By A.PORouteId";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getIntimationroute($CustomerCd, $IdExpDet, $MagazineCd, $IntimationNo, $searchVal) {
	$searchCnd='';
	if($CustomerCd!=''  && $IdExpDet!=''){
		$searchCnd	= " Where  A.PONo=".$IdExpDet." and A.CustomerCd=".$CustomerCd." AND  A.MagazineCd = ".$MagazineCd. " AND  A.IntimationNo=".$IntimationNo;
	}
	if($searchVal!=''){
		$searchCnd	= " Where  B.Descript like '%".$searchVal."%'";
	}
	$sql	= "SELECT A.PONo, A.MagazineCd, A.CustomerCd, A.RouteSeqNo, A.District, A.StateCd, A.District, A.EmailId, A.CCEmailId, A.CCOfficeAdd1
		, A.CCOfficeAdd2, A.DistrictReachedDate, xf_Proper(REPLACE(IFNULL(B.Descript,''),UPPER(IFNULL(B.City,'')),'')) AS Customer,
		IFNULL(C.Descript,'C.MagazineCd') as Magazine from so_ai_trans_route A
		LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd
		LEFT OUTER JOIN  so_magazine_m C ON A.MagazineCd=C.MagazineCd
		".$searchCnd."  Order By A.TransRouteId";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}


public function DeleteIntimationRoute($CustomerCd, $magazineCd, $IdExpDet, $IntimationNo) {
	$sql = "delete FROM so_ai_trans_route WHERE CustomerCd='".$CustomerCd."' and MagazineCd='".$magazineCd."' and PONo='".$IdExpDet."' and IntimationNo='".$IntimationNo."'";
	$failMsg  = $this->execUpdateQuery($sql);
	return $failMsg;

}

public function UpdateIntimationRoute($data) {
$LastSubNo=$data['LastSubNo'];
	for($i=1; $i<=$LastSubNo; $i++){
	$sql = " INSERT INTO so_ai_trans_route ( TransId, IntimationNo, PONo, CustomerCd, MagazineCd, RouteSeqNo, District, StateCd, EmailId, CCEmailId, CCOfficeAdd1, CCOfficeAdd2, DistrictReachedDate)
	VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');";
	$RouteSeqNo= $i;
	$District= $data['District_'.$i];
	$EmailId= $data['EmailId_'.$i];
	$ReachedDate = $this->convertDate($data['Reacheddays_'.$i], True, 1);
	$inputArr	= array($data['oldTransId'], $data['oldIntimationNo'], $data['oldIdExpDet'], $data['oldCustomerCd'],  $data['oldMagazineCd'], $RouteSeqNo, addslashes($District), 
	$data['StateCd_'.$i], addslashes($EmailId), addslashes($data['CCEmailId_'.$i]), addslashes($data['CCOfficeAdd1_'.$i]), addslashes($data['CCOfficeAdd2_'.$i]),
	$ReachedDate );
	$sql		= vsprintf($sql,$inputArr);
	if(($District && $EmailId )!=''){
	$returnData1 = $this->execUpdateQuery($sql);
	}
	}
	return $returnData1;
}


public function getDistrictMDisp() {
	$sql		= "SELECT * FROM so_ai_district_m order by District";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;	
}


public function getaimagazine() {
	$sql	= "SELECT * from so_ai_magazine_m";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getAdvIntimationDetails($IdExpdet, $MagazineCd) {
	$sql	= "SELECT A.*, B.*  from so_ai_trans A JOIN  so_ai_trans_route B ON A.TransId = B.TransId  AND A.IntimationNo = B.IntimationNo 
	  where A.PONo='$IdExpdet' and A.MagazineCd='$MagazineCd' order by B.TransRouteId";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function DeleteIntimationPOList($approveDocList, $MagazineList) {
	for($i=0; $i<sizeof($approveDocList); $i++){
	$stmt		= "UPDATE so_expdet_magazine SET ForAdvIntimation='%s' WHERE IdExpDet ='%s' and MagazineCd='%s' ";
	$inputArr 	= array('2', $approveDocList[$i], $MagazineList[$i]);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData=$this->execUpdateQuery($sql);
	}
	return $returnData;
}

public function isExistIntimation($IdExpdet, $MagazineCd) {
	$sql			= "SELECT * FROM so_ai_trans WHERE PONo='$IdExpdet' and MagazineCd='$MagazineCd'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function insertAdvanceIntimation($data) {
	$countroute=$data['countroute'];
	$sql1	= "SELECT  MAX(IntimationSeq) as IntimationSeq from so_ai_trans ";
	$returnData1 = $this->execSelectQuery($sql1);
	$IntimationSeq= $returnData1[0]['IntimationSeq'];
	$IntimationSeq=$IntimationSeq+100001;
	$IntimationSeq= str_pad($IntimationSeq, 6, "0", STR_PAD_LEFT);
	$IntimationNo= '7000'.date('y').+$IntimationSeq;
	$LicenceNo=  $data['LicenceFrom'];
	//$licence=  implode(", ", $LicenceNo);
	$licence=  $LicenceNo;
	
	$sql = "INSERT INTO so_ai_trans(IntimationSeq, IntimationNo, IntimationDate, Year, PODate, PONo, CustomerCd, MagazineCd
	, DispatchmentDate, ExpectedArrivalDate, LicenceFrom, CreatedBy, CreatedDateTime)
	VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')";
	$inputArr	= array($IntimationSeq, $IntimationNo, date('Y-m-d'), date('Y'), $data['POdatetime'],  $data['IdExpdet'], $data['CustomerCd']
	, $data['MagazineCd'], $this->convertDate($data['DispatchDate'], TRUE, 1), $this->convertDate($data['ExpReachDate'], TRUE, 1)
	, $licence, $_SESSION['UserName'], date('Y-m-d H:i:s'));
	$sql		= vsprintf($sql,$inputArr);
	$returnData = $this->execUpdateQuery($sql);
	$TransId = $this->getInsertId();
	for($i=0; $i<$countroute; $i++){
	$sql1 = "INSERT INTO so_ai_trans_route (TransId, IntimationNo, PONo, CustomerCd, MagazineCd, RouteSeqNo, District, DistrictReachedDate, StateCd, EmailId
	, CCEmailId, CCOfficeAdd1, CCOfficeAdd2)
	VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')";
	$inputArr1	= array($TransId, $IntimationNo, $data['IdExpdet'], $data['CustomerCd'], $data['MagazineCd'], $i+1, $data['District_'.$i]
	, $this->convertDate($data['districtdate_'.$i], TRUE, 1), $data['StateCd_'.$i], addslashes($data['Emailid_'.$i]),
	addslashes($data['CCEmailid_'.$i]), addslashes($data['CCAdd1_'.$i]), addslashes($data['CCAdd2_'.$i]));
	$querysql1		= vsprintf($sql1,$inputArr1);
	$returnData1 = $this->execUpdateQuery($querysql1);
	}
	return $returnData;
}

public function UpdateAIMagazine($data) {
	$stmt	= "UPDATE so_expdet_magazine SET ForAdvIntimation='%s' where IdExpdet='%s' and MagazineCd='%s'";
	$inputArr	= array('1', $data['IdExpdet'], $data['MagazineCd'] );	
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}



public function insertRouteMaster($data) {
	$LastSubNo=$data['LastSubNo'];
	for($i=1; $i<=$LastSubNo; $i++){
	$sql = " INSERT INTO so_ai_route_m (MagazineCd, CustomerCd, RouteSeqNo, District, StateCd, EmailId, CCEmailId, CCOfficeAdd1, CCOfficeAdd2, RDays, CreatedBy, CreatedDateTime)
	VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');";
	$RouteSeqNo= $i;
	$District= $data['District_'.$i];
	$EmailId= $data['EmailId_'.$i];
	$inputArr	= array($data['MagazineCd'],  $data['CustomerCd'], $RouteSeqNo, addslashes($District), $data['StateCd_'.$i], 
	addslashes($EmailId), addslashes($data['CCEmailId_'.$i]), addslashes($data['CCOfficeAdd1_'.$i]), addslashes($data['CCOfficeAdd2_'.$i]),
	$data['Reacheddays_'.$i], $_SESSION['UserName'], date('Y-m-d H:i:s'));
	
	$sql		= vsprintf($sql,$inputArr);
	if(($District && $EmailId )!=''){
	$returnData1 = $this->execUpdateQuery($sql);
	}
	}
	return $returnData1;
}

public function DeleteRoute($CustomerCd, $magazineCd) {
	$sql = "delete FROM so_ai_route_m WHERE CustomerCd='".$CustomerCd."' and MagazineCd='".$magazineCd."'";
	$failMsg  = $this->execUpdateQuery($sql);
	return $failMsg;

}

public function UpdateRouteMaster($data) {
$LastSubNo=$data['LastSubNo'];
	for($i=1; $i<=$LastSubNo; $i++){
	$sql = " INSERT INTO so_ai_route_m (MagazineCd, CustomerCd, RouteSeqNo, District, StateCd, EmailId, CCEmailId, CCOfficeAdd1, CCOfficeAdd2, RDays, CreatedBy, CreatedDateTime)
	VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');";
	$RouteSeqNo= $i;
	$District= $data['District_'.$i];
	$EmailId= $data['EmailId_'.$i];
	$inputArr	= array($data['oldMagazineCd'],  $data['oldCustomerCd'], $RouteSeqNo, addslashes($District), $data['StateCd_'.$i], 
	addslashes($EmailId), addslashes($data['CCEmailId_'.$i]), addslashes($data['CCOfficeAdd1_'.$i]), addslashes($data['CCOfficeAdd2_'.$i]),
	$data['Reacheddays_'.$i], $_SESSION['UserName'], date('Y-m-d H:i:s'));
	
	$sql		= vsprintf($sql,$inputArr);
	if(($District && $EmailId )!=''){
	$returnData1 = $this->execUpdateQuery($sql);
	}
	}
	return $returnData1;


	/*$LastSubNo=$data['LastSubNo'];
	for($i=1; $i<=$LastSubNo; $i++){
		$RouteSeqNo= $i;
		$UniqueId= $data['listid_'.$i];
		$District= $data['District_'.$i];
		$EmailId= $data['EmailId_'.$i];
		
		$stmt	= "UPDATE so_ai_route_m SET RouteSeqNo='%s', District='%s', StateCd='%s', EmailId='%s', CCEmailId='%s', CCAddress_1='%s'
			, CCAddress_2='%s', RDays='%s' where Id='%s'";
		$inputArr	= array($RouteSeqNo, addslashes($District), $data['StateCd_'.$i], addslashes($EmailId),  addslashes($data['CCEmailId_'.$i])
		,addslashes($data['CCOfficeAdd1_'.$i]), addslashes($data['CCOfficeAdd2_'.$i]), $data['Reacheddays_'.$i], $UniqueId );
	
		$sql		= vsprintf($stmt,$inputArr);
		if(($District && $EmailId )!=''){
			$returnData	= $this->execUpdateQuery($sql);
		}
	}
	return $returnData; */
}


public function isExistRouteM($CustomerCd, $MagazineCd) {
	$sql			= "SELECT * FROM so_ai_route_m  WHERE CustomerCd='".$CustomerCd."' and  MagazineCd='".$MagazineCd."'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}



public function DeletePORoute($CustomerCd, $magazineCd, $IdExpDet) {
	$sql = "delete FROM so_ai_po_route WHERE CustomerCd='".$CustomerCd."' and MagazineCd='".$magazineCd."' and PONo='".$IdExpDet."'";
	$failMsg  = $this->execUpdateQuery($sql);
	return $failMsg;

}

public function UpdatePORouteMaster($data) {
$LastSubNo=$data['LastSubNo'];
	for($i=1; $i<=$LastSubNo; $i++){
	$sql = " INSERT INTO so_ai_po_route ( PONo, MagazineCd, CustomerCd, RouteSeqNo, District, StateCd, EmailId, CCEmailId, CCOfficeAdd1, CCOfficeAdd2, RDays)
	VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');";
	$RouteSeqNo= $i;
	$District= $data['District_'.$i];
	$EmailId= $data['EmailId_'.$i];
	$inputArr	= array($data['oldIdExpDet'], $data['oldMagazineCd'],  $data['oldCustomerCd'], $RouteSeqNo, addslashes($District), $data['StateCd_'.$i], 
	addslashes($EmailId), addslashes($data['CCEmailId_'.$i]), addslashes($data['CCOfficeAdd1_'.$i]), addslashes($data['CCOfficeAdd2_'.$i]),
	$data['Reacheddays_'.$i]);
	
	$sql		= vsprintf($sql,$inputArr);
	if(($District && $EmailId )!=''){
	$returnData1 = $this->execUpdateQuery($sql);
	}
	}
	//return $returnData1;

	$stmt	= "UPDATE so_expdet_magazine SET For_RM_PO_Route='%s' where IdExpdet='%s'  and MagazineCd='%s'";
		$inputArr	= array(1, $data['oldIdExpDet'],  $data['oldMagazineCd']);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	
	return $returnData1; 
}



public function getDistrictList($search = null) {
	$searchCnd	= (isset($search)) ? " WHERE District like '". $search . "%'" : "";
	$sql		= "SELECT  * FROM so_ai_district_m ".$searchCnd." ORDER BY District";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function insertDistrict($data) {

	$stmt = " INSERT INTO so_ai_district_m (District, StateCd, MailId)
				VALUES('%s', '%s', '%s');";
	$inputArr	= array(addslashes($data['District']), addslashes(trim($data['StateCd'])), addslashes(trim($data['MailId'])));
	$sql        = vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}

public function updateDistrict($data) {

	$stmt		= "UPDATE so_ai_district_m  SET District = '%s', StateCd = '%s', MailId ='%s' where District_id='%s' ";
	$inputArr	= array(addslashes(trim($data['District'])), addslashes(trim($data['StateCd'])), trim($data['MailId']),  trim($data['oldDistrict_id']) );
	$sql		= vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}


public function isExistDistrict($mcode) {
	$sql			= "SELECT * FROM so_ai_district_m WHERE District='".$mcode."'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function deleteDistrict($District_id) {

	$sql = "delete FROM so_ai_district_m WHERE District_id IN (".$District_id .")";
	$failMsg  = $this->execUpdateQuery($sql);
	return $failMsg;
}

public function getDistrictselect($district) {
	$sql		= "SELECT * FROM so_ai_district_m where District='$district'  order by District";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;	
}

public function getDistrictM($District_id) {
	$stmt		= "SELECT * FROM so_ai_district_m WHERE District_id='%s'";
	$inputArr 	=  array($District_id);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function sendEMailAdvIntimate($toMailId, $subject, $body, $ccMailId, $pathoffile, $FileAttach) {
	$subject= 'Advance Intimation For RECL';
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($toMailId, $subject, $body, $ccMailId, $pathoffile, $FileAttach);
}

//=========================================

//===================================
// DespatchPlanItem (Grid-2) ------------------------------------------------------
public function getDespPlanItemInsertQuery() {
	$sql = "INSERT INTO so_desp_plan_item (CustomerCd, Date, IdSubdealer, ItemCd, DespPlanQty)"
		. " VALUES ('%s', '%s', %s, '%s', %s);";
	return $sql ;
}

public function getDespPlanItemUpdateQuery() {
	$sql	= "UPDATE so_desp_plan_item SET DespPlanQty=%s WHERE CustomerCd='%s' AND Date='%s' AND IdSubdealer=%s AND ItemCd='%s'";
	return $sql ;
}

public function getDespPlanItemDeleteQuery() {
	$sql	= "DELETE FROM so_desp_plan_item WHERE CustomerCd='%s' AND Date='%s' AND IdSubdealer=%s AND ItemCd='%s'";
	return $sql ;
}

public function insertDespPlanItem($data) {
	$queryInsert	= $this->getDespPlanItemInsertQuery();

	$ItemArr = explode(',', $data['ItemCdStrForDespQty']);	// 20000118,20000119,20000120,20000121
	$ItemCount = count($ItemArr);
	$returnData		= '';

	$CustomerCd	= $data['CustomerCd'];
	$Date = $this->convertDate($data['Date'],TRUE,1);

	for ($curRowNo=1; $curRowNo<=$data['LastRowNo2']; $curRowNo++) {
		$IdSubdealer	= (int)$data['IdSubdealer2_'.$curRowNo];
		for ($curItemCdIndex=0; $curItemCdIndex<$ItemCount; $curItemCdIndex++) {
			$ItemCd = $ItemArr[$curItemCdIndex];
			$DespPlanQty = (int)$data[$ItemCd.'2_'.$curRowNo];	// $data['200001182_1']
			if ($DespPlanQty>0) {
				$inputArr	= array($CustomerCd, $Date, $IdSubdealer, $ItemCd, $DespPlanQty);
				$sql		= vsprintf($queryInsert, $inputArr);
				$returnData	= $this->execUpdateQuery($sql);
				if ($returnData) return $returnData;
			}
		}
	}
return $returnData;
}

public function updateDespPlanItem($data) {
	$queryInsert	= $this->getDespPlanItemInsertQuery();
	$queryUpdate	= $this->getDespPlanItemUpdateQuery();
	$queryDelete	= $this->getDespPlanItemDeleteQuery();

	$ItemArr = explode(',', $data['ItemCdStrForDespQty']);
	$ItemCount = count($ItemArr);
	$returnData		= '';

	$CustomerCd	= $data['CustomerCd'];
	$Date = $this->convertDate($data['Date'],TRUE,1);

	for($curRowNo=1; $curRowNo<=$data['LastRowNo2']; $curRowNo++) {
		$IdSubdealer = (int)$data['IdSubdealer2_'.$curRowNo];
		for ($curItemCdIndex=0; $curItemCdIndex<$ItemCount; $curItemCdIndex++) {
			$ItemCd = $ItemArr[$curItemCdIndex];
			$DespPlanQty = (int)$data[$ItemCd.'2_'.$curRowNo];	// $data['200001182_1']
			if ($DespPlanQty<=0) {
				$inputArr	= array();
				$inputArr	= array($CustomerCd, $Date, $IdSubdealer, $ItemCd);
				$sql		= vsprintf($queryDelete, $inputArr);
				$returnData	= $this->execUpdateQuery($sql);
				if ($returnData) return $returnData;
			} else {
				$queryCheck	= "SELECT COUNT(*) AS Count FROM so_desp_plan_item WHERE CustomerCd='%s' AND Date='%s' AND IdSubdealer=%s AND ItemCd='%s'";
				$inputArr	= array();
				$inputArr	= array($CustomerCd, $Date, $IdSubdealer, $ItemCd);
				$sql		= vsprintf($queryCheck,$inputArr);
				$returnData	= $this->execSelectQuery($sql);
				if ($returnData[0]['Count']==0) {
					$inputArr	= array();
					$inputArr	= array($CustomerCd, $Date, $IdSubdealer, $ItemCd, $DespPlanQty);
					$sql		= vsprintf($queryInsert,$inputArr);
					$returnData	= $this->execUpdateQuery($sql);
				} else {
					$inputArr	= array();
					$inputArr	= array($DespPlanQty, $CustomerCd, $Date, $IdSubdealer, $ItemCd);
					$sql		= vsprintf($queryUpdate,$inputArr);
					$returnData	= $this->execUpdateQuery($sql);
				}
				if ($returnData) return $returnData;
			}
		}
	}
	return $returnData;
}

// DailySaleItem (Grid-3) ------------------------------------------------------
public function getDailySaleItemInsertQuery() {
	$sql = "INSERT INTO so_daily_sale_item (CustomerCd, Date, IdSubdealer, RE12No, ItemCd, RE12Date, SaleQty)"
		. " VALUES ('%s', '%s', %s, %s, '%s', '%s', %s);";
	return $sql ;
}

public function getDailySaleItemUpdateQuery() {
	$sql	= "UPDATE so_daily_sale_item SET RE12Date='%s', SaleQty=%s WHERE CustomerCd='%s' AND Date='%s' AND IdSubdealer=%s AND RE12No=%s AND ItemCd='%s'";
	return $sql ;
}

public function getDailySaleItemDeleteQuery() {
	$sql	= "DELETE FROM so_daily_sale_item WHERE CustomerCd='%s' AND Date='%s' AND IdSubdealer=%s AND RE12No=%s AND ItemCd='%s'";
	return $sql ;
}

public function insertDailySaleItem($data) {
	$queryInsert	= $this->getDailySaleItemInsertQuery();

	$ItemArr = explode(',', $data['ItemCdStrForSaleQty']);	// 20000118,20000119,20000120,20000121
	$ItemCount = count($ItemArr);
	$returnData		= '';

	$CustomerCd	= $data['CustomerCd'];
	$Date = $this->convertDate($data['Date'],TRUE,1);

	for ($curRowNo=1; $curRowNo<=$data['LastRowNo3']; $curRowNo++) {
		$IdSubdealer	= (int)$data['IdSubdealer3_'.$curRowNo];
		for ($curItemCdIndex=0; $curItemCdIndex<$ItemCount; $curItemCdIndex++) {
			$ItemCd = $ItemArr[$curItemCdIndex];
			$SaleQty = (int)$data[$ItemCd.'3_'.$curRowNo];	// $data['200001183_1']
			$RE12No		= (int)$data['RE12No3_'.$curRowNo];
			if ($IdSubdealer>0 && $RE12No>0 && $SaleQty>0) {
				$RE12Date	= $this->convertDate($data['RE12Date3_'.$curRowNo], TRUE, 1);
				$inputArr	= array($CustomerCd, $Date, $IdSubdealer, $RE12No, $ItemCd, $RE12Date, $SaleQty);
				$sql		= vsprintf($queryInsert, $inputArr);
				$returnData	= $this->execUpdateQuery($sql);
				if ($returnData) return $returnData;
			}
		}
	}
return $returnData;
}

public function updateDailySaleItem($data) {
	$queryInsert	= $this->getDailySaleItemInsertQuery();
	$queryUpdate	= $this->getDailySaleItemUpdateQuery();
	$queryDelete	= $this->getDailySaleItemDeleteQuery();

	$ItemArr = explode(',', $data['ItemCdStrForSaleQty']);
	$ItemCount = count($ItemArr);
	$returnData		= '';

	$CustomerCd	= $data['CustomerCd'];
	$Date = $this->convertDate($data['Date'],TRUE,1);

	for($curRowNo=1; $curRowNo<=$data['LastRowNo3']; $curRowNo++) {
		$IdSubdealer = (int)$data['IdSubdealer3_'.$curRowNo];
		for ($curItemCdIndex=0; $curItemCdIndex<$ItemCount; $curItemCdIndex++) {
			$RE12No	= (int)$data['RE12No3_'.$curRowNo];
			$RE12Date	= $this->convertDate($data['RE12Date3_'.$curRowNo], TRUE, 1);
			$ItemCd = $ItemArr[$curItemCdIndex];
			$SaleQty = (int)$data[$ItemCd.'3_'.$curRowNo];	// $data['200001183_1']
			if ($IdSubdealer<=0 || $RE12No<=0 || $SaleQty<=0) {
				$inputArr	= array();
				$inputArr	= array($CustomerCd, $Date, $IdSubdealer, $RE12No, $ItemCd);
				$sql		= vsprintf($queryDelete, $inputArr);
				$returnData	= $this->execUpdateQuery($sql);
				if ($returnData) return $returnData;
			} else {
				$queryCheck	= "SELECT COUNT(*) AS Count FROM so_daily_sale_item WHERE CustomerCd='%s' AND Date='%s' AND IdSubdealer=%s AND RE12No=%s AND ItemCd='%s'";
				$inputArr	= array();
				$inputArr	= array($CustomerCd, $Date, $IdSubdealer, $RE12No, $ItemCd);
				$sql		= vsprintf($queryCheck,$inputArr);
				$returnData	= $this->execSelectQuery($sql);
				if ($returnData[0]['Count']==0) {
					$inputArr	= array();
					$inputArr	= array($CustomerCd, $Date, $IdSubdealer, $RE12No, $ItemCd, $RE12Date, $SaleQty);
					$sql		= vsprintf($queryInsert,$inputArr);
					$returnData	= $this->execUpdateQuery($sql);
				} else {
					$inputArr	= array();
					$inputArr	= array($RE12Date, $SaleQty, $CustomerCd, $Date, $IdSubdealer, $RE12No, $ItemCd);
					$sql		= vsprintf($queryUpdate,$inputArr);
					$returnData	= $this->execUpdateQuery($sql);
				}
				if ($returnData) return $returnData;
			}
		}
	}
	return $returnData;
}

// -----------------------------------------------------------------------
public function getDailyStockSubdealerM($CustomerCd) {
	$inputArr 		= array($CustomerCd);
	$paraString		= vsprintf("'%s'",$inputArr);
	$sql			= "call sp_getDailyStockSubdealerM(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}
public function getDailyStockItem($CustomerCd, $Date, $StatusCd) {
	$inputArr 		= array($CustomerCd, $this->convertDate($Date,TRUE,1), $StatusCd);
	$paraString		= vsprintf("'%s', '%s', '%s'",$inputArr);
	$sql			= "call sp_getDailyStockItem(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
} 

public function getDailySaleItem($CustomerCd, $Date, $IsHeaderOwn) {
	$inputArr 		= array($CustomerCd, $this->convertDate($Date,TRUE,1), $IsHeaderOwn);
	$paraString		= vsprintf("'%s', '%s', %s",$inputArr);
	$sql			= "call sp_getDailySaleItem(" . $paraString. ")";

	$preResultsAr = array();
	$returnData = $this->execSelectQuery($sql,0, $preResultsAr);
	if (count($preResultsAr)==4)
		return $returnData;
	else
		return array();
}


public function getDespPlanItem($CustomerCd, $Date, $StatusCd) {
	$inputArr 		= array($CustomerCd, $this->convertDate($Date,TRUE,1), $StatusCd);
	$paraString		= vsprintf("'%s', '%s', '%s'",$inputArr);
	$sql			= "call sp_getDespPlanItem(" . $paraString. ")";

	$preResultsAr = array();
	$returnData = $this->execSelectQuery($sql,0, $preResultsAr);
	if (count($preResultsAr)==3)	// 1stResultset: Discard. 2nd Resultset (always): "@CTColumnStru := ..,". In case of valid records, 3rd Resultset. In case of No _source records, No resultset
		return $returnData;
	else
		return array();
}


public function sendEMailPOAccessApproval($approveDocList, $fromWhat) {
	switch ($fromWhat) {
	case 1:
		$Emailtemplate	= 2;
		$TableName		= 'so_po';
		$TransId		= 'IdPO';
		$Date			= 'Date';
		break;
	case 2:
	case 3:
		$Emailtemplate	= 23;
		$TableName		= 'so_expdet';
		$TransId		= 'IdExpDet';
		$Date			= 'DateTime';
		break;
	case 4:
	case 5:
		$Emailtemplate	= 12;
		$TableName		= 'so_accessory';
		$TransId		= 'IdAccessory';
		$Date			= 'Date';
		break;
	}
	$templateArr = $this->getEMailTemplate($Emailtemplate);
// Show VehicleNo only for X-Factory. If 'DUMMY', show Remark (assuming actual Vehicle No is put there with prompt)
	//$sql = "SELECT A.$TransId AS TransId, C.RE11PDF, DATE_FORMAT(A.$Date,'%d-%m-%Y') AS Date, CONCAT(TRIM(A.TokenNoPrefix),'/',A.TokenNo%100) AS TokenNoFull
	//		, IF(A.DespatchMode='X',IF(A.VehicleNo='DUMMY',CONCAT(' ',TRIM(A.Remark)),CONCAT('Vehicle No. is:',A.VehicleNo)),'') AS VehicleNo, B.EMailId FROM $TableName A INNER JOIN so_customer_m B 
	//		ON A.CustomerCd=B.CustomerCd  INNER JOIN so_expdet_magazine C ON A.IdExpdet= C.IdExpdet WHERE A.$TransId IN ($approveDocList)";
		$sql = "SELECT A.$TransId AS TransId, DATE_FORMAT(A.$Date,'%d-%m-%Y') AS Date, CONCAT(TRIM(A.TokenNoPrefix),'/',A.TokenNo%100) AS TokenNoFull
		, IF(A.DespatchMode='X',IF(A.VehicleNo='DUMMY',CONCAT(' ',TRIM(A.Remark)),CONCAT(' ' ,A.VehicleNo)),'') AS VehicleNo, B.EMailId FROM $TableName A INNER JOIN so_customer_m B
		ON A.CustomerCd=B.CustomerCd WHERE A.$TransId IN ($approveDocList)";
	
	$eMailDetailArr = $this->execSelectQuery($sql);
	foreach ($eMailDetailArr as $eMailDetailRow) {
		$IdExpdet = $eMailDetailRow['TransId'];
		$VehicleNo = $eMailDetailRow['VehicleNo'];
		$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($eMailDetailRow['TransId'], $eMailDetailRow['Date'], $eMailDetailRow['TokenNoFull'], $VehicleNo));
		$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
		
		if($Emailtemplate=='23'){
			$sqlMag = "SELECT RE11PDF FROM so_expdet_magazine WHERE  $TransId IN ($IdExpdet)";
			$RE11eMailDetailArr = $this->execSelectQuery($sqlMag);
			$attachment=array();
			$i=0;
			foreach($RE11eMailDetailArr as $UploadedPDF)
			{
				//$attachmentpa= "/var/zpanel/hostdata/solarexp/public_html/b2b_solarexplosives_com/upload/re11PDF/PO/";
				$attachmentpath='upload/re11PDF/PO/'.$UploadedPDF["RE11PDF"];
				//$attachmentpath='/var/zpanel/hostdata/solarexp/public_html/b2b_solarexplosives_com/upload/re11PDF/PO/'.$UploadedPDF["RE11PDF"];
				if($UploadedPDF["RE11PDF"]){
					array_push($attachment, $attachmentpath);
				}
			}
		}
		if($Emailtemplate=='12'){
			$sqlMag = "SELECT RE11PDF FROM so_accessory WHERE  $TransId IN ($IdExpdet)";
			$RE11eMailDetailArr = $this->execSelectQuery($sqlMag);
			$attachment=array();
			$i=0;
			foreach($RE11eMailDetailArr as $UploadedPDF)
			{
				$attachmentpath= 'upload/re11PDF/PO/'.$UploadedPDF["RE11PDF"];
				//$attachmentpath='/var/zpanel/hostdata/solarexp/public_html/b2b_solarexplosives_com/upload/re11PDF/Accessory/'.$UploadedPDF["RE11PDF"];
				if($UploadedPDF["RE11PDF"]){
					array_push($attachment, $attachmentpath);
				}
			}
		}
		$objSolarMailer = new solarMailer();
		if(sizeof($attachment)){
			$objSolarMailer->sendSolarMailPOApproval($eMailDetailRow['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC'], $attachment);
		}
		else{
			$objSolarMailer->sendSolarMail($eMailDetailRow['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
		}
		//$objSolarMailer->sendSolarMailPOApproval($eMailDetailRow['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC'], $attachment);
	}
}

public function Re11PDFMailSend($IdExpDet, $SubAction) {
	switch ($SubAction) {
	case 0:
		$Emailtemplate	= 39;
		$TableName		= 'so_expdet';
		$TransId		= 'IdExpDet';	
		$ReminderField		= 'CuruptedRE11MailReminder';
		$Date			= 'DateTime';
		break;
	case 1:
		$Emailtemplate	= 40;
		$TableName		= 'so_expdet';
		$TransId		= 'IdExpDet';
		$ReminderField		= 'OldRE11MailReminder';
		$Date			= 'DateTime';
		break;
	case 2:
		$Emailtemplate	= 41;
		$TableName		= 'so_expdet';
		$TransId		= 'IdExpDet';
		$Date			= 'DateTime';
		break;
	case 3:
		$Emailtemplate	= 45;
		$TableName		= 'so_expdet';
		$TransId		= 'IdExpDet';
		$ReminderField	= 'WrongRE11MailReminder';
		$Date			= 'DateTime';
		break;
	case 4:
		$Emailtemplate	= 46;
		$TableName		= 'so_expdet';
		$TransId		= 'IdExpDet';
		$ReminderField	= 'DigitalSignMissRE11MailReminder';
		$Date			= 'DateTime';
		break;
	case 5:
		$Emailtemplate	= 47;
		$TableName		= 'so_expdet';
		$TransId		= 'IdExpDet';
		$ReminderField	= 'SingleSideSignRE11MailReminder';
		$Date			= 'DateTime';
		break;
	}
	
	$templateArr = $this->getEMailTemplate($Emailtemplate);
	$sql = "SELECT A.$TransId AS IdExpDet, DATE_FORMAT(A.$Date,'%d-%m-%Y') AS Date, B.EMailId, A.$ReminderField FROM $TableName A INNER JOIN so_customer_m B
		ON A.CustomerCd=B.CustomerCd WHERE A.$TransId IN ($IdExpDet)";
	
	$eMailDetailArr = $this->execSelectQuery($sql);
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($IdExpDet));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$ReminderStatus = $eMailDetailArr[0][$ReminderField];
	$ReminderStatusdata=' ReminderStatus';
	if($ReminderStatus){
		if($ReminderStatus == 3){
		$ReminderStatusdata=' Final';		
	}
	 $eMailBody ="Reminder ".$ReminderStatusdata." \r \n ". $eMailBody;
	}
	
	if($ReminderStatus < 3){
		$ReminderStatus++;
	}
	
	$stmt		= "UPDATE so_expdet SET RE11ExpiredMail='%s', RE11ExpiredMailStatus='%s', $ReminderField='%s' WHERE  $TransId IN ($IdExpDet)";

	
	$inputArr	= array(1, $SubAction, $ReminderStatus);
 	$sql		= vsprintf($stmt, $inputArr);
	
	$returnData	= $this->execUpdateQuery($sql);
		$objSolarMailer = new solarMailer();
		$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	//	$objSolarMailer->sendSolarMail('websupport@solargroup.com', $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	}
	
public function Re11PDFMailSendAccessory($IdAccessory, $SubAction) {
	switch ($SubAction) {
	case 0:
		$Emailtemplate	= 39;
		$TableName		= 'so_accessory';
		$TransId		= 'IdAccessory';	
		$ReminderField	= 'CuruptedRE11MailReminder';
		$Date			= 'Date';
		break;
	case 1:
		$Emailtemplate	= 40;
		$TableName		= 'so_accessory';
		$TransId		= 'IdAccessory';
		$ReminderField	= 'OldRE11MailReminder';
		$Date			= 'Date';
		break;
	case 2:
		$Emailtemplate	= 41;
		$TableName		= 'so_accessory';
		$TransId		= 'IdAccessory';
		$Date			= 'Date';
		break;
	case 3:
		$Emailtemplate	= 45;
		$TableName		= 'so_accessory';
		$TransId		= 'IdAccessory';
		$ReminderField	= 'WrongRE11MailReminder';
		$Date			= 'Date';
		break;
	case 4:
		$Emailtemplate	= 46;
		$TableName		= 'so_accessory';
		$TransId		= 'IdAccessory';
		$ReminderField	= 'DigitalSignMissRE11MailReminder';
		$Date			= 'Date';
		break;
	case 5:
		$Emailtemplate	= 47;
		$TableName		= 'so_accessory';
		$TransId		= 'IdAccessory';
		$ReminderField	= 'SingleSideSignRE11MailReminder';
		$Date			= 'Date';
		break;
	}
	
	$templateArr = $this->getEMailTemplate($Emailtemplate);
	$sql = "SELECT A.$TransId AS IdAccessory, DATE_FORMAT(A.$Date,'%d-%m-%Y') AS Date, B.EMailId, A.$ReminderField FROM $TableName A INNER JOIN so_customer_m B
		ON A.CustomerCd=B.CustomerCd WHERE A.$TransId IN ($IdAccessory)";
	
	$eMailDetailArr = $this->execSelectQuery($sql);
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($IdAccessory));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$ReminderStatus = $eMailDetailArr[0][$ReminderField];
	$ReminderStatusdata=' ReminderStatus';
	if($ReminderStatus){
		if($ReminderStatus == 3){
		$ReminderStatusdata=' Final';		
	}
	 $eMailBody ="Reminder ".$ReminderStatusdata." \r \n ". $eMailBody;
	}
	
	if($ReminderStatus < 3){
		$ReminderStatus++;
	}
	
	$stmt		= "UPDATE so_accessory SET RE11ExpiredMail='%s', RE11ExpiredMailStatus='%s', $ReminderField='%s' WHERE  $TransId IN ($IdAccessory)";

	
	$inputArr	= array(1, $SubAction, $ReminderStatus);
 	$sql		= vsprintf($stmt, $inputArr);
	
	$returnData	= $this->execUpdateQuery($sql);
		$objSolarMailer = new solarMailer();
		$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	//	$objSolarMailer->sendSolarMail('websupport@solargroup.com', $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	}

public function Re11PDFExpireMailSend($IdExpDet, $SubAction, $RE11No, $RE11Date) {
	switch ($SubAction) {
	case 2:
		$Emailtemplate	= 41;
		$TableName		= 'so_expdet';
		$TransId		= 'IdExpDet';
		$Date			= 'DateTime';
		break;
	case 3:
		$Emailtemplate	= 42;
		$TableName		= 'so_expdet';
		$TransId		= 'IdExpDet';
		$Date			= 'DateTime';
		break;
	}
	
	$templateArr = $this->getEMailTemplate($Emailtemplate);
	$sql = "SELECT A.$TransId AS IdExpDet, DATE_FORMAT(A.$Date,'%d-%m-%Y') AS Date, B.EMailId FROM $TableName A INNER JOIN so_customer_m B
		ON A.CustomerCd=B.CustomerCd WHERE A.$TransId IN ($IdExpDet)";
	
	$eMailDetailArr = $this->execSelectQuery($sql);
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($IdExpDet, $RE11No, $RE11Date));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	}

public function Re11PDFReUploadMailSend($IdExpDet, $SubAction, $RE11No, $RE11Date) {
	switch ($SubAction) {
	case 3:
		$Emailtemplate	= 43;
		$TableName		= 'so_expdet';
		$TransId		= 'IdExpDet';
		$Date			= 'DateTime';
		break;
	}
	
	$templateArr = $this->getEMailTemplate($Emailtemplate);
	$sql = "SELECT A.$TransId AS IdExpDet, DATE_FORMAT(A.$Date,'%d-%m-%Y') AS Date, B.EMailId FROM $TableName A INNER JOIN so_customer_m B
		ON A.CustomerCd=B.CustomerCd WHERE A.$TransId IN ($IdExpDet)";
	
	$eMailDetailArr = $this->execSelectQuery($sql);
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($IdExpDet, $RE11No, $RE11Date));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	}
public function VanLoadingPDFReUploadMailSend($IdExpDet, $SubAction) {
	switch ($SubAction) {
	case 3:
		$Emailtemplate	= 53;
		$TableName		= 'so_expdet';
		$TransId		= 'IdExpDet';
		$Date			= 'DateTime';
		break;
	}
	
	$templateArr = $this->getEMailTemplate($Emailtemplate);
	$sql = "SELECT A.$TransId AS IdExpDet, DATE_FORMAT(A.$Date,'%d-%m-%Y') AS Date, B.EMailId FROM $TableName A INNER JOIN so_customer_m B
		ON A.CustomerCd=B.CustomerCd WHERE A.$TransId IN ($IdExpDet)";
	
	$eMailDetailArr = $this->execSelectQuery($sql);
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($IdExpDet));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
}

public function DriverAuthPDFReUploadMailSend($IdExpDet, $SubAction) {
	switch ($SubAction) {
	case 3:
		$Emailtemplate	= 54;
		$TableName		= 'so_expdet';
		$TransId		= 'IdExpDet';
		$Date			= 'DateTime';
		break;
	}
	
	$templateArr = $this->getEMailTemplate($Emailtemplate);
	$sql = "SELECT A.$TransId AS IdExpDet, DATE_FORMAT(A.$Date,'%d-%m-%Y') AS Date, B.EMailId FROM $TableName A INNER JOIN so_customer_m B
		ON A.CustomerCd=B.CustomerCd WHERE A.$TransId IN ($IdExpDet)";
	
	$eMailDetailArr = $this->execSelectQuery($sql);
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($IdExpDet));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
}

public function Form403PDFUploadMailSend($IdExpDet, $SubAction) {
	switch ($SubAction) {
	case 3:
		$Emailtemplate	= 44;
		$TableName		= 'so_expdet';
		$TransId		= 'IdExpDet';
		$Date			= 'DateTime';
		break;
	}
	
	$templateArr = $this->getEMailTemplate($Emailtemplate);
	$sql = "SELECT A.$TransId AS IdExpDet, DATE_FORMAT(A.$Date,'%d-%m-%Y') AS Date, B.EMailId FROM $TableName A INNER JOIN so_customer_m B
		ON A.CustomerCd=B.CustomerCd WHERE A.$TransId IN ($IdExpDet)";
	
	$eMailDetailArr = $this->execSelectQuery($sql);
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($IdExpDet));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
}

public function SubdealerInactiveMailSend($IdSubdealer, $SubAction) {
	switch ($SubAction) {
	case 1:
		$Emailtemplate	= 51;
		$TableName		= 'so_subdealer_m_dealer';
		$TransId		= 'IdSubdealer';
		break;
	}
	
	$templateArr = $this->getEMailTemplate($Emailtemplate);
	$sql = "SELECT A.$TransId, C.Descript, B.EMailId FROM $TableName A INNER JOIN so_customer_m B
		ON A.CustomerCd=B.CustomerCd INNER JOIN so_subdealer_m C ON A.IdSubdealer = C.IdSubdealer WHERE A.$TransId IN ($IdSubdealer)";
	
	$eMailDetailArr = $this->execSelectQuery($sql);
	//$EmailId = 'websupport@solargroup.com';
	foreach($eMailDetailArr as $email){
	$EmailId = $email['EMailId'];
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($IdSubdealer, $eMailDetailArr[0]['Descript']));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($EmailId, $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	}
}

public function ItemdelistMailSend($ItemCd, $Descript, $SubAction) {
	switch ($SubAction) {
	case 1:
		$Emailtemplate	= 52;
		$TableName		= 'so_customer_m';
		$TransId		= 'CustomerCd';
		break;
	}
	
	$templateArr = $this->getEMailTemplate($Emailtemplate);
	$sql = "SELECT Descript, EMailId  FROM $TableName  WHERE IsActive ='1' and SectorCd='" . $_SESSION['SectorCd']. "'";
	$eMailDetailArr = $this->execSelectQuery($sql);
	//$EmailId = 'websupport@solargroup.com';
	foreach($eMailDetailArr as $email){
	$EmailId = $email['EMailId'];
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($ItemCd, $Descript));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($EmailId, $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	}
}


	
public function sendEMailRE11Receipt($idTran, $fromWhat) {
	if ($fromWhat==1) {
		$Emailtemplate	= 3;
		$TableName		= 'so_po';
		$TransId		= 'IdPO';
		$Date			= 'Date';
	} elseif ($fromWhat==3) {
		$Emailtemplate	= 11;
		$TableName		= 'so_accessory';
		$TransId		= 'IdAccessory';
		$Date			= 'Date';
	} else {
		$Emailtemplate	= 24;
		$TableName		= 'so_expdet';
		$TransId		= 'IdExpDet';
		$Date			= 'DateTime';
	}
	$templateArr = $this->getEMailTemplate($Emailtemplate);
	//if($Emailtemplate==24){
	//$sql = "SELECT A.$TransId AS TransId, C.RE11PDF, DATE_FORMAT(A.$Date,'%d-%m-%Y') AS Date, DATE_FORMAT(A.RE11ReceiptDate,'%d-%m-%Y') AS RE11ReceiptDate, B.EMailId FROM $TableName A INNER JOIN so_customer_m B"
	//	. " ON A.CustomerCd=B.CustomerCd INNER JOIN so_expdet_magazine C ON A.IdExpDet=C.IdExpDet  WHERE A.$TransId = $idTran";
	//}
	//else{
	$sql = "SELECT A.$TransId AS TransId, DATE_FORMAT(A.$Date,'%d-%m-%Y') AS Date, DATE_FORMAT(A.RE11ReceiptDate,'%d-%m-%Y') AS RE11ReceiptDate, B.EMailId FROM $TableName A INNER JOIN so_customer_m B"
		. " ON A.CustomerCd=B.CustomerCd WHERE A.$TransId = $idTran";
	//}
	$eMailDetailArr = $this->execSelectQuery($sql);
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($eMailDetailArr[0]['RE11ReceiptDate'], $eMailDetailArr[0]['TransId'], $eMailDetailArr[0]['Date']));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$RE11PDF = $eMailDetailArr[0]['RE11PDF'];
	$attachment='upload/re11PDF/PO/'.$RE11PDF;
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($eMailDetailArr[0]['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
}

public function XuploadPO2SAP_Slice_1PO_AtATime() {
	$fileFolder = '/home/solarexplosives/solar_sap/po2sap/';
	$curPONumber = $_SESSION['ApprovePO'][0]['PONumber'];
	$fileName = "PO".(int)$curPONumber.'.txt';
	$folderFileName = $fileFolder.$fileName;
	$handle = fopen($folderFileName,'wb');
	$arrayKeys = array_keys($_SESSION['ApprovePO'][0]);
	$curRec = implode("\t", $arrayKeys)."\r\n";
	fwrite($handle, $curRec);
	while (count($_SESSION['ApprovePO'])>0 && $curPONumber == $_SESSION['ApprovePO'][0]['PONumber']) {
		$curRec = implode("\t", $_SESSION['ApprovePO'][0])."\r\n";
		fwrite($handle, $curRec);
		$_SESSION['ApprovePO'] = array_slice($_SESSION['ApprovePO'], 1);
	}
	fclose($handle);
	$this->downloadFile($folderFileName);
	if (count($_SESSION['ApprovePO'])==0)	unset($_SESSION['ApprovePO']);
//			sleep(1);
//		    header('Content-Description: File Transfer');
//			header("Content-type:application/txt");
//			header("Content-type: text/plain");
//			header("Content-type: application/force-download");
//			header('Content-Disposition: attachment; filename="'.$fileName.'"');
//			readfile($folderFileName);
//			unlink($fileName);
}

public function uploadPO2SAP($approvePOArr) {
// We only put the file in upload/po2sap folder. SAP thro an utility, would read & update in SAP & then move it to upload/Backup folder
	$fileFolder = '/home/solarexplosives/solar_sap/po2sap/';
	$row = 0;
	$rowTotal = count($approvePOArr);
	while ($row<$rowTotal) {
		$curPONumber = $approvePOArr[$row]['PONumber'];
		$fileName = "PO".(int)$curPONumber.'.txt';
		$folderFileName = $fileFolder.$fileName;
		$handle = fopen($folderFileName,'wb');
		
/*			$arrayKeys = array_keys($approvePOArr[$row]);
		$curRec = trim(implode("\t", $arrayKeys))."\r\n";
		fwrite($handle, $curRec);
*/			
		while ($row<$rowTotal && $curPONumber == $approvePOArr[$row]['PONumber']) {
			$curRec = trim(implode("\t", $approvePOArr[$row]))."\r\n";
			fwrite($handle, $curRec);
			$row++;
		}
		fclose($handle);
//			$this->downloadFile($folderFileName);
	}
}

public function XdownloadFile($fullPath) {
	$handle = @fopen($fullPath, "r");
	if ($handle) {
		while (!feof($handle)) {
			$buffer = fgets($handle, 4096);
			echo $buffer;
		}
		fclose($handle);
	}
}

public function tdownloadFile($fullPath) {
if ($fd = fopen ($fullPath, "r")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
    case "pdf":
    header("Content-type: application/pdf"); // add here more headers for diff. extensions
    header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
    break;
    default;
    header("Content-type: application/octet-stream");
    header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
header("Content-length: $fsize");
header("Cache-control: private"); //use this to open files directly
while(!feof($fd)) {
    $buffer = fread($fd, 2048);
    echo $buffer;
}
}
fclose ($fd);
}

public function downloadFile($fullPath) {
	// Must be fresh start
	if (headers_sent())		die('Headers Sent');

	// Required for some browsers
	if (ini_get('zlib.output_compression'))		ini_set('zlib.output_compression', 'Off');
	
	if (file_exists($fullPath)) {
		$fsize = filesize($fullPath);
		$path_parts = pathinfo($fullPath);
		$ext = strtolower($path_parts["extension"]);
		
		// Determine Content Type
		switch ($ext) {
		case "pdf": $ctype="application/pdf"; break;
		case "exe": $ctype="application/octet-stream"; break;
		case "zip": $ctype="application/zip"; break;
		case "doc": $ctype="application/msword"; break;
		case "xls": $ctype="application/vnd.ms-excel"; break;
		case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
		case "gif": $ctype="image/gif"; break;
		case "png": $ctype="image/png"; break;
		case "jpeg":
		case "jpg": $ctype="image/jpg"; break;
		default: $ctype="application/force-download";
		}
		
		header("Pragma: public"); // required
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Cache-Control: private", false); // required for certain browsers
		header("Content-Type: ".$ctype);
		header('Content-Disposition: attachment; filename="'.basename($fullPath).'";' );
		header("Content-Transfer-Encoding: binary");
		header("Content-Length: ".$fsize);
		ob_clean();
		flush();
		readfile($fullPath);
	} else die('File Not Found');
} 

public function XXdownloadFile($fullPath) {
	// Must be fresh start
//		if (headers_sent())		die('Headers Sent');

//echo "<script>alert('In DownloadFIle for $fullPath');</script>";
	// Required for some browsers
	if (ini_get('zlib.output_compression'))		ini_set('zlib.output_compression', 'Off');
	
	if (file_exists($fullPath)) {
		$fsize = filesize($fullPath);
		$path_parts = pathinfo($fullPath);
		$ext = strtolower($path_parts["extension"]);
		
		// Determine Content Type
		switch ($ext) {
		case "pdf": $ctype="application/pdf"; break;
		case "exe": $ctype="application/octet-stream"; break;
		case "zip": $ctype="application/zip"; break;
		case "doc": $ctype="application/msword"; break;
		case "xls": $ctype="application/vnd.ms-excel"; break;
		case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
		case "gif": $ctype="image/gif"; break;
		case "png": $ctype="image/png"; break;
		case "jpeg":
		case "jpg": $ctype="image/jpg"; break;
		default: $ctype="application/force-download";
		}
ob_start('ob_postprocess');			
		header("Pragma: public"); // required
		header("Expires: 0");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Cache-Control: private", false); // required for certain browsers
		header("Content-Type: ".$ctype);
		header('Content-Disposition: attachment; filename="'.basename($fullPath).'";' );
		header("Content-Transfer-Encoding: binary");
		header("Content-Length: ".$fsize);
//			ob_clean();
//			flush();
echo "1234567890\r\n";
echo "ABCDEFGHIJKLMNOPQRSTUVWXYZ\r\n";
ob_end_flush();
//			readfile($fullPath);
	} else die('File Not Found');
} 

// LoginMessage ---------------------------------------------------------------------------------------------------------------------------------
public function getLoginMessageList($search = null) {
	$searchCnd	= " WHERE " . ((isset($search)) ? " A.ShortDesc like '". $search . "%' AND " : "") . "A.MessageType != 'C'" ;
	$sql		= "SELECT  A.IdMessage, IF(MessageType='A','OneTime',IF(MessageType='B','Monthly','Header Msg')) AS MessageType, DATE_FORMAT(A.DateFrom,'%d-%m-%Y') AS DateFrom"
			. ", DATE_FORMAT(A.DateUpto,'%d-%m-%Y') AS DateUpto, DayFrom, DayUpto, ShortDesc, IsActive FROM so_login_message A "
			. $searchCnd. " ORDER BY A.MessageType, A.IdMessage";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function insertLoginMessageData($data) {
	$stmt = " INSERT INTO so_login_message (MessageType, DateFrom, DateUpto, DayFrom, DayUpto, ShortDesc, Message, IsActive)
				VALUES('%s', '%s', '%s', %s, %s, '%s', '%s', %s);";
	$inputArr	= array($data['MessageType'], $this->convertDate($data['DateFrom'],TRUE,1), $this->convertDate($data['DateUpto'],TRUE,1), (int)$data['DayFrom'], (int)$data['DayUpto']
					,addslashes(trim($data['ShortDesc'])), addslashes(trim($data['Message'])), (int)$data['IsActive']);
	$sql        = vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}

public function updateLoginMessageData($data) {

	$stmt		= " UPDATE so_login_message SET MessageType='%s', DateFrom='%s', DateUpto='%s', DayFrom=%s, DayUpto=%s, ShortDesc='%s', Message='%s', IsActive=%s WHERE IdMessage=%s";
	$inputArr	= array($data['MessageType'], $this->convertDate($data['DateFrom'],TRUE), $this->convertDate($data['DateUpto'],TRUE), (int)$data['DayFrom'], (int)$data['DayUpto']
					,addslashes(trim($data['ShortDesc'])), addslashes(trim($data['Message'])), (int)$data['IsActive'], (int)$data['oldIdMessage']);
	$sql		= vsprintf($stmt,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}

public function getLoginMessageData($ccode) {
	$stmt		= "SELECT * FROM so_login_message WHERE IdMessage=%s ";
	$inputArr	= array($ccode);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}


// Traget Yearly ---------------------------------------------------------------------------------------------------------------------------------------
public function getTargetYearList($search, $TargetForDate) {
$TargetForDate	= '01-' . $TargetForDate;
$DTSAnsi		= $this->convertDate($TargetForDate, TRUE);
$DTSAnsi		= substr($DTSAnsi, 0, 8) . '01';
$Year			= $this->getTargetYear($DTSAnsi);
$searchCnd	= " AND Year='" . $Year . "'";
$searchCnd	.= (isset($search)) ? " AND B.Descript like '". $search . "%' AND YMFlag=0" : " AND YMFlag=0";
$searchCnd	.= ($_SESSION['IsCustomer']) ? " AND A.CustomerCd='" .$_SESSION['CustomerCd']. "'" : "";
	$searchCnd	.= ($_SESSION['UserName'] && $_SESSION['HasCustomer'] == 1) ? " AND B.UserName='" .$_SESSION['UserName']. "'" : "";
switch ($_SESSION['StatusFilter']) {
case 0:
	break;
case 2:
	$searchCnd	.= " AND A.StatusCd='A'";
	break;
default:		// 1
	$searchCnd	.= " AND A.StatusCd='U'";
	break;
}
$sql		= "SELECT A.*,IFNULL(B.Descript,A.CustomerCd) AS Customer,IFNULL(C.Descript,A.StatusCd) AS Status FROM so_target A"
	. " LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd" 
	. " LEFT OUTER JOIN so_status_m C ON A.StatusCd=C.StatusCd WHERE B.SectorCd ='".$_SESSION['SectorCd']."'" 
	.$searchCnd. " ORDER BY A.Year DESC, B.StateCd, B.CustomerCtgCd, B.Descript";
$returnData = $this->execSelectQuery($sql);
return $returnData;
}


public function getTargetYearB2bCustomerItem($CustomerCd, $excludeDefCustomer, $Year, $StatusCd) {
	$AlterCustomer	= (($excludeDefCustomer) ? "" : self::DEFCUSTOMERCD);
	$inputArr 		= array($CustomerCd, $AlterCustomer, $Year, $StatusCd);
	$paraString		= vsprintf("'%s','%s', '%s', '%s'", $inputArr);
	$sql			= "call sp_getTargetYearB2bCustomerItem(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getTargetYearCib2bCustomerItem($CustomerCd, $excludeDefCustomer, $Year, $StatusCd) {
	$AlterCustomer	= (($excludeDefCustomer) ? "" : self::DEFCUSTOMERCD);
	$inputArr 		= array($CustomerCd, $AlterCustomer, $Year, $StatusCd);
	$paraString		= vsprintf("'%s','%s', '%s', '%s'", $inputArr);
	$sql			= "call sp_getTargetYearCib2bCustomerItem(" . $paraString. ")";
	
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getTargetYearHeader($CustomerCd, $Year) {
	$sql		= "SELECT * FROM so_target WHERE CustomerCd='".$CustomerCd."' AND YMFlag=0 AND Year='".$Year."'";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function isExistTargetYear($CustomerCd, $Year) {
	$sql			= "SELECT * FROM so_target WHERE CustomerCd='".$CustomerCd."' AND YMFlag=0 AND Year='".$Year."'";

	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function insertTargetYear($data) {
	$stmt		= "INSERT INTO so_target (CustomerCd, Year, YMFlag, Month, Date, StatusCd, Remark, TransUserName, TransDateTime)"
					. " VALUES ('%s', '%s', %s, %s, '%s', '%s', '%s', '%s', '%s');";
	$inputArr	= array($data['CustomerCd'], $data['Year'], 0, 0, $this->convertDate($data['Date'],TRUE)
			, $data['StatusCd'], $data['Remark'], $_SESSION['UserName'], date('Y-m-d H:i:s'));
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function updateTargetYear($data) {
	$stmt		= "UPDATE so_target SET StatusCd='%s', Remark='%s', TransUserName='%s', TransDateTime='%s'"
					. " WHERE CustomerCd='%s' AND Year='%s' AND YMFlag=0 AND Month=0";
	$inputArr	= array($data['StatusCd'], $data['Remark'], $_SESSION['UserName'], date('Y-m-d H:i:s'), $data['oldCustomerCd'], $data['oldYear']);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function insertTargetYearItemB2b($data) {
	$maxMonths	= ($data['IsB2b']=='1' ? 12 : 0);
	$queryInsert	= "INSERT INTO so_target_item (CustomerCd, Year, YMFlag, Month, ItemCd, Quantity)"
							. " VALUES ('%s', '%s', %s, %s, '%s', %s);";
	$returnData		= '';
	for ($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		if (!isset($data['ItemCd1_'.$curRowNo]) || trim($data['ItemCd1_'.$curRowNo])=='') {
			continue;
		}
		$ItemCd = $data['ItemCd1_'.$curRowNo];
		for ($curMonth=0; $curMonth<=12; $curMonth++) {
			$colSuffix = (($curMonth<10) ? '0'.$curMonth : $curMonth);
			$mnthQty	= (float)$data['Qty'.$colSuffix.'1_'.$curRowNo];
			$mnthQty	= (is_numeric($mnthQty) && $mnthQty>=0 ? $mnthQty : 0);
			if ($mnthQty==0) {
				continue;
			}
			$inputArr	= array();
			$inputArr	= array($data['CustomerCd'], $data['Year'], 0, $curMonth, $ItemCd, $mnthQty);
			$sql		= vsprintf($queryInsert,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		}
	}
return $returnData;
}

public function updateTargetYearItemB2b($data) {
	$queryDelete	= "DELETE FROM so_target_item WHERE CustomerCd='%s' AND Year='%s' AND YMFlag=0";
	$inputArr		= array($data['oldCustomerCd'], $data['oldYear']);
	$sql			= vsprintf($queryDelete,$inputArr);
	$returnData		= $this->execUpdateQuery($sql);
	if ($returnData) return $returnData;
	
	return $this->insertTargetYearItemB2b($data);
}

public function insertTargetYearItemCib2b($data) {
	$maxMonths	= ($data['IsB2b']=='1' ? 12 : 0);
	$queryInsert	= "INSERT INTO so_target_itemgroup (CustomerCd, Year, YMFlag, Month, ItemTargetGroupCd, Quantity)"
							. " VALUES ('%s', '%s', %s, %s, %s, %s);";
	$returnData		= '';
	for ($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		if (!isset($data['ItemTargetGroupCd1_'.$curRowNo]) || trim($data['ItemTargetGroupCd1_'.$curRowNo])=='') {
			continue;
		}
		$ItemTargetGroupCd = (int)$data['ItemTargetGroupCd1_'.$curRowNo];
		for ($curMonth=0; $curMonth<=0; $curMonth++) {
			$colSuffix = (($curMonth<10) ? '0'.$curMonth : $curMonth);
			$mnthQty	= (float)$data['Qty'.$colSuffix.'1_'.$curRowNo];
			$mnthQty	= (is_numeric($mnthQty) && $mnthQty>=0 ? $mnthQty : 0);
			if ($mnthQty==0) {
				continue;
			}
			$inputArr	= array();
			$inputArr	= array($data['CustomerCd'], $data['Year'], 0, $curMonth, $ItemTargetGroupCd, $mnthQty);
			$sql		= vsprintf($queryInsert,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		}
	}
return $returnData;
}

public function updateTargetYearItemCib2b($data) {
	$queryDelete	= "DELETE FROM so_target_itemgroup WHERE CustomerCd='%s' AND Year='%s' AND YMFlag=0";
	$inputArr		= array($data['oldCustomerCd'], $data['oldYear']);
	$sql			= vsprintf($queryDelete,$inputArr);
	$returnData		= $this->execUpdateQuery($sql);
	if ($returnData) return $returnData;
	
	return $this->insertTargetYearItemCib2b($data);
}

public function approveTargetYear($condTarget, $isApproved) {
	$stmt		= "UPDATE so_target SET StatusCd='%s', ApprovedByUserName='%s', ApprovalDateTime='%s' WHERE ".$condTarget;
	if ($isApproved)
		$inputArr 	= array('A', $_SESSION['UserName'], date('Y-m-d H:i:s'));
	else
		$inputArr 	= array('U', '', '');
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execUpdateQuery($sql);
	return $returnData;
}

// Traget Monthly ---------------------------------------------------------------------------------------------------------------------------------------
public function getTargetForMY() {
	if (isset($_POST['TargetForMY'])) {
		$TargetForMY = $_POST['TargetForMY'];
	} else {
		$DayOfMonth = (int)date('d');
		if ($DayOfMonth<20) {
			$TargetForMY = date('m-Y');
		} else {
			$TargetForMY =  $this->addDate(NULL, '+1 month', TRUE);
			$TargetForMY = substr($TargetForMY,3);
		}
	}
	return $TargetForMY;
}

public function getTargetMonthList($search, $TargetForMY) {
	$DTSAnsi		= preg_replace('/(\d{2})[-\/](\d{4})/', "$2-$1", $TargetForMY) . '-01';
	$Year			= $this->getTargetYear($DTSAnsi, $curMonth, $curLogMonth);
	$searchCnd	= " AND Year='" . $Year . "' AND Month=" . $curLogMonth;
	$searchCnd	.= (isset($search)) ? " AND B.Descript like '". $search . "%' AND YMFlag=1" : " AND YMFlag=1";
	$searchCnd	.= ($_SESSION['IsCustomer']) ? " AND A.CustomerCd='" .$_SESSION['CustomerCd']. "'" : "";
	$searchCnd	.= ($_SESSION['UserName'] && $_SESSION['HasCustomer'] == 1) ? " AND B.UserName='" .$_SESSION['UserName']. "'" : "";

	switch ($_SESSION['StatusFilter']) {
	case 0:
		break;
	case 2:
		$searchCnd	.= " AND A.StatusCd='A'";
		break;
	default:		// 1
		$searchCnd	.= " AND A.StatusCd='U'";
		break;
	}
	$sql		= "SELECT A.CustomerCd,A.Year, A.Month, DATE_FORMAT(CONCAT('2012-',(A.Month +2)%12 +1,'-01'),'%b') AS MonthName,IFNULL(B.Descript,A.CustomerCd) AS Customer,IFNULL(C.Descript,A.StatusCd) AS Status FROM so_target A"
		. " LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd" 
		. " LEFT OUTER JOIN so_status_m C ON A.StatusCd=C.StatusCd" 
		. " LEFT OUTER JOIN so_state_m D ON B.StateCd=D.StateCd WHERE B.SectorCd ='".$_SESSION['SectorCd']."'" 
		.$searchCnd. " ORDER BY A.Year DESC, A.Month DESC, B.IsActive DESC, D.DispOrder, B.CustomerCtgCd, B.Descript";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getTargetMonthB2bCompanyItem($CompanyCd) {
	$sql			= "select * from  so_item_m where CompanyCd='$CompanyCd'";
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getTargetMonthB2bCustomerItem($CustomerCd, $excludeDefCustomer, $Year, $Month, $StatusCd) {
	$AlterCustomer	= (($excludeDefCustomer) ? "" : self::DEFCUSTOMERCD);
	$inputArr 		= array($CustomerCd, $AlterCustomer, $Year, (int)$Month, $StatusCd);
	$paraString		= vsprintf("'%s','%s','%s', %s, '%s'", $inputArr);
	$sql			= "call sp_getTargetMonthB2bCustomerItem(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getTargetMonthCib2bCustomerItem($CustomerCd, $excludeDefCustomer, $Year, $Month, $StatusCd) {
	$AlterCustomer	= (($excludeDefCustomer) ? "" : self::DEFCUSTOMERCD);
	$inputArr 		= array($CustomerCd, $AlterCustomer, $Year, (int)$Month, $StatusCd);
	$paraString		= vsprintf("'%s','%s','%s', %s, '%s'", $inputArr);
	$sql			= "call sp_getTargetMonthCib2bCustomerItem(" . $paraString. ")";

	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getTargetMonthHeader($CustomerCd, $Year, $Month) {
	$sql		= "SELECT * FROM so_target WHERE CustomerCd='".$CustomerCd."' AND YMFlag=1 AND Year='".$Year."' AND Month=".(int)$Month;
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function isExistTargetMonth($CustomerCd, $Year, $Month) {
	$sql			= "SELECT * FROM so_target WHERE CustomerCd='".$CustomerCd."' AND YMFlag=1 AND Year='".$Year."' AND Month=".(int)$Month;
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function insertTargetMonth($data) {
	$stmt	= "INSERT INTO so_target (CustomerCd, Year, YMFlag, Month, Date, StatusCd, ComplaintNSuggestion, Remark, IsComplaintPending
			, ComplaintRemark, IsAnyMailReplyPending, MailReplyRemark, IsanysuggestionPending, SuggestionRemark, IsSatisfied, SatisfiedRemark
			, TransUserName, TransDateTime)"
			. " VALUES ('%s', '%s', %s, %s, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');";
	$inputArr	= array($data['CustomerCd'], $data['Year'], 1, (int)$data['Month'], $this->convertDate($data['Date'],TRUE)
		, $data['StatusCd'], $data['ComplaintNSuggestion'], $data['Remark'], $data['Complaint'], $data['ComplaintRemark']
		, $data['MailReply'], $data['MailReplyRemark'],  $data['Suggestion'], $data['SuggestionRemark'], $data['SatisfiedStatus']
		, $data['SatisfiedRemark'], $_SESSION['UserName'], date('Y-m-d H:i:s'));
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function insertTargetMonthB2bItem($data) {
	$queryInsert	= "INSERT INTO so_target_item (CustomerCd, Year, YMFlag, Month, ItemCd, Quantity, OwnUseQty, MonthlyAllocation, MonthStock)"
						. " VALUES ('%s', '%s', %s, %s, '%s', %s, %s, %s, %s);";
	$returnData		= '';
	for ($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		if (!isset($data['ItemCd1_'.$curRowNo]) || trim($data['ItemCd1_'.$curRowNo])=='') {
			continue;
		}
		$ItemCd		= $data['ItemCd1_'.$curRowNo];
		$mnthQty	= (float)$data['MonthCur1_'.$curRowNo];
		$mnthQty	= (is_numeric($mnthQty) && $mnthQty>=0 ? $mnthQty : 0);
		$ownUseQty	= (float)$data['MonthOwnUse1_'.$curRowNo];
		$ownUseQty	= (is_numeric($ownUseQty) && $ownUseQty>=0 ? $ownUseQty : 0);

		$MonthlyAllocation	= (float)$data['MonthlyAllocation1_'.$curRowNo];
		$MonthlyAllocation	= (is_numeric($MonthlyAllocation) && $MonthlyAllocation>=0 ? $MonthlyAllocation : 0);

		$mnthStock	= (float)$data['MonthStock1_'.$curRowNo];
		$mnthStock	= (is_numeric($mnthStock) && $mnthStock>=0 ? $mnthStock : 0);

		if ($mnthQty>0 || $ownUseQty>0 || $mnthStock>0) {
			$inputArr	= array();
			$inputArr	= array($data['CustomerCd'], $data['Year'], 1, (int)$data['Month'], $ItemCd, $mnthQty, $ownUseQty, $MonthlyAllocation, $mnthStock);
			$sql		= vsprintf($queryInsert, $inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		}
	}
return $returnData;
}

public function updateTargetMonth($data) {
	$stmt	= "UPDATE so_target SET StatusCd='%s', ComplaintNSuggestion='%s', Remark='%s', TransUserName='%s', TransDateTime='%s'"
		. " WHERE CustomerCd='%s' AND Year='%s' AND YMFlag=1 AND Month=%s";
	$inputArr	= array($data['StatusCd'], $data['ComplaintNSuggestion'], $data['Remark'], $_SESSION['UserName'], date('Y-m-d H:i:s'), $data['oldCustomerCd'], $data['oldYear'], $data['oldMonth']);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}



public function updateTargetMonthB2bItem($data) {
	$queryDelete	= "DELETE FROM so_target_item WHERE CustomerCd='%s' AND Year='%s' AND Month=%s AND YMFlag=1";
	$inputArr		= array($data['oldCustomerCd'], $data['oldYear'], $data['oldMonth']);
	$sql			= vsprintf($queryDelete,$inputArr);
	$returnData		= $this->execUpdateQuery($sql);
	if ($returnData) return $returnData;
	
	return $this->insertTargetMonthB2bItem($data);
}

public function insertTargetMonthCib2bItem($data) {
	$queryInsert	= "INSERT INTO so_target_itemgroup (CustomerCd, Year, YMFlag, Month, ItemTargetGroupCd, Quantity, MonthAllocateQty)"
						. " VALUES ('%s', '%s', %s, %s, %s, %s, %s);";
	$returnData		= '';
	for ($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		if (!isset($data['ItemTargetGroupCd1_'.$curRowNo]) || trim($data['ItemTargetGroupCd1_'.$curRowNo])=='') {
			continue;
		}
		$ItemTargetGroupCd		= (int)$data['ItemTargetGroupCd1_'.$curRowNo];
		$MonthPlanQty	= (float)$data['MonthPlanQty1_'.$curRowNo];
		$MonthPlanQty	= (is_numeric($MonthPlanQty) && $MonthPlanQty>=0 ? $MonthPlanQty : 0);
		$MonthAllocateQty	= (float)$data['MonthAllocateQty1_'.$curRowNo];
		$MonthAllocateQty	= (is_numeric($MonthAllocateQty) && $MonthAllocateQty>=0 ? $MonthAllocateQty : 0);

		if ($MonthPlanQty>0 || $MonthAllocateQty>0) {
			$inputArr	= array();
			$inputArr	= array($data['CustomerCd'], $data['Year'], 1, (int)$data['Month'], $ItemTargetGroupCd, $MonthPlanQty, $MonthAllocateQty);
			$sql		= vsprintf($queryInsert, $inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		}
	}
return $returnData;
}

public function updateTargetMonthCib2bItem($data) {
	$queryDelete	= "DELETE FROM so_target_itemgroup WHERE CustomerCd='%s' AND Year='%s' AND Month=%s AND YMFlag=1";
	$inputArr		= array($data['oldCustomerCd'], $data['oldYear'], $data['oldMonth']);
	$sql			= vsprintf($queryDelete,$inputArr);
	$returnData		= $this->execUpdateQuery($sql);
	if ($returnData) return $returnData;
	
	return $this->insertTargetMonthCib2bItem($data);
}

public function uploadTargetMonthCib2bCustomerItem($data){

	// We only put the file in upload/target folder. SAP thro an utility, would read & update in SAP & then move it to upload/Backup folder
	$CustomerItem = $this->getTargetMonthCib2bCustomerItem($data['CustomerCd'], $_SESSION['IsCustomer'], $data['Year'], $data['Month'], $data['StatusCd']);	// ReturnData of SAP Upload File for just Approved Target

	$fileFolder = '/home/solarexplosives/solar_sap/target/' . $_SESSION['Sector'] . '/';
	$row = 0;
	$rowTotal	= count($CustomerItem);
	$IsError	= FALSE;
	$CustomerCd = $data['CustomerCd'];
	$Month = $data['Month'];
	$Year = substr($data['Year'],0,4);
	$FromDate = date('d-m-Y',strtotime('01-'.$Month.'-'.date('Y')));
	
	while ($row<$rowTotal) {
		
		$fileName = "Target_".$CustomerCd.'_'.$Month.'-'.$Year.'_'.$_SESSION['SectorCd'].'.txt';
		$folderFileName = $fileFolder.$fileName;

		$handle = fopen($folderFileName,'wb');
		if (!$handle) {
			$IsError	= TRUE;
			break;
		}
		//$curRec = "Customer Code\t From Date\t To Date\t Material Description\t UOM\t Year Quantity\t Year Target For Month\t Target For Month\t Allocation For Month"."\r\n";
		//fwrite($handle, $curRec);
		while ($row<$rowTotal && $CustomerCd == $CustomerItem[$row]['CustomerCd']) {
				$curRow = $CustomerItem[$row];
				$curRec = $curRow['CustomerCd'] . "\t" . $FromDate . "\t" . $curRow['Descript'] . "\t" . $curRow['UOM'] . "\t" . $curRow['YearTarget'] . "\t" . $curRow['YearTargetPMonth'] . "\t" . $curRow['MonthPlanQty'] . "\t" . $curRow['MonthAllocateQty'] . "\r\n";
			fwrite($handle, $curRec);
			$row++;
		}
		fclose($handle);
	}
	return $IsError;
}

public function approveTargetMonth($condTarget, $isApproved) {
	$stmt		= "UPDATE so_target SET StatusCd='%s', ApprovedByUserName='%s', ApprovalDateTime='%s' WHERE ".$condTarget;
	if ($isApproved)
		$inputArr 	= array('A', $_SESSION['UserName'], date('Y-m-d H:i:s'));
	else
		$inputArr 	= array('U', '', '');
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execUpdateQuery($sql);
	return $returnData;
}
//========Target Yearly Trade===========================

public function getTradeTargetYearList($search, $TargetForDate) {
$TargetForDate	= '01-' . $TargetForDate;
$DTSAnsi		= $this->convertDate($TargetForDate, TRUE);
$DTSAnsi		= substr($DTSAnsi, 0, 8) . '01';
$Year			= $this->getTargetYear($DTSAnsi);
$searchCnd	= " AND Year='" . $Year . "'";
$searchCnd	.= (isset($search)) ? " AND B.Descript like '". $search . "%' AND YMFlag=0" : " AND YMFlag=0";
$searchCnd	.= ($_SESSION['IsCustomer']) ? " AND A.CustomerCd='" .$_SESSION['CustomerCd']. "'" : "";
	$searchCnd	.= ($_SESSION['UserName'] && $_SESSION['HasCustomer'] == 1) ? " AND B.UserName='" .$_SESSION['UserName']. "'" : "";
switch ($_SESSION['StatusFilter']) {
case 0:
	break;
case 2:
	$searchCnd	.= " AND A.StatusCd='A'";
	break;
default:		// 1
	$searchCnd	.= " AND A.StatusCd='U'";
	break;
}
$sql		= "SELECT A.*,IFNULL(B.Descript,A.CustomerCd) AS Customer,IFNULL(C.Descript,A.StatusCd) AS Status FROM so_target_trade A"
	. " LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd" 
	. " LEFT OUTER JOIN so_status_m C ON A.StatusCd=C.StatusCd WHERE B.SectorCd ='".$_SESSION['SectorCd']."'" 
	.$searchCnd. " ORDER BY A.Year DESC, B.StateCd, B.CustomerCtgCd, B.Descript";
$returnData = $this->execSelectQuery($sql);
return $returnData;
}


public function getTradeTargetYearB2bCustomerItem($CustomerCd, $excludeDefCustomer, $Year, $StatusCd) {
	$AlterCustomer	= (($excludeDefCustomer) ? "" : self::DEFCUSTOMERCD);
	$inputArr 		= array($CustomerCd, $AlterCustomer, $Year, $StatusCd);
	$paraString		= vsprintf("'%s','%s', '%s', '%s'", $inputArr);
	$sql			= "call sp_getTargetYearB2bCustomerItemTrade(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getTradeTargetYearHeader($CustomerCd, $Year) {
	$sql		= "SELECT * FROM so_target_trade WHERE CustomerCd='".$CustomerCd."' AND YMFlag=0 AND Year='".$Year."'";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function isExistTradeTargetYear($CustomerCd, $Year) {
	$sql			= "SELECT * FROM so_target_trade WHERE CustomerCd='".$CustomerCd."' AND YMFlag=0 AND Year='".$Year."'";

	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function insertTradeTargetYear($data) {
	$stmt		= "INSERT INTO so_target_trade (CustomerCd, Year, YMFlag, Month, Date, StatusCd, Remark, TransUserName, TransDateTime)"
					. " VALUES ('%s', '%s', %s, %s, '%s', '%s', '%s', '%s', '%s');";
	$inputArr	= array($data['CustomerCd'], $data['Year'], 0, 0, $this->convertDate($data['Date'],TRUE)
			, $data['StatusCd'], $data['Remark'], $_SESSION['UserName'], date('Y-m-d H:i:s'));
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function updateTradeTargetYear($data) {
	$stmt		= "UPDATE so_target_trade SET StatusCd='%s', Remark='%s', TransUserName='%s', TransDateTime='%s'"
					. " WHERE CustomerCd='%s' AND Year='%s' AND YMFlag=0 AND Month=0";
	$inputArr	= array($data['StatusCd'], $data['Remark'], $_SESSION['UserName'], date('Y-m-d H:i:s'), $data['oldCustomerCd'], $data['oldYear']);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function insertTradeTargetYearItemB2b($data) {
	$maxMonths	= ($data['IsB2b']=='1' ? 12 : 0);
	$queryInsert	= "INSERT INTO so_target_item_trade (CustomerCd, Year, YMFlag, Month, ItemCd, Quantity)"
							. " VALUES ('%s', '%s', %s, %s, '%s', %s);";
	$returnData		= '';
	for ($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		if (!isset($data['ItemCd1_'.$curRowNo]) || trim($data['ItemCd1_'.$curRowNo])=='') {
			continue;
		}
		$ItemCd = $data['ItemCd1_'.$curRowNo];
		for ($curMonth=0; $curMonth<=12; $curMonth++) {
			$colSuffix = (($curMonth<10) ? '0'.$curMonth : $curMonth);
			$mnthQty	= (float)$data['Qty'.$colSuffix.'1_'.$curRowNo];
			$mnthQty	= (is_numeric($mnthQty) && $mnthQty>=0 ? $mnthQty : 0);
			if ($mnthQty==0) {
				continue;
			}
			$inputArr	= array();
			$inputArr	= array($data['CustomerCd'], $data['Year'], 0, $curMonth, $ItemCd, $mnthQty);
			$sql		= vsprintf($queryInsert,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		}
	}
return $returnData;
}

public function updateTradeTargetYearItemB2b($data) {
	$queryDelete	= "DELETE FROM so_target_item WHERE CustomerCd='%s' AND Year='%s' AND YMFlag=0";
	$inputArr		= array($data['oldCustomerCd'], $data['oldYear']);
	$sql			= vsprintf($queryDelete,$inputArr);
	$returnData		= $this->execUpdateQuery($sql);
	if ($returnData) return $returnData;
	
	return $this->insertTradeTargetYearItemB2b($data);
}

public function approveTradeTargetYear($condTarget, $isApproved) {
	$stmt		= "UPDATE so_target_trade SET StatusCd='%s', ApprovedByUserName='%s', ApprovalDateTime='%s' WHERE ".$condTarget;
	if ($isApproved)
		$inputArr 	= array('A', $_SESSION['UserName'], date('Y-m-d H:i:s'));
	else
		$inputArr 	= array('U', '', '');
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execUpdateQuery($sql);
	return $returnData;
}

//========Target Monthly Trade==========================


public function getTradeTargetMonthList($search, $TargetForMY) {
	$DTSAnsi		= preg_replace('/(\d{2})[-\/](\d{4})/', "$2-$1", $TargetForMY) . '-01';
	$Year			= $this->getTargetYear($DTSAnsi, $curMonth, $curLogMonth);
	$searchCnd	= " AND Year='" . $Year . "' AND Month=" . $curLogMonth;
	$searchCnd	.= (isset($search)) ? " AND B.Descript like '". $search . "%' AND YMFlag=1" : " AND YMFlag=1";
	$searchCnd	.= ($_SESSION['IsCustomer']) ? " AND A.CustomerCd='" .$_SESSION['CustomerCd']. "'" : "";
	$searchCnd	.= ($_SESSION['UserName'] && $_SESSION['HasCustomer'] == 1) ? " AND B.UserName='" .$_SESSION['UserName']. "'" : "";

	switch ($_SESSION['StatusFilter']) {
	case 0:
		break;
	case 2:
		$searchCnd	.= " AND A.StatusCd='A'";
		break;
	default:		// 1
		$searchCnd	.= " AND A.StatusCd='U'";
		break;
	}
	$sql		= "SELECT A.CustomerCd,A.Year, A.Month, DATE_FORMAT(CONCAT('2012-',(A.Month +2)%12 +1,'-01'),'%b') AS MonthName,IFNULL(B.Descript,A.CustomerCd) AS Customer,IFNULL(C.Descript,A.StatusCd) AS Status FROM so_target_trade A"
		. " LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd" 
		. " LEFT OUTER JOIN so_status_m C ON A.StatusCd=C.StatusCd" 
		. " LEFT OUTER JOIN so_state_m D ON B.StateCd=D.StateCd WHERE B.SectorCd ='".$_SESSION['SectorCd']."'" 
		.$searchCnd. " ORDER BY A.Year DESC, A.Month DESC, B.IsActive DESC, D.DispOrder, B.CustomerCtgCd, B.Descript";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}
public function checkAllSubDealerTradeTargetMonthList( $TargetForMY){
	$DTSAnsi		= preg_replace('/(\d{2})[-\/](\d{4})/', "$2-$1", $TargetForMY) . '-01';
	$Year			= $this->getTargetYear($DTSAnsi, $curMonth, $curLogMonth);
	$searchCnd		= "WHERE  Year='" . $Year . "' AND Month=".$curLogMonth;
	$CustomerCd		= ($_SESSION['IsCustomer']) ? "CustomerCd='" .$_SESSION['CustomerCd']. "'" : "1";
	
	$sql1 			= "SELECT count(IdSubdealer) AS TotalSubdealer  FROM so_subdealer_m_dealer WHERE  $CustomerCd ";
	$returnData1	= $this->execSelectQuery($sql1);
	//return $returnData1;
	//print_r($returnData1);
	$sql2= "SELECT count(SubdealerCd) AS TargetSubdealer FROM so_subdealer_target_trade $searchCnd AND $CustomerCd AND StatusCd != '0'";
	$returnData2		= $this->execSelectQuery($sql2);
	//$returnData2[0]['TargetSubdealer'] =50;
	//print_r($returnData2);
	//return $returnData1;
	
	if($returnData1[0]['TotalSubdealer'] != $returnData2[0]['TargetSubdealer']){
		return 0;
	} 
	else{
		return 1;	
	}
}

public function isExistTradeTargetMonth($CustomerCd, $Year, $Month) {
	$sql			= "SELECT * FROM so_target_trade WHERE CustomerCd='".$CustomerCd."' AND YMFlag=1 AND Year='".$Year."' AND Month=".(int)$Month;
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}


public function insertTradeTargetMonth($data) {
	$stmt	= "INSERT INTO so_target_trade (CustomerCd, Year, YMFlag, Month, Date, StatusCd, ComplaintNSuggestion, Remark, IsComplaintPending
			, ComplaintRemark, IsAnyMailReplyPending, MailReplyRemark, IsanysuggestionPending, SuggestionRemark, IsSatisfied, SatisfiedRemark
			, TransUserName, TransDateTime)"
			. " VALUES ('%s', '%s', %s, %s, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');";
	$inputArr	= array($data['CustomerCd'], $data['Year'], 1, (int)$data['Month'], $this->convertDate($data['Date'],TRUE)
		, $data['StatusCd'], $data['ComplaintNSuggestion'], $data['Remark'], $data['Complaint'], $data['ComplaintRemark']
		, $data['MailReply'], $data['MailReplyRemark'],  $data['Suggestion'], $data['SuggestionRemark'], $data['SatisfiedStatus']
		, $data['SatisfiedRemark'], $_SESSION['UserName'], date('Y-m-d H:i:s'));
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function insertTradeTargetMonthB2bItem($data) {
	$queryInsert	= "INSERT INTO so_target_item_trade (CustomerCd, Year, YMFlag, Month, ItemCd, Quantity, OwnUseQty, AdditionalQty, MonthlyAllocation, MonthStock)"
						. " VALUES ('%s', '%s', %s, %s, '%s','%s', %s, '%s', %s, %s);";
	$returnData		= '';
	for ($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		if (!isset($data['ItemCd1_'.$curRowNo]) || trim($data['ItemCd1_'.$curRowNo])=='') {
			continue;
		}
		$ItemCd		= $data['ItemCd1_'.$curRowNo];
		$mnthQty	= (float)$data['MonthCur1_'.$curRowNo];
		$mnthQty	= (is_numeric($mnthQty) && $mnthQty>=0 ? $mnthQty : 0);
		$ownUseQty	= (float)$data['MonthOwnUse1_'.$curRowNo];
		$ownUseQty	= (is_numeric($ownUseQty) && $ownUseQty>=0 ? $ownUseQty : 0);
		
		$AdditionalQty	= (float)$data['AdditionalQty1_'.$curRowNo];
		$AdditionalQty	= (is_numeric($AdditionalQty) && $AdditionalQty>=0 ? $AdditionalQty : 0);

		$MonthlyAllocation	= (float)$data['MonthlyAllocation1_'.$curRowNo];
		$MonthlyAllocation	= (is_numeric($MonthlyAllocation) && $MonthlyAllocation>=0 ? $MonthlyAllocation : 0);

		$mnthStock	= (float)$data['MonthStock1_'.$curRowNo];
		$mnthStock	= (is_numeric($mnthStock) && $mnthStock>=0 ? $mnthStock : 0);

		if ($mnthQty>0 || $ownUseQty>0 || $mnthStock>0) {
			$inputArr	= array();
			$inputArr	= array($data['CustomerCd'], $data['Year'], 1, (int)$data['Month'], $ItemCd, $mnthQty,$ownUseQty, $AdditionalQty,$MonthlyAllocation, $mnthStock);
			$sql		= vsprintf($queryInsert, $inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		}
	}
return $returnData;
}

public function getTradeTargetMonthHeader($CustomerCd, $Year, $Month) {
	$sql		= "SELECT * FROM so_target_trade WHERE CustomerCd='".$CustomerCd."' AND YMFlag=1 AND Year='".$Year."' AND Month=".(int)$Month;
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}	
		
public function getTradeTargetMonthB2bCustomerItem($CustomerCd, $excludeDefCustomer, $Year, $Month, $StatusCd) {
	$AlterCustomer	= (($excludeDefCustomer) ? "" : self::DEFCUSTOMERCD);
	$inputArr 		= array($CustomerCd, $AlterCustomer, $Year, (int)$Month, $StatusCd);
	$paraString		= vsprintf("'%s','%s','%s', %s, '%s'", $inputArr);
	$sql			= "call sp_getTargetMonthB2bCustomerItemTrade(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}

public function updateTradeTargetMonth($data) {
	$stmt	= "UPDATE so_target_trade SET StatusCd='%s', ComplaintNSuggestion='%s', Remark='%s', TransUserName='%s', TransDateTime='%s'"
		. " WHERE CustomerCd='%s' AND Year='%s' AND YMFlag=1 AND Month=%s";
	$inputArr	= array($data['StatusCd'], $data['ComplaintNSuggestion'], $data['Remark'], $_SESSION['UserName'], date('Y-m-d H:i:s'), $data['oldCustomerCd'], $data['oldYear'], $data['oldMonth']);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function updateTradeTargetMonthB2bItem($data) {
	$queryDelete	= "DELETE FROM so_target_item_trade WHERE CustomerCd='%s' AND Year='%s' AND Month=%s AND YMFlag=1";
	$inputArr		= array($data['oldCustomerCd'], $data['oldYear'], $data['oldMonth']);
	$sql			= vsprintf($queryDelete,$inputArr);
	$returnData		= $this->execUpdateQuery($sql);
	if ($returnData) return $returnData;
	
	return $this->insertTradeTargetMonthB2bItem($data);
}

public function approveTradeTargetMonth($condTarget, $isApproved) {
	$stmt		= "UPDATE so_target_trade SET StatusCd='%s', ApprovedByUserName='%s', ApprovalDateTime='%s' WHERE ".$condTarget;
	if ($isApproved)
		$inputArr 	= array('A', $_SESSION['UserName'], date('Y-m-d H:i:s'));
	else
		$inputArr 	= array('U', '', '');
	$sql		= vsprintf($stmt,$inputArr);
	$returnData = $this->execUpdateQuery($sql);
	return $returnData;
}

//=======End of Target Trade Monthly===========


////////////====================================  Company Target==================================//

public function getComapnyTargetMonthList($search, $TargetForMY) {
	$DTSAnsi		= preg_replace('/(\d{2})[-\/](\d{4})/', "$2-$1", $TargetForMY) . '-01';
	$Year			= $this->getTargetYear($DTSAnsi, $curMonth, $curLogMonth);
	$searchCnd		= "  Year='" . $Year . "' AND Month=" . $curLogMonth;
	
	$sql		= "SELECT A.*, B.* FROM so_company_target A JOIN so_dailydispatch_rep_item  B ON A.ProductId=B.ProductId WHERE ".$searchCnd." ";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function isExistCompanyTargetMonth($Year, $Month) {
	$sql			= "SELECT * FROM so_company_target WHERE  Year='".$Year."' AND Month=".(int)$Month;
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function insertCompanyTargetMonth($data) {
$queryInsert	= "INSERT INTO so_company_target(Year, Month, ProductId, TargetQty, TransUserName, TransDateTime)
	VALUES ('%s', '%s', %s, %s, '%s', '%s');";
	$returnData		= '';
	for ($curRowNo=1; $curRowNo<=$data['countproduct']; $curRowNo++) {
		$ProductCd	= $data['ProductCd_'.$curRowNo];
		$ProductQty	= $data['ProductQty_'.$curRowNo];
		$Year		= $data['Year'];
		$Month		= $data['Month'];
		$Date		= date('Y-m_d');
		$TransUserName= $_SESSION['UserName'];
		$TransDateTime= date('Y-m-d H:i:s');
		
		if ($ProductQty>0) {
			$inputArr	= array();
			$inputArr	= array($Year, $Month, (int)$ProductCd, $ProductQty, $TransUserName, $TransDateTime);
			$sql		= vsprintf($queryInsert, $inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			//if ($returnData) return $returnData;
		}
	}
	return $returnData;
}

public function updateCompanyTargetMonth($data) {
	$stmt	= "UPDATE so_company_target SET SP25MM='%s', SP40MM='%s', SolarPrm='%s', SolarGel='%s', AED='%s', DF='%s', Ecodet='%s', TransUserName='%s', TransDateTime='%s'"
		. " WHERE Year='%s' AND Month=%s";
	$inputArr	= array($data['SP25MM'],  $data['SP40MM'], $data['SolarPrm'], $data['SolarGel'], $data['AED'], $data['DF'], $data['Ecodet'], $_SESSION['UserName'], date('Y-m-d H:i:s'),  $data['oldYear'], $data['oldMonth']);
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

//////////////////////--------------------------------------------------
public function getComapnyPartyDispatchVanList($DispatchPlannigDate) {
	$searchCnd		= "A.DispatchPlanDate = '". $DispatchPlannigDate . "'";
	$sql			= "SELECT A.* FROM so_comparty_van_dispatch_plan A WHERE ".$searchCnd." ";
	$returnData 	= $this->execSelectQuery($sql);
	return $returnData;
}

public function isExistCompanyPartyDispatchVan($VanDispatchDate) {
	$sql			= "SELECT * FROM so_comparty_van_dispatch_plan WHERE  DispatchPlanDate	='".$this->convertDate($VanDispatchDate, TRUE, 3)."'";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function insertCompanyPartyDispatchVan($data) {
$queryInsert	= "INSERT INTO so_comparty_van_dispatch_plan(DispatchPlanDate, TotalCompanyVanProg, CompanyVan, PartyVan, TransUserName, TransDateTime)
	VALUES ('%s', '%s','%s', '%s', '%s', '%s');";
	$returnData		= '';
	$inputArr	= array();
	$inputArr	= array($this->convertDate($data['VanDispatchDate'], TRUE, 3), $data['TotalCompanyVan'], $data['CompanyVan'], (int)$data['PartyVan'], $_SESSION['UserName'], date('Y-m-d H:i:s'));
	$sql		= vsprintf($queryInsert, $inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
	//return $sql;
}

public function updateCompanyPartyDispatchVan($data) {
	$stmt	= "UPDATE so_comparty_van_dispatch_plan SET TotalCompanyVanProg='%s', CompanyVan='%s', PartyVan='%s', UpdateUserName='%s', UpdateDateTime='%s'"
		. " WHERE DispatchPlanDate='%s'";
	$inputArr	= array($data['TotalCompanyVan'],  $data['CompanyVan'], $data['PartyVan'], $_SESSION['UserName'], date('Y-m-d H:i:s'), $this->convertDate($data['VanDispatchDate'], TRUE, 3) );
	$sql		= vsprintf($stmt,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}



// Customer Suggestion -----------------------------------------------------------------------------------------------------------------------------
public function getCustomerSuggestList($search = null) {
	$searchCnd	= (isset($search)) ? " WHERE B.Descript like '". $search . "%'" : " WHERE 1=1";
	if ($_SESSION['IsCustomer']) {
		$searchCnd .= " AND A.CustomerCd='" . $_SESSION['CustomerCd'] . "'";
	}
	$sql		= "SELECT A.IdSuggestion,A.UserName,IFNULL(B.Descript,A.CustomerCd) AS Customer,A.CompanyCd,DATE_FORMAT(A.Date,'%d-%m-%Y %T') AS Date FROM so_customer_suggest A LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd" .$searchCnd. " ORDER BY A.IdSuggestion DESC";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function insertCustomerSuggest($data) {
	$DocFileName = $this->uploadCustomerSuggestDocFile($data['CustomerCd']);
	$sql	= " INSERT INTO so_customer_suggest (UserName, CustomerCd, CompanyCd, Date, Suggestion, DocFileName, Action, Status, TransUserName, TransdateTime)
		VALUES('%s', '%s', %s, '%s', '%s', '%s', '%s', '%s', '%s', '%s');";
	$inputArr	= array(trim($data['UserName']),trim($data['CustomerCd']),(int)($data['CompanyCd']), $this->convertDate($data['Date'],TRUE,3), addslashes(trim($data['Suggestion']))
			,trim($DocFileName), addslashes(trim($data['Action'])), trim($data['Status']), $_SESSION['UserName'], date('Y-m-d H:i:s'));
	$sql		= vsprintf($sql, $inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function updateCustomerSuggest($data) {
	$sql	= " UPDATE so_customer_suggest set CompanyCd=%s, Suggestion='%s', Action='%s', Status='%s', TransUserName='%s', TransDateTime='%s' WHERE IdSuggestion=%s";
	$inputArr	= array((int)($data['CompanyCd']), addslashes(trim($data['Suggestion'])), addslashes(trim($data['Action']))
		, trim($data['Status']), $_SESSION['UserName'], date('Y-m-d H:i:s'), $data['oldIdSuggestion']);
	$sql		= vsprintf($sql, $inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function getCustomerSuggestHeader($IdSuggestion) {
	$sql		= "SELECT * FROM so_customer_suggest WHERE IdSuggestion=%s";
	$inputArr 	= array($IdSuggestion);
	$sql		= vsprintf($sql, $inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function uploadCustomerSuggestDocFile($CustomerCd) {
// Store uiploaded file in ./upload/CustomerCd folder with Name as .Extension. Not in use.
	$returnFileName = "";
//		if ((($_FILES["PaymentRefImageFileName"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/pjpeg") || ($_FILES["file"]["type"] == "application/msword") || ($_FILES["file"]["type"] == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"))) {
	if (TRUE && isset($_FILES["DocFileNameInput"]["name"]) && $_FILES["DocFileNameInput"]["error"] == 0) {
		$extension = substr(strrchr($_FILES["DocFileNameInput"]["name"], '.'), 1);
		$fileNameDir = trim($CustomerCd);
		if(!is_dir('upload/'.$fileNameDir)){
			mkdir('upload/'.$fileNameDir);
			chmod('upload/'.$fileNameDir,0777);		// should be 0777 for forcing it to Octal
		}
		$returnFileName = "upload/".$fileNameDir.'/'.time().'.'.$extension;
		move_uploaded_file($_FILES["DocFileNameInput"]["tmp_name"], $returnFileName);
	}
	return $returnFileName;
}
//////////////////////////////////////\


public function getcustomerstate() {
	$sql		= "SELECT * FROM so_customer_m WHERE CustomerCd=%s";
	$inputArr 	= array($_SESSION['CustomerCd']);
	$sql		= vsprintf($sql, $inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}






// Complaint -----------------------------------------------------------------------------------------------------------------------------
public function getComplaintList($search = null) {
	$searchCnd	= (isset($search)) ? " WHERE B.Descript like '". $search . "%'" : " WHERE 1=1";
	if ($_SESSION['IsCustomer']) {
		$searchCnd .= " AND A.CustomerCd='" . $_SESSION['CustomerCd'] . "'";
	}
	$sql	= "SELECT A.*,CONCAT(UPPER(LEFT(A.Complaint,1)),LOWER(SUBSTRING(A.COmplaint,2,34)),' ...') AS ComplaintShort,DATE_FORMAT(A.DateTime,'%d-%m-%Y') AS Date,IFNULL(B.Descript,A.CustomerCd) AS Customer,IFNULL(C.Descript,A.StatusCd) AS Status"
		. " FROM so_complaint A LEFT OUTER JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd" 
		. " LEFT OUTER JOIN so_status_m C ON A.StatusCd=C.StatusCd" .$searchCnd. " ORDER BY A.IdComplaint DESC";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}

public function getComplaintHeader($IdComplaint) {
	$sql		= "SELECT * FROM so_complaint WHERE IdComplaint=%s";
	$inputArr 	= array($IdComplaint);
	$sql		= vsprintf($sql, $inputArr);
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function insertComplaint($data) {
	$sql	= " INSERT INTO so_complaint (CustomerCd, DateTime, ComplaintType, PIDetail, ItemCd, BatchInvNo, BatchInvDate, Complaint, Action, StatusCd, TransUserName, TransdateTime)
		VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s');";
	$inputArr	= array(trim($data['CustomerCd']), $this->convertDate($data['DateTime'],TRUE,3), $data['ComplaintType'], $data['PIDetail']
			, trim($data['ItemCd']), addslashes(trim($data['BatchInvNo'])), $this->convertDate($data['BatchInvDate'],TRUE), addslashes(trim($data['Complaint']))
			, addslashes(trim($data['Action'])), $data['StatusCd'], $_SESSION['UserName'], date('Y-m-d H:i:s'));
	$sql		= vsprintf($sql, $inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function updateComplaint($data) {
	$sql	= " UPDATE so_complaint set ComplaintType='%s', PIDetail='%s', ItemCd='%s', BatchInvNo='%s', BatchInvDate='%s', Complaint='%s', Action='%s', StatusCd='%s', TransUserName='%s', TransDateTime='%s' WHERE IdComplaint=%s";
	$inputArr	= array($data['ComplaintType'], $data['PIDetail']
			, trim($data['ItemCd']), addslashes(trim($data['BatchInvNo'])), $this->convertDate($data['BatchInvDate'],TRUE), addslashes(trim($data['Complaint']))
			, addslashes(trim($data['Action'])), $data['StatusCd'], $_SESSION['UserName'], date('Y-m-d H:i:s'), $data['oldIdComplaint']);
	$sql		= vsprintf($sql, $inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	return $returnData;
}

public function sendEMailComplaintStatusChange($IdComplaint, $NewStatus, $OldStatus) {
	$EMailTemplateNo = 0;
	if ($NewStatus=='O' && $OldStatus=='') $EMailTemplateNo = 7;
	if ($NewStatus=='I' && $OldStatus=='O') $EMailTemplateNo = 8;
	if ($NewStatus=='R' && $OldStatus=='I') $EMailTemplateNo = 9;
	if ($NewStatus=='T' && $OldStatus=='I') $EMailTemplateNo = 10;
	if ($EMailTemplateNo==0) return;
	
	$templateArr = $this->getEMailTemplate($EMailTemplateNo);
	$sql = "SELECT A.IdComplaint, DATE_FORMAT(A.DateTime,'%d-%m-%Y') AS Date, DATE_FORMAT(A.TransDateTime,'%d-%m-%Y') AS StatusDate, A.CustomerCd, B.Descript AS Customer, B.EMailId FROM so_complaint A INNER JOIN so_customer_m B"
		. " ON A.CustomerCd=B.CustomerCd WHERE A.IdComplaint = $IdComplaint";
	$eMailDetailArr = $this->execSelectQuery($sql);
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($eMailDetailArr[0]['IdComplaint'], $eMailDetailArr[0]['Date'], $eMailDetailArr[0]['Customer'], $eMailDetailArr[0]['CustomerCd'], $eMailDetailArr[0]['StatusDate']));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$objSolarMailer = new solarMailer();
	$EMailId = ($EMailTemplateNo == 7 ? $templateArr['EMailIdCC'] : $eMailDetailArr[0]['EMailId']);
	$objSolarMailer->sendSolarMail($EMailId, $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
}


public function CheckTragetMonthsendEMail() {
	$date = date('d-m-Y');
	$month = ['MYS'=>date('m-Y', strtotime('+1 month', strtotime($date)))];
	$DTSAnsi	= $this->MY2AnsiDate($month['MYS']);
	$CustomerList = $this->MissingTargetData($DTSAnsi, $Year, $displayYear, $MonthName) ;
	$templateArr = $this->getEMailTemplate(50);
	$eMailBody = $this->strPositSubstitute($templateArr['Body']);
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	//$EMailId = 'websupport@solargroup.com';
	foreach($CustomerList as $customerDetail){
	$EMailId = $CustomerList['EmailId'];
	$objSolarMailer = new solarMailer();
	$objSolarMailer->sendSolarMail($EMailId, $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	}
return  $objSolarMailer;
}



public function CheckSubdealerMissingTargetSMS($Month, $Year, $TelNo){
	$uname = 'SIILJPRO'; //'SIILJPRP';
	$password = 'S(ol)!ar';// 'E9W!f9Y~';
	$info ='1';
	$test = '0';
	$from = 'iSOLAR';
	$dest =  '9406547095';   //'9765933450'; // $TelNo;  //'8793653028' //'919649569999'; //'918600993992';
	//$dest =  $TelNo;   //'9765933450'; // $TelNo;  //'8793653028' //'919649569999'; //'918600993992';
	$messages = "Dear Sir, Please note that you have not updated your Monthly Target for the month of ".$Month."-".$Year.". For further assistance please contact us on our EMail Id: ss@solargroup.com Thank You. Customer Service Department ";
	$data ="uname=".$uname."&pass=".$password."&msg=".$messages."&send=".$from."&dest=".$dest;
	$ch = curl_init("http://api.unicel.in/SendSMS/sendmsg.php?");
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$result = curl_exec($ch);
	curl_close($ch);
//return $result;
}



public function SaleReport($CompanyCd, $SectorCd, $CustomerCd, $StateCd, $DTSDays, $DTE, $StatusCdStr, $OnlyApproved, & $RecCount) {
	$DTE = $this->convertDate($DTE, TRUE, 1);
	$DTSDays = $this->convertDate($DTSDays, TRUE, 1);
	$inputArr 		= array($CompanyCd, $SectorCd, $CustomerCd, $StateCd, $DTSDays, $DTE, $StatusCdStr, $OnlyApproved);
	$paraString		= vsprintf("%s, '%s', '%s', '%s', '%s','%s', '%s', %s", $inputArr) . ", @RecCount";
	$sql			= "call sp_repSaleReport (" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql, 2);
	$sql1			= "SELECT @RecCount AS RecCount";
	$RecCount		= $this->execSelectQuery($sql, 0);
	return $returnData;
	
}

//Payment Tracking Report===================================================

public function getCustomerApprovePOList($searchVal=null, $companyCd=null){
	$curDate =(isset($searchVal) && $searchVal!='') ? $searchVal : date('Y-m-d');
	$companyCd =(isset($companyCd) && $companyCd!='') ? $companyCd : '1100';
	$sql = "SELECT A.IdExpDet,A.DateTime,A.CustomerCd,A.StatusCd, IFNULL(B.Descript,A.CustomerCd) AS Customer, B.City, A.CompanyCd
	,IF(A.DespatchMode='F','CompanyVan','X-Factory') AS DespatchModeDisp, IFNULL(D.ShortDesc,A.CompanyCd) AS Company, A.VehicleNo,A.TotAmt
	, CONCAT(TRIM(A.TokenNoPrefix),'/',A.TokenNo%100) AS TokenNoFull FROM so_expdet A JOIN so_customer_m B
	ON A.CustomerCd= B.CustomerCd JOIN so_company_m D on A.CompanyCd = D.CompanyCd  WHERE A.CompanyCd='$companyCd' AND  A.StatusCd = 'A' AND PaymentDate='$curDate'  Order By A.CustomerCd  DESC ";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getCustomerPendingPOList($searchVal=null, $companyCd=null){
	$curDate =(isset($searchVal) && $searchVal!='') ? $searchVal : date('Y-m-d');
	$companyCd =(isset($companyCd) && $companyCd!='') ? $companyCd : '1100';
	$sql = "SELECT A.IdExpDet,A.DateTime,A.CustomerCd,A.StatusCd, IFNULL(B.Descript,A.CustomerCd) AS Customer,B.City, A.CompanyCd
	,IF(A.DespatchMode='F','CompanyVan','X-Factory') AS DespatchModeDisp, IFNULL(D.ShortDesc,A.CompanyCd) AS Company, A.VehicleNo,A.TotAmt
	, CONCAT(TRIM(A.TokenNoPrefix),'/',A.TokenNo%100) AS TokenNoFull FROM so_expdet A JOIN so_customer_m B
	ON A.CustomerCd= B.CustomerCd JOIN so_company_m D on A.CompanyCd = D.CompanyCd WHERE A.CompanyCd='$companyCd' AND  A.StatusCd IN ('P','W')  AND PaymentDate='$curDate' Order By A.CustomerCd  DESC ";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}
public function getCustomerAccessoryList($searchVal=null, $companyCd=null,$Status){
	if($Status == 'A'){
		$statuscnd = " AND A.StatusCd ='A' ";
	}
	if($Status == 'P'){
		$statuscnd = " AND A.StatusCd IN ('P','W') ";
	}
	$curDate =(isset($searchVal) && $searchVal!='') ? $searchVal : date('Y-m-d');
	$companyCd =(isset($companyCd) && $companyCd!='') ? $companyCd : '1100';
	 $sql = "SELECT A.IdAccessory,A.CustomerCd,IFNULL(C.Descript,A.CustomerCd) AS Customer,C.City ,A.Date,IF(A.DespatchMode='F','CompanyVan','X-Factory') AS DespatchModeDisp,IFNULL(D.ShortDesc,B.CompanyCd) AS Company,A.VehicleNo,A.TotAmt,CONCAT(TRIM(A.TokenNoPrefix),'/',A.TokenNo%100) AS TokenNoFull FROM so_accessory A  INNER JOIN  so_accessory_ctg_m B ON A.AccessoryCtgCd = B.AccessoryCtgCd JOIN so_customer_m C
	ON A.CustomerCd= C.CustomerCd JOIN so_company_m D on B.CompanyCd = D.CompanyCd WHERE B.CompanyCd =  $companyCd   $statuscnd  AND A.PaymentDate='".$curDate."' Order By A.CustomerCd  DESC";
	//echo $sql;
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

//========================================End of Payment Tracking Report=========================================
	
public function reportExpDetOrderStatus($CompanyCd, $SectorCd, $CustomerCd, $DTSDays, $DTE, $StatusCdStr, $OnlyApproved, & $RecCount) {
	$DTE = $this->convertDate($DTE, TRUE, 1);
	$inputArr 		= array($CompanyCd, $SectorCd, $CustomerCd, $DTSDays, $DTE, $StatusCdStr, $OnlyApproved);
	$paraString		= vsprintf("%s, '%s', '%s', %s, '%s', '%s', %s", $inputArr) . ", @RecCount";
	$sql			= "call sp_repExpDetOrderStatus(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql, 2);
	$sql1			= "SELECT @RecCount AS RecCount";
	$RecCount		= $this->execSelectQuery($sql, 0);
	return $returnData;
	
}

public function getDispatchStock($CompnayCd, $SectorCd = ''){
		$DBTable = '';
			$SectorCd == $_SESSION['SectorCd'];
		if($SectorCd == 'T'){
			$DBTable = 'b2b_solar_sc.so_item_m';
		}else{
			$DBTable = 'cib2b_solar_sc.so_item_m';
		}
		$curdate = date('Y-m-d');
		//$curdate = '2016-05-10';

		 $sql = "SELECT B.ItemCd, IFNULL(E.Descript,C.Descript) AS Descript, IFNULL(E.GroupDesc,C.ShortDescript) AS ShortName, IFNULL(E.UOM,C.UOM) AS UOM, B.Dispatch, D.Descript AS Sector FROM scm_solar_sc.scm_stock_sales AS A LEFT OUTER JOIN  scm_solar_sc.scm_stock_sales_item AS B ON A.StockSalesID = B.StockSalesID LEFT OUTER JOIN scm_solar_sc.scm_item_m AS C ON B.ItemCd = C.ItemCd LEFT OUTER JOIN scm_solar_sc.scm_sector_m AS D ON A.SectorCd = D.SectorCd LEFT OUTER JOIN ".$DBTable." AS E ON B.ItemCd = E.ItemCd WHERE A.CompanyCd =".$CompnayCd." AND A.DateAdded = '".$curdate."' Group By B.ItemCd ORDER BY `B`.`Dispatch` ASC ";
	
		$returnData = $this->execSelectQuery($sql);
		$arrStock = array();
		foreach($returnData AS $index => $value){
			$ShortName = $returnData[$index]['ShortName'];
			$Dispatch = $returnData[$index]['Dispatch'];
			$UOM = $returnData[$index]['UOM'];
			$arrStock['ShortName'][] = $ShortName;
			$arrStock['Dispatch'][$ShortName] = $Dispatch;
			$arrStock['UOM'][$ShortName] = $UOM;
		}
		
		return $arrStock;		
	}

public function reportAccessoryStatus($CompanyCd, $SectorCd, $CustomerCd, $DTSDays, $DTE, $StatusCdStr, $OnlyApproved, &$RecCount) {
	$DTE = $this->convertDate($DTE, TRUE, 1);
	$inputArr 		= array($CompanyCd, $SectorCd, $CustomerCd, $DTSDays, $DTE, $StatusCdStr, $OnlyApproved);
	$paraString		= vsprintf("%s, '%s', '%s', %s, '%s', '%s', %s", $inputArr) . ", @RecCount";
	$sql			= "call sp_repAccessoryStatus(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql, 2);
	$sql			= "SELECT @RecCount AS RecCount";
	$RecCount		= $this->execSelectQuery($sql, 0);
	return $returnData;
}

public function reportStdVsActualVanTrip($SectorCd, $MagazineCd, $Transporter, $VehicleNo, $DTS, $DTE) {
	$DTS = $this->convertDate($DTS, TRUE, 1);
	$DTE = $this->convertDate($DTE, TRUE, 1);
	$inputArr 		= array($SectorCd, $MagazineCd, $Transporter, $VehicleNo, $DTS, $DTE);
	$paraString		= vsprintf("'%s', '%s', '%s', '%s', '%s', '%s'", $inputArr);
	$sql			= "call sp_repStdVsActualVanTrip(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql, 2);
	return $returnData;
}

public function reportStdVsActualDespatch($SectorCd, $CustomerCd, $MagazineCd, $DTS, $DTE) {
	$DTS = $this->convertDate($DTS, TRUE, 1);
	$DTE = $this->convertDate($DTE, TRUE, 1);
	$inputArr 		= array($SectorCd, $CustomerCd, $MagazineCd, $DTS, $DTE);
	$paraString		= vsprintf("'%s', '%s', '%s', '%s', '%s'", $inputArr);
	$sql			= "call sp_repStdVsActualDespatch(" . $paraString. ")";
	$returnData 	= $this->execSelectQuery($sql, 2);
	return $returnData;
}

public function emailDStockAdvIntimate() {
	$templateArr = $this->getEMailTemplate(36);
	$sql = "SELECT A.CustomerCd, A.EMailId FROM so_customer_m A WHERE A.HasDailyStock=1";
	$eMailDetailArr = $this->execSelectQuery($sql);
	foreach ($eMailDetailArr as $eMailDetailRow) {
		$eMailBody = $templateArr['Body'];
		$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
		$objSolarMailer = new solarMailer();
		$objSolarMailer->sendSolarMail($eMailDetailRow['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	}
}

public function emailDStockReminder() {
	$Yesterday	= $this->addDate(NULL, '-1 day', FALSE);
	$templateArr = $this->getEMailTemplate(37);
	$sql = "SELECT A.CustomerCd, A.EMailId FROM so_customer_m A WHERE A.HasDailyStock=1 
				AND NOT EXISTS(SELECT * FROM so_daily_stock B WHERE A.CustomerCd=B.CustomerCd AND B.Date='" . $Yesterday . "')";
	$eMailDetailArr = $this->execSelectQuery($sql);
	foreach ($eMailDetailArr as $eMailDetailRow) {
		$eMailBody = $templateArr['Body'];
		$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
		$objSolarMailer = new solarMailer();
		$objSolarMailer->sendSolarMail($eMailDetailRow['EMailId'], $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC']);
	}
}

// scm Report
public function reportCustomerVanStatus($CustomerCd) {
	$inputArr 		= array($CustomerCd);
	$paraString		= vsprintf("'%s'", $inputArr);
	$sql			= "call scm_solar_sc.sp_reportCustomerVanStatus(" . $paraString. ")";
	$preResults		= '';
	$returnData 	= $this->execSelectQuery($sql, 2, $preResults);
	return $preResults;
}

public function reportVanTurnaround($DTS, $DTE, $CustomerCd, $VehicleNo) {
	$reportTitle = "Van Turn-Around Time for $DTS - $DTE" ;
	$DTS = $this->convertDate($DTS, TRUE, 1);
	$DTE = $this->convertDate($DTE, TRUE, 1);
	$inputArr 		= array($DTS, $DTE, $CustomerCd, $VehicleNo);
	$paraString		= vsprintf("'%s', '%s', '%s', '%s'", $inputArr);
	$sql			= "call scm_solar_sc.sp_reportVanTurnaround(" . $paraString. ")";
//	$arrCustomerMDisp = $this->getCustomerMDisp(0, $CustomerCd);
	$reportData	= $this->execSelectQuery($sql, 2);
	If (count($reportData)==0) {
		echo '<script>alert("No data to print for the specified Date Range")</script>';
		return;
	}

	$reportTitle = $reportTitle;
	$classBusiLogic = $this;
	$actionBM = 0 + 0;
	$url = "DTS=".$DTS."&DTE=".$DTE."&CustomerCd=".$CustomerCd."&VehicleNo=".$VehicleNo;
	include_once("includes/inc.view.report.php");
	return;
}

public function getVehicleMDispComp($SectorCd) {
	$sql		= "SELECT VehicleNo,VehicleNo AS Descript FROM " . ($SectorCd=='T' ? self::DBNameTrade : self::DBNameNonTrade) . ".so_vehicle_m"
				. " WHERE CustomerCd=". self::DEFCOMPANYCD . " OR IsDummyCompanyVan ORDER BY VehicleNo";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;	
}

function utilSetFORCompVan($SectorCd, $CompanyCd, $IsAssignVan) {
	$inputArr 		= array($SectorCd, $CompanyCd, $IsAssignVan);
	$paraString		= vsprintf("'%s', %s, %s", $inputArr);
	$sql			= "call sp_utilSetFORCompanyVan(" . $paraString. ")";
	$preResults		= '';
	$returnData 	= $this->execSelectQuery($sql, 2, $preResults);
	return $preResults;
	//return $paraString;
}

public function utilSetFORCompVanSave($data) {
	$IsAssignVan	= $data['IsAssignVan']=='1';
	for ($CurSubNo=1; $CurSubNo<=$data['LastSubNo']; $CurSubNo++) {
		$Priority	= $data['Priority'.$CurSubNo.'_0'];
		//$VanNo		= $data['Van_No_'.$CurSubNo.'_0'];
		for ($CurRowNo=1; $CurRowNo<=$data['LastRowNo'.$CurSubNo]; $CurRowNo++) {
			$PONo	= $data['PO_No_'.$CurSubNo.'_'.$CurRowNo];
			$VanNo	= $data['Vehicle'.$CurSubNo.'_'.$CurRowNo];
			if ($IsAssignVan) {
				$inputArr = array($VanNo, (int)$PONo);
				$stmt	= "UPDATE " . ($data['SectorCd']=='T' ? self::DBNameTrade : self::DBNameNonTrade) . ".so_expdet SET VehicleNo='%s' WHERE IdExpDet=%s";
			} else {
				$inputArr = array((int)$Priority, (int)$PONo);
				$stmt	= "UPDATE " . ($data['SectorCd']=='T' ? self::DBNameTrade : self::DBNameNonTrade) . ".so_expdet SET FORVanPriority=%s WHERE IdExpDet=%s";
			}
			$sql	= vsprintf($stmt, $inputArr);
			$failMsg= $this->execUpdateQuery($sql);
		}
	}
	return $failMsg;
}		// class solarCustomer\


public function AEDCompVanPalnSave($data) {
	$IsAssignVan	= $data['IsAssignVan']=='1';
	for ($CurSubNo=1; $CurSubNo<$data['LastRowNo']; $CurSubNo++) {
			$PONo	= $data['IdExpdet_'.$CurSubNo];
			$VanNo	= $data['VehicleNo_'.$CurSubNo];
			if ($IsAssignVan) {
				$inputArr = array($VanNo, (int)$PONo);
				$stmt	= "UPDATE " . ($data['SectorCd']=='T' ? self::DBNameTrade : self::DBNameNonTrade) . ".so_expdet SET VehicleNo='%s' WHERE IdExpDet=%s";
			}
			$sql	= vsprintf($stmt, $inputArr);
			$failMsg= $this->execUpdateQuery($sql);
	}
	return $failMsg;
}

/**************************************** Customer Indent alert **************/
	
	public function CustomerIndentAlertList(){
	$sql = "SELECT IFNULL(C.Descript,A.StateCd) AS StateCd,A.Unique_id,A.CustomerIndentFromCategory,A.CustomerIndentToCategory,A.CustomerIndentFrom ,A.CustomerIndentTo,A.IndentDate,A.RE11No,A.BrandId,A.BrandName,A.Quantity,A.InfoLevel FROM so_customer_indent_alert A INNER JOIN so_state_m C ON A.StateCd = C.StateCd GROUP BY A.Unique_id";
	return $returnData 	= $this->execSelectQuery($sql);
	}
	
	public function getAllItemMDisp() {
// Always send UOM
	$sql		= "SELECT ItemCd,Descript FROM so_item_m  UNION All SELECT ItemCd, CONCAT(Descript, ' - ' ,BrandId) AS Descript FROM other_company_item_m ORDER BY Descript";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;	
}
	

	
	
	public function insertCustomerIndentAlertQuery(){
		$sql = "INSERT INTO so_customer_indent_alert(Unique_id,StateCd,CustomerIndentFromCategory,CustomerIndentFrom, 	CustomerIndentToCategory,CustomerIndentTo,IndentDate,RE11No,BrandId,BrandName,ProductCtg,Quantity,InfoLevel,TransUserName,TransDateTime) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')";
		return $sql;
	}

	public function insertCustomerIndentAlert($data){
		
		$sql1 			= "SELECT MAX(Unique_id) as UniqueId FROM so_customer_indent_alert";
		$returnData 	= $this->execSelectQuery($sql1);
		$UniqueId  		=	$returnData[0]['UniqueId']+1;
		$sql				='';
		$returnData			= '';
		$queryInsert		= $this->insertCustomerIndentAlertQuery();
		$returnData			= '';
		//$UniqueId 			= 0; 
		$StateCd       = $data['StateCdInput'];
		$CustomerIndentFromCategory = $data['CustomerIndentFromCategory'];
		$CustomerIndentFrom = $data['CustomerIndentFrom'];
		$CustomerIndentToCategory = $data['CustomerIndentToCategory'];
		$CustomerIndentTo	= $data['CustomerIndentTo'];
		$RE11No				= $data['RE11No'];
		$TransUserName		= $_SESSION['UserName'];
		$TransDateTime      = date('Y-m-d H:i:s');
		for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
			
			$Date    	= $this->convertDate($data['Date_'.$curRowNo],TRUE,1);
			$BrandId	= $data['BrandId_'.$curRowNo];
			$BrandName 	= $data['BrandName_'.$curRowNo];
			$ProductCtg = $data['ProductCtg_'.$curRowNo];
			$Quantity 	= $data['Quantity_'.$curRowNo];
			$Infolevel 	= $data['Infolevel_'.$curRowNo];
			if($Quantity<=0){
				continue;
			}
			$inputArr	= array();
			$inputArr	= array($UniqueId,$StateCd,$CustomerIndentFromCategory,$CustomerIndentFrom,$CustomerIndentToCategory,$CustomerIndentTo,$Date,$RE11No,$BrandId,$BrandName,$ProductCtg,$Quantity,$Infolevel,$TransUserName,$TransDateTime );
			$sql		= vsprintf($queryInsert,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		}
		return $returnData;
	}
	
	public function getCustomerIndentAlertHeader($UniqueId){
		$sql = "SELECT A.*,IFNULL(C.Descript,A.StateCd) AS CustomerTypeDescript  FROM so_customer_indent_alert A INNER JOIN so_state_m C ON A.StateCd = C.StateCd  where Unique_id = $UniqueId";
		$returnData 	= $this->execSelectQuery($sql);
		return $returnData;
	}
	
		public function updateCustomerIndentRE12Query(){
		$sql = "UPDATE so_customer_indent_RE12 SET Quantity = '%s',Status ='%s',BrandID ='%s',BrandName = '%S' WHERE CustomerIndentId='%s' AND RE12 = '%s' AND Id='%s'";
		return $sql;
	}
	
	public function deleteCustomerIndentRE12Query(){
		$sql = "DELETE FROM so_customer_indent_RE12 WHERE CustomerIndentId='%s' AND RE12 = '%s' AND Id='%s'";
		return $sql;
	}
	public function insertCustomerIndentRE12Query(){
		$sql = "INSERT INTO so_customer_indent_RE12 (CustomerIndentId,RE11,RE12,BrandID,BrandName,Date,Quantity,Status,TransUserName,TransDateTime) VALUES('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')";
		return $sql;
	}
	
	public function insertCustomerIndentRE12($data){
		$sql				='';
		$returnData			= '';
		$queryInsert		= $this->insertCustomerIndentRE12Query();
		$queryUpdate		= $this->updateCustomerIndentRE12Query();
		$queryDelete		= $this->deleteCustomerIndentRE12Query();
		$returnData			= '';
		$UniqueId 			= $data['UniqueId'];
		$RE11No				= $data['RE11No'];;
		$TransUserName		= $_SESSION['UserName'];
		$TransDateTime      = date('Y-m-d H:i:s');             
		for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
			$RE12No		= $data['RE12No_'.$curRowNo];
			$Date   	= $this->convertDate($data['Date_'.$curRowNo],TRUE,1);
			$BrandId 	= $data['BrandId_'.$curRowNo];
			$BrandName	= $data['BrandName_'.$curRowNo]; 
			$Quantity 	= $data['Quantity_'.$curRowNo];
			$Status  	= $data['Status_'.$curRowNo];
			$RE12Id     = isset($data['RE12Id_'.$curRowNo])?$data['RE12Id_'.$curRowNo]:'';
			if ($Quantity<=0) {
				$inputArr	= array();
				$inputArr	= array($UniqueId,$RE12No,$RE12Id);
				echo $sql		= vsprintf($queryDelete,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
				if ($returnData) return $returnData;
			}else{	
				$queryCheck = "SELECT count(*) as Total FROM so_customer_indent_RE12 WHERE CustomerIndentId='%s' AND RE12 = '%s' AND Id='%s'";
				$inputArr	= array();
				$inputArr	= array($UniqueId,$RE12No,$RE12Id);
				$sql		= vsprintf($queryCheck,$inputArr);
				$returnData	= $this->execSelectQuery($sql);
				if ($returnData[0]['Total']==0) {
					$inputArr	= array();
					$inputArr	= array($UniqueId,$RE11No,$RE12No,$BrandId,$BrandName,$Date,$Quantity,$Status,$TransUserName,$TransDateTime );
					$sql		= vsprintf($queryInsert,$inputArr);
					$returnData	= $this->execUpdateQuery($sql);
					if ($returnData) return $returnData;
				}else{ 
					$inputArr	= array();
					$inputArr	= array($Quantity,$Status,$BrandId,$BrandName,$UniqueId,$RE12No,$RE12Id);
					$sql	= vsprintf($queryUpdate,$inputArr);
					$returnData	= $this->execUpdateQuery($sql);
					if ($returnData) return $returnData;
				}
			}
		}
		return $returnData;
	}
	

	
	public function getCustomerIndentRE12($UniqueId,$RE11){
		$sql = "SELECT * FROM  so_customer_indent_re12 WHERE CustomerIndentId ='".$UniqueId."' AND RE11 ='".$RE11."'";
		$returnData 	= $this->execSelectQuery($sql);
		return $returnData;
	}

	public function insertCustomerIndentRE12Remark($data){
		$sql = "INSERT INTO so_customer_indent_Remark(CustomerIndentId,RE11No,FinalStatus,Remark,Remainder) VALUES ('".$data['UniqueId']."','".$data['RE11No']."','".$data['remark']."','".$data['finalstatus']."','".$data['remainder']."')";
		$returnData	= $this->execUpdateQuery($sql);
		return $returnData;
	}
	
public function deleteCustomerIndentAlertQuery(){
		$sql = "DELETE FROM so_customer_indent_alert WHERE Unique_id='%s' AND RE11No = '%s' AND BrandId='%s'";
		return $sql;
	}	
public function updateCustomerIndentAlertQuery(){
		$sql = "UPDATE so_customer_indent_alert SET Quantity = '%s',InfoLevel ='%s',ProductCtg ='%s' WHERE Unique_id='%s' AND RE11No = '%s' AND BrandId='%s'";
		return $sql;
	}

	
public function updateCustomerIndentAlert($data){
	
		$sql				= '';
		$returnData			= '';
		$queryInsert			= $this->insertCustomerIndentAlertQuery();
		$queryDelete			= $this->deleteCustomerIndentAlertQuery();
		$queryUpdate			= $this->updateCustomerIndentAlertQuery();
		$UniqueId  			= $data['UniqueId'];
		$StateCd       		= $data['StateCdInput'];
		$CustomerIndentFromCategory 	= $data['CustomerIndentFromCategory'];
		$CustomerIndentFrom 		= $data['CustomerIndentFrom'];
		$CustomerIndentToCategory 	= $data['CustomerIndentToCategory'];
		$CustomerIndentTo		= $data['CustomerIndentTo'];
		$RE11No				= $data['RE11No'];
		$TransUserName			= $_SESSION['UserName'];
		$TransDateTime      		= date('Y-m-d H:i:s');
		for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
			$Date    		= $this->convertDate($data['Date_'.$curRowNo],TRUE,1);
			$BrandId		= $data['BrandId_'.$curRowNo];
			$BrandName 		= $data['BrandName_'.$curRowNo];
			$ProductCtg 		= $data['ProductCtg_'.$curRowNo];
			$Quantity 		= $data['Quantity_'.$curRowNo];
			$Infolevel 		= $data['Infolevel_'.$curRowNo];

		if ($Quantity<=0) {
			$inputArr		= array();
			$inputArr		= array($UniqueId,$RE11No,$BrandId);
			$sql			= vsprintf($queryDelete,$inputArr);
			$returnData		= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		} else{
			$queryCheck		= "SELECT COUNT(*) AS Count FROM so_customer_indent_alert WHERE Unique_id='%s' AND RE11No='%s' AND BrandId = '%s'";
			$inputArr		= array();
			$inputArr		= array($UniqueId,$RE11No,$BrandId);
			$sql			= vsprintf($queryCheck,$inputArr);
			$returnData		= $this->execSelectQuery($sql);
			if ($returnData[0]['Count']==0) {
				$inputArr	= array();
				$inputArr	= array($UniqueId,$StateCd,$CustomerIndentFromCategory,$CustomerIndentFrom,$CustomerIndentToCategory,$CustomerIndentTo,$Date,$RE11No,$BrandId,$BrandName,$ProductCtg,$Quantity,$Infolevel,$TransUserName,$TransDateTime );
				echo $sql		= vsprintf($queryInsert,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
				if ($returnData) return $returnData;
			}else{
				$inputArr	= array();
				$inputArr	= array($Quantity,$Infolevel,$ProductCtg ,$UniqueId,$RE11No,$BrandId);
				echo $sql	= vsprintf($queryUpdate,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
				if ($returnData) return $returnData;
			}
		}
		}
		return $returnData;
	}



public function getCompetitorDealerMDisp(){
	$sql ="select CustomerCd,Descript from other_compititor_dealer_m ORDER BY Descript ASC";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getOtherCompanyMDisp(){
	$sql ="select CompanyCd,Descript from other_company_m ORDER BY Descript ASC";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}
public function isRE11Exist($RE11){
	$sql			= "SELECT * FROM so_customer_indent_alert WHERE RE11No = '$RE11' ";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}

public function getCategoryFromDetail($CustomerIndentFrom,$CustomerIndentFromCategory){
	switch ($CustomerIndentFromCategory) {
		case 'dealer':
		$FromTableName		= 'so_customer_m ';
		$TransId			= 'CustomerCd as FromCd,Descript AS FromDescript,City as FromCity';
		$where 				= 'WHERE CustomerCd = '.$CustomerIndentFrom;
		break;
		
		case 'subdealer':
		$FromTableName		= 'so_subdealer_m A';
		$TransId			= 'IdSubdealer as FromCd,Descript AS FromDescript,City as FromCity';
		$where 				= 'WHERE A.IdSubdealer = '.$CustomerIndentFrom;
		break;
	}
		$sql ="SELECT  $TransId FROM $FromTableName  $where ";
		$returnData = $this->execSelectQuery($sql);
		return $returnData;
}
	
public function getCategoryToDetail($CustomerIndentTo,$CustomerIndentToCategory){
	switch ($CustomerIndentToCategory) {
		case 'OtherCompany':
		$ToTableName		= 'other_company_m ';
		$TransId			= 'CompanyCd as FromCd,Descript AS FromDescript, City as FromCity';
		$where 				= 'WHERE CompanyCd = '.$CustomerIndentTo;
		break;

		case 'OwnCompany':
		$ToTableName		= 'so_company_m ';
		$TransId			= 'CompanyCd as FromCd,Descript AS FromDescript,"Nagpur" as FromCity';
		$where 				= 'WHERE CompanyCd = '.$CustomerIndentTo;
		break;

		case 'Customer':
		$ToTableName		= 'so_customer_m ';
		$TransId			= 'CustomerCd as FromCd,Descript AS FromDescript,City as FromCity';
		$where 				= 'WHERE CustomerCd = '.$CustomerIndentTo;
		break;

		case 'Competitor':
		$ToTableName		= 'so_subdealer_m A';
		$TransId			= 'IdSubdealer as FromCd,Descript AS FromDescript,City as FromCity';
		$where 				= 'WHERE IdSubdealer = '.$CustomerIndentTo;
		break;
	}
	$sql ="SELECT  $TransId FROM $ToTableName  $where ";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

/**************************************** end Customer Indent alert **************/
//===========================Customer Alert for Make PO=========

public function CustomerPOCreateAlertMail(){
		$sql ="select * from so_customer_m Where IsActive = '1' and AlertforCreatePO='1' AND  AlertCreatePODays!='0'";
		//$sql ="select CustomerCd, Descript, EMailId, TelNo, AlertforCreatePO, AlertCreatePODays, AlertCreatePOUpdateDate  from so_customer_m Where IsActive = '1'";
		$returnData = $this->execSelectQuery($sql);
		$resultmailalert='';
		foreach($returnData as $customer){
			$sql1 = "SELECT A1.IdExpDet, A1.CustomerCd, A1.DateTime, A1.StatusCd,B1.SAPInvDate FROM so_expdet A1
					INNER JOIN so_expdet_magazine B1 ON A1.IdExpDet = B1.IdExpDet
					
			WHERE A1.IdExpDet=(SELECT MAX(IdExpDet)as IdExpDet FROM so_expdet  WHERE CustomerCd ='".$customer['CustomerCd']."') AND  
			A1.DateTime < NOW() - INTERVAL 7 DAY AND B1.SAPInvDate < NOW() - INTERVAL 7 DAY  AND CustomerCd Not IN (select CustomerCd from so_customer_lastpo_alertlog A where A.EmailDate > NOW() - INTERVAL 7 DAY)";
			
			$result = $this->execSelectQuery($sql1);
			if(!empty($result)){
				
				if($result[0]['StatusCd']== 'C' || $result[0]['StatusCd']== 'B' || $result[0]['StatusCd']== 'T'){
					$IdExpDet	=  $result[0]['IdExpDet'];
					$DateTime 	= $result[0]['DateTime'];
					$DateTime    	= $this->convertDate($DateTime ,False,1);
					$SAPInvDate = $result[0]['SAPInvDate'];
					$AlertDate 	= $customer['AlertCreatePOUpdateDate'];
					$days 		= $customer['AlertCreatePODays'];
					$date 		= strtotime("+".$days." days", strtotime($AlertDate));
					$AlertSendDate =  date("Y-m-d", $date);
					$currentdate = date('Y-m-d');
					
					if($AlertSendDate >= $currentdate){
						$CustomerCd	= $customer['CustomerCd'];
						$CustomerName = $customer['Descript'];
						$EMailId	= $customer['EMailId'];
						$TelNo	= $customer['TelNo'];
						
						$resultmailalert = $this->SendMailCustomerPOCreate($IdExpDet,  $CustomerCd, $EMailId, $CustomerName, $DateTime);
						$this->UpdateCustomerCreatePOAlertsenddate($CustomerCd, $AlertSendDate);
					}
				}
			} 
		}
		return $resultmailalert;
	}


public function SendMailCustomerPOCreate($IdExpDet,  $CustomerCd, $EMailId, $CustomerName, $DateTime) {
//	$EMailId = 'websupport@solargroup.com';
	$templateArr = $this->getEMailTemplate(5);
	$eMailBody = $this->strPositSubstitute($templateArr['Body'], array($DateTime, $IdExpDet ));
	$eMailBody = str_replace(array('\r','\n'),array("\r","\n"), $eMailBody);
	$objSolarMailer = new solarMailer();
	$objSolarMailer->IsHTML(true);  
	$objSolarMailer->sendSolarMail($EMailId, $templateArr['Subject'], $eMailBody, $templateArr['EMailIdCC'], NULL, True);
}


/*public function SendTestmail() {
	$EMailId = 'websupport@solargroup.com';
	$mailer = new Swift_Mailer(new Swift_MailTransport()); // Create new instance of SwiftMailer  
	$message = Swift_Message::newInstance()  
			->setSubject('Daily Dispatch Report Report of ') // Message subject  
			->setTo(array('websupport@solargroup.com' => 'Atul Gupta')) // Array of people to send to 
			->setFrom(array('b2b.solarexplosives@gmail.com' => 'Admin@B2B.SolarExplosives')) // From:  
			 ->setBody("Tsts ", 'text/html');// Attach that HTML message from earlier  
	$response = $mailer->send($message);
	return $response;
}
*/

//================SemiActive Reason=============


public function getSemiActiveReasonData($Id =''){
	$whr = ($Id!='')?" Id = {$Id}":"1";
	$sql = "SELECT Id,SemiActiveResonRemark FROM so_semi_active_reson WHERE {$whr}";
	$result  = $this->execSelectQuery($sql);
	return $result ;
}

public function editSemiActiveReason($data){
	$sql = "SELECT *  FROM so_semi_active_reson WHERE SemiActiveResonRemark like '{$data['SemiactiveReason']}'";
	$result  = $this->execSelectQuery($sql);
	if(count($result)>0){
		$msg = array("Status"=>"Error","Message"=>"Record already present");
		return $msg ;
	}else{
		if($data['Id'] ==''){		
			$sql = " INSERT INTO so_semi_active_reson (SemiActiveResonRemark) VALUES('{$data['SemiactiveReason']}') ";
			$returnData = $this->execUpdateQuery($sql);
			$msg =  array("Status"=>"Success","Message"=>"Record Add Successfully");
			return $msg ;
		}else{
			$stmt 		= "UPDATE so_semi_active_reson SET SemiActiveResonRemark = '%s' WHERE Id = '%s'";
			$inputArr 	= array($data['SemiactiveReason'],$data['Id']);
			 $sql     	= vsprintf($stmt,$inputArr);
			$failMsg	= $this->execUpdateQuery($sql);
			$rowAffected = $this->objDBQuery->objDBConnect->affected_rows;
			if($rowAffected >0){
				$msg = array("Status"=>"Success","Message"=>"Record update Successfully");
			}else{
				$msg = array("Status"=>"Error","Message"=>"Error in  updating Record");
			}
			return $msg;
		}
	}
}


public function deleteSemiActiveReason($Id){
	$sql = "DELETE FROM so_semi_active_reson WHERE Id ='".$Id."'";
	$failMsg = $this->execUpdateQuery($sql);
	$rowAffected = $this->objDBQuery->objDBConnect->affected_rows;
	if($rowAffected >0){
		$msg = array("Status"=>"Success","Message"=>"Record Delete Successfully");
	}else{
		$msg = array("Status"=>"Error","Message"=>"Error in  Deleting Record");
	}
	return $msg;
}

//==================End of Semiactive Reason ==============

public function SendTestmail() {
	$EMailId = 'websupport@solargroup.com';
	$EMailIdCC = 'b2b.solarexplosives@gmail.com';
	$EMailIdBCC = 'kamaldayani@gmail.com';
	$eMailBody = "Test";
	$objSolarMailer = new solarMailer();
	$objSolarMailer->IsHTML(true);  
	$response = $objSolarMailer->sendSolarMail($EMailId, "Test", $eMailBody, $EMailIdCC, $EMailIdBCC );
	return $response;
}



public function InserCustomerCreatePOAlertLog($CustomerCd, $IdExpDet, $EmailId, $eMailBody, $currentdate, $EmailStatus ) {
	$sql = "INSERT INTO so_customer_lastpo_alertlog (CustomerCd, IdExpDet,EmailId, MailBody, EmailDate, EmailStatus) VALUES('%s','%s','%s','%s','%s','%s')";
	$inputArr	= array($CustomerCd, $IdExpDet, $EmailId, $eMailBody, $currentdate, $EmailStatus);
	$sql		= vsprintf($sql,$inputArr);
	$failMsg	= $this->execUpdateQuery($sql);
	return $failMsg;
}

//============================================End of Customer Alert============


/******************************************************** market Report *************************************************/


public function getMarketReportList($CustomerCd,$SearchDate) {
	$whr = 1;
	if($CustomerCd != ''){
		$whr = "A.CustomerCd = '".$CustomerCd."'";
	}
	$date = $this->convertDate($SearchDate, TRUE, 1);
	$sql = "SELECT A.ReportId,A.MaterialType,A.Details,A.CustomerCd,IFNULL(B.Descript,A.CustomerCd) as CustomerName,DATE_FORMAT(A.Date,'%d-%m-%Y') as Date FROM  so_market_report A INNER JOIN so_customer_m B ON A.CustomerCd = B.CustomerCd WHERE $whr AND A.Date = '".$date."'";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function insertMarketReport($data){
	if (isset($data['materialType'])) $materialType = $data['materialType'];
	$count_entry 		= 0;
	$CustomerCd 		= $data['CustomerCd'];
	$date 				= date('Y-m-d');
	$TransUserName		= $_SESSION['UserName'];
	$TransDateTime		= date('Y-m-d H:i:s');
	foreach($materialType AS $materialType_index => $materialType_value){
			$flag = 0;
			
			for($i = 0; $i < sizeof($data[$materialType_value]['message']); $i++) {
				$message = $data[$materialType_value]['message'][$i];
				if(isset($message) && $message != '') {
					$count_entry++;
					$message 		= $data[$materialType_value]['message'][$i];
					
					echo $sql = "INSERT INTO so_market_report (MaterialType,Details,CustomerCd,Date,TransUserName, TransDateTime) VALUES('".$materialType_value."','".$message."','".$CustomerCd."','".$date."','".$TransUserName."','".$TransDateTime."')";			
					$failMsg  = $this->execUpdateQuery($sql);
				}
			}
		}
}


public function updateMarketReport($data){
	if (isset($data['materialType'])) $materialType = $data['materialType'];
	$count_entry 		= 0;
	$CustomerCd 		= $data['CustomerCd'];
	$ReportId			= $data['ReportId'];
	$date 				= $data['Date'];
	$TransUserName		= $_SESSION['UserName'];
	$TransDateTime		= date('Y-m-d H:i:s');
	foreach($materialType AS $materialType_index => $materialType_value){
			$flag = 0;
			
			for($i = 0; $i < sizeof($data[$materialType_value]['message']); $i++) {
				$message = $data[$materialType_value]['message'][$i];
				if(isset($message) && $message != '') {
					$count_entry++;
					$message 		= $data[$materialType_value]['message'][$i];
					
					$sql = " UPDATE so_market_report SET Details = '".$message."' 
					WHERE MaterialType = '".$materialType_value."' AND  CustomerCd = '".$CustomerCd."' AND Date = '".$date."' AND ReportId = '".$ReportId."'";			
					$failMsg  = $this->execUpdateQuery($sql);
				}
			}
		}
}

public function getMarketReportData($ReportId) {
	$sql = "SELECT * FROM  so_market_report WHERE ReportId = '".$ReportId."'";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}


public function getReportMarketReport($DTS, $DTE, $where_str){
		$DTS = $this->convertDate($DTS, TRUE, 1);
		$DTE = $this->convertDate($DTE, TRUE, 1);
	$sql = "SELECT A.*,IFNULL(B.Descript,A.CustomerCd) as CustomerName FROM so_market_report A INNER JOIN so_customer_m B ON A.CustomerCd = B.CustomerCd WHERE A.Date >= '".$DTS."' AND A.Date <= '".$DTE."' $where_str ";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

/************************************** End Market Report *************************************************/
public function getCustomerDetails($CustomerCd,$company){
	
	
	$sql1 		= "SELECT MAX(DATE) AS date FROM so_daily_stock_item where CustomerCd = '".$CustomerCd."'";
	$result 	= $this->execSelectQuery($sql1);
		if($result[0]['date']== NULL){
				$whrDate 	= 1;
				$whr =1;
		}
		else{
			$whrDate 	= "A.Date = '".$result[0]['date']."'";
			if($company == '1800'){
				$whr 	= " A.ItemCd IN('20000120','20000121','20005315')";
			}else{
				$whr 	= " A.ItemCd IN('20001340','20009157','20001341','20002672','20009999','20009996','20005568')";
			}				
		}
		
	$sql		= "SELECT SUM(OpStockQty) AS OpStockQty,SUM(A.ArrivalQty) AS ArrivalQty, SUM(A.PendingQty) AS PendingQty,B.City FROM so_daily_stock_item A INNER JOIN so_customer_m B ON A.CustomerCd = B.CustomerCd WHERE ".$whrDate." AND A.CustomerCd = '$CustomerCd'  AND  ".$whr."";
	$returnData = $this->execSelectQuery($sql);
	return $returnData; 
}

public function insertAEDAllocationQuery(){
	$sql 		= "INSERT INTO so_aed_allocation (AEDAllocationId,CompanyCd,VehicleNo,CustomerCd,City,TodayStock,Arrival,Pending,TotalStock,POPlanTotal,Rout,TransUserName,TransDateTime) VALUES('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')";
	return $sql;
}

public function insertAEDAllocation($data){
	$sql1 		= "SELECT MAX(AEDAllocationId) as UniqueId FROM so_aed_allocation";
	$returnData = $this->execSelectQuery($sql1);
	$UniqueId	= $returnData[0]['UniqueId']+1;
		
	$sql		= '';
	$returnData = '';
	$queryInsert = $this->insertAEDAllocationQuery();
	$CompanyCd  = $data['CompanyCd'];
	if($CompanyCd  == '1800'){
		$CompanyPOPlanTotal  = "SolarPOPlanTotal_";
	}else{
		$CompanyPOPlanTotal  = "EcoPOPlanTotal_";
	}
	$TransUserName	= $_SESSION['UserName'];
	$TransDateTime	= date('Y-m-d H:i:s');
	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++){
		$Vehicle	=	$data['Vehicle_'.$curRowNo];
		$CustomerCd =	$data['Customer_'.$curRowNo];
		$City		=	$data['City_'.$curRowNo];
		$TodayStock	=	$data['TodayStock_'.$curRowNo];
		$Arrival	=	$data['Arrival_'.$curRowNo];
		$Pending	=	$data['Pending_'.$curRowNo];
		$Total		=	$data['Total_'.$curRowNo];
		$POPlanTotal =  $data[$CompanyPOPlanTotal.$curRowNo];
		$Rout		=	$data['Rout_'.$curRowNo];
		if($CustomerCd <=0){
			continue;
		} 
		$inputArr	= array();
		$inputArr	= array($UniqueId,$CompanyCd,$Vehicle,$CustomerCd,$City,$TodayStock,$Arrival,$Pending,$Total,$POPlanTotal,$Rout,$TransUserName,$TransDateTime);
		$sql		= vsprintf($queryInsert,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
	}
	$this->lastInsertTranNo	= $this->getInsertId();
	return $returnData;
}

public function insertAEDAllocationPOPlanQuery(){
	$sql 	= "INSERT INTO so_aed_allocation_po_plan (AEDAllocationId,CustomerCd,Item,Quantity,TransUserName,TransDateTime) VALUES('%s','%s','%s','%s','%s','%s')";
	return $sql;
}

public function insertAEDAllocationPOPlan($data){
	$sqlid 				= "SELECT AEDAllocationId FROM so_aed_allocation WHERE Id = '".$data['AllocationId']."'";
	$result 			= $this->execSelectQuery($sqlid);
	$AllocationId  		= $result[0]['AEDAllocationId'];
	$sql				= '';
	$returnData         = '';
	$queryInsert		= $this->insertAEDAllocationPOPlanQuery();
	$TransUserName		= $_SESSION['UserName'];
	$TransDateTime		= date('Y-m-d H:i:s');
	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++){
		$CustomerCd 	=	$data['Customer_'.$curRowNo];
		if($data['EcoItem'] == ''){
			$item 		= json_decode($data['SolarItem'], true);
		}else{
			$item 		= json_decode($data['EcoItem'], true);
		}
		if($CustomerCd <=0){
			continue;
		} 
		foreach($item as $row){
			$str 			= str_replace('.','',$row);
			$Item			= $data[$str.'_item_'.$curRowNo];
			$Quantity		= $data[$str.'_'.$curRowNo];
			if($Quantity !=0 && $Quantity !=''){
				$inputArr	= array();
				$inputArr	= array($AllocationId,$CustomerCd,$Item,$Quantity,$TransUserName,$TransDateTime);
				$sql		= vsprintf($queryInsert,$inputArr);
				$returnData	= $this->execUpdateQuery($sql);
			}
		}
	}
	return $returnData;
}

public function getAEDAllocationDataHeader($AEDAllocationId){	
	static $solarItemList 	  = array('20000120'=>'SED1.5','20000121'=>'SED1.8','20005315'=>'SED3.0');	
	static $economicsItemList = array('20001340'=>'EED1.5','20009157'=>'EED1.5US','20001341'=>'EED1.8','20002672'=>'EED3.0','20009999'=>'Nonal','20009996'=>'Delay','20005568'=>'SPD');	
	
	$sql1  	= "SELECT CompanyCd FROM so_aed_allocation WHERE AEDAllocationId = '".$AEDAllocationId."'" ;
	$result = $this->execSelectQuery($sql1);
	if($result[0]['CompanyCd'] == '1100'){
		$item 	= $economicsItemList;
	}else{
		$item 	= $solarItemList;
	}
	$sql 		= "SELECT A.*,";
	foreach($item as $index=>$value){
		$row  	= str_replace('.','',$value);
		$sql 	.= "max(case when B.Item  ='".$index."' then B.Quantity end) as '".$row."', ";
	}
	$sql 	 	.= "B.CustomerCd FROM so_aed_allocation A INNER JOIN  so_aed_allocation_po_plan B ON A.CustomerCd =B.CustomerCd AND A.AEDAllocationId = B.AEDAllocationId  WHERE A.AEDAllocationId = '".$AEDAllocationId."'  GROUP BY A.CustomerCd";
	$returnData  = $this->execSelectQuery($sql);
	return $returnData;
}

public function updateAEDAllocationQuery(){
	$sql 		= "UPDATE so_aed_allocation SET TodayStock ='%s',Arrival = '%s',Pending ='%s',TotalStock = '%s',POPlanTotal='%s',Rout = '%s' WHERE AEDAllocationId = '%s' AND CustomerCd = '%s'";
	return $sql;
	}

public function updateAEDAllocation($data){
	$sql				= '';
	$queryUpdate		= $this->updateAEDAllocationQuery();
	$queryInsert		= $this->insertAEDAllocationQuery();
	$returnData			= '';
	$AEDAllocationId 	= $data['AEDAllocationId'];
	$CompanyCd          = $data['CompanyCd'];
	if($CompanyCd  == '1800'){
		$CompanyPOPlanTotal  = "SolarPOPlanTotal_";
	}else{
		$CompanyPOPlanTotal  = "EcoPOPlanTotal_";
	}
	$TransUserName		= $_SESSION['UserName'];
	$TransDateTime		= date('Y-m-d H:i:s');
	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++){
		$Vehicle		=	$data['Vehicle_'.$curRowNo];
		$CustomerCd 	=	$data['Customer_'.$curRowNo];
		$City			=	$data['City_'.$curRowNo];
		$TodayStock		=	$data['TodayStock_'.$curRowNo];
		$Arrival		=	$data['Arrival_'.$curRowNo];
		$Pending		=	$data['Pending_'.$curRowNo];
		$Total			=	$data['Total_'.$curRowNo];
		$POPlanTotal 	=   $data[$CompanyPOPlanTotal.$curRowNo];
		$Rout			=	$data['Rout_'.$curRowNo];
		if($CustomerCd <=0){
			continue;
		} 
		$queryCheck = "SELECT COUNT(*) AS Total FROM so_aed_allocation WHERE AEDAllocationId = '%s' AND CustomerCd = '%s'";
		$inputArr		 = array();
		$inputArr	     = array($AEDAllocationId,$CustomerCd);
		$sql		     = vsprintf($queryCheck,$inputArr);
		$returnData	= $this->execSelectQuery($sql);
		if($returnData[0]['Total']==0){
			$inputArr	 = array();
			$inputArr	 = array($AEDAllocationId,$CompanyCd,$Vehicle,$CustomerCd,$City,$TodayStock,$Arrival,$Pending,$Total,$POPlanTotal,$Rout,$TransUserName,$TransDateTime);
			$sql		 = vsprintf($queryInsert,$inputArr);
			$returnData	 = $this->execUpdateQuery($sql);		
		}else{
			$inputArr	 = array();
			$inputArr	 = array($TodayStock,$Arrival,$Pending,$Total,$POPlanTotal,$Rout,$AEDAllocationId,$CustomerCd);
			$sql	 = vsprintf($queryUpdate,$inputArr);
			$returnData	 = $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		}
	}
 return $returnData;	
}

public function updateAEDAllocationPOPlanQuery(){
	$sql 	= "UPDATE so_aed_allocation_po_plan SET Quantity = '%s' WHERE  AEDAllocationId = '%s' AND CustomerCd = '%s' AND Item = '%s'";
	return $sql;
}


public function updateAEDAllocationPOPlan($data){
	$sql				= '';
	$queryUpdate		= $this->updateAEDAllocationPOPlanQuery();
	$queryInsert		= $this->insertAEDAllocationPOPlanQuery();
	$returnData			= '';
	$AEDAllocationId 	= $data['AEDAllocationId'];
	$TransUserName		= $_SESSION['UserName'];
	$TransDateTime		= date('Y-m-d H:i:s');
	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++){
		$CustomerCd 	=	$data['Customer_'.$curRowNo];
		if($data['EcoItem'] == ''){
			$item 		= json_decode($data['SolarItem'], true);
		}else{
			$item 		= json_decode($data['EcoItem'], true);
		}
		if($CustomerCd <=0){
			continue;
		} 
		foreach($item as $row){
			$str 		= str_replace('.','',$row);
			$Item		= $data[$str.'_item_'.$curRowNo];
			$Quantity	= $data[$str.'_'.$curRowNo];
			//if($Quantity !=0 && $Quantity !=''){
				$queryCheck = "SELECT count(*)AS Total FROM so_aed_allocation_po_plan WHERE  AEDAllocationId = '%s' AND CustomerCd = '%s' AND Item = '%s'";
				$inputArr		 = array();
				$inputArr	     = array($AEDAllocationId,$CustomerCd,$Item);
				$sql		     = vsprintf($queryCheck,$inputArr);
				$returnData	= $this->execSelectQuery($sql);
				if($returnData[0]['Total']==0){
					$inputArr	= array();
					$inputArr	= array($AEDAllocationId,$CustomerCd,$Item,$Quantity,$TransUserName,$TransDateTime);
					$sql		= vsprintf($queryInsert,$inputArr);
					$returnData	= $this->execUpdateQuery($sql);
				}else{
					$inputArr	= array();
					$inputArr	= array($Quantity,$AEDAllocationId,$CustomerCd,$Item);
					$sql		= vsprintf($queryUpdate,$inputArr);
					$returnData	= $this->execUpdateQuery($sql);
				}
			//}
		}
	}
	return $returnData;
}


public function getAEDAllocationList(){
	$sql =  "SELECT A.AEDAllocationId,A.CompanyCd,IFNULL(B.Descript,A.CompanyCd) as Company, DATE_FORMAT(A.TransDateTime,'%d-%m-%Y') AS Date FROM so_aed_allocation A INNER JOIN so_company_m B ON A.CompanyCd = B.CompanyCd GROUP BY A.AEDAllocationId ORDER BY  A.TransDateTime DESC ";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

/********************************* End AED Allocation *********************************************************/


/******************** STOCK BATCH DATEWISE ***************************************/
public function viewstockBatchDatewise(){
	$sql = " SELECT StockBatchId,DATE_FORMAT(StockDate, '%d-%m-%Y') AS StockDate,DATE_FORMAT(DateFrom, '%d-%m-%Y') AS DateFrom,DATE_FORMAT(DateTo, '%d-%m-%Y') AS DateTo,GROUP_CONCAT(DISTINCT  StateCd SEPARATOR ',') StateCd  FROM so_stock_batch_datewise  GROUP BY StockBatchId ORDER BY StockDate ASC";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}


public function insertstockBatchDatewiseQuery(){
	$sql = "INSERT INTO so_stock_batch_datewise (StockBatchId,StateCd,StockDate,ItemCd,DateFrom,DateTo,Dealer,Subdealer,TranUserName,TransDateTime) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')";
	return $sql;
}

public function insertstockBatchDatewise($data){
	$sql1 			= "SELECT MAX(StockBatchId) as UniqueId FROM so_stock_batch_datewise";
	$returnData 	= $this->execSelectQuery($sql1);
	$StockBatchId 	= $returnData[0]['UniqueId']+1;
		
	$sql				='';
	$queryInsert		= $this->insertstockBatchDatewiseQuery();
	$returnData			= '';
	$StateCd			= $data['State'];
	foreach($StateCd as $State){
		$StockDate			= $this->convertDate($data['StockDate'],TRUE,1);
		$DateFrom			= $this->convertDate($data['FromDate'],TRUE,1);
		$DateTo				= $this->convertDate($data['ToDate'],TRUE,1);
		$TransUserName		= $_SESSION['UserName'];
		$TransDateTime		= date('Y-m-d H:i:s');
		for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++){
			$ItemCd				= $data['ItemCd_'.$curRowNo];
			$Dealer				= (isset($data['Dealer_'.$curRowNo])) ? 1 : 0;
			$Subdealer			= (isset($data['Subdealer_'.$curRowNo]))? 1 : 0 ;
			
			if($ItemCd ==''){
				continue;
			} 
			$inputArr	= array();
			$inputArr	= array($StockBatchId,$State,$StockDate,$ItemCd,$DateFrom,$DateTo,$Dealer,$Subdealer,$TransUserName,$TransDateTime);
			$sql		= vsprintf($queryInsert,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			if ($returnData) return $returnData;
		}
	}
	return $returnData;
}

public function getStockBatchwiseHeader($StockBatchId){
	$sql = "SELECT StockBatchId,StateCd, DATE_FORMAT(StockDate,'%d-%m-%Y') AS StockDate,ItemCd,DATE_FORMAT(DateFrom,'%d-%m-%Y')  AS DateFrom ,DATE_FORMAT(DateTo,'%d-%m-%Y')  AS DateTo,Dealer,Subdealer, TranUserName,TransDateTime FROM so_stock_batch_datewise WHERE StockBatchId = $StockBatchId GROUP BY ItemCd";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function getState($StockBatchId){
	$sql = "SELECT StateCd FROM so_stock_batch_datewise WHERE StockBatchId = $StockBatchId GROUP BY StateCd";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

public function updateStockBatchDatewiseQuery(){
	$sql = "UPDATE so_stock_batch_datewise SET Dealer = '%s',Subdealer = '%s' WHERE StockBatchId ='%s' AND ItemCd = '%s'";
	return $sql;
}
public function deleteStockBatchDatewiseQuery(){
	$sql = "DELETE FROM  so_stock_batch_datewise  WHERE StockBatchId ='%s' AND ItemCd = '%s' AND StateCd='%s'";
	return $sql;
}

public function updateStockBatchDatewise($data){
	$sql				= '';
	$returnData			= '';
	$queryInsert		= $this->insertstockBatchDatewiseQuery();
	$queryDelete		= $this->deleteStockBatchDatewiseQuery();
	$queryUpdate		= $this->updateStockBatchDatewiseQuery();
	$StateCd			= $data['State'];
	$str 				= explode(",",$StateCd);
	foreach($str as $State){
	$StockDate			= $this->convertDate($data['StockDate'],TRUE,1);
	$DateFrom			= $this->convertDate($data['FromDate'],TRUE,1);
	$DateTo				= $this->convertDate($data['ToDate'],TRUE,1);
	$StockBatchId  		= $data['StockBatchId'];
	$TransUserName		= $_SESSION['UserName'];
	$TransDateTime      = date('Y-m-d H:i:s');
	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++) {
		$ItemCd			= $data['ItemCd_'.$curRowNo];
		$Dealer			= (isset($data['Dealer_'.$curRowNo])) ? 1 : 0;
		$Subdealer		= (isset($data['Subdealer_'.$curRowNo]))? 1 : 0 ;
		if($ItemCd =='') {
		$inputArr	= array();
		$inputArr	= array($StockBatchId,$ItemCd,$State);
		$sql		= vsprintf($queryDelete,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
	} else{ 
		$queryCheck	= "SELECT COUNT(*) AS Count FROM so_stock_batch_datewise WHERE StockBatchId='%s' AND ItemCd='%s' and StateCd ='$State' ";
		$inputArr	= array();
		$inputArr	= array($StockBatchId,$ItemCd);
		$sql		= vsprintf($queryCheck,$inputArr);
		$returnData	= $this->execSelectQuery($sql);
		if ($returnData[0]['Count']==0) {	
			$inputArr	= array();
			$inputArr	= array($StockBatchId,$State,$StockDate,$ItemCd,$DateFrom,$DateTo,$Dealer,$Subdealer,$TransUserName,$TransDateTime);
			$sql		= vsprintf($queryInsert,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
		//	if ($returnData) return $returnData;
		}else{
			$inputArr	= array();
			$inputArr	= array($Dealer,$Subdealer,$StockBatchId,$ItemCd,);
			$sql		= vsprintf($queryUpdate,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
			//if ($returnData) return $returnData;
			}
		}
	
	} 
	}
	return $returnData;
}

public function removeStockBatchItem($StateCd,$StockBatchId,$ItemCd){
	$sql				='';
	$returnData			= '';
	$queryDelete		= $this->deleteStockBatchDatewiseQuery();
	$str 				= explode(",",$StateCd);
	foreach($str as $State){
		$inputArr	= array();
		$inputArr	= array($StockBatchId,$ItemCd,$State);
		$sql		= vsprintf($queryDelete,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
	}
}

public function reportStockBatchDatewise($data){
	$StateCd 		= isset($data['StateCd'])? $data['StateCd'] :'';
	$CustomerType 	= isset($data['CustomerType'])? $data['CustomerType'] :'';
	$StateCd 		= isset($data['StateCd'])? $data['StateCd'] :'';
	$DealerSubdealerCd 	= isset($data['DealerSubdealerCd'])? $data['DealerSubdealerCd'] :'';
	$StockDate 		= isset($data['StockDate'])? $data['StockDate'] :'';
	$DTS 			= isset($data['DTS'])? $this->convertDate($data['DTS'],TRUE,1):'';
	$DTE 			= isset($data['DTE'])? $this->convertDate($data['DTE'],TRUE,1):'';
	$whr			= '';
	$customer 		= '';
	$joinTable 		= '';
	if(isset($StateCd) && $StateCd !=''){
		$whr .= " AND A.StateCd = '".$StateCd."'";
	}
	if(isset($CustomerType) && $CustomerType !=''){
		$whr .= " AND B.CustomerType ='".$CustomerType."'";
	}
	if(isset($DealerSubdealerCd) && $DealerSubdealerCd != ''){
		$whr .= " AND B.CustomerCd ='".$DealerSubdealerCd."'";
	} 
	
	if(isset($CustomerType) && $CustomerType =='Customer' || $CustomerType ==''){
		$customer .= " ,IFNULL(C.Descript,B.CustomerCd) AS Customer ";
		$joinTable .= " INNER JOIN so_customer_m C ON B.CustomerCd = C.CustomerCd  ";
	}
	
	
	if(isset($CustomerType) && $CustomerType =='Sub Dealer'){
		$customer  .= " ,IFNULL(D.Descript,B.CustomerCd) AS Customer";
		$joinTable .= " INNER JOIN so_subdealer_m D ON B.CustomerCd = D.IdSubdealer ";
	}
	
	$sqlItem 	= "SELECT DISTINCT A.ItemCd, IFNULL(B.ShortDescript,A.ItemCd) as Item FROM so_stock_batch_datewise A INNER JOIN so_item_m B ON A.ItemCd = B.ItemCd WHERE A.StockDate >= '".$DTS."' AND A.StockDate <= '".$DTE."'";
	$result		= $this->execSelectQuery($sqlItem);

	$sql 	= "SELECT DATE_FORMAT(A.StockDate,'%d-%m-%Y') as StockDate,";
	foreach($result as $value){
		$sql .= "max(case when B.Product  ='".$value['ItemCd']."' then B.Stock end) as '".$value['Item']."', ";
	}
	$sql .= " B.CustomerCd,B.BatchNo,B.CustomerType,B.PurchaseFrom,DATE_FORMAT(B.BatchDate,'%d-%m-%Y') as BatchDate".$customer." FROM so_stock_batch_datewise A INNER JOIN so_stock_batch_datewise_trans B ON A.StockBatchId = B.StockBatchId " .$joinTable. "WHERE A.StockDate >= '".$DTS."' AND A.StockDate <= '".$DTE."'".$whr." GROUP BY B.BatchDate,B.BatchNo ORDER BY  B.CustomerCd";
	$returnData = $this->execSelectQuery($sql);
	return array('Item'=>$result,'Data'=>$returnData);
}

/************   for stockBatchDatewise popup **************************/
public function getstockBatchDatewiseCustomer($ccode){
	$CurDate = date('Y-m-d');
	$sql = "SELECT A.*, DATE_FORMAT(A.StockDate, '%d-%m-%Y') AS Date,IFNULL(B.Descript,A.ItemCd) as ItemName FROM so_stock_batch_datewise A  JOIN so_item_m B ON A.ItemCd = B.ItemCd ";  
	if($_SESSION['IsCustomer']){
		$sql .= " WHERE StateCd = (SELECT StateCd FROM so_customer_m WHERE CustomerCd = '".$ccode."'  AND AcceptStockBatchDatewise = '1') AND A.Dealer = '1' ";
	}
	if($_SESSION['IsSubDealer']){
		$sql .= " WHERE StateCd = (SELECT StateCd FROM so_subdealer_m WHERE IdSubdealer = '".$ccode."' AND A.Subdealer = '1') ";
	}
	$sql .= " AND '".$CurDate."' >= A.DateFrom AND '".$CurDate."' <= A.DateTo";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}


public function insertStockBatchDatewiseCustomerQuery(){
	$sql = "INSERT INTO so_stock_batch_datewise_trans(TransId, StockBatchId,StockDate,Customertype, CustomerCd,PurchaseFrom,Product,RE12No,RE12Date, Stock,BatchNo,BatchDate,TranUserName,TransDateTime) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')";
	return $sql ;
}

public function insertStockBatchDatewiseCustomer($data){
	$sql1 			= "SELECT MAX(TransId) as UniqueId FROM so_stock_batch_datewise_trans";
	$returnData 	= $this->execSelectQuery($sql1);
	$TransId	 	= $returnData[0]['UniqueId']+1;
		
	$sql			= '';
	$queryInsert	= $this->insertStockBatchDatewiseCustomerQuery();
	$msg			= '';
	$CustomerCd		= $data['Ccode'];
	$StockDate 		= $data['StockDate'];
	$Customertype	= $data['UserTypeName'];
	$StockBatchId      = $data['StockBatchId'];
	$TransUserName	= $_SESSION['UserName'];
	$TransDateTime	= date('Y-m-d H:i:s');
	for($curRowNo=1; $curRowNo<=$data['LastRowNo']; $curRowNo++){
		$PurchaseFrom	= isset($data['PurchaseFrom_'.$curRowNo])? $data['PurchaseFrom_'.$curRowNo] : 0;
		$Product	= $data['ItemCd_'.$curRowNo] ;
		$RE12No	= $data['RE12No_'.$curRowNo] ;
		$RE12Date	= $this->convertDate($data['RE12Date_'.$curRowNo],TRUE,1) ;
		$Stock		= $data['Stock_'.$curRowNo];
		$BatchNo	= $data['BatchNo_'.$curRowNo];
		$BatchDate	= $this->convertDate($data['BatchDate_'.$curRowNo],TRUE,1);
		
		if($Stock==''){
			continue;
		} 
		$inputArr	= array();
		$inputArr	= array($TransId,$StockBatchId,$StockDate,$Customertype,$CustomerCd,$PurchaseFrom,$Product,$RE12No,$RE12Date,$Stock,$BatchNo,$BatchDate,$TransUserName,$TransDateTime);
		$sql		= vsprintf($queryInsert,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
		$rowaffected = $this->objDBQuery->objDBConnect->affected_rows;
	}
	if ($rowaffected >= 1) {
			$msg = array("status" => "success", "message" => "Stock Updated Successfully");
				return $msg;
		}else{
			$msg = array("status" => "error", "message" => "Error in Updating Stock");
			return $msg;
		}
}

public function checkstockBatchDatewiseCustomerPresent($ccode){
	$sql1 = "SELECT MAX(TransDateTime) AS maxDate FROM so_stock_batch_datewise_trans where CustomerCd = '$ccode'";
	$result =  $this->execSelectQuery($sql1);
	
	
	$sql = "SELECT * FROM so_stock_batch_datewise ";  
	if($_SESSION['IsCustomer']){
		$sql .= " WHERE StateCd = (SELECT StateCd FROM so_customer_m WHERE CustomerCd = '".$ccode."')";
	}
	if($_SESSION['IsSubDealer']){
		$sql .= " WHERE StateCd = (SELECT StateCd FROM so_subdealer_m WHERE IdSubdealer = '".$ccode."') ";
	}
	$sql .= " AND '".$result[0]['maxDate']."' BETWEEN DateFrom AND DateTo";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}

/************************** end stock batch ****************************///
//============Dealer Target Conformation=========================

public function isExistDealerTargetConformation($CustomerCd) {
	$sql = "SELECT * FROM so_dealer_target_confirmation A  JOIN so_customer_m B ON A.CustomerCd=B.CustomerCd WHERE B.StateCd='MH' and A.CustomerCd='".$CustomerCd."' group by A.CustomerCd
	";
	$queryResult	= $this->execSelectQuery($sql);
	return $queryResult;
}

public function insertDealerTargetConformation($data) {
	$filename= $data['CustomerCd'].'.pdf';
	$target_path = 'upload/DealerTargetConfirmation/';
	$target_path = $target_path.$filename;
	$returnData='';
	//$target_path = $target_path . basename( $_FILES['rellPDF']['name']); 
	if(move_uploaded_file($_FILES['UploadDealerConffirmation']['tmp_name'], $target_path)) {
		$sql = "INSERT INTO so_dealer_target_confirmation (CustomerCd, UploadLetter, Status, TransUserName, TransDateTime) VALUES ('%s','%s','%s','%s','%s') ";
		$TransUserName 		= $_SESSION['UserName'];
		$TransDateTime 		= date('Y-m-d H:i:s');
		$CustomerCd		= $data['CustomerCd'];
		$inputArr		= array($CustomerCd,$filename,0,$TransUserName,$TransDateTime);
		$sql		= vsprintf($sql,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
	}
	return $returnData;
}

	
	public function dealerTargetConfirmation(){
		$sql = "SELECT A.CustomerCd,IFNULL(B.Descript,A.CustomerCd) AS CustomerName,A.UploadLetter,A.Status,DATE_FORMAT(A.TransDateTime,'%d-%m-%Y') As Date FROM so_dealer_target_confirmation A LEFT JOIN so_customer_m B ON A.CustomerCd = B.CustomerCd";
		$returnData = $this->execSelectQuery($sql);
		return $returnData;	
		
	}
	
	
	public function approveDealerTargetConfirmation($CustomerCd){
		$ApprovedUserName = $_SESSION['UserName'];
		$ApprovedDateTime = date('Y-m-d H:i:s');
		$sql = "UPDATE so_dealer_target_confirmation SET Status = '1', ApprovedUserName = '".$ApprovedUserName."', ApprovedDateTime = '".$ApprovedDateTime."'  WHERE CustomerCd  IN (".$CustomerCd.")";
		$returnData	= $this->execUpdateQuery($sql);
		$rowaffected = $this->objDBQuery->objDBConnect->affected_rows;
		if($rowaffected >0){
			$sql=" Update so_user_m SET ActiveFlag='0' where CustomerCd IN (".$CustomerCd.")" ;
			$returnData	= $this->execUpdateQuery($sql);
			$_SESSION['IsFullyActive'] =0;
			$_SESSION['IsSemiActive'] ='';
			$_SESSION['ActiveFlag'] ='0';
			$msg = array("status" => "success", "message" => "Target  Approved Successfully");
			return $msg;
		}else{
			$msg = array("status" => "error", "message" => "Target  Approved  Failed Please try again");
			return $msg;
		}
	}

//====================Subdealer Dealer Preferenc===================

public function isExistSubdealerDealerM($IdSubdealer) {
	$sql			= "SELECT A.IdSubdealer, A.CustomerCd, B.StateCd, B.SubdealerCd FROM so_subdealer_dealer_preference A  JOIN so_subdealer_m B ON A.IdSubdealer=B.IdSubdealer WHERE A.TransDateTime>='2016-07-18' and B.StateCd='MH' and A.IdSubdealer='".$IdSubdealer."' group by IdSubdealer
	UNION
	SELECT  A.IdSubdealer, A.CustomerCd, B.StateCd, B.SubdealerCd FROM so_subdealer_m_dealer A  JOIN so_subdealer_m B ON A.IdSubdealer=B.IdSubdealer WHERE A.TransDateTime>='2016-07-18' and B.StateCd='MH'  and A.IdSubdealer='".$IdSubdealer."' group by IdSubdealer
	";
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	if($rowCount>0){ $_SESSION['DealerPreferances']=1; }
	else{ $_SESSION['DealerPreferances']=0; }
	
	return $queryResult;
}



public function insertSubDealerPercantageInsertQuery(){
	$sql = "INSERT INTO so_subdealer_dealer_preference (IdSubdealer, SubdealerCd, Preference, CustomerCd, RegnDate, PercentageOfWork, TransUserName, TransDateTime ) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s') ";
	return $sql;
}

public function insertSubDealerPercantage($data){
	$queryInsert	 	= $this->insertSubDealerPercantageInsertQuery();
	$IdSubdealer 		= $data['IdSubdealer'];
	$sql1 			= "SELECT SubdealerCd FROM so_subdealer_m where IdSubdealer='$IdSubdealer' ";
	$returnData 	= $this->execSelectQuery($sql1);
	$SubdealerCd = $returnData[0]['SubdealerCd'];
	$TransUserName 		= $_SESSION['UserName'];
	$TransDateTime 		= date('Y-m-d H:i:s');
	for($i=1;$i<=2;$i++){
		$CustomerCd		= $data['Dealer'.$i];
		$Percentage 	= $data['Percentage'.$i];
		$RegnDate 		= $this->convertDate($data['RegnDate'.$i],TRUE) ;	
		if($Percentage != 0 ){
		$inputArr		= array($IdSubdealer,$SubdealerCd,$i,$CustomerCd,$RegnDate,$Percentage,$TransUserName,$TransDateTime);
		$sql		= vsprintf($queryInsert,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
		}
	}
}



public function SubDealerPercantageList($search = null,$download){
	$searchCnd = ($search == '') ? 1 : $search;
	$sql = "SELECT t1.IdSubdealer,
	IFNULL(C.Descript,t1.IdSubdealer) AS subdealerName, C.City, C.TelNo, DATE_FORMAT(t1.TransDateTime,'%d-%m-%Y') As TransDate,
	t1.IsApproved, t1.CustomerCd as CustomerCd1,
	IFNULL(B1.Descript,t1.CustomerCd) AS Customer1,
	(t1.PercentageOfWork) AS Percentage1,
	t2.CustomerCd as CustomerCd2,
		IFNULL(B2.Descript,t2.CustomerCd) AS Customer2,
	(t2.PercentageOfWork) AS Percentage2,
	t3.CustomerCd as CustomerCd3,
	IFNULL(B3.Descript,t3.CustomerCd) AS Customer3,
	(t3.PercentageOfWork) AS Percentage3,
	t4.CustomerCd as CustomerCd4,
	IFNULL(B4.Descript,t4.CustomerCd) AS Customer4,
	(t4.PercentageOfWork) AS Percentage4
	
	FROM so_subdealer_dealer_preference t
	LEFT JOIN so_subdealer_dealer_preference t1 ON t.IdSubdealer = t1.IdSubdealer AND t1.Preference ='1' and t1.IsApproved IN ('0','1','2')
	LEFT JOIN so_subdealer_dealer_preference t2 ON t1.IdSubdealer = t2.IdSubdealer AND t2.Preference ='2' and t2.IsApproved IN ('0','1','2')
	LEFT JOIN so_subdealer_dealer_preference t3 ON t1.IdSubdealer = t3.IdSubdealer AND t3.Preference ='3' and t3.IsApproved IN ('0','1','2')
	LEFT JOIN so_subdealer_dealer_preference t4 ON t1.IdSubdealer = t4.IdSubdealer AND t4.Preference ='4'  and t4.IsApproved IN ('0','1','2')
	JOIN so_subdealer_m C ON t1.IdSubdealer = C.IdSubdealer
	LEFT JOIN so_customer_m B1 ON t1.CustomerCd = B1.CustomerCd
	LEFT JOIN so_customer_m B2 ON t2.CustomerCd = B2.CustomerCd
	LEFT JOIN so_customer_m B3 ON t3.CustomerCd = B3.CustomerCd
	LEFT JOIN so_customer_m B4 ON t4.CustomerCd = B4.CustomerCd  WHERE " .$searchCnd. "   GROUP BY t1.IdSubdealer ORDER BY t1.IsApproved DESC ";
	$returnData = $this->execSelectQuery($sql,2);
	
	if($download){
		$curDateTime = date('Y-m-d_His');
		$fileName = './../wrk/Subdealer_dealer_purchase_percentage'.trim($curDateTime).'.xls';
		$repTitle = str_repeat("\t",1) . " Subdealer Dealer Purchase Percentage List ";
		$returnData = $this->makeTabReport($returnData, 3, $fileName, -1, $repTitle, True, 0); 
		return  $fileName; 
	}
	else{
		return $returnData;	
	}
	
}

public function SubDealerPercantageFindDealerStatus($customerCd,$SubDealerCd){
	$sql = "SELECT IsApproved FROM  so_subdealer_dealer_preference WHERE CustomerCd =  '$customerCd' AND IdSubdealer = '$SubDealerCd' and IsApproved IN ('0','1', '2') ";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;	
}


public function approveSubdealerPercentageByAdmin($SubDealerCd){
	$sql = "UPDATE so_subdealer_dealer_preference SET IsApproved = '2' WHERE IdSubdealer  IN (".$SubDealerCd.") AND IsApproved IN ('0','1')";
	$returnData	= $this->execUpdateQuery($sql);
	$rowaffected = $this->objDBQuery->objDBConnect->affected_rows;
	if($rowaffected >0){
		$insertLog = $this->insertSubdealerDealerMIntoLog($SubDealerCd);
	}else{
		//$this->manageTransaction(-1);
	}
}

/*
public function insertSubdealerDealerMIntoLog($SubDealerCd){
	$sqllastid = $this->execSelectQuery("SELECT MAX(TransLogId) as maxid FROM so_subdealer_m_dealer_log");
	$maxId = $sqllastid[0]['maxid']+1;
	$TransUserName = $_SESSION['UserName'];
	$TransDateTime = date('Y-m-d H:i:s');
	 $sql = " INSERT INTO so_subdealer_m_dealer_log (TransLogId, IdSubdealer, SubdealerCd, Preference, CustomerCd, RegnDate, Relation, PercentageOfWork,  TransUserName, TransDateTime, CreditNoOfDays, CreditLimitAmount, SubdealerMagazineDistance, `DealerApprovedUserName`, DealerApprovedDateTime, ApprovedUserName, ApprovedDateTime) 
	SELECT '$maxId', IdSubdealer, SubdealerCd, Preference, CustomerCd, RegnDate, Relation, PercentageOfWork, TransUserName, TransDateTime, CreditNoOfDays, CreditLimitAmount, SubdealerMagazineDistance, DealerApprovedUserName, DealerApprovedDateTime, '$TransUserName','$TransDateTime' FROM so_subdealer_m_dealer WHERE IdSubdealer IN (".$SubDealerCd.")";
	$returnData	= $this->execUpdateQuery($sql);
	$rowaffected = $this->objDBQuery->objDBConnect->affected_rows;
	if($rowaffected >0){
		$insertLog = $this->deleteSubdealerDealerM($SubDealerCd);
	}else{
		//$this->manageTransaction(-1);
	}
}
*/


public function insertSubdealerDealerMIntoLog($SubDealerCd){
	$querycheck = $this->execSelectQuery("SELECT COUNT(*) AS Total FROM so_subdealer_m_dealer WHERE IdSubdealer IN (".$SubDealerCd.")");
	if($querycheck[0]['Total'] == 0){
		$insertLog = $this->insertSubdealerDealerMFromDealerPreference($SubDealerCd);
	}else{
		$sqllastid 		= $this->execSelectQuery("SELECT MAX(TransLogId) as maxid FROM so_subdealer_m_dealer_log");
		$maxId 			= $sqllastid[0]['maxid']+1;
		$TransUserName 	= $_SESSION['UserName'];
		$TransDateTime 	= date('Y-m-d H:i:s');
		$sql = " INSERT INTO so_subdealer_m_dealer_log (TransLogId, IdSubdealer, SubdealerCd, Preference, CustomerCd, RegnDate, Relation, PercentageOfWork,  TransUserName, TransDateTime, CreditNoOfDays, CreditLimitAmount, SubdealerMagazineDistance, `DealerApprovedUserName`, DealerApprovedDateTime, ApprovedUserName, ApprovedDateTime) 
		SELECT '$maxId', IdSubdealer, SubdealerCd, Preference, CustomerCd, RegnDate, Relation, PercentageOfWork, TransUserName, TransDateTime, CreditNoOfDays, CreditLimitAmount, SubdealerMagazineDistance, DealerApprovedUserName, DealerApprovedDateTime, '$TransUserName','$TransDateTime' FROM so_subdealer_m_dealer WHERE IdSubdealer IN (".$SubDealerCd.")";
		$returnData	= $this->execUpdateQuery($sql);
		$rowaffected = $this->objDBQuery->objDBConnect->affected_rows;
		if($rowaffected >0){
			$insertLog = $this->deleteSubdealerDealerM($SubDealerCd);
		}else{
			//$this->manageTransaction(-1);
		}
	}
}
public function deleteSubdealerDealerM($SubDealerCd){
	$sql = "DELETE FROM so_subdealer_m_dealer WHERE IdSubdealer IN (".$SubDealerCd.")";
	$returnData	= $this->execUpdateQuery($sql);
	$rowaffected = $this->objDBQuery->objDBConnect->affected_rows;
	if($rowaffected >0){
		$insertLog = $this->insertSubdealerDealerMFromDealerPreference($SubDealerCd);
		return;
	}else{
		//$this->manageTransaction(-1);
	}
}

public function insertSubdealerDealerMFromDealerPreference($SubDealerCd){
	$ApprovedUserName = $_SESSION['UserName'];
	$ApprovedDateTime = date('Y-m-d H:i:s');
 	$sql = " INSERT INTO so_subdealer_m_dealer (IdSubdealer, SubdealerCd, Preference, CustomerCd, RegnDate, PercentageOfWork, TransUserName,  TransDateTime, CreditNoOfDays, CreditLimitAmount, SubdealerMagazineDistance, DealerApprovedUserName, DealerApprovedDateTime, ApprovedUserName, ApprovedDateTime) 
	SELECT IdSubdealer, SubdealerCd, Preference, CustomerCd, RegnDate, PercentageOfWork, TransUserName, TransDateTime, CreditNoOfDays, CreditLimitAmount, SubdealerMagazineDistance, ApprovedUserName, ApprovedDateTime, '$ApprovedUserName', '$ApprovedDateTime' FROM so_subdealer_dealer_preference WHERE IdSubdealer IN (".$SubDealerCd.") AND IsApproved ='2'";
	$returnData	= $this->execUpdateQuery($sql);
	$rowaffected = $this->objDBQuery->objDBConnect->affected_rows;
	if($rowaffected <0){
		//$this->manageTransaction(-1);
	}
}



public function getSubDealerDealerPreferenceList($CustomerCd){
		$sql = "SELECT A.IdSubdealer,IFNULL(B.Descript,A.IdSubdealer) AS SubdealerName  ,A.PercentageOfWork,A.IsApproved,A.CreditNoOfDays,A.CreditLimitAmount,A.SubdealerMagazineDistance,B.City,B.ContactPerson1 FROM so_subdealer_dealer_preference A LEFT JOIN so_subdealer_m B ON A.IdSubDealer = B.IdSubdealer WHERE A.CustomerCd = '".$CustomerCd."'";	
		$returnData = $this->execSelectQuery($sql);
		return $returnData;	
	}
	
	public function insertNotificationSubDealerPercantageQuery(){
		$sql = " UPDATE so_subdealer_dealer_preference SET CreditNoOfDays = '%s',CreditLimitAmount='%s',SubdealerMagazineDistance = '%s',IsApproved = '%s',ApprovedUserName = '%s', ApprovedDateTime = '%s' WHERE CustomerCd = '%s' AND IdSubdealer = '%s' AND IsApproved = 0";
		return $sql;
	}
	
	public function insertNotificationSubDealerPercantage($data){
		$sql = '';
		$queryUpdate =  $this->insertNotificationSubDealerPercantageQuery();
		$CustomerCd	 = $data['CustomerCd'];	
		$ApprovedUserName = $_SESSION['UserName'];
		$ApprovedDateTime =  date('Y-m-d H:i:s');
		for($curRowNo = 1;$curRowNo<=$data['LastRowNo'];$curRowNo++){
			$SubdealerCd		= $data['SubdealerCd_'.$curRowNo];
			$CreditNoOfDays		= $data['CreditNoOfDays_'.$curRowNo];
			$CreditLimitAmount	= $data['CreditLimitAmount_'.$curRowNo];
			$SubdealerMagazineDistance	= $data['SubdealerMagazineDistance_'.$curRowNo];
			$IsApproved			= isset($data['CheckedRow_'.$curRowNo]) ? 1:0;
			if($IsApproved == 0){
				continue;
			}
			$inputArr	= array();
			$inputArr	= array($CreditNoOfDays,$CreditLimitAmount,$SubdealerMagazineDistance,$IsApproved,$ApprovedUserName,$ApprovedDateTime,$CustomerCd,$SubdealerCd);
			$sql		= vsprintf($queryUpdate,$inputArr);
			$returnData	= $this->execUpdateQuery($sql);
		}
	}

	
	public function getDealerSubdealerPercentage($SubdealerCd){
		$sql 	= "SELECT UniqueId, CustomerCd,PercentageOfWork FROM so_subdealer_m_dealer WHERE IdSubdealer = '".$SubdealerCd."' ";
		$returnData = $this->execSelectQuery($sql);
		return $returnData;
	}

	public function getDealerSubdealerPrefPercentage($SubdealerCd){
		$sql 	= "SELECT CustomerCd,PercentageOfWork FROM so_subdealer_dealer_preference WHERE IdSubdealer = '".$SubdealerCd."' ";
		$returnData = $this->execSelectQuery($sql);
		return $returnData;
	}


public function updateSubDealerPercantage($data){
	$IdSubdealer 	= $data['IdSubdealer'];
	$sql	 		= "UPDATE so_subdealer_dealer_preference SET IsApproved = '3' WHERE IdSubdealer = '".$IdSubdealer."'";
	$returnData		= $this->execUpdateQuery($sql);
	$queryInsert	= $this->insertSubDealerPercantage($data);
}

//=============================
//==========================Customer Payment Upload  ==================

public function importCustomerBankPayment($srcFile, $tableName, $row1Status=1) {
// Import data from Tab limited Text file in specified Table. 
// row1Status 0: No Column Names in 1st Row. Data starts from 1st row. Assume ALL column values given in proper order. Can not skip any column
// 			  1: 1st Row with proper Column Names. (May contain Spaces, which are removed by this proc). Can skip any column (provided they have Null allowed or Default Values)
//			 -1: 1st Row with Column Names which have to be ignored. Data starts from 2nd row, but act as row1Status=0
//echo $sql = "TRUNCATE TABLE ". $tableName;
//$queryResult	= $this->execUpdateQuery($sql);
	$handle = fopen($srcFile, "r");
	if ($handle) { 
		$arrSrcData = explode("\n", fread($handle, filesize($srcFile))); 	
	}

	$sizearrSrcData = count($arrSrcData);
	$dataRow = ($row1Status==0) ? 0 : 1;

	$columnCount	= 1000;
	if ($row1Status == 1) {
		$curRec	= explode("\t", $arrSrcData[0]);
		 //print_r($curRec);
		$j		= count($curRec)-1;
		$isEmptyHead	= TRUE;
		while ($isEmptyHead && $j >= 0 ) {
			if (trim($curRec[$j])=='') {
				$j--;
			} else {
				$isEmptyHead = FALSE;
			}
		}
		 $curRec		= array_slice($curRec, 0, $j+1);
		
		 $columnCount= count($curRec);
		 
		 $columnList	= str_replace(",", "`,`", "`" . trim(implode("`,`", $curRec)) . "`");
		 $columnList = $columnList.",`Flag`, `IsAccessoryPO`, `EntryDate`,  `TransUserName` ";
		
	}
	$errorarr = array();
	for ($dataRow; $dataRow < $sizearrSrcData; $dataRow++) {
		$curRec	= explode("\t", $arrSrcData[$dataRow]);
		$curRec	= array_slice($curRec, 0, $columnCount);
		$curRec	= preg_replace('/"$/','',preg_replace('/^"/', '', $curRec));	// remove " at Start & End of any string (put by Excel when converting Strings including ,)
		$curRec	= str_replace("'","\'",$curRec);		// Escape embeded 's with \'s
		
		$rowData		= str_replace("\r", '', implode("", $curRec));
		
		if (!empty($rowData)) {
			//$rowData	= trim(implode("','", $curRec));
			
			$rowData	=  str_replace(",", "','", "'" . trim(implode("','", $curRec)) . "'");
			$datalist=  explode(",", $rowData);
			//echo substr($datalist[0], 1,-1);
			$details = explode("CNN", substr($datalist[0],1, -1));
			//print_r($details);
			 $CustomerCd = $details[0];
			$IdExpDet='';
			if(sizeof($details)>1){
				$IdExpDet = $details[1];
			}
			/*if($IdExpDet ==''){
				$Expdet = explode("CNN", substr($datalist[1],1,-1));
				$IdExpDet = trim($Expdet[1], 1);
			}
			*/
			$Flag = '0';
			$sql 	= "SELECT count(IdExpDet) as count , TotAmt, CompanyCd FROM so_expdet WHERE IdExpDet = '".$IdExpDet."' AND CustomerCd = '".$CustomerCd."' AND StatusCd IN ('U', 'A', 'W') ";
			$returnData = $this->execSelectQuery($sql);
			$DiffAmt = (substr($datalist[4],1,-1) -$returnData[0]['TotAmt']);
			$ComapanyMatch= 0;
			
			$IsAccessoryPO ='0';
			/*echo "@".$returnData[0]['count'];
			echo "_".$ComapanyMatch;
			echo "_".$returnData[0]['CompanyCd'];
			echo "_".$datalist[8];
			echo "_".strlen($datalist[2]);
			echo "_".$DiffAmt;
			echo "_".$datalist[4];
			echo "_".$returnData[0]['TotAmt'];
			echo "<br/>";
			*/
			if($returnData[0]['count']==0){
				$sql 	= "SELECT count(A.IdAccessory) as count , A.TotAmt, B. CompanyCd FROM so_accessory A JOIN so_accessory_ctg_m B ON  A.AccessoryCtgCd = B.AccessoryCtgCd WHERE IdAccessory = '".$IdExpDet."' AND CustomerCd = '".$CustomerCd."' AND StatusCd IN ('U', 'A', 'W', 'P') ";	
				$returnData = $this->execSelectQuery($sql);		
				if($returnData[0]['count']>0){ $IsAccessoryPO ='1'; }
			}
			if($returnData[0]['CompanyCd'] == 1800){ if($datalist[8] =="'SOLAR'"){ $ComapanyMatch = 1;}}
			if($returnData[0]['CompanyCd'] == 1100 && $datalist[8] =="'ECOEX'" ){ $ComapanyMatch = 1;}
			if($returnData[0]['count']>0 && $ComapanyMatch=='1' &&  strlen($datalist[2])>10 && $DiffAmt >= 0 ){ $Flag = '1'; }
			
			$CurrDate = date('Y-m-d');
			$querycheck = "SELECT COUNT(*) AS Tot FROM ".$tableName." WHERE UTR = ".$datalist[5];
				$result     = $this->execSelectQuery($querycheck);
				if($result[0]['Tot']>0  ){
					$returnResult 	= explode(',',$curRec[0]); 	
					$curRec 		= explode(',',$curRec[0]);
					$returnResult 	= array_merge($returnResult,$curRec);
					array_push($errorarr,$returnResult);
				}
				
				else{
					if($datalist[8] =="'SOLAR'" || $datalist[8] =="'ECOEX'" ){
						$rowData = $rowData.", ".$Flag. ", ".$IsAccessoryPO.",  '".$CurrDate."', '".$_SESSION['UserName']."'";
						$sql	= "INSERT INTO " . $tableName . ($row1Status==1 ? "(" . $columnList . ")" : "") . " VALUES (" . $rowData . ");";
						$queryResult= $this->execUpdateQuery($sql);		
						$paymentStatus = $this->updateCustomerBankPayment_PaymentStatus($IdExpDet);
						if($Flag == 0){
							//$string = substr($string, 0, strpos($datalist[5], "'"));
							$sql12 	= "SELECT IdExpDet, CustomerCd  FROM so_expdet WHERE UTR like '%".trim($datalist[5],"'")."%' AND StatusCd IN ('U', 'A', 'W') ";
							$returnData12 = $this->execSelectQuery($sql12);
							if(Count($returnData12) > 0){
								$queryUpdate 	= " UPDATE so_expdet_customer_bank_payment SET  CNN_NO = 'CNN".$returnData12[0]['IdExpDet']."'  WHERE UTR = ".$datalist[5]."";
								$result 		= $this->execUpdateQuery($queryUpdate);								
							}
						}
					}
					else{
						$returnResult 	= explode(',',$curRec[0]); 	
						$curRec 		= explode(',',$curRec[0]);
						$returnResult 	= array_merge($returnResult,$curRec);
						array_push($errorarr,$returnResult);						
					}
				}
				//$rowData = $rowData.", ".$Flag. ", ".$IsAccessoryPO.",  '".$CurrDate."', '".$_SESSION['UserName']."'";
				//$sql	= "INSERT INTO " . $tableName . ($row1Status==1 ? "(" . $columnList . ")" : "") . " VALUES (" . $rowData . ");";
				//$queryResult= $this->execUpdateQuery($sql);
		}
	}
	return $errorarr;
}




public function updateCustomerBankPayment_PaymentStatus($IdExpDet){
	$sql 	= "SELECT TotAmt, CustomerCd, CompanyCd  FROM so_expdet where  IdExpDet = '".$IdExpDet."'";
	$returnData = $this->execSelectQuery($sql);
	$sql1 	= "SELECT IFNULL(TRN_AMOUNT,0) AS CustomerPayment, CNN_NO, REMITTER_CODE, REMITTER_TYPE FROM  so_expdet_customer_bank_payment where  CNN_NO = 'CNN".$IdExpDet."'";
	$returnData1 = $this->execSelectQuery($sql1);
	//print_r($returnData);
	//print_r($returnData1);
	$PORemitterCd = $returnData[0]['CustomerCd'].'CNN'.$IdExpDet;
	if($returnData[0]['CompanyCd'] == '1800'){ $POcompany = 'SOLAR'; }
	else if($returnData[0]['CompanyCd'] == '1100'){ $POcompany = 'ECOEX'; }
	$checklistData=0;
	$CustomerPayment=0;
	for ($i=0;  $i< count($returnData1); $i++) {
			if($PORemitterCd == $returnData1[$i]['REMITTER_CODE'] && $POcompany==$returnData1[$i]['REMITTER_TYPE']){
				$checklistData =$checklistData+1;
				$CustomerPayment =$returnData1[$i]['CustomerPayment']+$CustomerPayment;
				
			}
			else{
				$checklistData =$checklistData+0;
				$CustomerPayment =$returnData1[$i]['CustomerPayment']+$CustomerPayment;
				
			}
		}
	if($checklistData>0){
		if(count($returnData1)==$checklistData){$checklist=1; }else{$checklist=0; }
		if($returnData[0]['TotAmt'] <= $CustomerPayment && $checklist==1 ){
		$queryUpdate 	= " UPDATE so_expdet SET  PaymentStatus = 1 WHERE IdExpDet = '".$IdExpDet."'";
		$result 		= $this->execUpdateQuery($queryUpdate);	
		}
		else{
		$queryUpdate 	= " UPDATE so_expdet SET  PaymentStatus = 2 WHERE IdExpDet = '".$IdExpDet."'";
		$result 		= $this->execUpdateQuery($queryUpdate);	
		}
	}
	else{
		$queryUpdate 	= " UPDATE so_expdet SET  PaymentStatus = 0 WHERE IdExpDet = '".$IdExpDet."'";
		$result 		= $this->execUpdateQuery($queryUpdate);	
		}
}



/*
public function getCustomerBankPaymentData($searchDate='',$Id='',$download='',$paymentReturn='',$data){
	$Id 	= ($Id!='')? "Id ='$Id'":1;
	$date	 = $this->convertDate($searchDate, TRUE, 1);
	$searchcnd 	= ($searchDate !='')?" AND EntryDate = '".$date."'":' AND 1';
	if($data !=''){
		$searchcnd 	.= "  AND Id IN (".$data.")";
	}
	 $sql 	= "SELECT Id, REMITTER_CODE, CNN_NO, B.IdExpDet, REMITTER_NAME, DATE_FORMAT(VALUE_DATE,'%d-%m-%Y') AS VALUE_DATE, DATE_FORMAT(EntryDate,'%d-%m-%Y') as EntryDate, TRN_AMOUNT, UTR, REMITTER_AC, SENDER_ACNO, REMITTER_TYPE, PAYSYS_ID, NARRATION, SENDER_IFSC_CODE, SENDER_BANK, SENDER_BRANCH, Email_list, Flag,IsFileGenrated, B.TotAmt, B.TotBox, B.CompanyCd, C.Descript as CUSTOMER_NAME, B.VehicleNo, B.DespatchMode, D.Descript as Status, E.Capacity";
	if(($download ) || ($paymentReturn)){
		$Id .= " AND A.PaymentReturn ='1'";
		$sql .=",(CASE WHEN A.Remark = '1' THEN 'Without CNN' 
		WHEN A.Remark = '2' THEN 'Wrong Company' 
		WHEN A.Remark = '3' THEN 'Partial Payment' 
		WHEN A.Remark = '4' THEN 'Wrong CustomerCd / RemitterCd' 
		WHEN A.Remark = '5' THEN 'Underload' 
		WHEN A.Remark = '6' THEN 'Late Payment' 
		WHEN A.Remark = '11' THEN 'Clubbed Van PO' 
		WHEN A.Remark = '12' THEN 'Holded By Customer' 
		WHEN A.Remark = '13' THEN 'Van Provided Already Servicing PO' 
		END) AS Remark,IF(A.PaymentReturn ='0','No','Yes') AS PaymentReturn";
	}else{
		$sql .=", A.Remark,A.PaymentReturn";
		$Id .= " AND A.PaymentReturn <>'1'";
	}
	$sql .=" FROM so_expdet_customer_bank_payment A LEFT JOIN so_expdet B ON A.CNN_NO = CONCAT('CNN', B.IdExpdet)  LEFT JOIN  so_customer_m C ON B.CustomerCd = C.CustomerCd LEFT JOIN so_status_m D ON B.StatusCd = D.StatusCd LEFT JOIN so_vehicle_m E ON B.VehicleNo = E.VehicleNo  WHERE ".$Id.$searchcnd."  ORDER BY `Flag` ASC";
	//echo $sql;
	$returnData	= $this->execSelectQuery($sql,2);
	
	if($download){
		$curDateTime = date('Y-m-d_His');
		$fileName = './../wrk/CustomerBankPayment'.trim($curDateTime).'.xls';
		$repTitle = str_repeat("\t",1) . " Customer Bank Payment List ";
		$returnData = $this->makeTabReport($returnData, 3, $fileName, -1, $repTitle, True, 0); 
		
		$query = " UPDATE so_expdet_customer_bank_payment SET IsFileGenrated = '1' WHERE Id IN (".$data.")";
		$returnData	= $this->execUpdateQuery($query);
		
		return  $fileName; 
	}else{
		return $returnData;
	}
}
*/

public function getCustomerBankPaymentData($searchDate,$Id='',$download='',$paymentReturn='',$data, $CompanyCd=''){
	$Id 	= ($Id!='')? "Id ='$Id'":1;
	$date	 = $this->convertDate($searchDate, TRUE, 1);
	if($CompanyCd=='1800'){ $RemitterType ='SOLAR'; } else{ $RemitterType='ECOEX'; }
	$searchcnd 	= ($searchDate !='')?" AND EntryDate = '".$date."' AND REMITTER_TYPE = '".$RemitterType."'":' AND 1';
	//$searchcnd 	= ($searchDate !='')?" AND EntryDate = '".$date."' ":' AND 1';
	if($data !=''){
		$searchcnd 	.= "  AND Id IN (".$data.")";
	}
	
	$wrongListRemarkArr = array('1' => 'Without CNN','2'=>'Wrong Company','3'=>'Partial Payment','4'=>'Wrong CustomerCd /RemitterCd','5'=>'Underload');
	$finalListRemarkArr = array('11' => 'Clubbed Van PO','12'=>'Holded By Customer','13'=>'Van Provided Already Servicing PO');
	$array = $wrongListRemarkArr + $finalListRemarkArr;
	$curDate = date('d-m-Y');
		if($download){
			$Id .= " AND A.PaymentReturn ='1'";		
			//$sql ="SELECT 'P' as 'Parent Child Identifier', A.REMITTER_CODE as 'Customer Code',A.REMITTER_TYPE as 'Customer Name', A.CNN_NO, DATE_FORMAT(A.VALUE_DATE,'%d-%m-%Y') AS 'Instrument Value Date', A.TRN_AMOUNT as ' Amount',A.UTR, A.REMITTER_AC, A.REMITTER_NAME AS 'Beneficiary Name', A.SENDER_BANK as 'Beneficiary Bank Code', A.SENDER_IFSC_CODE AS 'Beneficiary Branch Code',  A.SENDER_ACNO as 'Credit Account No', A.SENDER_BRANCH as 'Beneficiary Branch', C.Address as 'Beneficiary Add Line 1', '' as 'Beneficiary Add Line 2', '' as 'Beneficiary Add Line 3', '' as 'Beneficiary Add Line 4',C.City as City, C.StateCd as 'State Code', '' as 'Pin Code', CONCAT(A.Email_list, ';dd@solargroup.com') as 'Email Id', C.TelNo as Phone, '' as 'Customer Ref No'	, '' as 'Remarks 1'
		//	, '' as 'Remarks 2', '' as 'ADDITIONAL FIELD 1', '' as 'ADDITIONAL FIELD 2', '' AS 'ADDITIONAL FIELD 3' ,'' AS 'ADDITIONAL FIELD 4','' AS 'ADDITIONAL FIELD 5' FROM so_expdet_customer_bank_payment A LEFT JOIN so_expdet B ON A.CNN_NO = CONCAT('CNN', B.IdExpdet)  LEFT JOIN  so_customer_m C ON B.CustomerCd = C.CustomerCd LEFT JOIN so_status_m D ON B.StatusCd = D.StatusCd WHERE ".$Id.$searchcnd."  ORDER BY `Flag` ASC,REMITTER_TYPE DESC";
	
			$sql ="SELECT 'P' as 'Parent Child Identifier',IF(A.REMITTER_TYPE = 'SOLAR','\'000255','\'000256') as 'Customer Code'
			, IF(A.REMITTER_TYPE = 'SOLAR','Solar Industries India Ltd','Economic Explosives Ltd') as 'Customer Name'
			, IF(A.REMITTER_TYPE = 'SOLAR','10374783693','10374784143') as 'Debit Account No', '' as 'Product Code'
			, '$curDate' AS 'Instrument Value Date', A.TRN_AMOUNT as ' Amount', A.REMITTER_NAME AS 'Beneficiary Name', A.SENDER_BANK as 'Beneficiary Bank Code', C.IFSCCode AS 'Beneficiary Branch Code',  C.BankAccountNo as 'Credit Account No', C.BankBranch as 'Beneficiary Add Line 1', '' as 'Beneficiary Add Line 2', '' as 'Beneficiary Add Line 3', '' as 'Beneficiary Add Line 4',C.City as City, C.StateCd as 'State Code', '' as 'Pin Code', CONCAT(C.EMailId, ';dd@solargroup.com') as 'Email Id', C.TelNo as Phone, C.CustomerCd as 'Customer Ref No'	, A.CNN_NO as 'Remarks 1'
			, '' as 'Remarks 2', '' as 'ADDITIONAL FIELD 1', '' as 'ADDITIONAL FIELD 2', A.TRN_AMOUNT  AS 'ADDITIONAL FIELD 3' ,0 AS 'ADDITIONAL FIELD 4',A.TRN_AMOUNT  AS 'ADDITIONAL FIELD 5' FROM so_expdet_customer_bank_payment A LEFT JOIN so_expdet B ON A.CNN_NO = CONCAT('CNN', B.IdExpdet)  LEFT JOIN  so_customer_m C ON B.CustomerCd = C.CustomerCd LEFT JOIN so_status_m D ON B.StatusCd = D.StatusCd WHERE ".$Id.$searchcnd."  ORDER BY `Flag` ASC,REMITTER_TYPE DESC";
						
						
		}else{	
		 	$sql 	= "SELECT A.Id, A.REMITTER_CODE, A.CNN_NO, A.REMITTER_NAME, DATE_FORMAT(A.VALUE_DATE,'%d-%m-%Y') AS VALUE_DATE, DATE_FORMAT(A.EntryDate,'%d-%m-%Y') as EntryDate,  A.TRN_AMOUNT, if(A.IsAccessoryPO =1,E.TotAmt,B.TotAmt) as TotAmt, B.TotBox,  A.UTR, A.REMITTER_AC, A.SENDER_ACNO,  A.REMITTER_TYPE,  A.PAYSYS_ID, A.NARRATION, A.SENDER_IFSC_CODE, A.SENDER_BANK, A.SENDER_BRANCH, A.Email_list,if(A.IsAccessoryPO =1,E.VehicleNo,B.VehicleNo) as  VehicleNo, if(A.IsAccessoryPO =1,E.DespatchMode,B.DespatchMode) as DespatchMode, F.Capacity as Capacity, C.Descript as CUSTOMER_NAME,  D.Descript as Status"; 


			if($paymentReturn){
				$Id .= " AND A.PaymentReturn ='1' ";		
				
				$orderBy = " ORDER BY REMITTER_TYPE DESC,B.StatusCd ";
				$sql .=",(CASE";
				foreach ($array AS $key => $value){
					$sql .=" WHEN A.Remark = {$key} THEN '{$value}'";
				}
				$sql .=" END) AS Remark,IF(A.PaymentReturn ='0','No','Yes') AS PaymentReturn,B.CompanyCd,A.IsFileGenrated";
			}else{
				$sql .=",B.CompanyCd, A.Remark,A.PaymentReturn, B.IdExpDet,A.Flag, A.IsAccessoryPO";
				$Id .= " AND A.PaymentReturn <>'1' ";
				$orderBy = " ORDER BY Flag ASC , REMITTER_TYPE DESC,B.StatusCd ";
			}
			
			$sql .=" FROM so_expdet_customer_bank_payment A 
				LEFT JOIN so_accessory E ON A.CNN_NO = CONCAT('CNN', E.IdAccessory)  AND A.IsAccessoryPO = 1
				LEFT JOIN so_expdet B ON A.CNN_NO = CONCAT('CNN', B.IdExpdet) AND A.IsAccessoryPO = 0 
				LEFT JOIN  so_customer_m C ON B.CustomerCd = C.CustomerCd  OR E.CustomerCd = C.CustomerCd 
				LEFT JOIN  so_vehicle_m F ON B.VehicleNo = F.VehicleNo OR E.VehicleNo = F.VehicleNo
				LEFT JOIN so_status_m D ON B.StatusCd = D.StatusCd OR E.StatusCd = D.StatusCd  WHERE ".$Id.$searchcnd.$orderBy;
		}
		//echo $sql;
	
	$returnData	= $this->execSelectQuery($sql,2);
	
	if($download){
		$curDateTime = date('Y-m-d_His');
		$fileName = './../wrk/CustomerBankPayment'.trim($curDateTime).'.xls';
		$repTitle = str_repeat("\t",1) . " Customer Bank Payment List ";
		$returnData = $this->makeTabReport($returnData, 3, $fileName, -1, $repTitle, TRUE, 0); 
		$query = " UPDATE so_expdet_customer_bank_payment SET IsFileGenrated = '1' WHERE Id IN (".$data.")";
		$returnData	= $this->execUpdateQuery($query);
		return  $fileName; 
	}else{
		return $returnData;
	}
}
public function getCustomerBankPaymentDataLog($Id){
	$sql 	= "SELECT Id, REMITTER_CODE, CNN_NO, REMITTER_NAME,  DATE_FORMAT(VALUE_DATE,'%d-%m-%Y') AS  VALUE_DATE, TRN_AMOUNT, UTR, REMITTER_AC, SENDER_ACNO, REMITTER_TYPE, PAYSYS_ID, NARRATION, SENDER_IFSC_CODE, SENDER_BANK, SENDER_BRANCH, Email_list,Flag, Remark,PaymentReturn,EntryDate,UpdateBy,UpdateDateTime FROM so_expdet_customer_bank_payment_log WHERE Id = '".$Id."' ORDER BY `UpdateDateTime` DESC";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}
/*
public function updateCustomerBankPayment($data){
	$sql = "UPDATE so_expdet_customer_bank_payment SET REMITTER_CODE='%s',REMITTER_NAME='%s',VALUE_DATE='%s',CNN_NO='%s' WHERE Id = '%s'";
	$date = $this->convertDate($data['ValueDate'],TRUE);
	$inputArr	= array($data['RemitterCode'],$data['RemitterName'],$date,$data['CNNNO'],$data['Id']); 
	$sql		= vsprintf($sql,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	
}
*/


public function updateCustomerBankPayment($data){
	$CNN 		= explode("CNN",$data['CNNNO']); 
	$IdExpDet 	= @$CNN[1];
	
	$details = explode("CNN", $data['RemitterCode']);
	//print_r($details);
	$CustomerCd = $details[0];
	if(!isset($details[1]) || $details[1] ==''){ $details[1]=0; }
	$Flag 		= 0;
	
	//echo $sql1 			= "SELECT count(IdExpDet) as count , TotAmt, CompanyCd FROM so_expdet WHERE IdExpDet = '".$IdExpDet."' ";
	$IsAccessoryPO =0;
	 $sql1 	= "SELECT count(IdExpDet) as count , TotAmt, CompanyCd FROM so_expdet WHERE IdExpDet = '".$IdExpDet."' AND CustomerCd = '".$CustomerCd."' AND StatusCd IN ('U', 'A', 'W') ";
	 $returnData1 	= $this->execSelectQuery($sql1);
	 if($returnData1[0]['count']==0){
			$sql 	= "SELECT count(A.IdAccessory) as count , A.TotAmt, B. CompanyCd FROM so_accessory A JOIN so_accessory_ctg_m B ON  A.AccessoryCtgCd = B.AccessoryCtgCd WHERE IdAccessory = '".$IdExpDet."' AND CustomerCd = '".$CustomerCd."' AND StatusCd IN ('U', 'A', 'W', 'P') ";	
			$returnData1 = $this->execSelectQuery($sql);		
			if($returnData1[0]['count']>0){ $IsAccessoryPO ='1'; }
		}
	
	$sql2			="SELECT * FROM so_expdet_customer_bank_payment WHERE Id = '".$data['Id']."'";
	$returnData2 	= $this->execSelectQuery($sql2);
	
	$DiffAmt 		= ($returnData2[0]['TRN_AMOUNT']-$returnData1[0]['TotAmt']);
	$ComapanyMatch	= 0;
	if($returnData1[0]['CompanyCd'] == 1800){ if($returnData2[0]['REMITTER_TYPE'] =="SOLAR"){ $ComapanyMatch = 1;}}
	if($returnData1[0]['CompanyCd'] == 1100 && $returnData2[0]['REMITTER_TYPE'] =="ECOEX" ){ $ComapanyMatch = 1;}
		
	if($returnData1[0]['count'] > 0 && $ComapanyMatch=='1' &&  strlen($data['RemitterName'])>10 && $DiffAmt >= 0 && $details[1] == $IdExpDet ){
		$Flag = '1';
	}
	
	/*
	echo $Flag;
	echo "@".$returnData1[0]['count'];
		echo "_".$ComapanyMatch;
		echo "_".$returnData1[0]['CompanyCd'];
		echo "_".$returnData2[0]['REMITTER_TYPE'];
		echo "_".strlen($data['RemitterName']);
		echo "_".$DiffAmt;
		echo "_".$returnData2[0]['TRN_AMOUNT'];
		echo "_".$returnData1[0]['TotAmt'];
		echo "<br/>";
	*/
	
	$sql = "UPDATE so_expdet_customer_bank_payment SET REMITTER_CODE='%s',REMITTER_NAME='%s',VALUE_DATE='%s',CNN_NO='%s', Flag = '%s', IsAccessoryPO ='%s', UpdateBy='%s',UpdateDateTime='%s' WHERE Id = '%s' ";
	$date = $this->convertDate($data['ValueDate'],TRUE);
	$UpdateBy   = $_SESSION['UserName'];
	$UpdateDateTime	= date('Y-m-d H:i:s');
	$inputArr	= array($data['RemitterCode'],$data['RemitterName'],$date,$data['CNNNO'],$Flag, $IsAccessoryPO, $UpdateBy,$UpdateDateTime,$data['Id']); 
	$sql		= vsprintf($sql,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	$paymentStatus = $this->updateCustomerBankPayment_PaymentStatus($IdExpDet);
}

public function updateCustomerBankPaymentRemarks($data){
	$queryUpdate = "UPDATE so_expdet_customer_bank_payment SET Remark = '%s',PaymentReturn='%s',UpdateBy='%s',UpdateDateTime='%s'WHERE Id='%s'";
	
	for($curRow =1;$curRow <=$data['lastRow'];$curRow++){
		$BankpaymentId 	= $data['BankpaymentId_'.$curRow];
		$Remark 		= $data['Remark_'.$curRow];
		$paymentReturn 	= isset($data['paymentReturn_'.$curRow])?1:0;
		$UpdateBy   	= $_SESSION['UserName'];
		$UpdateDateTime	= date('Y-m-d H:i:s');
		
		if($Remark =='' && $paymentReturn==0){
			continue;
		}
		$inputArr = array();
		$inputArr = array($Remark,$paymentReturn,$UpdateBy,$UpdateDateTime,$BankpaymentId);
		$sql = vsprintf($queryUpdate,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
	}
}

//==========================Customer Payment Upload End ==================

	
public function inserAddressDetailQuery(){
	$sql = "INSERT INTO so_user_address_details (UserCd, UserType, AddressLine1, AddressLine2, AddressLine3, AtPost, Tehsil,District, StateCd, PinCode, PhoneNo,TransUserName,TransDateTime) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')";
	return $sql;
}
public function insertAddressDetails($data){
	
	$queryInsert= $this->inserAddressDetailQuery();
	$TransUserName = $_SESSION['UserName'];
	$TransDateTime =  date('Y-m-d H:i:s');
	$UserCd 		= $data['UserCd']; 
	$UserType 		= $data['UserType']; 
	$AddressLine1 	= $data['AddressLine1']; 
	$AddressLine2 	= $data['AddressLine2']; 
	$AddressLine3 	= $data['AddressLine3']; 
	$AtPost 	= $data['AtPost']; 
	$Tehsil 	= $data['Tehsil']; 
	$District 	= $data['District']; 
	$StateCd 	= $data['StateCd']; 
	$PinCode 	= $data['PinCode']; 
	$PhoneNo 	= $data['PhoneNo']; 
	
	$inputArr	= array();
	$inputArr	= array($UserCd,$UserType,$AddressLine1,$AddressLine2,$AddressLine3,$AtPost,$Tehsil,$District,$StateCd,$PinCode,$PhoneNo,$TransUserName,$TransDateTime);
	$sql		= vsprintf($queryInsert,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	$rowaffected = $this->objDBQuery->objDBConnect->affected_rows;
		if($rowaffected >0){
			$msg = array("status" => "success", "message" => "Address submited successfully");
			return $msg;
		}else{
			$msg = array("status" => "error", "message" => "Address submited Failed");
			return $msg;
		}
}



public function isExistAddress(){
	if($_SESSION['IsCustomer']){
		$UserCd 	= $_SESSION['CustomerCd'];
	}
	if($_SESSION['IsSubDealer']){
		$UserCd 	= $_SESSION['SubdealerCd'];
	}
	$sql = "SELECT * FROM so_user_address_details WHERE UserCd = '".$UserCd."'";
	
	$queryResult	= $this->execSelectQuery($sql);
	$rowCount		= count($queryResult);
	return $rowCount;
}


public function getUserAddress($UserCd=''){
	$whr = ($UserCd != '')?  'A.UserCd='.$UserCd : 1;
	$sql = "SELECT A.UserCd, A.UserType, A.AddressLine1, A.AddressLine2, A.AddressLine3, A.AtPost, A.Tehsil, A.District, A.StateCd, A.PinCode, A.PhoneNo,IF(A.UserType= 'Customer', B.Descript, C.Descript) AS Name  
	FROM so_user_address_details A 
	LEFT JOIN so_customer_m B ON (A.UserType= 'Customer' AND A.UserCd = B.CustomerCd)
	LEFT JOIN so_subdealer_m C ON (A.UserType!= 'Customer' AND A.UserCd = C.Idsubdealer) WHERE ".$whr." ORDER BY  A.UserType ";
	$returnData = $this->execSelectQuery($sql);
	return $returnData;
}


public function editAddressDetails($data){
	$UserCd 		= $data['UserCd']; 
	$AddressLine1 	= $data['AddressLine1']; 
	$AddressLine2 	= $data['AddressLine2']; 
	$AddressLine3 	= $data['AddressLine3']; 
	$AtPost 	= $data['AtPost']; 
	$Tehsil 	= $data['Tehsil']; 
	$District 	= $data['District']; 
	$StateCd 	= $data['StateCd']; 
	$PinCode 	= $data['PinCode']; 
	$PhoneNo 	= $data['PhoneNo']; 
	
	$sql = "UPDATE so_user_address_details SET AddressLine1 = '%s', AddressLine2 = '%s', AddressLine3='%s', AtPost='%s', Tehsil='%s', District='%s', StateCd='%s', PinCode='%s', PhoneNo='%s' WHERE UserCd = '%s'";
	$inputArr	= array();
	$inputArr	= array($AddressLine1,$AddressLine2,$AddressLine3,$AtPost,$Tehsil,$District,$StateCd,$PinCode,$PhoneNo,$UserCd);
	 $sql		= vsprintf($sql,$inputArr);
	$returnData	= $this->execUpdateQuery($sql);
	$rowaffected = $this->objDBQuery->objDBConnect->affected_rows;
		if($rowaffected >0){
			$msg = array("status" => "success", "message" => "Address Updated successfully");
			return $msg;
		}else{
			$msg = array("status" => "error", "message" => "Address Updatation Failed");
			return $msg;
		}
}

///====================================Postal Address//////




public function getNoOfRE11($IdExpDet){
	$sql = "SELECT A.RE11No,A.MagazineCd,B.MagazineLicNo  FROM so_expdet_magazine A INNER JOIN  so_magazine_m B ON A.MagazineCd = B.MagazineCd  WHERE IdExpDet = {$IdExpDet}";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}


public function getRe11Data($IdExpDet,$MagazineCd){
	$sql = "SELECT RE11No, RE11Check, RE11Date, RE11Company, RE11MagazineLicNo, RE11Product, RE11Qty, RE11DigitalSignSingleSide, RE11DigitalSignDoubleSide  FROM so_expdet_re11_checklist WHERE IdExpDet = {$IdExpDet} AND  MagazineCd = {$MagazineCd}";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}


public function updatePORE11check($data){
	$queryInsert = "INSERT INTO so_expdet_re11_checklist(IdExpDet,MagazineCd, RE11No,RE11Check,RE11Date, RE11Company, RE11MagazineLicNo,RE11Product,  RE11Qty, RE11DigitalSignSingleSide,RE11DigitalSignDoubleSide,TransUserName) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s') ";
	
	$queryUpdate = "UPDATE so_expdet_re11_checklist SET RE11Check='%s',RE11Date= '%s', RE11Company= '%s',  RE11MagazineLicNo= '%s', RE11Product= '%s', RE11Qty= '%s',RE11DigitalSignSingleSide='%s', RE11DigitalSignDoubleSide= '%s' WHERE IdExpDet= '%s' AND  MagazineCd= '%s'";
	
	$IdExpDet 		= $data['IdExpDet'];
	$LastSubNo 		= $data['LastSubNo'];
	$TranUserName 	= $_SESSION['UserName'];
	for($curRow=1;$curRow<=$LastSubNo;$curRow++){
		$RE11No 	 = $data['RE11No'.$curRow.'_1'];
		$MagazineCd  = $data['MagazineCd'.$curRow.'_1'];
		$TotAmt  = isset($data['TotAmt'.$curRow.'_1'])?($data['TotAmt'.$curRow.'_1']):0;
		$Company 	 = isset($data['CheckRE11Company_'.$curRow])?1:0;
		$RE11Check 	 = isset($data['CheckRE11Check_'.$curRow])?1:0;
		$Re11Date 	 = isset($data['CheckRE11Date_'.$curRow])?1:0;
		$Product 	 = isset($data['CheckRE11Product_'.$curRow])?1:0;
		$Magazine 	 = isset($data['CheckRE11MagazineLic_'.$curRow])?1:0;
		$Re11Qty 	 = isset($data['CheckRE11Qty_'.$curRow])?1:0;
		$DigitalSign = isset($data['CheckRE11DigiSign_'.$curRow])?1:0;
		$DigitalSignSingleSide = isset($data['CheckRE11DigiSignSinle_'.$curRow])?1:0;
		
		$queryCheck = "SELECT COUNT(*) AS Total FROM so_expdet_re11_checklist WHERE IdExpDet= '$IdExpDet' AND  MagazineCd= '$MagazineCd'";
		$result  	= $this->execSelectQuery($queryCheck);
		if($result[0]['Total']==0 && $MagazineCd!='' && $TotAmt!=0 ){
			$inputArr = array();
			$inputArr = array($IdExpDet,$MagazineCd,$RE11No,$RE11Check,$Re11Date,$Company,$Magazine,$Product,$Re11Qty,$DigitalSignSingleSide,$DigitalSign,$TranUserName);
			 $sql      = vsprintf($queryInsert,$inputArr);
			$queryResult= $this->execUpdateQuery($sql);	
		}else{
			$inputArr = array();
			$inputArr = array($RE11Check,$Re11Date,$Company,$Magazine,$Product,$Re11Qty,$DigitalSignSingleSide,$DigitalSign,$IdExpDet,$MagazineCd);
			$sql      = vsprintf($queryUpdate,$inputArr);
			$queryResult= $this->execUpdateQuery($sql);
		}
		/*if($RE11Check=='1' && $Re11Date=='1' &&  $Company =='1' && $Magazine=='1' && $Product=='1' && $Re11Qty =='1' && $DigitalSignSingleSide =='1' && $DigitalSign =='1') {
			$queryUpdateExpdet = "UPDATE so_expdet  SET RE11CheckStatus ='%s' where IdExpDet= '%s'";
			$inputArr = array('1', $IdExpDet);
			 $sql      = vsprintf($queryUpdateExpdet,$inputArr);
			$queryResult= $this->execUpdateQuery($sql);
		}
		else{
			$queryUpdateExpdet = "UPDATE so_expdet  SET RE11CheckStatus ='%s' where IdExpDet= '%s'";
			$inputArr = array('0', $IdExpDet);
			 $sql      = vsprintf($queryUpdateExpdet,$inputArr);
			$queryResult= $this->execUpdateQuery($sql);
		}
		*/		
	}
	$result  	= $this->updatePORE11Totalcheck($IdExpDet);
	
}

public function updatePORE11Totalcheck($IdExpDet){
	$sql ="SELECT COUNT(IdExpDet) AS TotPO FROM so_expdet_re11_checklist WHERE IdExpDet = '".$IdExpDet ."'";
	$returnData	= $this->execSelectQuery($sql);
	
	$sqlTot = "SELECT  count(*) as TotCorrectEntry FROM so_expdet_re11_checklist WHERE RE11Check=1 AND RE11Date=1 AND  RE11Company=1 AND  RE11MagazineLicNo=1 AND  RE11Product=1 AND  RE11Qty=1 AND RE11DigitalSignSingleSide=1 AND  RE11DigitalSignDoubleSide=1 AND IdExpDet = '".$IdExpDet ."'";
	$returnDataTot	= $this->execSelectQuery($sqlTot);
	
	if($returnData[0]['TotPO'] == $returnDataTot[0]['TotCorrectEntry']){
		 $sql ="UPDATE  so_expdet SET RE11CheckStatus ='1' WHERE  IdExpDet = '".$IdExpDet ."'";
		$queryResult= $this->execUpdateQuery($sql);
	}
	/* not approved By Despatch Person and Sir 01-10-2016
	elseif($returnDataTot[0]['TotCorrectEntry'] >0 && $returnData[0]['TotPO'] > $returnDataTot[0]['TotCorrectEntry'] ){
		$sql ="UPDATE  so_expdet SET RE11CheckStatus ='2' WHERE  IdExpDet = '".$IdExpDet ."'";
		$queryResult= $this->execUpdateQuery($sql);
	}*/
	else {
		$sql ="UPDATE  so_expdet SET RE11CheckStatus ='0' WHERE  IdExpDet = '".$IdExpDet ."'";
		$queryResult= $this->execUpdateQuery($sql);
		
	}
}



public function get_RE11_n_PO_details_magazine($IdExpDet){
	$sql 	 = " SELECT A.RE11No, A.MagazineCd, B.MagazineLicNo  FROM so_expdet_magazine A JOIN so_magazine_m B ON A.MagazineCd = B.MagazineCd WHERE A.IdExpDet = '$IdExpDet' GROUP BY A.RE11No";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function get_RE11_n_PO_details($IdExpDet, $MagazineCd){
	$sql 	 = " SELECT A.RE11No, B.RE11Check, B.RE11Company, B.RE11Date, B.RE11Product, B.RE11MagazineLicNo, B.RE11Qty, B.RE11DigitalSignDoubleSide, B.RE11DigitalSignSingleSide,C.MagazineLicNo FROM so_expdet_magazine A LEFT JOIN so_expdet_re11_checklist B ON A.IdExpDet = B.IdExpDet LEFT JOIN so_magazine_m C ON A.MagazineCd = C.MagazineCd WHERE B.IdExpDet = '$IdExpDet' AND B.MagazineCd = '$MagazineCd'  GROUP BY A.RE11No";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}



//==========================PDF Parser =======================


public function pdfParserTxt($file){
	//print_r($file); 
	$filename			= $_FILES['file']['name'].".txt";
	$target_path 		= 'upload/pdfToText/PDF/';
	$target_path 		= $target_path.$filename;
	$newfile ="";
	if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
		include './Application/pdfparser/vendor/autoload.php';
		$path 		= './upload/pdfToText/PDF/';
		$file 		= $path.$filename;
		$parser 	= new \Smalot\PdfParser\Parser();
		$pdf    	= $parser->parseFile($file);
		$text 	= $pdf->getText();
		
		$filename 	= preg_replace('/\.' . preg_quote(pathinfo($filename, PATHINFO_EXTENSION), '/') . '$/', '', $filename);
		$dest 		= './upload/pdfToText/TEXT/'.$filename;
		$newfile 	= fopen($dest.'.txt', "w");
		fwrite($newfile, $text); 
	}
	return $newfile;
}

//============================End of PDF Parser ============================



public function importPESODataFile($srcFile, $tableName, $row1Status=1) {

$handle = fopen($srcFile, "r");
if ($handle) {
	$onlyfiletxt = fread($handle, filesize($srcFile));
    $arrSrcData = explode("\r\n", fread($handle, filesize($srcFile)));
}
//print_r ($onlyfiletxt);
/*$indentarray = explode("/", trim($arrSrcData[6]));
//echo "<br/>RE-11 No ".$indentarray[2];
$indentdatearray = explode(":", trim($arrSrcData[7]));
//echo "<br/>RE-11 Date ".$indentdatearray[1];
$placeofmagazinearray = explode(":", trim($arrSrcData[8]));
//echo "<br/>Place Of Magazine ". trim($placeofmagazinearray[1]);
//echo "<br/>Company Name ".trim($arrSrcData[10]).trim($arrSrcData[11]);
*/
$arr = array($onlyfiletxt);
//$matches  = preg_grep("/Sr\\. No\\. Explosive Name\\(Brand ID\\) Class Division Quantity Unit\\r\\n(\\d.*\\r\\n)*/", $arr);
//$matches  = preg_grep("/Sr. No. Explosive Name(Brand ID) Class Division Quantity Unit/", $arr);
//print_r ($matches); 


$subject = $onlyfiletxt;
$pattern = "/Sr\\. No\\. Explosive Name\\(Brand ID\\) Class Division Quantity Unit\\r\\n(\\d.*\\r\\n)*/";
preg_match($pattern, $subject, $matches);
echo '<pre>';
print_r($matches);

//return $arrSrcData;
}


public function upadtePenaltysubdealerWrk(){
	$curMonth	= date('m');
	$curYear	= date('Y');
	
	$curLogYear	= $curYear . '-' . ($curYear+1);		// eg 2011-2012
	$curLogMonth= (($curMonth+8) % 12) + 1;				
	
	$first_day_this_month = '2016-'.sprintf("%02d", ($curMonth+1)).'-01';
	$last_day_this_month  = date('Y-m-t', strtotime($first_day_this_month));

	$query0 = "Delete FROM so_subdealer_m_penalty_wrk WHERE 1";
	$result0 = $this->execUpdateQuery($query0);
    
	$query = "SELECT IdSubdealer FROM so_subdealer_m WHERE stateCd IN ('MH', 'MP')  AND IsActive=1 AND  PenaltyFromDate != '".$first_day_this_month."' and PenaltyToDate != '".$last_day_this_month."' AND IdSubdealer NOT IN (SELECT SubdealerCd FROM so_subdealer_target_trade WHERE month='".$curLogMonth."' AND Year = '".$curYear."' AND YMFlag = 1 )";
   $result = $this->execSelectQuery($query);
   
   foreach($result AS $cur){
	 $IdSubdealer = $cur['IdSubdealer'];
	 
		$queryInsert = "INSERT INTO so_subdealer_m_penalty_wrk(IdSubdealer, Month, Year, DateFrom, DateTo, CreatedDateTime) VALUES ('%s','%s','%s','%s','%s','%s')";
	
		$inputArr = array($IdSubdealer,$curLogMonth,$curYear,$first_day_this_month,$last_day_this_month, date('Y-m-d H:i:s'));
		$sql      = vsprintf($queryInsert,$inputArr);
		$queryResult= $this->execUpdateQuery($sql);	
	}
	 
   }   

public function upadtePenaltysubdealerLog_M(){
	$curMonth	= date('n');
	$curYear	= date('Y');
	
	$curLogYear	= $curYear . '-' . ($curYear+1);		// eg 2011-2012
	$curLogMonth= (($curMonth+8) % 12) + 1;				

	$first_day_this_month = '2016-'.sprintf("%02d", ($curMonth+1)).'-01';
	$last_day_this_month  = date('Y-m-t', strtotime($first_day_this_month));
	
	$query0 = "SELECT * FROM so_subdealer_m_penalty_wrk";
	$result0 = $this->execSelectQuery($query0);
  
   foreach($result0 AS $cur){
	 $IdSubdealer = $cur['IdSubdealer'];
		$queryUpdate = "Update so_subdealer_m SET IsPenalty='1', PenaltyFromDate='".$first_day_this_month."', PenaltyToDate ='".$last_day_this_month."' where IdSubdealer='".$IdSubdealer."'";
		$sql     	= vsprintf($queryUpdate,$inputArr);
		$queryResult= $this->execUpdateQuery($sql);	
		
		$queryInsert = "INSERT INTO so_subdealer_m_penaltylog(IdSubdealer, Month, Year, DateFrom, DateTo, CreatedDateTime) VALUES ('%s','%s','%s','%s','%s','%s')";
	
		$inputArr = array($IdSubdealer,$curLogMonth,$curLogYear,$first_day_this_month,$last_day_this_month, date('Y-m-d H:i:s'));
		$sql      = vsprintf($queryInsert,$inputArr);
		$queryResult= $this->execUpdateQuery($sql);	
	}
	 
   }   

 //=============================Template -> SalePlanning ================================
 
 
 public function EmailSendTofinalDispatch($reportData) {
	$curRow=1;
	//  $curEMailId = 'websupport@solargroup.com;rahul@solargroup.com;solartrade@solargroup.com';
	//	$EMailIdBCC ='b2b.solarexplosives@gmail.com';
	$curEMailId = 'websupport@solargroup.com'; //$EMailId;
	$EMailIdBCC = 'websupport@solargroup.com';
	echo $eMailBody =$reportData;
	$objSolarMailer = new solarMailer();
	$objSolarMailer->IsHTML(true);  
	$returnData = $objSolarMailer->sendSolarMail($curEMailId, 'Daily Dispatch Report', $eMailBody, '', $EMailIdBCC, True);
	return $returnData;

}

//====================User Authentication Control ==========================

public function insertAccessControll($arr){
	$queryInsert = " INSERT IGNORE INTO b2b_solar_sc.so_access_control (Action, Admin) VALUES ('%s','%s')";	
	foreach($arr as $CurData => $value){
		$inputArr = array($value,1);
		$sql		= vsprintf($queryInsert,$inputArr);
		$returnData	= $this->execUpdateQuery($sql);
	}
}

public function getAccessControll(){
	$sql = " SELECT * FROM b2b_solar_sc.so_access_control ";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function getUserType(){	
	$sql = " SELECT * FROM so_user_type_m ";
	$returnData	= $this->execSelectQuery($sql);
	return $returnData;
}

public function checkAccess($action){	
	$sql = " SELECT COUNT(*) As Count FROM b2b_solar_sc.so_access_control WHERE Action = '".$action."'   AND ".$_SESSION['UserTypeName']." ='1' ";
	$returnData	= $this->execSelectQuery($sql);
	if($returnData[0]['Count'] == 1){
		return 1;
	}else{
		return 0;
	}

}

public function UpdateAccessControll($Descript, $Id, $value,$stat){
	if($stat == 1 ){    // 1 == Update Authority ....... 2 == update menu name 
		$sql = " UPDATE b2b_solar_sc.so_access_control SET ".$Descript." = '".$value."'  WHERE  Id = ".$Id ;
	}else if($stat == 0 ){
		$sql = " UPDATE b2b_solar_sc.so_access_control SET Menu = '".$Descript."'   WHERE  Id = ".$Id ;
	}else{
		$sql = " UPDATE b2b_solar_sc.so_access_control SET SubMenu = '".$Descript."'   WHERE  Id = ".$Id ;	
	}
	$returnData	= $this->execUpdateQuery($sql);
	if($returnData == null){
		return 0;
	}else{
		return 1 ;
	}
}


}		// class solarCustomer
?>
