<?php
if (!class_exists("phpmailer")) {
require_once('./../../../classes/b2b.class.mailer.php');
}
class SalePlanningClass {
	
	const DTUserM 		= 'b2b_solar_sc.so_user_m'; 
	const DTUserTypeM 	= 'b2b_solar_sc.so_user_type_m';
	const DTSectorM 	= 'b2b_solar_sc.so_sector_m';

	private 	$objDBQuery;
	private		$dbName;
	private		$classBusiLogic;
		
	public function __construct($objDBQuery, $dbName, $classBusiLogic) {
		$this->objDBQuery			= $objDBQuery;
		$this->dbName				= $dbName;
		$this->classBusiLogic		= $classBusiLogic;
		date_default_timezone_set('Asia/Kolkata');
	}

	public function getDailyStockList($search, $ListForMY) {
		$this->classBusiLogic->insertActivityLog("getDailyStockList",__Function__,array('Search'=>$search,'ListForMY'=>$ListForMY),"view Advance Daily Stock and Position List");
		$DTSAnsi	= preg_replace('/(\d{2})[-\/](\d{4})/', "$2-$1", $ListForMY) . '-01';
		$DTEAnsi	= $this->classBusiLogic->addDate($this->classBusiLogic->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->classBusiLogic->execSelectQuery($sql);
		return $returnData;
	}

	public function getSubdealerDealerItem() {
		$sql		= "SELECT * FROM so_target_item_group";
		$returnData	= $this->classBusiLogic->execSelectQuery($sql);
		return $returnData;
	}
	
	public function getDespPlanItem($CustomerCd, $Date, $StatusCd) {
		$inputArr 		= array($CustomerCd, $this->classBusiLogic->convertDate($Date,TRUE,1), $StatusCd);
		$paraString		= vsprintf("'%s', '%s', '%s'",$inputArr);
		$sql			= "call sp_getDespPlanItem(" . $paraString. ")";

		$preResultsAr = array();
		$returnData = $this->classBusiLogic->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 getDailySaleItem($CustomerCd, $Date, $IsHeaderOwn) {
		 $stmt           = "SELECT  A.ItemCd, IFNULL(IF(B.UOMType='W','Box',B.UOM),' ') AS UOM, B.ItemCtgCd as ItemCtg, IFNULL(B.ShortDescript,A.ItemCd)AS Item FROM so_customer_m_item_rate_type A INNER JOIN so_item_m B ON A.ItemCd=B.ItemCd
							WHERE A.CustomerCd='%s' AND A.IsSubdealerItem=1 AND B.AcceptDailyStock=1  ORDER BY  B.UOM DESC";
		$inputArr 		= array($CustomerCd);
		$sql		= vsprintf($stmt,$inputArr);
		$returnData = $this->classBusiLogic->execSelectQuery($sql,0, $preResultsAr);
		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->classBusiLogic->execSelectQuery($sql);
		return $returnData;
	}

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

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


	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;
	}
//=======================Stock  & Position=====================//
	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($postData) {
		parse_str($postData, $data);
		$this->classBusiLogic->insertActivityLog("insertDailyStockItem",__Function__,array($data),"insert Daily Stock and Position");
		$queryInsert	= $this->getDailyStockItemInsertQuery();
		$returnData		= '';
		$CustomerCd	= $data['StockCustomerCdInput'];
		$Date = $this->classBusiLogic->convertDate($data['StockDate'],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->classBusiLogic->execUpdateQuery($sql);
			
		}
		if (!$returnData) {
				$queryInsertFinalSale = "INSERT INTO `so_daily_stock`(`CustomerCd`, `Date`, `CreateDateTime`, `StatusCd`, `TransUserName`, `TransDateTime`) VALUES ('%s','%s','%s','%s','%s','%s')";
				$inputArr	= array($CustomerCd, $Date, date('Y-m-d H:i:s'), 'A', $_SESSION['UserName'],  date('Y-m-d H:i:s'));
				$sql		= vsprintf($queryInsertFinalSale , $inputArr);
				$returnFinalData	= $this->classBusiLogic->execUpdateQuery($sql);
			}
			if(!$returnFinalData){
				$returnData =1;
			}
			
			
			
	return $returnData;
	}
/*
	public function updateDailyStockItem($data) {
		
		$this->classBusiLogic->insertActivityLog("updateDailyStockItem",__Function__,array($data),"Update Daily Stock and Position");
		$queryInsert	= $this->getDailyStockItemInsertQuery();
		$queryUpdate	= $this->getDailyStockItemUpdateQuery();
		$queryDelete	= $this->getDailyStockItemDeleteQuery();
		$returnData		= '';

		$CustomerCd	= $data['StockCustomerCdInput'];
		$Date = $this->convertDate($data['StockDate'], 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;
			}
		}
			if (!$returnData) {
				$queryUpdateFinalSale = "UPDATE  so_daily_stock SET StatusCd = 'A' WHERE CustomerCd='%s' AND Date ='%s'";
				$inputArr	= array($CustomerCd, $Date);
				$sql		= vsprintf($queryUpdateFinalSale , $inputArr);
				$returnFinalData	= $this->classBusiLogic->execUpdateQuery($sql);
			}
			if(!$returnFinalData){
					$returnData =1;
				}
		
		return $returnData;
	}
*/

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

		$CustomerCd	= $data['StockCustomerCdInput'];
		$Date = $this->classBusiLogic->convertDate($data['StockDate'], 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->classBusiLogic->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->classBusiLogic->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->classBusiLogic->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->classBusiLogic->execUpdateQuery($sql);
				}				
			}
		}
		if (!$returnData) {
				$queryUpdateFinalSale = "UPDATE  so_daily_stock SET StatusCd = 'A' WHERE CustomerCd='%s' AND Date ='%s'";
				$inputArr	= array($CustomerCd, $Date);
				$sql		= vsprintf($queryUpdateFinalSale , $inputArr);
				$returnFinalData	= $this->classBusiLogic->execUpdateQuery($sql);
			}
				if(!$returnFinalData){
					$returnData =1;
				}
		return $returnData;
	}
//===============================End of Stock & Position======================//

