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

session_start();

date_default_timezone_set('Asia/Jakarta');

$table	="retur_pj";

$kode	=$_POST['kode'];
$kodeub	=$_POST['kodeub'];
$kodeplg=$_POST['kodeplg'];
$nomorfk=$_POST['nomorfk'];
$total	=$_POST['total'];
$tothpp	=$_POST['tothpp'];
$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'];
$piut 	= $r['piutang'];
$persed = $r['persed'];
$labapb = $r['laba_pb'];
$retjual= $r['retur_jual'];
$nohpp 	= $r['hpp'];
$labrug = $r['laba_rugi'];
$nobppi = $piut.$kodeplg;
$bpkas 	= $kas.$kodeub.'0001';

$sql = mysql_query("SELECT * FROM $table WHERE kode_rj='$kode' ORDER BY kode_rj");

$namast='';
while ($r=mysql_fetch_array($sql)){
	$kodest	=$r['kode_st'];
	$namast	=$namast.'. '.$r['nama_st'];
	$namapl	=$r['nama_pl'];
	$junit	=$r['jml_unit'];
	
	mysql_query("UPDATE stock SET jml_stok=jml_stok-$junit WHERE kode_st='$kodest'");
}
$laba=$total-$tothpp;

// --->retur penjualan debet dikurangi
mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$total WHERE noakun='$retjual'");

// --->persediaan debet dikurangi
mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$tothpp WHERE noakun='$persed'");

// --->kas / piutang kredit dikurangi
if($caraby=='Tunai'){
	mysql_query("UPDATE akun_bb SET mutasi_kd=mutasi_kd-$total WHERE noakun='$kas'");
	mysql_query("UPDATE akun_bp SET mutasi_kd=mutasi_kd-$total WHERE noakun='$bpkas'");	
}
else{
	mysql_query("UPDATE akun_bb SET mutasi_kd=mutasi_kd-$total WHERE noakun='$piut'");
	
	mysql_query("UPDATE akun_bp SET mutasi_kd=mutasi_kd-$total WHERE noakun='$nobppi'");	
}

// --->hpp kredit dikurangi
mysql_query("UPDATE akun_bb SET mutasi_kd=mutasi_kd-$tothpp WHERE noakun='$nohpp'");

// --->laba periode berjalan debet dikurangi
mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$laba WHERE noakun='$labapb'");

// --->laba rugi kredit dikurangi
mysql_query("UPDATE akun_bb SET mutasi_kd=mutasi_kd-$laba WHERE noakun='$labrug'");
mysql_query("DELETE FROM $table WHERE kode_rj='$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 PENJUALAN','$kode','$namast','Tanggal retur $tanggal, pelanggan $namapl')");

echo "Retur penjualan kode $kode telah dibatalkan.";
?>