<?php

class PengendalianBarang extends Database {

   protected $mSqlFile;
   public $mFilePath = 'file/';
   
   function __construct($connectionNumber=0) {
      $this->mSqlFile = 'module/'.Dispatcher::Instance()->mModule.'/business/pengendalian_barang.sql.php';
      parent::__construct($connectionNumber);
      #$this->setDebugOn();
   }
   
   function GetDataUserByUsername ($name)
   {
      if (isset($this->mUserByUserName[$name])) return $this->mUserByUserName[$name];
      $result = $this->Open($this->mSqlQueries['get_data_user_by_username'], array($name));
      $this->mUserByUserName[$name] = $result[0];
      return $result[0];
   }
    
   function getStatusBarang(){
   	return $this->Open($this->mSqlQueries['get_status_barang'],array());
	}
	
    function getStatusKondisiBarang(){
   	return $this->Open($this->mSqlQueries['get_status_kondisi_barang'],array());
    }
    
    function getPrioritas(){
        return $this->Open($this->mSqlQueries['get_prioritas'],array());
    }
	
    # multiunit
	function getUnitKerja($idUnit=''){
            $user = $this->GetDataUserByUsername($_SESSION['username']);
            $sql = $this->mSqlQueries['get_unit_kerja'];
            if($idUnit <> '') $sql = str_replace('[UNIT]', 'AND unitkerjaId = '.$idUnit, $sql);
            else $sql = str_replace('[UNIT]', '', $sql);
            return $this->Open($sql,array($user['unitkerjaKodeSistem'],$user['unitkerjaKodeSistem'].".%"));
	}
	
	function getLokasiBarang($idUnit,$idLokasi=''){
		$sql = $this->mSqlQueries['get_lokasi_barang'];
		if($idLokasi <> '') $sql = str_replace('[RUANG]', 'AND ruangId = '.$idLokasi, $sql);
		else $sql = str_replace('[RUANG]', '', $sql);
		return $this->Open($sql,array($idUnit));
	}
	
        function GetCount(){
            $result = $this->Open($this->mSqlQueries['get_count'],array());
            return $result[0]['total'];
        }
        
	function GetDataGridCount($filter)
   {
      $tglAwal = $filter['tanggal_awal_year'].'-'.$filter['tanggal_awal_mon'].'-'.$filter['tanggal_awal_day'];
      $tglAkhir = $filter['tanggal_akhir_year'].'-'.$filter['tanggal_akhir_mon'].'-'.$filter['tanggal_akhir_day'];
      if (strtotime($tglAwal) > strtotime($tglAkhir)) list($tglAwal, $tglAkhir) = array($tglAkhir, $tglAwal);
      
      if (empty($filter)) $arg = array
      (
         '0000-00-00','0000-00-00',
         '0000-00-00','0000-00-00',
         'all','all',
         'all','all',
         '%', '%'
      );
      else $arg = array
      (
         $tglAwal,$tglAwal,
         $tglAkhir,$tglAkhir,
         $filter['unit_kerja'],$filter['unit_kerja'],
         $filter['status_barang'],$filter['status_barang'],
         "%${filter['aset']}%", "%${filter['aset']}%"
      );
      
		$result = $this->Open($this->mSqlQueries['get_list_pengendalian_barang_count'], $arg);
      return $result[0]['total'];
	}
	
