<?php
require_once GTFWConfiguration::GetValue( 'application', 'docroot').
   'module/inventarisasi/business/AppInventarisasi.class.php';

class ProcessReInventarisasi
{
	var $_POST;
	var $Obj;
	var $pageView;
	var $pageInput;
	var $errmsg;
	//css hanya dipake di view
	var $cssDone = "notebox-done";
	var $cssFail = "notebox-warning";

	var $return;

	function __construct() {
		$this->Obj = new AppInventarisasi;
		$this->_POST = $_POST->AsArray();
		$this->pageView = Dispatcher::Instance()->GetUrl('inventarisasi', 'inventarisasi', 'view', 'html', true);
		$this->pageInput = Dispatcher::Instance()->GetUrl('inventarisasi', 'ReInventarisasi', 'view', 'html', true);
	}
   
   function Check ()
   {
      if (isset($this->_POST['btnbalik'])) return $this->pageView;
      if (!isset($this->_POST['invBarangId'])) return $this->pageInput;
      unset($this->_POST['btnsimpan']);
      
      $msg = array();
      $KibList = $this->Obj->ConvertCombo($this->Obj->GetCbxJenisKib());
      $KIB = $KibList[$this->_POST['golbrgId']];
      
      $MustExists = array("invBarangId", "invMstLabel", "invTglPembelian", "invUmurEkonomis", "invUnitKerja");
      if(strpos($KIB, 'KIB B:') === 0) // KIB A: Tanah atau KIB C: Gedung dan Bangunan
         array_push($MustExists, "invLuasTanah", "invNilaiPerolehanSatuan"/*, "invNilaiFaktur"*/, "invNJOP");
      elseif(strpos($KIB, 'KIB D:') === 0) // KIB B: Peralatan dan Mesin
         array_push($MustExists, /*"invNilaiFaktur", */"invNilaiResidu");
      elseif(strpos($KIB, 'KIB C:') === 0 OR strpos($KIB, 'KIB F:') === 0) // KIB E: Aset Lainnya
         array_push($MustExists, "invNilaiPerolehanSatuan", "invNilaiResidu", "lokasiAset");
      $MustNumeric = array
      (
         'invTglPembelian' => 'Tahun Pembelian',
         'invUmurEkonomis' => 'Umur Ekenomis',
         'invJumlahAset' => 'Jumlah Aset',
         'invLuasTanah' => 'Luas Tanah',
         'invNilaiPerolehanSatuan' => 'Nilai Perolehan per Satuan',
         'invNilaiFaktur' => 'Nilai Faktur',
         'invTotalPerolehan' => 'Total Perolehan',
         'invNilaiResidu' => 'Nilai Residu',
         'invNJOP' => 'NJOP'
      );
      
      foreach ($MustExists as $val) if ((string)$this->_POST[$val] == '')
         {$msg[] = 'Isian bertanda * (bintang) tidak boleh kosong!'; break;}
      
      foreach ($MustNumeric as $key=>$val)
         if (!is_numeric($this->_POST[$key]) AND $this->_POST[$key] != '')
            $list[] = $val;
      foreach ($this->_POST['biaya_lain'] as $val)
         if (!is_numeric(@$this->_POST[$val]) AND @$this->_POST[$val] != '')
            {$list[] = "Biaya lain"; break;}
      if (isset($list))
      {
         $tmp = "Field berikut harap diisi dengan bilangan numerik!\n";
         foreach ($list as $val)
            $tmp .= "\t\t<li style='margin-left: 2em; list-style: circle'>$val</li>\n";
         $msg[] = "$tmp\t";
      }
      
      if(!$this->CheckUploadedImage('invNamaFile'))
      	$msg[] = $this->errmsg;
      // if ($this->_POST['invUmurEkonomis'] < 1) $msg[] = "Umur ekonomis tidak boleh 0!";
      
      if (count($msg) > 0)
      {
         $msg = array($this->_POST, $msg, '');
         $this->msg = $msg;
         
         $return = $this->pageInput;
         if (isset($_GET['id'])) $return .= "&id=".$_GET['id'];
         return $return;
      }
      
		// Penyesuaian data input
		$proxy =& $this->_POST;
		$proxy['invTglPembelian'] = date(intval($proxy['invTglPembelian']).'-m-d H:i:s', time());
		if ($proxy['isInvSertifikat'] != 'checked') $proxy['invSertifikat'] = '';
		if ($proxy['isInvAkta'] != 'checked') $proxy['invAkta'] = '';
		if ($proxy['isInvBPKB'] != 'checked') $proxy['invBPKB'] = '';
		if ($proxy['isInvSTNK'] != 'checked') $proxy['invSTNK'] = '';
		$proxy['isinvGedungId'] = intval($proxy['invGedungId']);
		$proxy['isinvRuanganId'] = intval($proxy['invRuanganId']);
		// ---------
		
      return true;
   }
   