// DespatchPlanItem (Grid-2) ------------------------------------------------------
	public function getDespPlanItemData($cat, $CustomerCd,$Date){
		$Date = $this->classBusiLogic->convertDate($Date,TRUE,1);
		$IsHeaderOwn = 1;
		$ItemList  = $this->getDailySaleItem($CustomerCd, $Date, $IsHeaderOwn);
		$itemAccessorylist = array();
		$itemExplosivelist = array();
		foreach ($ItemList as $key => $value) {
			if($value['ItemCtg'] == '6-3'){
				 array_push($itemAccessorylist,$value['ItemCd']);
			}else{
				 array_push($itemExplosivelist,$value['ItemCd']);
			}
		}
			$sql = " SELECT A.IdSubdealer,IFNULL(B.Descript,A.IdSubdealer) AS Subdealer, ";
			if($cat =='1'){
				$itemList = $itemExplosivelist;
			}else{
				$itemList = $itemAccessorylist;
			}
			foreach( $itemList as $index=>$value){
				$row  	 = str_replace('.','',$value);
				$sql 	.= "max(case when A.ItemCd  ='".$row."' then A.DespPlanQty end) as '".$row."', ";
			}
			$sql 	.= " DATE_FORMAT(A.Date,'%d-%m-%Y') AS Date FROM so_desp_plan_item A INNER JOIN so_subdealer_m B ON A.IdSubdealer = B.IdSubdealer WHERE A.CustomerCd = '".$CustomerCd."' AND A.Date = '$Date'  GROUP BY A.IdSubdealer order by A.ItemCd";
			$returnData  = $this->classBusiLogic->execSelectQuery($sql);
			return $returnData;
	}


	public function getDespPlanItemInsertQuery() {
		$sql = "INSERT IGNORE  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 addDispatchPlan($postData) {
		parse_str($postData, $data);
		$this->classBusiLogic->insertActivityLog("addDispatchPlan",__Function__,array($data),"Insert  Daily Dispatch & planning");
		$queryInsert	= $this->getDespPlanItemInsertQuery();
		$category       = $data['category'];
		if($category =='Explo'){
			$ItemArr 		= explode(',', $data['ItemCdExplo']);	
		}else{
			$ItemArr 		= explode(',', $data['ItemCdAcces']);	
		}
		
		$ItemCount 		= count($ItemArr);
		$returnData		= '';

		$CustomerCd	= $data['CustomerCdInput'];
		$Date = $this->classBusiLogic->convertDate($data['Date'],TRUE,1);
		for ($curRowNo=1; $curRowNo<=$data['LastDispatchRow']; $curRowNo++) {
			$IdSubdealer	= (int)$data['IdSubdealer1_'.$curRowNo];
			for ($curItemCdIndex=0; $curItemCdIndex<$ItemCount; $curItemCdIndex++) {
				$ItemCd = $ItemArr[$curItemCdIndex];
				$DespPlanQty = (int)$data[$ItemCd.'_'.$curRowNo];	// $data['200001182_1']
				if ($DespPlanQty>0) {
					$inputArr	= array($CustomerCd, $Date, $IdSubdealer, $ItemCd, $DespPlanQty);
					$sql		= vsprintf($queryInsert, $inputArr);
					$returnData	= $this->classBusiLogic->execUpdateQuery($sql);
				}
					//return $returnData;	
			}
			$sqlSubd 		= " SELECT IFNULL(Descript,IdSubdealer) AS Subdealer, TelNo1, EMailId from so_subdealer_m where IdSubdealer='$IdSubdealer'";
			$returnDataSubd	= $this->classBusiLogic->execSelectQuery($sqlSubd);
			$SubdealerName 	= $returnDataSubd[0]['Subdealer'];
			$SubdealerTelNo = $returnDataSubd[0]['TelNo1'];
			$SubdealerEMailId = $returnDataSubd[0]['EMailId'];
					
			$sqlCust 		= " SELECT IFNULL(Descript,CustomerCd) AS Customer, TelNo, EMailId from so_customer_m where CustomerCd='$CustomerCd'";
			$returnDataCust	= $this->classBusiLogic->execSelectQuery($sqlCust);
			$CustomerName 	= $returnDataCust[0]['Customer'];
			$CustomerEMailId 	= $returnDataCust[0]['EMailId'];
			
			$message = $this->SubdealerPlaningSMS($CustomerName,$SubdealerName, $data, $curRowNo, $SubdealerTelNo);
			$message = $this->DealerSubdelaerUnderPlanningEmail($CustomerName,$SubdealerName, $data, $curRowNo, $SubdealerEMailId, $CustomerEMailId);
		}
		if($returnData == null){
			return 1;	
		}else{
			return 0;
		}
	}


	public function updateDispatchPlan($postData){
		parse_str($postData, $data);
		$this->classBusiLogic->insertActivityLog("updateDispatchPlan",__Function__,array($data),"Update  Daily Dispatch & planning");
		$queryInsert	= $this->getDespPlanItemInsertQuery();
		$queryUpdate	= $this->getDespPlanItemUpdateQuery();
		$queryDelete	= $this->getDespPlanItemDeleteQuery();
		$IdSubdealer  	= $data['EditDispatchPlan-IdSubdealer'];
		$CustomerCd 	= $data['CustomerCd'];
		$Date   		= $this->classBusiLogic->convertDate($data['EditDispatchPlan-date'],TRUE,1);
		for($i=0;$i<$data['EditDispatchPlan-TotalItem'];$i++){
				$ItemCd 	= $data['EditDispatchPlan-ItemCd-'.$i];
				$DespPlanQty	= $data['Item-'.$i];
				$queryCheck = "SELECT * FROM so_desp_plan_item WHERE CustomerCd='$CustomerCd ' AND Date='$Date ' AND IdSubdealer='$IdSubdealer' AND ItemCd='$ItemCd' ";
				$result  	= $this->classBusiLogic->execSelectQuery($queryCheck);
				if(count($result) > 0){	
					if(($DespPlanQty == 0) || ($DespPlanQty=='')){
						$inputArr	= array($CustomerCd, $Date, $IdSubdealer, $ItemCd);
						$sql		= vsprintf($queryDelete, $inputArr);
						$returnData	= $this->classBusiLogic->execUpdateQuery($sql);
					}else{						
						$inputArr	= array($DespPlanQty,$CustomerCd, $Date, $IdSubdealer, $ItemCd);
						$sql		= vsprintf($queryUpdate, $inputArr);
						$returnData	= $this->classBusiLogic->execUpdateQuery($sql);
					}
				}else{
					if(($DespPlanQty == 0) || ($DespPlanQty=='')){
						continue;
					}
					$inputArr	= array($CustomerCd, $Date, $IdSubdealer, $ItemCd, $DespPlanQty);
					$sql		= vsprintf($queryInsert, $inputArr);
					$returnData	= $this->classBusiLogic->execUpdateQuery($sql);
				}
		}
		if($returnData == null){
			return  1;
		}else{
			return 0;
		}
	}