	# multiunit
	function GetDataGrid($filter, $start, $limit)
   {
      $user = $this->GetDataUserByUsername($_SESSION['username']);      
      $tglAwal = $filter['tanggal_awal_year'].'-'.$filter['tanggal_awal_mon'].'-'.$filter['tanggal_awal_day'];
      $tglAkhir = $filter['tanggal_akhir_year'].'-'.$filter['tanggal_akhir_mon'].'-'.$filter['tanggal_akhir_day'];
      if (strtotime($tglAwal) > strtotime($tglAkhir)) list($tglAwal, $tglAkhir) = array($tglAkhir, $tglAwal);
      
      if (empty($filter)) $arg = array
      (
         '0000-00-00','0000-00-00',
         '0000-00-00','0000-00-00',
         'all','all',
      	 $user['unitkerjaKodeSistem'],
         $user['unitkerjaKodeSistem'].'.%',
         'all','all',
         '%', '%',
         $start, $limit
      );
      else $arg = array
      (
         $tglAwal,$tglAwal,
         $tglAkhir,$tglAkhir,
         $filter['unit_kerja'],$filter['unit_kerja'],
         $user['unitkerjaKodeSistem'],
         $user['unitkerjaKodeSistem'].'.%',
         $filter['status_barang'],$filter['status_barang'],
         "%${filter['aset']}%", "%${filter['aset']}%",
         $start, $limit
      );
      
		$result = $this->Open($this->mSqlQueries['get_list_pengendalian_barang'], $arg);
      return $result;
	}
   
   function GetPengendalianById ($id)
   {
      $result = $this->Open($this->mSqlQueries['get_pengendalian_by_id'], array($id));
      if (empty($result)) return false;
      else $return = $result[0];
      
      $return['barangPengendalian'] = $this->Open($this->mSqlQueries['get_barang_by_pengendalian_id'], array($id));
      
      return $return;
   }
   
   function GetPengendalianByIdForDetail ($id)
   {
      $result = $this->Open($this->mSqlQueries['get_pengendalian_by_id_for_detail'], array($id));
      if (empty($result)) return false;
      else $return = $result[0];
      
      $return['barangPengendalian'] = $this->Open($this->mSqlQueries['get_barang_by_pengendalian_id'], array($id));
      
      return $return;
   }
   
   function GetLogHeader ($id)
   {
      $result = $this->Open($this->mSqlQueries['get_log_header'], array($id));
      return $result[0];
   }
   
   function GetLogPengendalianBarang ($id)
   {
      $result = $this->Open($this->mSqlQueries['get_log_pengendalian_barang'], array($id));
		return $result;
   }
   
   /////////
   // Do Query
   /////////
   
