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

session_start();

date_default_timezone_set('Asia/Jakarta');

$table	="faktur_pj";

$kode	=$_POST['kode'];
$kodecab=$_POST['kodecab'];
$kodepl	=$_POST['kodepl'];
$jenisby=$_POST['jenisby'];
$nobank =$_POST['nobank'];
$total	=$_POST['total'];
$charge	=$_POST['charge'];
$bayar	=$_POST['tbayar'];
$potong	=$_POST['tpotong'];
$thpp 	=$_POST['thpp'];
$netto	=$total+$charge-$potong;
$laba	=$netto-$thpp;

$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 	= '111'.$kodecab;
$persed	= $r['persed'];
$labapb	= $r['laba_pb'];
$jual 	= $r['penjualan'];
$potjual= $r['pot_jual'];
$pendedc= $r['pendap_edc'];
$potjual= $r['pot_jual'];
$nohpp 	= $r['hpp'];
$labrug = $r['laba_rugi'];

$sql = mysql_query("SELECT * FROM $table WHERE kode_pj='$kode' AND posting='P' AND batal='' ORDER BY no_urut ");
$row = mysql_num_rows($sql);

if($row>0){
	$namast='';
	while ($r=mysql_fetch_array($sql)){
		$kodest =$r['kode_st'];
		$namast	=$namast.'. '.$r['nama_st'];
		$namapl	=$r['nama_pl'];
		$jmlunit=$r['jml_unit'];
		$kodegr	=substr($kodest,0,3);
		
		mysql_query("UPDATE stock SET jml_stok=jml_stok+$jmlunit WHERE kode_st='$kodest' AND kode_cab='$kodecab'");
	}
	if($namapl=='') $namapl='UMUM';
	
	if($jenisby=='TUNAI'){
		mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$netto WHERE noakun='$kas'");		
	}else{
		mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$netto WHERE noakun='$nobank'");
		
		if(!$charge==''){
			mysql_query("UPDATE akun_bb SET mutasi_kd=mutasi_kd-$charge WHERE noakun='$pendedc'");
		}
	}
	
	if($potong>0) mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$potong WHERE noakun='$potjual'");
	
	// --->hpp debet	
	mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$thpp WHERE noakun='$nohpp'");
	// --->penjualan kredit
	mysql_query("UPDATE akun_bb SET mutasi_kd=mutasi_kd-$total WHERE noakun='$jual'");	
	// --->persediaan kredit
	mysql_query("UPDATE akun_bb SET mutasi_kd=mutasi_kd-$thpp WHERE noakun='$persed'");	
	// --->laba rugi debet
	mysql_query("UPDATE akun_bb SET mutasi_db=mutasi_db-$laba WHERE noakun='$labrug'");	
	// --->laba periode berjalan kredit
	mysql_query("UPDATE akun_bb SET mutasi_kd=mutasi_kd-$laba WHERE noakun='$labapb'");
	
	mysql_query("UPDATE $table SET posting='' WHERE kode_pj='$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 PENJUALAN TUNAI','$kode','$namast','Tanggal faktur $tanggal, pelanggan $namapl')");
	echo "Faktur penjualan kode $kode telah dibatalkan.";
}
?>