<?php
//echo phpinfo();die;
include('connectdb.inc.php');
//sleep(55);

date_default_timezone_set('Asia/Kolkata');
$sqlI = 'INSERT INTO '.$DB->pre.'wallet SET userCode="T"';
//$DB->dbQuery($sqlI);
$sqlAD  = 'SELECT * FROM '.$DB->pre.'users WHERE isActive="1" AND userType="1" AND status="1" ORDER BY id DESC';
$AD = $DB->dbRows($sqlAD);
$currentTime = date('H:i:s');
 //$lotTime = date("h:i", strtotime("+10 minutes", strtotime(drawTimeCrone())));
  $lotTime = drawTimeCrone();
//$lotTime = '9:50';
if($currentTime >= "10:00" && $currentTime <= '21:51'){
	$sqlP = 'SELECT per FROM '.$DB->pre.'percentage';
	$P = $DB->dbRow($sqlP);
	 $per1 = $P['per'];
	// $per = 20;


	//Winning By Retailer Logic Start From Here
//	$allRet = 'SELECT uID FROM '.$DB->pre.'lottary WHERE lotTime="'.$lotTime.'" AND lotDate="'.date('Y-m-d').'" group by uID order by rand()';
     $allRet = 'SELECT L.uID,U.remark FROM mx_lottary as L
				LEFT JOIN mx_users as U on L.uID = U.id WHERE lotTime="'.$lotTime.'" AND lotDate="'.date('Y-m-d').'"  group by L.uID order by rand()';
	$RET = $DB->dbRows($allRet);

	
	$RETWIN = 0;
	foreach($RET as $RET){
		
		//All Sale
		$sqlALLSR = 'select (sum(cv)*point) as S FROM mx_lottary WHERE   lotdate="'.date('Y-m-d').'" AND uID="'.$RET['uID'].'"';
		$ALLSR = $DB->dbRow($sqlALLSR);

		
		//All Winning	
	//	$sqlALLWINR = 'select sum(S) as S from (select claimAmount as S from mx_result_win WHERE date(dateAdded)="'.date('Y-m-d').'" AND uID="'.$RET['uID'].'" GROUP BY barcode) as C';
		
			$sqlALLWINR = 'select sum(S) as S from (select claimAmount as S from mx_result_win WHERE date(dateAdded)="'.date('Y-m-d').'" AND uID="'.$RET['uID'].'") as C';
		$ALLWINR = $DB->dbRow($sqlALLWINR);
		
		
		//Pending Claim Logic
		$sqlPendClaim = 'select sum(L.cv*point*90) as cv from mx_lottary as L
		LEFT JOIN mx_result_tran as R on L.cellID = R.cellID AND L.lotTime = R.lotTime 
		WHERE L.lotdate="'.date('Y-m-d').'" AND R.lotdate="'.date('Y-m-d').'" AND L.uID="'.$RET['uID'].'" ';

		$PC = $DB->dbRow($sqlPendClaim);

		$PCA = ($PC['cv']-$ALLWINR['S']);

		//Pending Claim Logic End Here

		//echo $ALLSR['S'].'---'.$ALLWINR['S'].'---'.$RET['uID'].'<br>';

		$winTotR = 0;
		
		//personal winning 
		$per = $per1;
		$per = (intval($RET['remark'])>0?intval($RET['remark']):$per);
		
		$winTotTempR = (($ALLSR['S']/100)*$per);//current draw winning
		
		$tempWinR = ($winTotTempR-($ALLWINR['S']+intval($PCA)));
			if($tempWinR <= 0){
			$winTotR= 0;
		}else{
			$winTotR = $tempWinR;
		}

		
	//	$sqlALLTR = 'select cellID,min((cv*point)*90) as cv,ticketTot,`point`,lotnum ,sernum,barcode from (SELECT sum(cv) as cv,cellID,ticketTot,`point`,lotnum ,sernum,barcode FROM mx_lottary WHERE lotTime="'.$lotTime.'" AND lotdate="'.date('Y-m-d').'" AND uID="'.$RET['uID'].'" group by lotnum  order by rand(), ticketTot desc) as C group by barcode order by ticketTot DESC';
	$sqlALLTR = 'select cellID,min((cv*point)*90) as cv,ticketTot,`point`,lotnum ,sernum,barcode from (SELECT cv,cellID,ticketTot,`point`,lotnum ,sernum,barcode FROM mx_lottary WHERE lotTime="'.$lotTime.'" AND lotdate="'.date('Y-m-d').'" AND uID="'.$RET['uID'].'" group by barcode order by rand(), ticketTot desc,isadvance asc) as C group by barcode order by ticketTot DESC';
		$ALLTR = $DB->dbRows($sqlALLTR);
	
		$allWinR = 0;

		if(count($ALLTR) > 0){
			
			foreach($ALLTR as $ALLR){
				$sql1 = 'SELECT lotID FROM '.$DB->pre.'result_tran WHERE   lotnum="'.$ALLR['lotnum'].'" AND lotdate="'.date('Y-m-d').'" AND lotTime="'.$lotTime.'" AND uID="1"';
				$D1 = $DB->dbRow($sql1);
				
				$sqlRCV = 'SELECT sum(cv) as cv,point from mx_lottary where lotTime="'.$lotTime.'" and lotdate="'.date('Y-m-d').'" and cellID="'.$ALLR['cellID'].'" and barcode <> "'.$ALLR['barcode'].'" group by cellID';
				$RCV = $DB->dbRow($sqlRCV);

			//	$ORCV = (($RCV['cv']*$RCV['point'])*90);
				$ORCV = ((intval($RCV['cv'])*intval($RCV['point']))*90);
					
			if($D1['lotID'] == '' && (intval($winTotR) > (intval($ALLR['cv'])+intval($allWinR)+intval($ORCV))) && (intval($allWinR) < intval($winTotR))){
					
					$sqlI1 = 'INSERT INTO '.$DB->pre.'result_tran SET cellID="'.$ALLR['cellID'].'",sernum="'.$ALLR['sernum'].'",lotnum="'.$ALLR['lotnum'].'" ,lotdate="'.date('Y-m-d').'",lotTime="'.$lotTime.'",uID="1",winAmt="'.$RET['uID'].'",dateAdded="'.date('Y-m-d h:i:s').'"';
					//echo $ALL['cv'];
					$allWinR += $ALLR['cv'];
					$RETWIN += $ALLR['cv'];

					$DB->dbQuery($sqlI1);
					
					
					
				}
			}
		}

	}
	//Winning By Retailer Login End Here
//echo $RETWIN;die;



	
	$sqlALLS = 'select (sum(cv)*point) as S FROM mx_lottary WHERE   lotdate="'.date('Y-m-d').'"';
	$ALLS = $DB->dbRow($sqlALLS);

    $sqlALLWIN = 'select sum(S) as S from (select claimAmount as S from mx_result_win WHERE lotdate="'.date('Y-m-d').'" GROUP BY barcode) as C';
	$ALLWIN = $DB->dbRow($sqlALLWIN);

	  $winTot= 0;
//	 echo $per;
	$winTotTemp = (($ALLS['S']/100)*$per);//current draw winning
	
	$tempWin = ($winTotTemp-($ALLWIN['S']+$RETWIN));
	 if($tempWin <= 0){
		$winTot= 0;
	}else{
		// $winTot = (($ALLS['S']/100)*$per);//give total winning
		$winTot = $tempWin;
	}

	//echo $winTot;die;

foreach($AD as $AD){
	

	

	
	
	$serArr = array(
	'0000'=>array('00','01','02','03','04','05','06','07','08','09'),
	'1000'=>array('10','11','12','13','14','15','16','17','18','19'),
	'2000'=>array('20','21','22','23','24','25','26','27','28','29'),
	'3000'=>array('30','31','32','33','34','35','36','37','38','39'),
	'4000'=>array('40','41','42','43','44','45','46','47','48','49'),
	'5000'=>array('50','51','52','53','54','55','56','57','58','59'),
	'6000'=>array('60','61','62','63','64','65','66','67','68','69'),
	'7000'=>array('70','71','72','73','74','75','76','77','78','79'),
	'8000'=>array('80','81','82','83','84','85','86','87','88','89'),
	'9000'=>array('90','91','92','93','94','95','96','97','98','99') 
	);
	
	//foreach($D as $D){		
		
		// $userLotWin = $allWin;	
		$userLotWin = $RETWIN;
		 
	foreach($serArr as $key=>$serArr1){
		shuffle($serArr1);
		
		
		foreach($serArr1 as $serArr2){
			// loop start here
			
			 // $sqlUS = 'select sum(S) as S FROM(SELECT sum(distinct(ticketTot)) as S FROM mx_lottary WHERE lotnum="'.$serArr2.'" AND lotTime="'.$lotTime.'" AND lotdate="'.date('Y-m-d').'"   group by tranID) as T';
		  $sqlUS = 'select sum(cv*point) as S from mx_lottary where lotTime="'.$lotTime.'" AND lotdate="'.date('Y-m-d').'" and sernum="'.$key.'"';
		 $US = $DB->dbRow($sqlUS);
		
		
		
		
	
		$cell = array();
			$cv = array();

			  $sqlL = 'SELECT  cellID,sum(cv) as CV,point FROM '.$DB->pre.'lottary WHERE lotnum="'.$serArr2.'" AND   lotTime="'.$lotTime.'" AND lotdate="'.date('Y-m-d').'"   group by cellID order by cellID';
			$L = $DB->dbRows($sqlL);
			foreach($L as $L){
				$cell[] = $L['cellID'];
				$cv[] = (($L['CV']*90)*$L['point']);
			}
			
			 
			
			$sql1 = 'SELECT lotID FROM '.$DB->pre.'result_tran WHERE   lotnum="'.$serArr2.'" AND lotdate="'.date('Y-m-d').'" AND lotTime="'.$lotTime.'" AND uID="'.$AD['id'].'"';
			$D1 = $DB->dbRow($sql1);
			
			//array_unique($cell)
			
			if($D1['lotID'] == ''){
					
				if(count(($cell)) > 0){
					
					$minCell = array_rand(array_flip(array_keys($cv, min($cv))));
					
			 		
				
					if(($cv[$minCell]+$userLotWin) < $winTot && $userLotWin < $winTot){
						//echo $D['id'].'--'.$cv[$minCell].'----'.$winTot.'---'.$userLotWin.'---'.$serArr2.'<br>';
					//	$sqlI1 = 'INSERT INTO '.$DB->pre.'result_tran SET cellID="'.$cell[$minCell].'",sernum="'.$key.'",lotnum="'.$serArr2.'" ,lotdate="'.date('Y-m-d').'",lotTime="'.$lotTime.'",uID="'.$AD['id'].'",winAmt="'.$cv[$minCell].'",dateAdded="'.date('Y-m-d h:i:s').'"';
					//echo "<br>";
				//	$DB->dbQuery($sqlI1);
				//	$userLotWin += $cv[$minCell];
				
				    //new logic
					if(count($cell)<100){
						$resultCount = array();
							for($i=0;$i<=99;$i++){
								$i = (strlen($i)==1?'0'.$i:$i);
									$flag = in_array($serArr2.$i,$cell);
									if(!$flag){
										//$newCell = $i;
										//echo $splt[0].$i.'&nbsp;';
										$resultCount[]=$serArr2.$i;
									}
								
							}
							 $newCell = array_rand($resultCount);
						 
							 $sqlI1 = 'INSERT INTO '.$DB->pre.'result_tran SET cellID="'.$resultCount[$newCell].'",sernum="'.$key.'",lotnum="'.$serArr2.'" , lotdate="'.date('Y-m-d').'",lotTime="'.$lotTime.'",uID="'.$AD['id'].'",dateAdded="'.date('Y-m-d h:i:s').'"';
						//echo "<br>";
						$DB->dbQuery($sqlI1);
					//	$userLotWin = ($cv[$minCell]+$userLotWin);
					}else{
						$sortCell = array_count_values($cv);
						//$minCell = array_search(min($cv), $cv);
						   $minCell = array_rand(array_flip(array_keys($cv, min($cv))));
						$sqlI2 = 'INSERT INTO '.$DB->pre.'result_tran SET cellID="'.$cell[$minCell].'",sernum="'.$key.'",lotnum="'.$serArr2.'" , lotdate="'.date('Y-m-d').'",lotTime="'.$lotTime.'",winAmt="'.$cv[$minCell].'",uID="'.$AD['id'].'",dateAdded="'.date('Y-m-d h:i:s').'"';
						$DB->dbQuery($sqlI2);
						$userLotWin += $cv[$minCell];
					}	
					//new logic end here
				    
				    
					
					}else{
						if(count($cell)<100){
							$resultCount = array();
								for($i=0;$i<=99;$i++){
									$i = (strlen($i)==1?'0'.$i:$i);
										$flag = in_array($serArr2.$i,$cell);
										if(!$flag){
											//$newCell = $i;
											//echo $splt[0].$i.'&nbsp;';
											$resultCount[]=$serArr2.$i;
										}
									
								}
								 $newCell = array_rand($resultCount);
							 
								 $sqlI1 = 'INSERT INTO '.$DB->pre.'result_tran SET cellID="'.$resultCount[$newCell].'",sernum="'.$key.'",lotnum="'.$serArr2.'" , lotdate="'.date('Y-m-d').'",lotTime="'.$lotTime.'",uID="'.$AD['id'].'",dateAdded="'.date('Y-m-d h:i:s').'"';
							//echo "<br>";
							$DB->dbQuery($sqlI1);
						//	$userLotWin = ($cv[$minCell]+$userLotWin);
						}else{
							$sortCell = array_count_values($cv);
							//$minCell = array_search(min($cv), $cv);
                   			$minCell = array_rand(array_flip(array_keys($cv, min($cv))));
							$sqlI2 = 'INSERT INTO '.$DB->pre.'result_tran SET cellID="'.$cell[$minCell].'",sernum="'.$key.'",lotnum="'.$serArr2.'" , lotdate="'.date('Y-m-d').'",lotTime="'.$lotTime.'",winAmt="'.$cv[$minCell].'",uID="'.$AD['id'].'",dateAdded="'.date('Y-m-d h:i:s').'"';
							$DB->dbQuery($sqlI2);
							$userLotWin += $cv[$minCell];
						}
						
						
					}
					
				}else{
					$resultCount = array();
					for($i=0;$i<=99;$i++){
							$i = (strlen($i)==1?'0'.$i:$i);
								$resultCount[]=$serArr2.$i;	
					}
						//print_r($resultCount);
						  $newCell = array_rand($resultCount);
					 
					    $sqlI1 = 'INSERT INTO '.$DB->pre.'result_tran SET cellID="'.$resultCount[$newCell].'",sernum="'.$key.'",lotnum="'.$serArr2.'" , lotdate="'.date('Y-m-d').'",lotTime="'.$lotTime.'",uID="'.$AD['id'].'",dateAdded="'.date('Y-m-d h:i:s').'"';
					//echo "<br>";
					$DB->dbQuery($sqlI1);
					
				}
			}
		
		// loop end here
		}
		
	//}
}
//echo $userLotWin;
}
	
	
  
  
  
  
  
//}
}
echo "OK";
function getAllRetailerCron($ID){
	global $DB;
	$sql = 'SELECT id,userType FROM '.$DB->pre.'users WHERE underHead="'.$ID.'" ';
	$D = $DB->dbRows($sql);
	if(count($D) > 0){
		foreach($D as $D){
			if($D['id'] !=''){
				if($D['userType'] == 3){
					$GLOBALS['retailer'] .= $D['id'].',';
				}
				getAllRetailerCron($D['id']);
			}
		}
	}
}




function drawTimeCrone(){
	global $DB;
	date_default_timezone_set('Asia/Kolkata');

$currentTime = time(); // Get current timestamp
 $nextInterval = $currentTime + (10 * 60) - ($currentTime % (10 * 60));
return  date('h:i', $nextInterval);
}



?>