//============= Stock Sale ===============================================

	public function getAdvanceDispatchPlan($cat, $CustomerCd,$Date ){
		$Date =  $this->classBusiLogic->convertDate($Date,TRUE,1); 
		$ItemList =[];
		$ItemList  = $this->getDailySaleItem($CustomerCd, $Date, 1);
		$itemAccessorylist = array();
		$itemExplosivelist = array();
		foreach ($ItemList as $key => $value) {
			if($value['ItemCtg'] == '6-3'){
				 array_push($itemAccessorylist,$value['ItemCd']);
			}else{
				 array_push($itemExplosivelist,$value['ItemCd']);
			}
		}
			$sql = " SELECT A.IdSubdealer,IFNULL(B.Descript,A.IdSubdealer) AS Subdealer, B.City, B.SubdealerCtgCd as Tier,	 ";
			if($cat =='Explo'){
				$itemList = $itemExplosivelist;
			}else{
				$itemList = $itemAccessorylist;
			}
			foreach( $itemList as $index=>$value){
				$row  	 = str_replace('.','',$value);
				$sql 	.= "IFNULL(max(case when A.ItemCd  ='".$row."' then A.DespPlanQty end),0) as '".$row."', ";
			}
			$sql 	.= " DATE_FORMAT(A.Date,'%d-%m-%Y') AS Date FROM so_desp_plan_item A INNER JOIN so_subdealer_m B ON A.IdSubdealer = B.IdSubdealer WHERE A.CustomerCd = '".$CustomerCd."' AND A.Date = '$Date' GROUP BY A.IdSubdealer";
		
			$returnData  = $this->classBusiLogic->execSelectQuery($sql);
			return $returnData;
	}

	public function getTodayOwnUseSaleQty($CustomerCd, $Date, $itemCd) {    // if IsHeaderOwn is 1 = Explo and 2 =Acess
		$sql = " SELECT IFNULL(Sum(SaleQty), 0) as SaleQty FROM so_daily_sale_item  WHERE CustomerCd = '".$CustomerCd."' AND  Date = '$Date' and ItemCd = '".$itemCd."'";
		$returnData  = $this->classBusiLogic->execSelectQuery($sql);
		return $returnData;
	}

	public function getSaleItemData($CustomerCd, $Date, $IsHeaderOwn, $IsDispatched) {    // if IsHeaderOwn is 1 = Explo and 2 =Acess
		$Date = $this->classBusiLogic->convertDate($Date,TRUE,1);
		$ItemList =[];
		$ItemList  = $this->getDailySaleItem($CustomerCd, $Date, 1);
		$itemAccessorylist = array();
		$itemExplosivelist = array();
		foreach ($ItemList as $key => $value) {
			if($value['ItemCtg'] == '6-3'){
				 array_push($itemAccessorylist,$value['ItemCd']);
			}else{
				 array_push($itemExplosivelist,$value['ItemCd']);
			}
		}
		  $sql = " SELECT 0 AS  DailySaleItemId, A.IdSubdealer,IFNULL(B.Descript,A.IdSubdealer) AS Subdealer, B.City, B.SubdealerCtgCd as Tier, A.RE12No, DATE_FORMAT(A.RE12Date,'%d-%m-%Y') AS RE12Date, A.VanNo, A.DriverName, A.MobileNo, IsDispatched, ";
		if($IsHeaderOwn =='1'){
			$itemList = $itemExplosivelist;
		}else{
			$itemList = $itemAccessorylist;
		}
		foreach( $itemList as $index=>$value){
			$row  	 = str_replace('.','',$value);
			$sql 	.= "IFNULL(max(case when A.ItemCd  ='".$row."' then A.SaleQty end),0) as '".$row."', ";
		}
		
		$sql 	.= " DATE_FORMAT(A.Date,'%d-%m-%Y') AS Date FROM so_daily_sale_item A INNER JOIN so_subdealer_m B ON A.IdSubdealer = B.IdSubdealer WHERE A.CustomerCd = '".$CustomerCd."' AND  A.Date = '$Date' AND IsDispatched=  '$IsDispatched' GROUP BY A.VanNo, A.IdSubdealer, A.RE12No Order By A.VanNo ";

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

	public function getStockNSaleItemInsertQuery() {
		$sql = "INSERT  INTO so_daily_sale_item (CustomerCd, Date, IdSubdealer,RE12No, ItemCd, RE12Date, VanNo, SaleQty)"
			. " VALUES ('%s', '%s', %s, '%s', '%s', '%s', '%s', '%s');";
		return $sql ;
	}

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

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


	public function addStockNSale($postData) {
		parse_str($postData, $data);
		$returnString  	= '';
		$this->classBusiLogic->insertActivityLog("insertDailySaleItem",__Function__,array($data),"insert Advance Daily Sales ");
		//print_r($data);
		$queryInsert	= $this->getStockNSaleItemInsertQuery();
		$ItemArr 		= explode(',', $data['ItemCdStrForSaleQty']);	
		$ItemCount 		= count($ItemArr);
		$CustomerCd		= $data['SaleCustomerCdInput'];
		$salecategory	= $data['salecategory'];
		$Date = $this->classBusiLogic->convertDate($data['SaleDate'],TRUE,1);
		if($salecategory =='Explo'){
			$ItemArr = explode(',', $data['ItemCdSaleExplo']);	
		}
		else{
			$ItemArr = explode(',', $data['ItemCdSaleAcces']);	 
		}
		$ItemCount = count($ItemArr);
		$returnData		= '';
		for ($curRowNo=1; $curRowNo<=$data['LastSaleRow']; $curRowNo++) {
			$IdSubdealer	= (int)$data['IdSubdealer1_'.$curRowNo];
			$SelectSale	= (int)@$data['SelectSale1_'.$curRowNo];
			$RE12No	= (int)$data['re12No_'.$curRowNo];
			$RE12Date = $this->classBusiLogic->convertDate($data['re12Date_'.$curRowNo],TRUE,1);
			//$RE12Date	= $data['re12Date_'.$curRowNo];
			$VanNo	=  $data['VanNo_'.$curRowNo];
			for ($curItemCdIndex=0; $curItemCdIndex<$ItemCount; $curItemCdIndex++) {
				$ItemCd = $ItemArr[$curItemCdIndex];
				 $SaleQty = (int)$data[$ItemCd.'_'.$curRowNo];	// $data['200001182_1']
				if ($SaleQty>0 && $SelectSale==1 && $VanNo !='') {
					$sqlcheck  = " SELECT COUNT(*) AS total FROM so_daily_sale_item WHERE CustomerCd='".$CustomerCd."' AND Date='".$Date."' AND IdSubdealer='".$IdSubdealer."' AND ItemCd='".$ItemCd."'  and RE12No ='".$RE12No."' "; 
					$result  = $this->classBusiLogic->execSelectQuery($sqlcheck);
					if($result[0]['total'] == 0){
						$inputArr	= array($CustomerCd, $Date, $IdSubdealer, $RE12No, $ItemCd, $RE12Date, $VanNo, $SaleQty);
						$sql		= vsprintf($queryInsert, $inputArr);
						
						$returnData	= $this->classBusiLogic->execUpdateQuery($sql);
						if ($returnData) return $returnData;
					}else{
						$returnString .=  ','.$RE12No;
					}
				}
			}
		}
		if($returnString == null){
			return 1;				
		}else{
			$response =   array('status'=>'Error', 'msg'=>" Duplicated  Entry for RE-12 No : ". ltrim($returnString,','));	
			return $response;
		}	
	}





	public function updateSaleItemData($postData){
		parse_str($postData, $data);
		$this->classBusiLogic->insertActivityLog("updateSaleItemData",__Function__,array($data),"Update Advance Daily Sales ");
		$queryInsert	= $this->getStockNSaleItemInsertQuery();
		$queryUpdate	= $this->getStockNSaleItemUpdateQuery();
		$queryDelete	= $this->getStockNSaleItemDeleteQuery();
		$IdSubdealer  	= $data['EditSaleList-SaleIdSubdealer'];
		$SaleRE12No  	= $data['EditSaleList-SaleRE12No'];
		$SaleRE12Date  	= $data['EditSaleList-SaleRE12Date'];
		$SaleVanNo  	= $data['EditSaleList-SaleVanNo'];
		$CustomerCd 	= $data['CustomerCd'];
		$DailySaleItemId 	= $data['EditSaleList-DailySaleItemId'];
		$Date   		= $this->classBusiLogic->convertDate($data['EditSaleList-Saledate'],TRUE,1);
		
		for($i=0;$i<$data['EditSaleList-TotalItem']; $i++){
				$ItemCd 	= $data['EditSaleList-ItemCd-'.$i];
				$SaleQty	= $data['Item-'.$i];
				$queryCheck = "SELECT * FROM so_daily_sale_item WHERE CustomerCd='$CustomerCd' AND Date='$Date' AND IdSubdealer='$IdSubdealer' 
				AND ItemCd='$ItemCd' AND RE12No ='$SaleRE12No' ";
				$result  	= $this->classBusiLogic->execSelectQuery($queryCheck);
				if(count($result) > 0){	
					if(($SaleQty == 0) || ($SaleQty=='')){
						$inputArr	= array($CustomerCd, $Date, $IdSubdealer, $ItemCd, $SaleRE12No);
						$sql		= vsprintf($queryDelete , $inputArr);
						$returnData	= $this->classBusiLogic->execUpdateQuery($sql);
					}else{ 
						if($SaleVanNo !=''){
							$inputArr	= array($SaleVanNo, $SaleQty, $CustomerCd, $Date, $IdSubdealer, $ItemCd, $SaleRE12No );
							$sql		= vsprintf($queryUpdate, $inputArr);
							$returnData	= $this->classBusiLogic->execUpdateQuery($sql);
						}
					}
				}else{
					if(($SaleQty == 0) || ($SaleQty=='')){
						continue;
					}
					$inputArr	= array($CustomerCd, $Date, $IdSubdealer, $SaleRE12No, $ItemCd, $SaleRE12Date, $SaleVanNo, $SaleQty);
					$sql		= vsprintf($queryInsert, $inputArr);
					$returnData	= $this->classBusiLogic->execUpdateQuery($sql);
				}
		}
		if($returnData == null){
			return  1;
		}else{
			return 0;
		}
	}

	public function DeleteStockNSaleData($CustomerCd,$IdSubdealer, $Date, $RE12No, $RE12Date, $VanNo ){
		$this->classBusiLogic->insertActivityLog("DeleteStockNSaleData",__Function__,array('CustomerCd'=>$CustomerCd, 'IdSubdealer'=>$IdSubdealer, 'Date'=>$Date, 'RE12No'=>$RE12No, 'RE12Date'=>$RE12Date, 'VanNo'=>$VanNo ),"Delete Advance Daily Sales ");
		$queryDelete	= "DELETE FROM so_daily_sale_item WHERE CustomerCd='%s' AND  IdSubdealer='%s' AND Date='%s'  AND RE12No='%s' and RE12Date ='%s' and  VanNo='%s'";
		$Date= $this->classBusiLogic->convertDate($Date,TRUE,1);
		$RE12Date= $this->classBusiLogic->convertDate($RE12Date,TRUE,1);
		$inputArr	= array($CustomerCd, $IdSubdealer, $Date, $RE12No, $RE12Date, $VanNo);
		$sql		= vsprintf($queryDelete , $inputArr);
		$returnData	= $this->classBusiLogic->execUpdateQuery($sql);
		return $returnData;
	}



//--------- Redilivery Master---------------------------

	public function getRedeliveryDriverM($userCd){
		if($userCd ==''){
			$whr = 1;
		}else{
			$whr = " A.CustomerCd = '".$userCd."'";
		}
		$sql   = "SELECT A.Id, A.DriverName, IFNULL(B.Descript,A.CustomerCd) AS Customer, A.MobileNo, A.LicNo, DATE_FORMAT(A.LicExpDate,'%d-%m-%Y') AS LicExpDate, A.AssociatedType, A.CustomerCd, A.IdSubdealer, A.EnterBy, A.TransDateTime  FROM so_redelivery_driver_m A INNER JOIN so_customer_m B ON A.CustomerCd = B.CustomerCd WHERE $whr ORDER BY A.CustomerCd  ";
		$returnData  = $this->classBusiLogic->execSelectQuery($sql);
		return $returnData;
	}

	public function insertDriverMasterQuery(){
		$sql = "INSERT INTO so_redelivery_driver_m ( DriverName, MobileNo, LicNo, LicExpDate, AssociatedType, CustomerCd, IdSubdealer, EnterBy,TransUserName) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s') ";
		return $sql;
	}

	public function updateDriverMasterQuery(){
		$sql = "UPDATE so_redelivery_driver_m SET DriverName='%s', MobileNo='%s', LicNo='%s', LicExpDate='%s',AssociatedType='%s',IdSubdealer='%s', EnterBy = '%s'WHERE Id='%s' ";
		return $sql;
	}

	public function insertDriverMaster($postData) {
		parse_str($postData, $data);
		$queryInsert 		= $this->insertDriverMasterQuery();
		$queryUpdate		= $this->updateDriverMasterQuery();
		$DriverName 		= $data['DriverName'];
		$DriverUniqueId  	= $data['DriverUniqueId'];
		$DriverMobNo 		= $data['DriverMobNo'];
		$DriverLicNo 		= $data['DriverLicNo'];
		$DriverEnterBy 		= $data['DriverEnterBy'];
		$DriverLicExpDate 	= $this->classBusiLogic->convertDate($data['DriverLicExpDate'],TRUE,1);
		$DriverAssociated 	= isset($data['DriverAssociated'])?$data['DriverAssociated']:'';
		$IdSubdealer 		= $data['DriverMasterIdSubdealer'];			 
		$CustomerCd 		= $data['CustomerCd'];
		if($DriverUniqueId >0){
			$inputArr 		= array($DriverName, $DriverMobNo, $DriverLicNo, $DriverLicExpDate,$DriverAssociated,$IdSubdealer,$DriverEnterBy ,$DriverUniqueId);
			$sql 			= vsprintf($queryUpdate, $inputArr);
		}else{
			$inputArr 		= array($DriverName, $DriverMobNo, $DriverLicNo, $DriverLicExpDate, $DriverAssociated,$CustomerCd,$IdSubdealer,$DriverEnterBy ,$_SESSION['UserName'] );
			$sql 			= vsprintf($queryInsert, $inputArr);
		}
		$returnData	= $this->classBusiLogic->execUpdateQuery($sql);
		if($returnData == null){
		return  1;
		}else{
			return 0;
		}
	}
//--------------------- van master ---------------
	public function getRedeliveryVanM($userCd){
		if($userCd ==''){
			$whr = 1;
		}else{
			$whr = " A.CustomerCd = '".$userCd."'";
		}
		$sql  		 = "SELECT A.Id,A.VanNo, A.LicHolderName, A.LicNo,DATE_FORMAT(A.LICExpDate,'%d-%m-%Y') AS LICExpDate, A.Dockey, A.AssociatedType, A.CustomerCd, A.IdSubdealer,A.EnterBy,DATE_FORMAT(A.TransDateTime,'%d-%m-%Y') AS TransDateTime,IFNULL(B.Descript,A.CustomerCd) AS Customer FROM so_redelivery_van_m A INNER JOIN so_customer_m B ON A.CustomerCd = B.CustomerCd  WHERE $whr  ORDER BY A.CustomerCd  ";
		$returnData  = $this->classBusiLogic->execSelectQuery($sql);
		return $returnData;
}

	public function insertVanMasterQuery(){
		$sql = "INSERT INTO so_redelivery_van_m ( VanNo, LicHolderName, LicNo,LICExpDate, Dockey, AssociatedType, CustomerCd,IdSubdealer, EnterBy) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s') ";
		return $sql;
	}

	public function updateVanMasterQuery(){
		$sql = "UPDATE so_redelivery_van_m SET VanNo='%s', LicHolderName='%s', LicNo='%s',LICExpDate='%s', Dockey='%s' ,AssociatedType='%s',IdSubdealer='%s',EnterBy='%s 'WHERE Id='%s' ";
		return $sql;
	}



	public function insertVanMaster($postData) {
		parse_str($postData, $data);		
		$queryInsert 		= $this->insertVanMasterQuery();
		$queryUpdate		= $this->updateVanMasterQuery();
		$VanUniqueId 		= $data['VanUniqueId'];
		$VanNo 				= $data['VanMaster-VanNo'];
		$VanLicHolderName  	= $data['VanMaster-LicHolderName'];
		$VanLicNo 			= $data['VanMaster-LicNo'];
		$VanDokey 			= $data['VanMaster-Dokey'];
		$VanEnterBy 		= $data['VanEnterBy'];
		$VanLicExpDate 		= $this->classBusiLogic->convertDate($data['VanMaster-LicExpDate'],TRUE,1);
		$VanAssociated 		= isset($data['VanAssociated'])?$data['VanAssociated']:'';
		$IdSubdealer 		= $data['IdSubdealer'];			 
		$CustomerCd 		= $data['CustomerCd'];
	
		if($VanUniqueId >0){
			$inputArr 		= array($VanNo, $VanLicHolderName, $VanLicNo,$VanLicExpDate ,$VanDokey,$VanAssociated,$IdSubdealer,$VanEnterBy,$VanUniqueId);
			$sql 			= vsprintf($queryUpdate, $inputArr);
			$returnData		= $this->classBusiLogic->execUpdateQuery($sql);
		}else{
			$inputArr 		= array($VanNo, $VanLicHolderName, $VanLicNo,$VanLicExpDate, $VanDokey, $VanAssociated,$CustomerCd,$IdSubdealer,$VanEnterBy ,$_SESSION['UserName'] );
			$sql 			= vsprintf($queryInsert, $inputArr);
			$returnData	= $this->classBusiLogic->execUpdateQuery($sql);
		}

		if($returnData == null){
		return  1;
		}else{
			return 0;
		}
	}


//-*-------------------------- sale contact ---------------------------*

	public function getsaleContactData($userCd){
		if($userCd ==''){
			$whr = 1;
		}else{
			$whr = " A.CustomerCd = '".$userCd."'";
		}
		$sql  		 = "SELECT A.Id, A.CustomerCd,A.CustomerCd, IFNULL(B.Descript,A.CustomerCd) AS Customer,B.City,A.Designation, A.MobileNo1, A.MobileNo2  FROM so_redelivery_salecontact_m A INNER JOIN so_customer_m B ON A.CustomerCd =B.CustomerCd WHERE $whr  ORDER BY A.CustomerCd ";
		$returnData  = $this->classBusiLogic->execSelectQuery($sql);
		return $returnData;
	}

	public function insertSaleContactQuery(){
		$sql = " INSERT INTO so_redelivery_salecontact_m (CustomerCd, Designation, MobileNo1, MobileNo2) VALUES ('%s','%s','%s','%s')"; 
		return $sql;
	}

	public function updateSaleContactQuery(){
		$sql = "UPDATE so_redelivery_salecontact_m SET MobileNo1='%s', MobileNo2='%s' WHERE CustomerCd='%s' AND  Designation='%s'";	
		return $sql;
	}

public function insertSaleContact($postData){
	parse_str($postData,$data);
	$queryInsert = $this->insertSaleContactQuery();
	$queryUpdate = $this->updateSaleContactQuery();
	$CustomerCd = $data['CustomerCd'];
	$designation = array('Owner','Manager','Dispatcher','Coordinator');
	foreach ($designation as  $value) {
		$Designation 	=  $value;
		$MobileNo1 		=  $data['SaleContact'.$value.'1'];
		$MobileNo2 		=  $data['SaleContact'.$value.'2'];
		$queryCheck = "SELECT * FROM so_redelivery_salecontact_m WHERE CustomerCd='$CustomerCd' AND  Designation='$Designation'";
		$result  = $this->classBusiLogic->execSelectQuery($queryCheck);
		if(count($result)>0){
			if(($MobileNo1==0 && $MobileNo2==0)||($MobileNo1=='' && $MobileNo2=='')){
				$sqlDelete = " DELETE FROM  so_redelivery_salecontact_m  WHERE CustomerCd='$CustomerCd' AND  Designation='$Designation '";	
				$returnData1	= $this->classBusiLogic->execUpdateQuery($sqlDelete);
			}else{				
				$inputArr 	= array($MobileNo1,$MobileNo2,$CustomerCd,$Designation);
				$sql 		= vsprintf($queryUpdate, $inputArr);
			}					
		}else{
			if(($MobileNo1==0 && $MobileNo2==0)|| ($MobileNo1=='' && $MobileNo2=='')){
					continue;
			}else{
				$inputArr 	= array($CustomerCd,$Designation,$MobileNo1,$MobileNo2);
				$sql 		= vsprintf($queryInsert, $inputArr);
			}
		}		
		$returnData	= $this->classBusiLogic->execUpdateQuery($sql);
		if($returnData) return $returnData;
	}
	if($returnData == null){
		return  1;
	}else{
		return 0;
	}

}



public function getTodaySaleItem($CustomerCd,$date,$IsHeaderOwn=NULL){  // $IsHeaderOwn =0 ==> ownuse; 1 ==> sale
	$date = $this->classBusiLogic->convertDate($date,TRUE,1);
	$result=null;	
	
	if($IsHeaderOwn ==0){
		$sql1 = " SELECT A.IdSubdealer FROM  so_subdealer_m A  WHERE A.SubdealerCd = '$CustomerCd'  "; 
		$result = $this->classBusiLogic->execSelectQuery($sql1);
	}else{
		  $sql1 = " SELECT A.IdSubdealer FROM so_daily_sale_item A  INNER JOIN so_subdealer_m B ON A.IdSubdealer = B.IdSubdealer  WHERE B.SubdealerCd <> $CustomerCd AND A.Date = '$date' "; 
		$result = $this->classBusiLogic->execSelectQuery($sql1);
	}
		
	$grpIdSubdealer = '';
	$whr = '';
	if(!empty($result)){
		foreach($result as $value){
			$grpIdSubdealer .= "'".$value['IdSubdealer']."',";
		}	
		
	}else{
		$grpIdSubdealer ='';
	}
	if($IsHeaderOwn ==2){
		$whr = '';
	}
	if($IsHeaderOwn == '0' ){
		
		$whr = (!empty($result)) ? " AND IdSubdealer  IN (".rtrim($grpIdSubdealer,',').") ": "AND IdSubdealer  IN ('')";	
	}
	elseif( $IsHeaderOwn == '1'	){
		$whr = (!empty($result)) ? " AND IdSubdealer  IN (".rtrim($grpIdSubdealer,',').") ": "AND IdSubdealer  IN ('')";	
	}
		
	  $sql = " SELECT SUM(SaleQty) AS SaleQty,ItemCd FROM `so_daily_sale_item` WHERE CustomerCd ='$CustomerCd' AND  Date='$date' AND  IsDispatched='1'  $whr  GROUP BY ItemCd";	
	$returnData	= $this->classBusiLogic->execSelectQuery($sql);		
	return  $returnData;
}


public function getOtherRecieptItem($CustomerCd,$date){  // $IsHeaderOwn =0 ==> ownuse; 1 ==> sale
	$date = $this->classBusiLogic->convertDate($date,TRUE,1);
	$sql = " SELECT SUM(SaleQty) AS OtherReciept, ItemCd FROM `so_inter_branch_transfer` WHERE SAPCode ='$CustomerCd' AND  Date='$date' GROUP BY ItemCd";	
	$returnData	= $this->classBusiLogic->execSelectQuery($sql);
	return $returnData;
}

public function getTodayDispatchItem($CustomerCd,$date,$IsHeaderOwn=NULL){  // $IsHeaderOwn =0 ==> ownuse; 1 ==> sale
	$date = $this->classBusiLogic->convertDate($date,TRUE,1);
	$sql = " SELECT SUM(DespPlanQty) AS DespPlanQty,ItemCd FROM `so_desp_plan_item` WHERE CustomerCd ='$CustomerCd' AND  Date='$date' GROUP BY ItemCd";	
	$returnData	= $this->classBusiLogic->execSelectQuery($sql);
	
	return $returnData;
}

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

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

/****************************************/

public function checkDayClose($CustomerCd,$date){
		$date 		= $this->classBusiLogic->convertDate($date,TRUE,1);
		$sql 		= " SELECT * FROM so_daily_stock WHERE CustomerCd = '".$CustomerCd."' AND Date = '".$date."' AND  StatusCd = 'A'";
		$returnData = $this->classBusiLogic->execSelectQuery($sql);
		if(count($returnData) > 0){
			$returnData = 1;
		}else{
			$returnData = 0;
		}
		return $returnData;
	}


public function CustomerSaleFinalDisp($postData){
	parse_str($postData,$data);
	$this->classBusiLogic->insertActivityLog("CustomerSaleFinalDisp",__Function__,array($data),"Advance Daily Sales Final Dispatch ");
	$SaleVanNo 		= $data['DispatchVanNo'];
	$DispatchDriver = $data['DispatchDriver'];
	$DispatchMobileNo = $data['DispatchMobileNo'];
	$CustomerCd    	= $data['CustomerCd'];
	$Date 			= $this->classBusiLogic->convertDate($data['Date'], TRUE, 1);
	$lastRow 		= $data['DispatchLastRow'];
	$TotItem 		= $data['ItemCount'];
	$TelNo   ='';
	$EmailId = '';
	$returnData='';
	for($i=1;$i<=$lastRow;$i++){
		$IdSubdealer  = $data['finalDispatchIdSubdealer_'.$i];
		$SaleRE12No   = $data['finalDispatchRE12No_'.$i];
		$SaleRE12Date = $this->classBusiLogic->convertDate($data['finalDispatchRE12Date_'.$i], TRUE, 1); 
			$query = " select B.CustomerCd,A.SubdealerCd, A.IdSubdealer from so_subdealer_m A inner join so_customer_m B on A.SubdealerCd = B.CustomerCd  and A.SubdealerCd <> $CustomerCd  WHERE A.IdSubdealer = '".$IdSubdealer."' ";
			$queryResult	= $this->classBusiLogic->execSelectQuery($query);
			if(count($queryResult)>0){
				$sqlInsert = "INSERT INTO so_inter_branch_transfer (CustomerCd,Date,IdSubdealer,SAPCode,RE12No,RE12Date,ItemCd,SaleQty,TransDateTime) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s')";
				$inputArr  = array();
				for($j=0; $j<=$data['ItemCount']; $j++ ){
					if($data['ItemValue_'.($i).'_'.$j] !=0){
						$saleQty = $data['ItemValue_'.($i).'_'.$j];
						$ItemCd  = $data['ItemCd_'.($i).'_'.$j] ;				 	
							$inputArr  	= array($CustomerCd,$Date,$IdSubdealer,$queryResult[0]['SubdealerCd'],$SaleRE12No,$SaleRE12Date,$ItemCd,$saleQty,date('Y-m-d H:i:s'));
							$sql1  		=  vsprintf($sqlInsert, $inputArr);
							$returnData	= $this->classBusiLogic->execUpdateQuery($sql1);
						}
					}				
			}
			
			$querySaleFinalDisp	= "UPDATE so_daily_sale_item SET IsDispatched= '1', DriverName='%s',MobileNo='%s' WHERE CustomerCd='%s' AND Date='%s' AND IdSubdealer='%s' and RE12No ='%s' AND RE12Date='%s' ";
			$inputArr	= array($DispatchDriver,$DispatchMobileNo,$CustomerCd,$Date, $IdSubdealer,  $SaleRE12No, $SaleRE12Date);
			$sql		= vsprintf($querySaleFinalDisp , $inputArr);
			$returnData	= $this->classBusiLogic->execUpdateQuery($sql);
			if($returnData){
				return $returnData ;
			}
			$sqlSubd 		= " SELECT IFNULL(Descript,IdSubdealer) AS Subdealer, TelNo1 from so_subdealer_m where IdSubdealer='$IdSubdealer'";
			$returnDataSubd	= $this->classBusiLogic->execSelectQuery($sqlSubd);
			$SubdealerName 	= $returnDataSubd[0]['Subdealer'];
			$SubdealerTelNo = $returnDataSubd[0]['TelNo1'];
			
			$sqlCust 		= " SELECT IFNULL(Descript,CustomerCd) AS Customer, TelNo, EmailId from so_customer_m where CustomerCd='$CustomerCd'";
			$returnDataCust	= $this->classBusiLogic->execSelectQuery($sqlCust);
			$CustomerName 	= $returnDataCust[0]['Customer'];
			$EmailId 	= $returnDataCust[0]['EmailId'];
			
			$sqlSalesContactCust 		= "SELECT * from so_redelivery_salecontact_m where CustomerCd='$CustomerCd'";
			$returnDataSalesContactCust	= $this->classBusiLogic->execSelectQuery($sqlSalesContactCust);
			foreach($returnDataSalesContactCust as $telNo){
				$TelNo .= $telNo['MobileNo1'].',';
			}
			$TelNo = ltrim(trim($TelNo), ",");
			$TelNo = rtrim(trim($TelNo), ",");

			$message = $this->DealerOrderDispatchSMS($CustomerName,$SubdealerName, $data, $i, $TelNo);
			$message = $this->SubdealerOrderDispatchConfirmSMS($CustomerName,$SubdealerName, $data, $i,  $SubdealerTelNo);
			$message = $this->DealerSubdelaerDespatchedEmail($CustomerName,$SubdealerName, $data, $i, $EmailId);
	}
	
	return 1;
	}


public function SubdealerPlaningSMS($CustomerName,$SubdealerName, $reportData, $curRow, $TelNo){  //  Sub Dealer Order under Planning 
	//print_r($reportData);
	$uname = 'SIILJPRO'; //'SIILJPRP';
	$password = 'S(ol)!ar';// 'E9W!f9Y~';
	
	//$uname = 'SIILJPRP';
	//$password = 'E9W!f9Y~';
	$info ='1';
	$test = '0';
	$from = 'Tsolar';
	//$dest =  '8793653028';   //'9765933450'; // $TelNo;  //'8793653028' //'919649569999'; //'918600993992';
	$dest =  $TelNo.', 9784011812';
	$dest = ltrim(trim($dest), ",");
	
	$messages = "Today M/s ".str_replace("&", "and", $CustomerName)." noted your order ";
	$ItemCtg = $reportData['category'];
		if($ItemCtg=='Explo'){
			$ItemCd = explode(',', $reportData['ItemCdExplo']);
		}
		else{
			$ItemCd = explode(',', $reportData['ItemCdAcces']);
		}	
		for($i=0; $i<count($ItemCd); $i++ ){
			 $item = $ItemCd[$i].'_'.$curRow;
			 $ItemVal = ($reportData[$item]? $reportData[$item] :0);
			if( $ItemVal !=0){
				$sqlitem 		= "SELECT ShortDescript, IFNULL(IF(UOMType='W','Box',UOM),' ') AS UOM from so_item_m where ItemCd='$ItemCd[$i]'";
				$returnDataitem	= $this->classBusiLogic->execSelectQuery($sqlitem);
				$Descript 	= $returnDataitem[0]['ShortDescript'];
				$UOM 	= $returnDataitem[0]['UOM'];
				$messages .= ' '. $Descript .' ' .$ItemVal.' '.$UOM.', ';
			}
		}
		
	$messages .=' and tentative dispatch date will be '.$reportData['Date'].'.  “Above details has been generated as per data entered by Dealer”.';
	$messages .=' Thank You,  '.str_replace("&", "and", $CustomerName).'';
	$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);
	$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	$curl_errno= curl_errno($ch);
	if($curl_errno!=0 || $http_status!=200)
	{	$Status= 0;
	}
	else{
		$Status= 1;
	}
	 curl_close($ch);
	$this->classBusiLogic->insertMessageLog('AddDispatchPlanning', 'SubdealerPlaningSMS', $result, $from,  $dest, $messages, $Status);
	
return $result;
}

