<?php
 // Update quantity when there is any branch sales amendment*****************************************************
   $recex=mysqli_query($cons, "SELECT *FROM `stouse` WHERE `Action`='SALES' AND `Upda`='1' AND `Status`='20' AND `Voucher`!='0' ORDER BY `Voucher` DESC LIMIT 60");
   if($fecex=mysqli_num_rows($recex)){
				while($rex=mysqli_fetch_assoc($recex)){
					$nuo=$rex['Number'];
					$ito=$rex['Item'];
					$qto=$rex['Quantity'];
					$dest=$rex['Invoice'];

		$doix=mysqli_query($cons, "SELECT `Number` FROM `branches` WHERE `Name`='$dest' ORDER BY `Number` DESC LIMIT 1");
		if($foix=mysqli_num_rows($doix)){
			$roix=mysqli_fetch_assoc($doix);
				$br=$roix['Number'];
					$bra="S$br";

	$dow=mysqli_query($cons, "UPDATE `items` SET `$bra`=`$bra`+'$qto' WHERE `Number`='$ito' ORDER BY `Number` ASC LIMIT 1");
		}
		else{
		$doq=mysqli_query($cons, "UPDATE `items` SET `Quantity`=`Quantity`+'$qto', `Star`=`Star`-'1' WHERE `Number`='$ito' ORDER BY `Number` ASC LIMIT 1");
				$bra="Quantity";
		}

		if($rex['Status']=='20')
			$upi=", `Status`='0', `Voucher`='0'";
		else
			$upi="";

			$dova=mysqli_query($cons, "SELECT *FROM `items` WHERE `Number`<'$ito' ORDER BY `Number` DESC LIMIT 1");
				$rova=mysqli_fetch_assoc($dova);
						$qty=$rova["$bra"];
	$thent=mysqli_query($cons, "UPDATE `stouse` SET `Upda`='0', `Closing`='$qty' $upi WHERE `Number`='$nuo' ORDER BY `Number` ASC LIMIT 1");
				}
   }

   // Roll back payments when there is an branch sales amendment ****************************************************************
	$doit=mysqli_query($cons, "SELECT *FROM `payment` WHERE `Status`>'0' AND `Action`='SALES' AND `Voucher`!='0' AND `Upda`='1' ORDER BY `Number` ASC LIMIT 10");
				while($roit=mysqli_fetch_assoc($doit)){
					$nuo=$roit['Number'];
					$custo=$roit['Branche'];
					if($roit['Pline']=='CREDIT'){
						$cre=$roit['Amount'];
						$cus=$roit['Customer'];

			$crdi=mysqli_query($cons, "UPDATE `account` SET `Balance`=`Balance`-'$cre' WHERE `Customer`='$cus' AND `Branche`='$brc' ORDER BY `Number` ASC LIMIT 1");
					}
					if($roit['Pline']=='BANK'){
						$pa=$roit['Amount'];
						$pda=$roit['Date'];
						$cheno=$roit['Cheno'];
						$cuso=$roit['Customer'];
						$bna=$roit['Bname'];
						$vous=$roit['Voucher'];
						$descri="Invoice No: $vous";

		$and=mysqli_query($cons, "DELETE FROM `deposit` WHERE `Item`='DEPOSIT' AND `Refer`='$cheno' AND `Amount`='$pa' AND `Customer`='$cuso' AND `Operation`='SALES' AND `Account`='$bna' AND `Descri`='$descri' AND `Voucher`='$vous' AND `Branche`='$custo'");
					}

		if($roit['Status']=='2')
			$upi=", `Status`='0', `Voucher`='0'";
		else
			$upi="";

			$thent=mysqli_query($cons, "UPDATE `payment` SET `Upda`='0' $upi WHERE `Number`='$nuo' ORDER BY `Number` ASC LIMIT 1");
				}
				?>