   function Add ($data)
   {
		//print_r($data);
		//exit;
		extract($data);
      $this->StartTrans();
      
      // pengendalian_barang_mst
      if ($_FILES['pengFile']['name'] !== '')
      {
         $tmp = dechex(mt_rand(65536, 1048576));
         $pengFile = "PB-".$_FILES['pengFile']['name']."-$tmp.".$_FILES['pengFile']['ext'];
      }
      
      $pengBrgTgl = strtotime($pengBrgTgl_year.'-'.$pengBrgTgl_mon.'-'.$pengBrgTgl_day);
      if ($pengBrgTgl == 0) $pengBrgTgl = time();
      
      $arg = array
      (
         $pengBrgUnitId,
         $pengBrgLokasi,
         date('Y-m-d H:i:s', $pengBrgTgl),
         $pengBAPeng,
         $pengPIC,
         $pengKet,
         $pengFile,
			$pengTindakLanjut
      );
      
      if (!$this->Execute($this->mSqlQueries['add_pengendalian_barang_mst'], $arg))
      {
         $this->EndTrans(false);
         return 1;
      }
      // ---------
      
      // pengendalian_barang_det
      $id_mst = $this->Insert_ID($this->mSqlQueries['add_pengendalian_barang_det']);
      $sql = rtrim($this->mSqlQueries['add_pengendalian_barang_det']);
      $arg = array();
      
//       reset($barangPengendalian);
//       while ($a = current($barangPengendalian))
//       {
//          array_push($arg, $id_mst, $a['barangId'], $a['pengBrgStatusId'], $a['barangKondisiId'], $a['pengBrgPrioritasId'],$a['pengBrgHrgJual']);
//          if(next($barangPengendalian)) $sql .= ",\r\n   (%s, %s, %s, %s, %s, %s)";
//       }

      $i = 1;
      foreach($barangPengendalian as $a){
      	if ($a['isFixed'] == '0'){
      		if($i == 1) $sql .= "('$id_mst','".$a['barangId']."','".$a['pengBrgStatusId']."','".$a['barangKondisiId']."','".$a['pengBrgPrioritasId']."','".$a['pengBrgHrgJual']."')";
      		else $sql .= ",('$id_mst','".$a['barangId']."','".$a['pengBrgStatusId']."','".$a['barangKondisiId']."','".$a['pengBrgPrioritasId']."','".$a['pengBrgHrgJual']."')";
      	}
      }      
      
      if (!$this->Execute($sql, $arg))
      {
         $this->EndTrans(false);
         return 2;
      }
      // ---------

		if (!$this)
      // upload file pengendalian barang
      if ($_FILES['pengFile']['name'] != '' AND !move_uploaded_file($_FILES['pengFile']['tmp_name'], GTFW_APP_DIR.'/'.$this->mFilePath.'/'.$pengFile))
      {
         $this->EndTrans(false);
         return 3;
      }
      // ---------
      
      // add inv_kondisi_history
      $userId = trim(Security::Instance()->mAuthentication->GetCurrentUser()->GetUserId());
      $query = rtrim($this->mSqlQueries['add_inv_konsidi_history']);
      $arg = array();

//       reset($barangPengendalian);
//       while ($b = current($barangPengendalian))
//       {
//          array_push($arg, $b['barangId'], $b['barangKondisiId'], date('Y-m-d', $pengBrgTgl), date('Y-m-d H:i:s'), $userId);
//          if(next($barangPengendalian)) $query .= ",\r\n   (%s, %s, %s, %s, %s)";
//       }

      $i = 1;
      foreach($barangPengendalian as $b){
      	if ($b['isFixed'] == '0'){
      		if($i == 1) $query .="('".$b['barangId']."','". $b['barangKondisiId']."','".date('Y-m-d', $pengBrgTgl)."','".date('Y-m-d H:i:s')."','$userId')";
      		else $query .=",('".$b['barangId']."','". $b['barangKondisiId']."','".date('Y-m-d', $pengBrgTgl)."','".date('Y-m-d H:i:s')."','$userId')";
      	}
      }      

	  if (!$this->Execute($query, $arg))
		{			
         $this->EndTrans(false);
         return 4;
      }
      // ------
      
      // update inventarisasi_detail
      $sql = rtrim($this->mSqlQueries['update_inventarisasi_detail']);
      $arg = array();
      
      foreach($barangPengendalian as $c)
      {
         $arg = array($c['pengBrgStatusId'], $c['barangKondisiId'], $c['barangId']);
         if (!$this->Execute($sql,$arg)){
            $this->EndTrans(false);
            return 5;
         }
      }
      // ---------
		
      $this->EndTrans(true);
      return 0;
   }
   