public function DealerSubdelaerUnderPlanningEmail($CustomerName,$SubdealerName, $reportData, $curRow, $EmailId, $CustomerEMailId) {
	$curEMailId = $EmailId;
	$EMailIdCC = $CustomerEMailId;
	
	$EMailIdBCC = '';
	
	$Subject ='Daily Sale Dispatch Plan';
	$eMailBody = "<BR/>M/s ".$SubdealerName.".<br/><br/>We have Plannes your order on date ".$reportData['Date']." as per following  :";
	$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>Qty</th>
					<th>UOM</th>
				</tr>";
	//$eMailDetailRowCount = $reportData['26LastDispatchRow'];
	//$curRow=1;
	//while ($curRow <= $eMailDetailRowCount) {
		$ItemCtg = $reportData['category'];
		if($ItemCtg=='Explo'){
			$ItemCd = explode(',', $reportData['ItemCdExplo']);
		}
		else{
			$ItemCd = explode(',', $reportData['ItemCdAcces']);
		}	
		for($i=0; $i<count($ItemCd); $i++ ){
			$item = $ItemCd[$i].'_'.$curRow;
			 $ItemVal = ($reportData[$item]? $reportData[$item] :0);
			if( $ItemVal !=0){
				$sqlitem 		= "SELECT ShortDescript, IFNULL(IF(UOMType='W','Box',UOM),' ') AS UOM from so_item_m where ItemCd='$ItemCd[$i]'";
				$returnDataitem	= $this->classBusiLogic->execSelectQuery($sqlitem);
				$Descript 	= $returnDataitem[0]['ShortDescript'];
				$UOM 	= $returnDataitem[0]['UOM'];
				$eMailBody .= "<tr>";
				$eMailBody .= "<td align='center' width='5%'>".($i+1)."</td>";
				$eMailBody .= "<td width='35%'>".$Descript."</td>";
				$eMailBody .= "<td width='10%' style='color:red;' align='center'>".$ItemVal ."</td>";
				$eMailBody .= "<td width='10%' style='color:red;' align='center'>".$UOM ."</td>";
				$eMailBody .= "</tr>";	
			}
		}
		//$curRow++;
	//}
	$eMailBody .= "</table><br/>";
	$eMailBody .= "<p style='color: red'>Note : Tentative Dispatch Date will be:".date("d-m-Y", strtotime('+1 days', strtotime($reportData['Date']))) . " </p>";
		$eMailBody .= "Thanks<br/>".$CustomerName."<br/><br/>
		
		<p style='size: 10px'> Disclaimer : This data has been generated as per Dealer discretion and the input decided & entered by them in dealer supply chain program. For any issue please contact respective dealer only.</p>
		<p style='size: 10px'>We have just provided an interface to dealer to facilitate their day to day works.
		This is  No Reply  email ID, so do not send email on this email ID.</p><br/>";
		$objSolarMailer = new solarMailer();
		$objSolarMailer->IsHTML(true);  
		$returnData = $objSolarMailer->sendSolarMail($curEMailId, $Subject, $eMailBody, $EMailIdCC, $EMailIdBCC, True);
	return $returnData;
}


