<?php
include '../includes/connection.php';

$getallbusinesses = mysqli_query($con,"SELECT business_id FROM business");
$today=date('Y-m-d');
if (mysqli_num_rows($getallbusinesses)>0) {
	while ($allbusinesses=mysqli_fetch_array($getallbusinesses)) {
	 	 $sbusiness_id=$allbusinesses['business_id'];
		$getallbranches=mysqli_query($con,"SELECT branch_id FROM branches where status=1&& business_id='$sbusiness_id'");
				if (mysqli_num_rows($getallbranches)>0) {
					while ($allbranches=mysqli_fetch_array($getallbranches)) {
					 	$sbranch_id=$allbranches['branch_id'];
					 	$date=date('Y-m-d', strtotime($today. ' - 1 day'));
					 	$getstockvalues=mysqli_query($con,"SELECT * FROM stock_values where DATE_FORMAT(date, '%Y-%m-%d')='$date' && branch_id='$sbranch_id' && business_id='$sbusiness_id'");
					 	if (mysqli_num_rows($getstockvalues)<1) {
					 		$stockvalue=mysqli_fetch_array(mysqli_query($con,"SELECT sum(buying_price*quantity) as stockvalue FROM stock WHERE branch_id='$sbranch_id' && business_id='$sbusiness_id'"));
					 		// echo (int)$stockvalue['stockvalue']." bra".$sbranch_id." bs ".$sbusiness_id."<br>";
					 		$value =(int) $stockvalue['stockvalue'];
					 		$insertvalue=mysqli_query($con,"INSERT INTo stock_values(date,stock_value,branch_id,business_id) VALUES('$date','$value','$sbranch_id','$sbusiness_id')");

					 		if ($insertvalue) {
					 			$getmaximumstock=mysqli_fetch_array(mysqli_query($con,"SELECT MAX(id) as sid from stock_values where branch_id='$sbranch_id' && business_id='$sbusiness_id' ")); 
					 			  $sstockvalueid=$getmaximumstock['sid'];
					 			  $gtstocklist=mysqli_query($con,"SELECT * FROM stock WHERE branch_id='$sbranch_id' && business_id='$sbusiness_id'");

					 			   while ($stocklist=mysqli_fetch_array($gtstocklist)) {

					 			   		$sproduct=$stocklist['product_name'];
					 			   		$squantity=$stocklist['quantity'];
					 			   		$sbuying_price=$stocklist['buying_price'];
					 			   		$sselling_price=$stocklist['selling_price'];
					 			   		$hhh=mysqli_query($con,"INSERT INTO stock_value_details(stock_value_id, product_id, quantity, buying_price, selling_price, branch_id, business_id) 
					 			   			VALUES('$sstockvalueid','$sproduct','$squantity','$sbuying_price','$sselling_price','$sbranch_id','$sbusiness_id')");
					 			   		if ($hhh) {
					 			   			# code...
					 			   		}else{
					 			   			// echo "Failed ".mysqli_error($con);
					 			   		}
					 			   }

					 		}else{
					 			echo "Error: ".mysqli_error($con);
					 		}
					 	}
					 	
					 } 
				}
	 } 
}


?>