<?php
set_time_limit(0);
include("config.php");
include("functions.php");

@ini_set('zlib.output_compression',0);
@ini_set('implicit_flush',1);
@ob_end_clean();

///For Cron
$start = "select * from settings where name='Cron_start'";
$start_que_start = mysqli_query($connect,$start);
$startData = mysqli_fetch_array($start_que_start);
$startArray = explode(":",$startData['value']);
//print_r($startArray);

$stopQuery = "select * from settings where name='Cron_stop'";
$start_que_stop = mysqli_query($connect,$stopQuery);
$stopData = mysqli_fetch_array($start_que_stop);
$stopArray = explode(":",$stopData['value']);
$cronStop = date("H:i",strtotime($stopData['value']));
$cronStart = date("H:i",strtotime($startData['value']));

if(date("H:i") <= $cronStop and date("H:i") >= $cronStart){

	$sqlres="SELECT * FROM settings WHERE id=6";
	$queryres=mysqli_query($connect,$sqlres);
	$res_row = mysqli_fetch_array($queryres);
	//echo $res_row["value"];

	if($res_row["value"] == "Unlocked"){
		echo "Script start at ". date("H:i:s")."<br>";
		 $sqlupdate = "UPDATE settings SET value = 'Locked' WHERE id=6";
		 $resupdate = mysqli_query($connect,$sqlupdate);
		
			$sms_per_sec = returnName1("value", "settings", "name", "SMS_PER_SECOND",$connect);
			$sms_wait_sec = returnName1("value", "settings", "name", "SMS_WAIT_TIME",$connect);
			SendAllSMS($sms_per_sec,$sms_wait_sec,$connect);
			
		$sqlupdate1 = "UPDATE settings SET value = 'Unlocked' WHERE id =6";
		$resupdate1 = mysqli_query($connect,$sqlupdate1);
		ob_end_flush(); 
	}
		
}else{
	echo "Cron Stops !!";
	exit;
}

function SendAllSMS($sms_per_sec,$sms_wait_sec,$connect){
	$sms_force_off = "0";
	$sms_force_off = returnName1("value", "settings", "name", "SMS_FORCE_OFF",$connect);
		
		if($sms_force_off != "1"){
		$sqlsms="SELECT * FROM sms_urls WHERE sms_status = 'Pending' ORDER BY sms_id ASC LIMIT $sms_per_sec";
		$querysms=mysqli_query($connect,$sqlsms);
		if(mysqli_num_rows($querysms) >0 ){
			while($row=mysqli_fetch_array($querysms))
			{
				$smsID = $row["sms_id"];
				$sms_url = $row["sms_url"];
				//exec("lynx -dump ".$sms_url." >/dev/null 2>&1 & echo $!");
				exec("lynx --dump '".$sms_url."' > /dev/null &");
				flush();
				ob_flush();
				ob_clean ();
				ob_end_clean(); 
				//sendSMSLinkKanel($sms_url);			
				
				$sqlUpdateSMS="UPDATE sms_urls SET sms_status='Sent' where sms_id='$smsID'";
				//$sqlUpdateSMS="DELETE FROM sms_urls where sms_id='$smsID'";
				$queryUpdateSMS=mysqli_query($connect,$sqlUpdateSMS);

			 }
				usleep($sms_wait_sec);
				SendAllSMS($sms_per_sec,$sms_wait_sec,$connect);
				//exit;
			}else{
				$sqlupdate1 = "UPDATE settings SET value = 'Unlocked' WHERE id =6";
				$resupdate1 = mysqli_query($connect,$sqlupdate1);
				echo "Script end at ". date("H:i:s")."<br>";
				
				exit;
			}
		  }else{
			// exit if forecefully shutdown
		 	echo "Cron forecefully shutdown !!";
		    ob_end_flush();
			exit;
		  
		  }	
		
		}							
?>
