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

session_start();

date_default_timezone_set('Asia/Jakarta');

$kode	=$_POST['kode'];
$tanggal=$_POST['tanggal'];
$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'];
$potjual= $r['pot_jual'];
$labapb	= $r['laba_pb'];
$labrug	= $r['laba_rugi'];

$query 	= mysql_query("SELECT * FROM jurppi WHERE kode_ppi='$kode'");
$ttunai	= 0;
$tpot  	= 0;

$tnofak	= '';
$namapl	= '';
while($data=mysql_fetch_array($query)){
	$nofak	 = $data['nofak'];
	$tnofak	 = $tnofak.'. '.$nofak;
	$kodepl  = $data['kode_pl'];
	$namapl  = $data['nama_pl'];
	$nobppi	 = $piut.$kodepl;
	$tunai   = $data['tunai'];
	$potongan= $data['potongan'];
	$ttunai  = $ttunai+$data['tunai'];
	$tpot	 = $tpot+$data['potongan'];
		
	$sql1	= mysql_query("SELECT kode_pl,nofak,jumlah FROM piutang WHERE kode_pl='$kodepl' AND nofak='$nofak'");
	$r1 	= mysql_fetch_assoc($sql1);
	$saldo 	= $r1['jumlah']+$tunai+$potongan;
		
	mysql_query("UPDATE piutang SET jumlah='$saldo' WHERE kode_pl='$kodepl' AND nofak='$nofak'");
}

// --->kredit piutang berkurang
$sql = mysql_query("SELECT noakun,mutasi_kd FROM akun_bb WHERE noakun='$piut' ");
$r 	 = mysql_fetch_assoc($sql);	
$kredit = $r['mutasi_kd']-$ttunai-$tpot;
		
mysql_query("UPDATE akun_bb SET mutasi_kd='$kredit' WHERE noakun='$piut'");
		
$sql= mysql_query("SELECT noakun,mutasi_kd FROM akun_bp WHERE noakun='$nobppi'");
$r 	= mysql_fetch_assoc($sql);
$kredit = $r['mutasi_kd']-$ttunai-$tpot;
		
mysql_query("UPDATE akun_bp SET mutasi_kd='$kredit' WHERE noakun='$nobppi'");

if(!($ttunai==0)){
	// --->debet kas bertambah
	mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$ttunai WHERE noakun='$kas'");	
}

if(!($tpot==0)){
	// --->debet potongan penjualan
	mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$tpot WHERE noakun='$potjual'");
	mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$tpot WHERE noakun='$labapb'");
	mysql_query("UPDATE akun_bb SET mutasi_kd=mutasi_kd-$tpot WHERE noakun='$labrug'");
}

mysql_query("UPDATE jurppi SET batal='BATAL' WHERE kode_ppi='$kode'");
mysql_query("UPDATE rekapjur SET batal='BATAL' WHERE kode_tr='$kode'");

mysql_query("INSERT INTO log_history (user,tanggal,jam,aktivitas,no_bukti,nama_st,keterangan) VALUES('$user','$tgllap','$jam','BATAL PENERIMAAN PIUTANG','$kode','$tnofak','Tanggal PPI $tanggal, pelanggan $namapl')");
?>