public function DealerOrderDispatchSMS($CustomerName,$SubdealerName, $reportData, $curRow, $TelNo=NULL){  //  Message is Owner / Manager / Dispatcher / Co coordinator / Mag In Charge
	$uname = 'SIILJPRO'; //'SIILJPRP';
	$password = 'S(ol)!ar';// 'E9W!f9Y~';
	//$uname = 'SIILJPRP';
	//$password = 'E9W!f9Y~';
	
	$info ='1';
	$test = '0';
	$from = 'Tsolar';
	//$dest =  '8793653028`';   //'9765933450'; // $TelNo;  //'8793653028' //'919649569999'; //'918600993992';
	$dest =  $TelNo.',9784011812';
	$dest = ltrim(trim($dest), ",");
	 $messages = "Today M/s ".str_replace("&", "and", $CustomerName)." has been dispatched M/s ".str_replace("&", "and", $SubdealerName)." : ";
	//$curRow=1;
	//$dataCount = $reportData['DispatchLastRow'];
	//while ($curRow <= $dataCount) {
		for($i=0; $i<=$reportData['ItemCount']; $i++ ){
			if($reportData['ItemValue_'.($curRow).'_'.$i] !=0){
				$messages .= ' '. $reportData['Item_'.($curRow).'_'.$i] .' ' .$reportData['ItemValue_'.($curRow).'_'.$i].' '.$reportData['UOM_'.($curRow).'_'.$i].', ';
			}
		}
		//$curRow++;
	//}
	$messages .='in Van No '.$reportData['DispatchVanNo'].' “Above details has been generated as per data entered by Dealer”.';
	$messages .='Thank You, '.str_replace("&", "and", $CustomerName).'';
	//$data ="uname=".$uname."&pass=".$password."&msg=".$messages."&send=".$from."&dest=".$dest."&unicode=1";
	$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);
	$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	$curl_errno= curl_errno($ch);
	if($curl_errno!=0 || $http_status!=200)
	{	$Status= 0;
	}
	else{
		$Status= 1;
	}
	 curl_close($ch);
	$this->classBusiLogic->insertMessageLog('CustomerSaleFinalDisp', 'DealerOrderDispatchSMS', $result, $from,  $dest, $messages, $Status);
