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

session_start();

date_default_timezone_set('Asia/Jakarta');

$table	="retur_pb";

$kode	=$_POST['kode'];
$kodesup=$_POST['kodesup'];
$nomorfk=$_POST['nomorfk'];
$total	=$_POST['total'];
$caraby	=$_POST['caraby'];

$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'];
$noutdg	= $utdg.$kodesup;

$sql = mysql_query("SELECT * FROM $table WHERE kode_rb='$kode' ORDER BY kode_rb");
$trugi=0;
$tasal=0;
$total=0;

$namast='';
while($r=mysql_fetch_array($sql)){	
	$kodest 	=$r['kode_st'];
	$namast		=$namast.'. '.$r['nama_st'];
	$namasup	=$r['nama_sup'];
	$jmlretur	=$r['jml_retur'];		
	$rugi		=$r['jumlah_asal']-$r['jumlah'];
	$trugi		=$trugi+$rugi;
	$tasal		=$tasal+$r['jumlah_asal'];
	$total		=$total+$r['jumlah'];
	
	mysql_query("UPDATE stock SET jml_stokb=jml_stokb+$jmlretur WHERE kode_st='$kodest'");
}

if($caraby=='Tunai')
	mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$total WHERE noakun='$kas'");	
else{	
	mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$total WHERE noakun='$utdg'");
	mysql_query("UPDATE akun_bp SET mutasi_db=mutasi_db-$total WHERE noakun='$noutdg'");
	mysql_query("UPDATE hutang SET jumlah=jumlah+$total WHERE kode_sp='$kodesup' AND nofak='$nomorfk' ");
}
mysql_query("UPDATE akun_bb SET mutasi_kd=mutasi_kd-$tasal WHERE noakun='$persed'");
mysql_query("INSERT INTO rekapjur (kode_tr,jurnal,tanggal,no_bukti,no_urut,noakun,nosub,nobp,nofak,debet,kredit,keterangan,user) VALUES('$kode','RPB','$tanggal','$kode','$nourut','$persed','$nosubps','','','0','$tasal','Retur faktur $nomorfk $namasup','$user')");

if(!($trugi==0)){
	mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$trugi WHERE noakun='$rugiretur'");
	mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$trugi WHERE noakun='$labapb'");
	mysql_query("UPDATE akun_bb SET mutasi_kd=mutasi_kd-$trugi WHERE noakun='$labrug'");	
}
mysql_query("UPDATE $table SET batal='BATAL' WHERE kode_rb='$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 RETUR PEMBELIAN','$kode - $nomorfk','$namast','Tanggal retur $tanggal, supplier $namasup')");
echo "Retur pembelian kode $kode telah dibatalkan.";
?>