<?php
/*
	@ClassName : BhpPindahGudang
	@Copyright : PT Gamatechno Indonesia
	@Analyzed By : Dyan Galih
	@Author By : Didi Zuliansyah
	@Version : 01
	@StartDate : 2013-01-01
	@LastUpdate : 2013-01-01
	@Description : Class BhpPindahGudang
*/

class BhpPindahGudang extends Database
{
	protected $mSqlFile;

	function __construct ($connectionNumber=0)
	{
		$this->mSqlFile = 'module/'.Dispatcher::Instance()->mModule.'/business/bhp_pindah_gudang.sql.php';
		parent::__construct($connectionNumber);
		#$this->setDebugOn();
	}
	
	# =========== GET FUNCTION ============== #
	
	function GetKodeSistem(){
		$userId = Security::Instance()->mAuthentication->GetCurrentUser()->GetUserId();
		$result = $this->Open($this->mSqlQueries['get_kode_sistem'], array($userId));
		return $result[0]['unitkerjaKodeSistem'];
	}
	
	function GetDataBHPPindahGudang($noTransaksi,$unitAsal,$unitTujuan,$namaBarang,$startRec,$itemViewed){
		$result =  $this->Open($this->mSqlQueries['get_data_bhp_pindah_ruang'],array('%'.$noTransaksi.'%','%'.$namaBarang.'%','%'.$unitAsal.'%','%'.$unitTujuan.'%',$startRec,$itemViewed));
		return $result;
	}
	
	# multiunit
	function GetDataUsulanBhp($startRec, $itemViewed, $unitKerja, $noUsulanBhp, $namaBarang){
		$kodeSistem = $this->GetKodeSistem();
		$sql = $this->mSqlQueries['get_data_usulan_bhp'];
		$sql = ($unitKerja <> '' && $unitKerja <> 'all') ? str_replace('[SEARCH_UNIT]', ' AND usulanBrgUnitId = '.$unitKerja, $sql) : str_replace('[SEARCH_UNIT]', '', $sql);
		$result = $this->Open($sql,array('%'.$noUsulanBhp.'%','%'.$namaBarang.'%',$kodeSistem,$kodeSistem.'.%',$startRec, $itemViewed));
		return $result;
	}
	
	function GetDataUsulanBhpById($usulanId){
		$result = $this->Open($this->mSqlQueries['get_data_usulan_bhp_by_id'],array($usulanId));
		return $result[0];
	}
	
	# multiunit
	function GetDataUnitkerja ($offset, $limit, $unitkerja='', $kode='',$group=1) {
		# show unit group default
		$kodeSistem = ($group == 1) ? $this->GetKodeSistem() : '';
		$sql = $this->mSqlQueries['get_data_unitkerja'];
		$sql = ($kodeSistem <> '') ? str_replace('[KODE_SISTEM]', "AND (a.unitkerjaKodeSistem = '".$kodeSistem."' OR a.unitkerjaKodeSistem LIKE '".$kodeSistem.".%%')", $sql) : str_replace('[KODE_SISTEM]', "", $sql);
		$result = $this->Open($sql, array('%'.$kode.'%', '%'.$kode.'%', '%'.$unitkerja.'%', '%'.$unitkerja.'%', $offset, $limit));
		return $result;
	}
	
	# multiunit
	function GetComboUnitKerja(){
		$kodeSistem = $this->GetKodeSistem();
		$result = $this->Open($this->mSqlQueries['get_combo_unit_kerja'],array($kodeSistem,$kodeSistem.'.%'));
		return $result;
	}
	
	function GetComboGudang($idUnit){
		$result = $this->Open($this->mSqlQueries['get_combo_gudang'],array($idUnit));
		return $result;
	}
	
	function GetCount(){
		$result = $this->Open($this->mSqlQueries['get_count'],array());
		return $result[0]['total'];
	}
	
