<?php

class importBmn000000 extends Database
{
	protected $mSqlFile;
	var $pageView;
	var $cssDone = "notebox-done";
	var $cssFail = "notebox-warning";

	function __construct ($connectionNumber=0){
		# increase execution time & memory
		set_time_limit(0);
		ini_set('memory_limit', '1024M');
		ini_set('max_execution_time', 1800);
		
		$this->mSqlFile = 'module/'.Dispatcher::Instance()->mModule.'/business/import_bmn_000000.sql.php';
		parent::__construct($connectionNumber);
		$this->pageView = Dispatcher::Instance()->GetUrl(Dispatcher::Instance()->mModule, 'ImportBmn', 'view', 'html');
		#$this->setDebugOn();
	}
	
	function countInventarisasiDetail(){
		$result = $this->Open($this->mSqlQueries['count_inventarisasi_detail'], array());
		return $result[0]['total'];
	}
	
	# First Conversion
	function firstConvert(){
		
		$masterSql = $this->mSqlQueries;
		$this->StartTrans();
		$success['status'] = true;
		$univName = strtoupper(GTFWConfiguration::GetValue('organization','company_name'));
		foreach($masterSql as $key => $sql){
			if(substr($key,0,3) == 'FC_'){
				$sql = str_replace('[UNIV_NAME]',$univName, $sql);
				$sqlArr = explode(';',$sql);
				foreach($sqlArr as $val){
					if($val <> ''){
						if ($this->Connect()) 
							$result = $this->Execute($val,array());
						else{
							# false when connection lost
							$success['msg'] = $key;
							$success['status'] = false;
							break;
						}
						if(!$result){
							$success['msg'] = $key;
							$success['status'] = false;
							break;
						}
					}
				}
				if($success['status'] == false) break;
			}
		}
		$this->EndTrans($success['status']);
		return $success;
	}
	
	function importBmn(){
		if(isset($_POST['btnsimpan'])){
			$isFirstConvertion = $this->countInventarisasiDetail();
			if((int)$isFirstConvertion == 0){
				# do first convertion
				$startTime = microtime(true);
				$result = $this->firstConvert();
				$endTime = microtime(true);
				if($result['status'])
					Messenger::Instance()->Send(Dispatcher::Instance()->mModule, 'importBmn', 'view', 'html', array($_POST,'Konversi SIMAKBMN Berhasil (exec. time '.($endTime-$startTime).' detik)',$this->cssDone),Messenger::NextRequest);
				else
					Messenger::Instance()->Send(Dispatcher::Instance()->mModule, 'importBmn', 'view', 'html', array($_POST,'Konversi SIMAKBMN Gagal (exec. time '.($endTime-$startTime).' detik)<br>Error : '.$result['msg'],$this->cssFail),Messenger::NextRequest);
				return $this->pageView;
 			}else{
 				# do update content
				Messenger::Instance()->Send(Dispatcher::Instance()->mModule, 'importBmn', 'view', 'html', array($_POST,'Update SIMAKBMN Gagal',$this->cssFail),Messenger::NextRequest);
				return $this->pageView;
 			}
		}else
			return $this->pageView;
	}
}
?>
