<?php

include "../../config/koneksi.php";
$awal = $_GET['awal'];
$db = $_GET['db'];
$akhir = $_GET['akhir'];

if($akhir =="Y"){
	$equal = "= ";
}else{
	$equal = "";
}

	mysql_query("TRUNCATE kitchenc_data.$db");
	
	$cek = mysql_query("select 'Beli' AS `jenis`,`beli`.`billno` AS `billno`,`beli`.`billdate` AS `billdate`,`beli`.`dateadded` AS `dateadded`,`belidetail`.`produk` AS `produk`,`belidetail`.`qty` AS `qty`,`belidetail`.`harga` AS `harga`,(select sum(`belimasuk`.`qty`) from `belimasuk` where `belimasuk`.`id_detail` = `belidetail`.`id`) AS `reall` from (`beli` join `belidetail` on(`beli`.`billno` = `belidetail`.`billno` and `beli`.`status` = 'V' and `beli`.`isretur` = 'N')) where beli.billno not in (select belino from $db where jenis = 'Non') and beli.billdate <$equal '$awal' ");
	while ($r=mysql_fetch_array($cek)){	
	
		mysql_query("insert into $db(jenis,belino, belidate,beliprice,qtybeli,produk) values('Non','$r[billno]','$r[billdate]','$r[harga]','$r[qty]','$r[produk]')");
	}
	
	
	$cek = mysql_query("select 'BeliTax' AS `jenis`,`buy`.`billno` AS `billno`,`buy`.`billdate` AS `billdate`,`buy`.`dateadded` AS `dateadded`,`buydetail`.`produk` AS `produk`,`buydetail`.`qty` AS `qty`,`buydetail`.`harga2` AS `harga`,(select sum(`buymasuk`.`qty`) from `buymasuk` where `buymasuk`.`id_detail` = `buydetail`.`id`) AS `reall` from (`buy` join `buydetail` on(`buy`.`billno` = `buydetail`.`billno` and `buy`.`status` = 'V' and `buy`.`isretur` = 'N')) where buy.billno not in (select belino from $db where jenis = 'Tax') and buy.billdate <$equal '$awal' ");
	while ($r=mysql_fetch_array($cek)){	
	
		mysql_query("insert into $db(jenis,belino, belidate,beliprice,qtybeli,produk) values('Tax','$r[billno]','$r[billdate]','$r[harga]','$r[qty]','$r[produk]')");
	}
	
	
	$cek = mysql_query("select 'Jual' AS `jenis`,`jualcs`.`billno` AS `billno`,`jualcs`.`ucode` AS `ucode`,`jualcs`.`billdate` AS `billdate`,`jualcs`.`dateadded` AS `dateadded`,`jualcsdetail`.`produk` AS `produk`, `jualcsdetail`.`qty` AS `qty`, (select sum(`jualklr`.`qty`) from `jualklr` where `jualklr`.`id_detail` = `jualcsdetail`.`id`) AS `reall` from (`jualcs` join `jualcsdetail` on(`jualcs`.`billno` = `jualcsdetail`.`billno` and `jualcs`.`ucode` = `jualcsdetail`.`ucode` and `jualcs`.`isretur` = 'N' and `jualcs`.`status` = 'N'  and jualcs.billdate <$equal '$awal'))   ");
	while ($r=mysql_fetch_array($cek)){	
		$qjual = $r['qty'];
		$cek2 = mysql_query("select * from $db where produk = $r[produk] and qtyjual < qtybeli");
		while ($r2=mysql_fetch_array($cek2)){	
			$qbeli = $r2['qtybeli'];
			$qty = 0;
			if ($qjual <= $qbeli){			
				$qty = $qbeli - $qjual;
			}else{
				$qty = $qbeli;
			}
			
			if($qjual > 0 ){
				mysql_query("update $db set qtyjual = '$qty' , jualno = '$r2[billno]' , ucode = '$r2[ucode]' where id = $r2[id]");
			}
			$qjual = $qjual - $qty;
		}
	}

?>