	# FOR POPUP KODE BARANG
	function GetDataJenis($data,  $unitId, $gudangId, $usulId, $start = 0, $limit = 1000)
	{
		extract ($data);
		if (is_numeric($CARI_GOLONGAN))
			$newQuery = str_replace('%golongan%', 'AND', $this->mSqlQueries['get_data_jenis']);
		else $newQuery = str_replace('%golongan%', 'OR', $this->mSqlQueries['get_data_jenis']);
	
		if (is_numeric($CARI_BIDANG_ID))
			$newQuery = str_replace('%bidang%', 'AND', $newQuery);
		else $newQuery = str_replace('%bidang%', 'OR', $newQuery);
	
		if (is_numeric($CARI_KELOMPOK_ID))
			$newQuery = str_replace('%kelompok%', 'AND', $newQuery);
		else $newQuery = str_replace('%kelompok%', 'OR', $newQuery);
	
		if (is_numeric($CARI_SUB_KELOMPOK_ID))
			$newQuery = str_replace('%subKelompok%', 'AND', $newQuery);
		else $newQuery = str_replace('%subKelompok%', 'OR', $newQuery);
	
		if (is_numeric($CARI_JENIS_BARANG))
			$newQuery = str_replace('%jenisBarang%', 'AND', $newQuery);
		else $newQuery = str_replace('%jenisBarang%', 'OR', $newQuery);
		
		if ($usulId <> '' && $usulId <> NULL){
			$arrUsul = $this->GetDataUsulanBhpById($usulId);
			$newQuery = str_replace('[VAR_JML_USULAN]', ',"'.$arrUsul['stok_pindah'].'" AS stokPindah', $newQuery);
			$newQuery = str_replace('[SEARCH_BRG_USULAN]', ' AND invAtkJenisRefId = '.$arrUsul['barangId'], $newQuery);
		}else{
			$newQuery = str_replace('[VAR_JML_USULAN]', '', $newQuery);
			$newQuery = str_replace('[SEARCH_BRG_USULAN]', '', $newQuery);
		}
	
		$arg = array
		(
				$unitId,
				$gudangId,
				$CARI_GOLONGAN,
				$CARI_BIDANG_ID,
				$CARI_KELOMPOK_ID,
				$CARI_SUB_KELOMPOK_ID,
				"%$CARI_NAMA_BARANG%",
				"%$CARI_NAMA_BARANG%",
				$CARI_JENIS_BARANG,
				$start,
				$limit
		);
		$result = $this->Open($newQuery, $arg);
		if (count($result) == 0) return array();
		foreach ($result as $value)
			$return[$value['idKelompok']][$value['idSubKelompok']][$value['idBarang']][$value['id']] = $value;
		return $return;
	}
	
	function GetDataBarang($data, $start = 0, $limit = 1000)
	{
		extract ($data);
		if (is_numeric($CARI_GOLONGAN))
			$newQuery = str_replace('%golongan%', 'AND', $this->mSqlQueries['get_data_barang']);
		else $newQuery = str_replace('%golongan%', 'OR', $this->mSqlQueries['get_data_barang']);
	
		if (is_numeric($CARI_BIDANG_ID))
			$newQuery = str_replace('%bidang%', 'AND', $newQuery);
		else $newQuery = str_replace('%bidang%', 'OR', $newQuery);
	
		if (is_numeric($CARI_KELOMPOK_ID))
			$newQuery = str_replace('%kelompok%', 'AND', $newQuery);
		else $newQuery = str_replace('%kelompok%', 'OR', $newQuery);
	
		if (is_numeric($CARI_SUB_KELOMPOK_ID))
			$newQuery = str_replace('%subKelompok%', 'AND', $newQuery);
		else $newQuery = str_replace('%subKelompok%', 'OR', $newQuery);
	
		if (is_numeric($CARI_JENIS_BARANG))
			$newQuery = str_replace('%jenisBarang%', 'AND', $newQuery);
		else $newQuery = str_replace('%jenisBarang%', 'OR', $newQuery);
	
		$arg = array
		(
				$CARI_GOLONGAN,
				$CARI_BIDANG_ID,
				$CARI_KELOMPOK_ID,
				$CARI_SUB_KELOMPOK_ID,
				"%$CARI_NAMA_BARANG%",
				"%$CARI_NAMA_BARANG%",
				$CARI_JENIS_BARANG,
				$start,
				$limit
		);
		$result = $this->Open($newQuery, $arg);
		if (count($result) == 0) return array();
		foreach ($result as $value)
			$return[$value['idKelompok']][$value['idSubKelompok']][$value['id']] = $value;
		return $return;
	}
	
	function GetKelompokList()
	{
		$result = $this->Open($this->mSqlQueries['get_kelompok_list'], array());
		if (count($result) == 0) return array();
		foreach ($result as $value)
			$return[$value['id']] = $value;
		return $return;
	}
	
	function GetSubKelompokList()
	{
		$result = $this->Open($this->mSqlQueries['get_sub_kelompok_list'], array());
		foreach ($result as $value)
			$return[$value['idKelompok']][$value['id']] = $value;
		return $return;
	}
	
	function GetLastInsertId(){
		$result = $this->Open($this->mSqlQueries['get_last_insert_id'], array());
		return $result[0]['id'];
	}
	
	# ====== UPDATE STOK GUDANG ======= #
	function ab($nilai,$data,$i,$akhir,$habis){
		if ($i < $akhir){
			if ($habis==1){
				$sisa = $data[$i];
			}	else	{
				$sisa = $nilai-$data[$i];
				$sisa2 = $sisa;
				if($sisa<0){
					$sisa = $sisa*(-1);
					$habis = 1;
				} elseif($sisa){
					$sisa=0;
				}
			}
				
			$x = $i+1;
				
			$this->ab($sisa2,$data,$x,$akhir,$habis);
			$_SESSION['hasil'][] = $sisa;
		}
	}
	
	function GetMstByBrgId($barangId)
	{
		$result = $this->Open($this->mSqlQueries['get_mst_id'], array($barangId));
		return $result['0']['invAtkMstId'];
	}
	