return $result;
}

public function SubdealerOrderDispatchConfirmSMS($CustomerName,$SubdealerName, $reportData, $curRow, $TelNo=NULL){  //  Sub Dealer Order Dispatched Details
	$uname = 'SIILJPRO'; //'SIILJPRP';
	$password = 'S(ol)!ar';// 'E9W!f9Y~';
	
	//$uname = 'SIILJPRP';
	//$password = 'E9W!f9Y~';
	
	$info ='1';
	$test = '0';
	$from = 'Tsolar';
	//$dest =  '8793653028';   //'9765933450'; // $TelNo;  //'8793653028' //'919649569999'; //'918600993992';
	$dest =  $TelNo.',9784011812';
	$dest = ltrim(trim($dest), ",");
	$messages = "M/s ".str_replace("&", "and", $SubdealerName)." on ".$reportData['Date']." M/s ".str_replace("&", "and", $CustomerName )." has Dispatched ";
	//$curRow=1;
	//$dataCount = $reportData['DispatchLastRow'];
	//while ($curRow <= $dataCount) {
		for($i=0; $i<=$reportData['ItemCount']; $i++ ){
			if($reportData['ItemValue_'.($curRow).'_'.$i] !=0){
				$messages .= ' '. $reportData['Item_'.($curRow).'_'.$i] .' ' .$reportData['ItemValue_'.($curRow).'_'.$i].' '.$reportData['UOM_'.($curRow).'_'.$i].', ';
			}
		}
		$messages .='RE12No '.$reportData['finalDispatchRE12No_'.$curRow].' in Van No '.$reportData['DispatchVanNo'].' having driver name '.$reportData['DispatchDriver'].' Mob No. '.$reportData['DispatchMobileNo'].' Approx reach date '.date("d-m-Y", strtotime('+1 days', strtotime($reportData['Date']))).' “ Above details has been generated as per data entered by Dealer”. ';
		$messages .='Thank You, '.str_replace("&", "and", $CustomerName).'';
		//$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);
		$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	$curl_errno= curl_errno($ch);
	if($curl_errno!=0 || $http_status!=200)
	{	$Status= 0;
	}
	else{
		$Status= 1;
	}
	 curl_close($ch);
	$this->classBusiLogic->insertMessageLog('CustomerSaleFinalDisp', 'SubdealerOrderDispatchConfirmSMS', $result, $from,  $dest, $messages, $Status);
return $result;

}


