<?php
$nextTime = time() + 50;
function objectToArray($d)
{
    if (is_object($d))
        $d = get_object_vars($d);
    if (is_array($d))
        return array_map(__FUNCTION__, $d);
    else
        return json_decode($d,true);
}
function cronJobReport($timeCron = '') {
global $nextTime;
include("config.php");


$time = mktime(date("H"),date("i"),date("s"),date("n"),date("j"),date("Y")); 
if(empty($timeCron)) {
$querySendReport="SELECT `id` FROM `reports` WHERE `complete`!='1' AND (ISNULL(`group_time`) || `group_time`='')  ORDER BY `id` ASC LIMIT 0, 1";
$resultSendReport = mysqli_query($conn, $querySendReport);
$numSendReport=mysqli_num_rows($resultSendReport);
if($resultSendReport && $numSendReport)
	while($rowSendReport = mysqli_fetch_assoc($resultSendReport))
		mysqli_query($conn, "UPDATE `reports` SET `group_time`='$time' WHERE `id`='$rowSendReport[id]'");
$timeCron = $time;	
}
$querySelectReport = "SELECT * FROM `reports` WHERE `complete`!='1' AND `group_time`='$timeCron' ORDER BY `id` ASC LIMIT 0, 1";
$resultSelectReport = mysqli_query($conn, $querySelectReport);
$numSelectReport = mysqli_num_rows($resultSelectReport);
$msgIdsArr = array();

if($resultSelectReport && !empty($numSelectReport)){
	while($rowSelectReport = mysqli_fetch_assoc($resultSelectReport)) {
		$repourtData = $rowSelectReport['details'];
		$detailsArr = objectToArray($repourtData);
		foreach($detailsArr['results'] as $keyJson => $valuejson) {
			$queryInsertReport = "INSERT INTO `reports_one_msg` (msgIdMobily,number,status,`report_id`) VALUES ('".$valuejson['msgId']."','".$valuejson['to']."','".$valuejson['status']."','".$rowSelectReport['id']."')";
			$resultInsertReport = mysqli_query($conn, $queryInsertReport);
		}
		mysqli_query($conn, "UPDATE `reports` SET `complete`='1',`group_time`='".time()."' WHERE id='$rowSelectReport[id]'");
	}
}
	mysqli_close($conn);
	if(time()<$nextTime)
	{
		ob_flush();
		sleep(5);
		if(empty($numSelectReport))
			cronJobReport();
		else
			cronJobReport($time);
	}
	return 0;
}
cronJobReport();

?>