   function Update ($id_mst, $data)
   {
      extract($data);
      $this->StartTrans();
      
      // pengendalian_barang_mst
      if ($_FILES['pengFile']['name'] !== '')
      {
         $tmp = dechex(mt_rand(65536, 1048576));
         $pengFile = "PB-".$_FILES['pengFile']['name']."-$tmp.".$_FILES['pengFile']['ext'];
      }
      
      $pengBrgTgl = strtotime($pengBrgTgl_year.'-'.$pengBrgTgl_mon.'-'.$pengBrgTgl_day);
      if ($pengBrgTgl == 0) $pengBrgTgl = time();
      
      $arg = array
      (
         $pengBrgUnitId,
         $pengBrgLokasi,
         date('Y-m-d H:i:s', $pengBrgTgl),
         $pengBAPeng,
         $pengPIC,
         $pengKet,
         $pengFile,
			$pengTindakLanjut,
         $id_mst
      );
      
      if (!$this->Execute($this->mSqlQueries['update_pengendalian_barang_mst'], $arg))
      {
         $this->EndTrans(false);
         return 1;
      }
      // ---------
      
      // pengendalian_barang_det
      if (!$this->Execute($this->mSqlQueries['delete_pengendalian_barang_det'], array($id_mst)))
      {
         $this->EndTrans(false);
         return 2;
      }
      
      $sql = rtrim($this->mSqlQueries['add_pengendalian_barang_det']);
      $arg = array();
      
//       reset($barangPengendalian);
//       while ($a = current($barangPengendalian))
//       {
//       	 if($a['isFixed'] <> '0') continue;
//          array_push($arg, $id_mst, $a['barangId'], $a['pengBrgStatusId'], $a['barangKondisiId'], $a['pengBrgPrioritasId'],$a['pengBrgHrgJual']);
//          if(next($barangPengendalian) && ) $sql .= ",\r\n   (%s, %s, %s, %s, %s, %s)";
//       }
	  $i = 1;
      foreach($barangPengendalian as $a){
      	if ($a['isFixed'] == '0'){
      		if($i == 1) $sql .= "('$id_mst','".$a['barangId']."','".$a['pengBrgStatusId']."','".$a['barangKondisiId']."','".$a['pengBrgPrioritasId']."','".$a['pengBrgHrgJual']."')";
      		else $sql .= ",('$id_mst','".$a['barangId']."','".$a['pengBrgStatusId']."','".$a['barangKondisiId']."','".$a['pengBrgPrioritasId']."','".$a['pengBrgHrgJual']."')";
      	}
      }
      
      if (!$this->Execute($sql, $arg))
      {
         $this->EndTrans(false);
         return 2;
      }
      // ---------
      
      // upload file pengendalian barang
      if ($_FILES['pengFile']['name'] != '' AND !move_uploaded_file($_FILES['pengFile']['tmp_name'], GTFW_APP_DIR.'/'.$this->mFilePath.'/'.$pengFile))
      {
         $this->EndTrans(false);
         return 3;
      }
      // ---------
      
      // inv_kondisi_history
      $userId = trim(Security::Instance()->mAuthentication->GetCurrentUser()->GetUserId());
      $query = rtrim($this->mSqlQueries['add_inv_konsidi_history']);
      $arg = array();

//       reset($barangPengendalian);
//       while ($b = current($barangPengendalian))
//       {
//       	 if($b['isFixed'] <> '0') continue;
//          array_push($arg, $b['barangId'], $b['barangKondisiId'], date('Y-m-d', $pengBrgTgl), date('Y-m-d H:i:s'), $userId);
//          if(next($barangPengendalian)) $query .= ",\r\n   (%s, %s, %s, %s, %s)";
//       }

      $i = 1;
      foreach($barangPengendalian as $b){
      	if ($b['isFixed'] == '0'){
      		if($i == 1) $query .="('".$b['barangId']."','". $b['barangKondisiId']."','".date('Y-m-d', $pengBrgTgl)."','".date('Y-m-d H:i:s')."','$userId')";
      		else $query .=",('".$b['barangId']."','". $b['barangKondisiId']."','".date('Y-m-d', $pengBrgTgl)."','".date('Y-m-d H:i:s')."','$userId')";
      	}
      }

		if (!$this->Execute($query, $arg))
		{	
         $this->EndTrans(false);
         return 4;
      }
      // --------
      
      // update inventarisasi_detail
      $sql = rtrim($this->mSqlQueries['update_inventarisasi_detail']);
      $arg = array();
      
      foreach ($barangPengendalian as $c)
      {
      	 if($c['isFixed'] <> '0') continue;
         $arg = array($c['pengBrgStatusId'], $c['barangKondisiId'], $c['barangId']);
         if (!$this->Execute($sql,$arg)){
            $this->EndTrans(false);
            return 5;
         }
      }
      // ---------
		
      $this->EndTrans(true);
      return 0;
   }
   
   function Delete ($id)
   {
      if (!is_array($id)) $id = array($id);
      $sql = str_replace('%s', implode(',', array_fill(0, count($id), "%s")), $this->mSqlQueries['delete_pengendalian_barang']);
      if ($this->Execute($sql, $id)) return count($id) - $this->Affected_Rows();
      
      // delete one by one
      $return = 0;
      foreach ($id as $value) if (!$this->Execute($this->mSqlQueries['delete_pengendalian_barang'], array($value))) $return++;
      return $return;
   }
}
?>