	function GetBrgByMstId($id)
	{
		$result = $this->Open($this->mSqlQueries['get_brg_by_mst_id'], array($id));
		return $result;
	}
	
	function GetMaxGdgByDetId($detId, $ruangId)
	{
		$result = $this->Open($this->mSqlQueries['get_max_gdg_by_det_id'], array($detId, $ruangId));
		return $result[0]['jumlah'];
	}
	
	function UpdateGudangMax($data)
	{
		$result = $this->Execute($this->mSqlQueries['update_gudang_max'], $data);
		return $this->AffectedRows();
	}
	
	function AddGudangTujuan($gudangId,$atkBrgId,$jumlah){
		$result = $this->Execute($this->mSqlQueries['add_gudang_tujuan'], array($gudangId,$atkBrgId,$jumlah));
		return $this->AffectedRows();
	}
	
	function AddInvAtkBrg($atkJenisRefId,$jumlah){
		$result = $this->Execute($this->mSqlQueries['add_inv_atk_brg'], array($atkJenisRefId,$jumlah));
		return $this->AffectedRows();
	}
	
	function AddLogUpdate($data){
		$result = $this->Execute($this->mSqlQueries['add_log_update'], $data);
		return $this->AffectedRows();
	}
	
	function UpdateStokGedung($data,$noTrans,$unitTujuan,$gudangTujuan)
	{
		foreach($data as $val){
			if($val['jumlah'] <= $val['stok']){
				$mstId = $this->GetMstByBrgId($val['mstId']);
				$detId = $this->GetBrgByMstId($mstId);
				$keymax = array_keys($detId, max($detId));
				$detIdMax = $detId[$keymax[0]]['invBrgAtkId'];
	
				foreach($detId as $value){
					$jumlah[] = (int)$this->GetMaxGdgByDetId($value['invBrgAtkId'], $val['ruangId']);
				}
	
				$x = 0;
				$habis = 2;
				$akhir = sizeof($jumlah);
				$this->ab($val['jumlah'], $jumlah, $x, $akhir, $habis);
				$resultx = array_reverse($_SESSION['hasil']);
	
				foreach($detId as $values){
					$dataDet = array($resultx[$x], $val['ruangId'], $values['invBrgAtkId']);
					$result = $this->UpdateGudangMax($dataDet);
					$x++;
				}
	
				# update/insert gudang tujuan
				$addInvAtkBrg = $this->AddInvAtkBrg($val['barangId'],$val['jumlah']);
				$atkBrgId = $this->GetLastInsertId();
				$addGudangTujuan = $this->AddGudangTujuan($gudangTujuan,$atkBrgId,$val['jumlah']);
				
				# add log atk
				$dataDet = array($val['ruangId'], $detIdMax, $val['jumlah'], $unitTujuan, $gudangTujuan, $noTrans); # log gudang asal
				# log gudang tujuan (optional)
				$result = $this->AddLogUpdate($dataDet);
			}
			unset($jumlah);
			unset($_SESSION['hasil']);
		}
		return $result;
	}
	
	# ======== INSERT BHP PINDAH GUDANG ========= #
	
	function AddBhpMutasiMst($arrData){
		return $this->Execute($this->mSqlQueries['add_bhp_mutasi_mst'],$arrData);
	}
	
	function AddBhpMutasiDet($arrData){
		return $this->Execute($this->mSqlQueries['add_bhp_mutasi_det'],$arrData);
	}
	
	function InsertBhpPindahGudang($data){
		$this->StartTrans();
		
		# add bhp_mutasi_mst
		$userId = Security::Instance()->mAuthentication->GetCurrentUser()->GetUserId();
		$data['usulanbhpid'] = ($data['usulanbhpid'] == '') ? NULL : $data['usulanbhpid'];
		$arrDataMst = array(
						$data['unitasalid'],
						$data['gudangasal'],
						$data['unittujuanid'],
						$data['gudangtujuan'],
						$data['usulanbhpid'],
						$data['tglpindah_year'].'-'.$data['tglpindah_mon'].'-'.$data['tglpindah_day'],
						$data['pic'],
						$data['notrans'],
						$data['keterangan'],
						$userId
					  );
		$addBhpMutasiMst = $this->AddBhpMutasiMst($arrDataMst);
		
		$detil = $data['barangList'];
		
		# add bhp_mutasi_det
		$mstId = $this->GetLastInsertId();
		foreach($detil as $value){
			$arrDataDet = array(
						$mstId,
						$value['mstId'],
						$value['jumlah']
				);
			$addBhpMutasiDet = $this->AddBhpMutasiDet($arrDataDet);
			if(!$addBhpMutasiDet) break;
		}
		
		# update stok gudang Asal
		$updateStokGudang = $this->UpdateStokGedung($detil,$data['notrans'],$data['unittujuanid'],$data['gudangtujuan']);
		
		if($addBhpMutasiMst && $addBhpMutasiDet && $updateStokGudang){
			$this->EndTrans(true);
			return true;
		}else{
			$this->EndTrans(false);
			return false;
		}
		
	}
}
?>