public function DealerSubdelaerDespatchedEmail($CustomerName,$SubdealerName, $reportData, $curRow, $EmailId) {
	$Subject ='Daily Sale Dispatch';
	$curEMailId = $EmailId;
	$EMailIdCC = '';
	//$EMailIdBCC = 'websupport@solargroup.com';
	$EMailIdBCC = '';
	
	$eMailDetailRowCount = count($reportData);
	$eMailBody = "<BR/>M/s ".$SubdealerName.". <br/><br/> Today we have dispatched your order dated ".date('d-m-Y')." as per following :";
	$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>Qty (Case)</th>
					<th>RE12 No</th>
				</tr>";
	$eMailDetailRowCount = $reportData['DispatchLastRow'];
	//$curRow=1;
		//while ($curRow < $eMailDetailRowCount) {
			for($i=0; $i<=$reportData['ItemCount']; $i++ ){
				if($reportData['ItemValue_'.($curRow).'_'.$i] !=0){
					$eMailBody .= "<tr>";
					$eMailBody .= "<td align='center' width='5%'>".$curRow."</td>";
					$eMailBody .= "<td width='35%'>".$reportData['Item_'.($curRow).'_'.$i]."</td>";
					$eMailBody .= "<td width='10%' style='color:red;' align='center'>".$reportData['ItemValue_'.($curRow).'_'.$i]."</td>";
					$eMailBody .= "<td align='center' width='10%' align='right'>".$reportData['finalDispatchRE12No_'.$curRow]."</td>";
					$eMailBody .= "</tr>";	
				}
			}
			//$curRow++;
		//}
		$eMailBody .= "</table><br/>";
		
		$eMailBody .= "Van No: ".$reportData['DispatchVanNo']."  <br/> Driver Name: ".$reportData['DispatchDriver']." <br/> Contact No: ".$reportData['DispatchMobileNo']. "<br/> Tentative reach Date /Time will be: ".date("d-m-Y", strtotime('+1 days', strtotime($reportData['Date'])))." <br/>";
		$eMailBody .= "<p>This data has been generated as per Dealer discretion and the input decided & entered by them in dealer supply chain program. For any issue please contact respective dealer only.</p>
		<p>We have just provided an interface to dealer to facilitate their day to day works.
		This is “No Reply” email ID, so do not send email on this email ID.</p><br/>";
		$eMailBody .= " Thanks<br/> ".$CustomerName."<br/>";
		$objSolarMailer = new solarMailer();
		$objSolarMailer->IsHTML(true);  
		$returnData = $objSolarMailer->sendSolarMail($curEMailId, $Subject, $eMailBody, $EMailIdCC, $EMailIdBCC, True);
	return $returnData;
}

 
 public function EmailSendTofinalDispatch($reportData, $CustomerCd) {
	$sqlCust 		= " SELECT IFNULL(Descript,CustomerCd) AS Customer, TelNo, EmailId from so_customer_m where CustomerCd='$CustomerCd'";
	$returnDataCust	= $this->classBusiLogic->execSelectQuery($sqlCust);
	$CustomerName 	= $returnDataCust[0]['Customer'];
	$EmailId 	= $returnDataCust[0]['EmailId'];
	$curRow=1;
	//  $curEMailId = 'websupport@solargroup.com;rahul@solargroup.com;solartrade@solargroup.com';
	//	$EMailIdBCC ='';
	$curEMailId = $EmailId;
	$EMailIdCC = '';
	$EMailIdBCC = '';
	$eMailBody = "M/s ".$CustomerName.". <br/><br/> Today you dispatched following order - ";
	$eMailBody .=$reportData;
	//$objSolarMailer = new solarMailer1();
	$objSolarMailer = new solarMailer();
	$objSolarMailer->IsHTML(true);  
	$returnData = $objSolarMailer->sendSolarMail($curEMailId, 'Daily Dispatch Report', $eMailBody, $EMailIdCC, $EMailIdBCC, True);
	return $returnData;

}