   function Add()
   {
      $check = $this->Check();
      if ($check !== true)
      {
         @Messenger::Instance()->Send('inventarisasi', 'ReInventarisasi', 'view', 'html', $this->msg, Messenger::NextRequest);
         return $check;
      }
      $this->_POST['invNamaFile'] = $this->UploadImage('invNamaFile');
      $result = $this->Obj->AddReInventarisasi($this->_POST);
      if ($result === 0)
         $msg = array(1=>'Penambahan Data Berhasil Dilakukan.', $this->cssDone);
      else $msg = array(1=>'Proses Penambahan Data Gagal!'.$result, $this->cssFail);
      Messenger::Instance()->Send('inventarisasi', 'inventarisasi', 'view', 'html', $msg, Messenger::NextRequest);
      
      return $this->pageView;
   }
   
   function Update()
   {
      $this->pageInput = Dispatcher::Instance()->GetUrl('inventarisasi', 'inventarisasiEdit', 'view', 'html');
      $check = $this->Check();
      if ($check !== true)
      {
         @Messenger::Instance()->Send('inventarisasi', 'inventarisasiEdit', 'view', 'html', $this->msg, Messenger::NextRequest);
         return $check;
      }
		
		$files1 = explode('-', $this->_POST['invNamaFileOld']);
		$files2 = explode('.', $files1[1]);
		$filesA = $files1[0].'.'.$files2[1];
		$filesB = $_FILES['invNamaFile']['name'].'.'.$_FILES['invNamaFile']['ext'];
		if($this->_POST['oldKondisi'] == $this->_POST['invKondisiBrgKondId'] && ($filesA == $filesB || $_FILES['invNamaFile']['error']=='4')){
			$this->_POST['invNamaFile'] = $this->_POST['invNamaFileOld'];
		} else {
			$this->_POST['invNamaFile'] = $this->UploadImage('invNamaFile');
			if(empty($this->_POST['invNamaFile'])){
				$this->_POST['invNamaFile'] = $this->_POST['invNamaFileOld'];
			}
		}

      $result = $this->Obj->UpdateReInventarisasi($_GET['id']->Integer()->Raw(), $this->_POST);
		
      if($result === 0)$msg = array(1=>'Perubahan Data Berhasil Dilakukan.', $this->cssDone);
      else $msg = array(1=>'Tidak Berhasil Mengubah Data!', $this->cssFail);
      Messenger::Instance()->Send('inventarisasi', 'inventarisasi', 'view', 'html', $msg, Messenger::NextRequest);

      return $this->pageView;
   }
	
	function CheckUploadedImage($image,$fileChange=false)
   {
   	  $maxSize = GTFWConfiguration::GetValue('application','max_upload_size');
      $fileName = strrev($_FILES[$image]['name']);
      $fileExtPos = strpos($fileName, '.');
      $fileExt = strtolower(strrev(substr($fileName, 0, $fileExtPos)));
      if($fileChange){
      	$_FILES[$image]['name']= strrev(substr($fileName, $fileExtPos + 1));
      	$_FILES[$image]['ext']= $fileExt;
      }
      if
      (
         $_FILES[$image]['error'] !== 0 ||
         strpos($_FILES[$image]['type'], 'image') !== 0 ||
      	 ($_FILES[$image]['size']/pow(1024,2)) > $maxSize ||
         !in_array($fileExt, array('gif','jpg','jpeg','png','bmp')) AND
         $fileName !== ''
      ){
      	 if (($_FILES[$image]['size']/pow(1024,2)) > $maxSize) $this->errmsg = 'Ukuran file tidak boleh lebih dari '.$maxSize.' MB';
         return false;
      }else return true;
   }
	
	function UploadImage($image)
   {
      if (!$this->CheckUploadedImage($image,true)) return false;
      $fileName = $_FILES[$image]['name'];
      if ($fileName === '') return '';
      
      $fileExt = $_FILES[$image]['ext'];
      $fileName .= "-".dechex(mt_rand(65536,1048575)).".$fileExt";
      if (move_uploaded_file($_FILES[$image]['tmp_name'], GTFW_APP_DIR."/document/inventarisasi/$fileName")) 
         return $fileName;
      else return false;
   }
}
?>