<?php
include "../../inc/inc.koneksi.php";
include "../../inc/fungsi_tanggal.php";

session_start();

date_default_timezone_set('Asia/Jakarta');

$table	="faktur_pb";

$kode	=$_POST['kode'];
$kodesup=$_POST['kodesup'];
$nomorfk=$_POST['nomorfk'];
$user	=$_SESSION['username'];
$tgllap	=date('d-m-Y');
$jam	=date('H:i:s');
$tanggal=jin_date_str($tanggal);

$sql	= mysql_query("SELECT * FROM interface");
$r 	 	= mysql_fetch_assoc($sql);
$kas 	= $r['kas'];
$persed = $r['persed'];
$utdg 	= $r['hutang_dg'];
$potbeli= $r['pot_beli'];
$labapb	= $r['laba_pb'];
$labrug	= $r['laba_rugi'];
$noutdg = $utdg.$kodesup;

$sql	 = mysql_query("SELECT * FROM $table WHERE kode_pb='$kode' AND batal='' ORDER BY no_urut");
$row = mysql_num_rows($sql);
if($row>0){
	$namast='';
	$total=0;
	$potong=0;
	$bayar=0;
	
	while ($r=mysql_fetch_array($sql)){
	    $kodeopb=$r['kode_opb'];
		$kodest =$r['kode_st'];
		$namast	=$namast.'. '.$r['nama_st'];
		$namasup=$r['nama_sup'];
		$junit	=$r['jml_unit'];
		$total  =$total+$r['jumlah'];
		$potong =$potong+$r['potongan'];
		$bayar  =$bayar+$r['bayar'];
		
		mysql_query("UPDATE stock SET jml_stokb=jml_stokb-$junit WHERE kode_st='$kodest' AND kode_cab='01'");
		mysql_query("UPDATE sopb SET nofak='',tgl_kirim='' WHERE kode_opb='$kodeopb' AND kode_st='$kodest'");
	}
	$kurang=$total-$potong-$bayar;
	
	mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$total WHERE noakun='$persed'");

	if(!$potong==0){
		mysql_query("UPDATE akun_bb SET mutasi_kd=mutasi_kd-$potong WHERE noakun='$potbeli'");
		mysql_query("UPDATE akun_bb SET mutasi_kd=mutasi_kd-$potong WHERE noakun='$labapb'");
		mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$potong WHERE noakun='$labrug'");
	}
	
	if(!$bayar==0)	mysql_query("UPDATE akun_bb SET mutasi_kd=mutasi_kd-$bayar WHERE noakun='$kas'");

	if(!$kurang==0) mysql_query("UPDATE akun_bb SET mutasi_kd=mutasi_kd-$kurang WHERE noakun='$utdg'");
	
	mysql_query("UPDATE akun_bp SET mutasi_kd=mutasi_kd-$kurang WHERE noakun='$noutdg'");
	mysql_query("DELETE FROM hutang where kode_sp='$kodesup' AND nofak='$nomorfk'");
	mysql_query("UPDATE $table SET batal='BATAL' WHERE kode_pb='$kode'");
	mysql_query("DELETE FROM rekap_mbr WHERE kode_tr='$kode'");
	mysql_query("DELETE FROM rekapjur WHERE kode_tr='$kode'");
	
	mysql_query("INSERT INTO log_history (user,tanggal,jam,aktivitas,no_bukti,nama_st,keterangan) VALUES('$user','$tgllap','$jam','BATAL PEMBELIAN','$kode - $nomorfk','$namast','Tanggal faktur $tanggal, supplier $namasup')");
	echo "Faktur pembelian kode $kode telah dibatalkan.";
}
?>