public function getInterBranchData($searchByDealer,$searchBysubdealer,$searchByRE12no,$searchByItem,$searchByDate){
		$whr = " WHERE 1";
		if($searchByDealer !=''){
			$whr .= " AND  B.Descript LIKE '%".trim($searchByDealer)."%' ";
		} 

		if($searchBysubdealer !=''){
			$whr .= " AND  C.Descript LIKE '%".trim($searchBysubdealer)."%' ";
		} 

		if($searchByRE12no !=''){
			$whr .= " AND  A.RE12No  = '".trim($searchByRE12no)."' ";
		} 

		if($searchByItem !=''){
			$whr .= "  AND D.ShortDescript LIKE '%".trim($searchByItem)."%' ";
		} 

		if($searchByDate !=''){
			$searchByDate = $this->classBusiLogic->convertDate(trim($searchByDate),TRUE,1);
			$whr .= "  AND A.Date = '".$searchByDate."' ";
		} 

		$sql = " SELECT A.CustomerCd ,IFNULL(B.Descript,A.CustomerCd) AS Customer,  DATE_FORMAT(A.Date,'%d-%m-%Y') AS Date , A.IdSubdealer , IFNULL(C.Descript,A.IdSubdealer) AS Subdealer, A.SAPCode,A.RE12No,A.RE12Date,A.ItemCd, IFNULL(D.ShortDescript,A.ItemCd) AS Item , A.SaleQty,A.TransDateTime FROM  so_inter_branch_transfer A  INNER JOIN so_customer_m B ON A.CustomerCd = B.CustomerCd INNER JOIN so_subdealer_m C ON A.IdSubdealer = C.IdSubdealer INNER JOIN so_item_m D ON A.ItemCd = D.ItemCd   $whr  ORDER BY  A.CustomerCd, Date DESC" ;	
		$returnData = $this->classBusiLogic->execSelectQuery($sql);
		return $returnData;
	}


	public function getTodayReciept($customerCd, $date){
		$date = $this->classBusiLogic->convertDate($date,TRUE,1);	
	 	$sql = " SELECT ItemCd,SaleQty FROM so_inter_branch_transfer WHERE CustomerCd = '".$customerCd."' AND Date = '".$date."'";
		$returnData = $this->classBusiLogic->execSelectQuery($sql);
		return $returnData;											
	}


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

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

	public function changeStockNSalePositionStatus($customerCd,$date,$status){
		$date = $this->classBusiLogic->convertDate($date,TRUE,1);
		echo $sql = " UPDATE so_daily_stock SET StatusCd ='".$status."' WHERE CustomerCd = '".$customerCd."' AND Date = '".$date."'";
		$returnData	= $this->classBusiLogic->execUpdateQuery($sql);
		return $returnData;
	}

	public function missingReportDailyStockNPlan($data){		
		$StartDate 	   = $data['StartDate'];		
		$EndDate 	   = $data['EndDate'];
		$CustomerCd 	= $data['CustomerCd'];	
		//(isset)		
	//	$firstDay  = date("Y-m-d", mktime(0, 0, 0, $Month,1 ,date("Y"))); 
	//	$lastday   = date("Y-m-d", mktime(0, 0, 0, $Month+1,0,date("Y")));
		
		
		$dataarray = array();
		while (strtotime($StartDate) <= strtotime($EndDate)) {
			echo $sql = "SELECT '".$StartDate."' as Date, A.CustomerCd, A.Descript, A.EMailId  FROM so_customer_m A WHERE A.IsActive = 1 AND  A.CustomerCd NOT IN  ( SELECT  CustomerCd FROM so_daily_stock B WHERE B.Date = '".$StartDate."') AND  CustomerCd='$CustomerCd'";
			$reportData = $this->classBusiLogic->execSelectQuery($sql);
			array_push($dataarray,$reportData);
			$StartDate = date ("Y-m-d", strtotime("+1 day", strtotime($StartDate)));
		}

		print_r($dataarray);
		
		
//		$sql = " SELECT A.Date A.CustomerCd,A.Descript, A.EMailId  FROM so_customer_m A WHERE A.IsActive = 1 AND  A.CustomerCd NOT IN  (SELECT CustomerCd FROM so_daily_stock B WHERE B.Date BETWEEN '".$StartDate."' AND '".$EndDate ."' )  ";
//		$reportData = $this->classBusiLogic->execSelectQuery($sql);
		//print_r($reportData );
		$fileName = 'wrk/repMissingDailyStockNSale-' . $data['MYS'] . '.xls';
		$handle = fopen($fileName,'wb');


		If (count($reportData)==0) {
			echo '<script>alert("No data to print for specified Year+Month.")</script>';
			return;
		}

			fwrite($handle, str_repeat("\t",1) . "List of Customers for Missing Daily Sale and Stock for " .$data['MYS']. "\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 UnapprovedStockSale($postData){
		parse_str($postData,$data);
		for($i=1;$i<=$data['totalRecord'];$i++){					
			if(isset($data['CheckedRow_'.$i])){
				$CustomerCd = $data['CustomerCd_'.$i];
				$Date 		= $data['Date_'.$i];
				$date = $this->classBusiLogic->convertDate($Date,TRUE,1);
				$sql = " UPDATE so_daily_stock SET StatusCd = 'U' WHERE CustomerCd = '".$CustomerCd."' AND Date = '".$date ."' ";
				$returnData	= $this->classBusiLogic->execUpdateQuery($sql);
				if($returnData) return $returnData ;
			}
		}
		if($returnData == null){
			return 1;
		}
	}


}



?>