<?php
class DeliveryOrder extends Database
{

   protected $mSqlFile;
   public $mFilePath = 'file/';

   function __construct ($connectionNumber=0)
   {
      $this->mSqlFile = 'module/'.Dispatcher::Instance()->mModule.'/business/DeliveryOrder.sql.php';
      parent::__construct($connectionNumber);
      #$this->setDebugOn();
   }

   function GetDataUserById ($userId)
   {
      if (isset($this->mUserById[$userId])) return $this->mUserById[$userId];
      $result = $this->Open($this->mSqlQueries['get_data_user_by_id'], array($userId));
      $this->mUserById[$userId] = $result[0];
      return $result[0];
   }

   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];
   }

   # multiunit
   function GetComboUnit ()
   {
      $tmp = $this->GetDataUserByUsername($_SESSION['username']);
      return $this->Open($this->mSqlQueries['get_combo_unit'], array($tmp['unitkerjaKodeSistem'],$tmp['unitkerjaKodeSistem'].'.%'));
   }
   
   # multiunit
   function GetComboUnitDetail ($id)
   {
   	$tmp = $this->GetDataUserByUsername($_SESSION['username']);
   	return $this->Open($this->mSqlQueries['get_combo_unit_detail'], array($id,$tmp['unitkerjaKodeSistem'],$tmp['unitkerjaKodeSistem'].'.%'));
   }

   function GetComboRuang ($id)
   {
		//$user = $this->GetDataUserByUsername($_SESSION['username']);
      return $this->Open($this->mSqlQueries['get_combo_ruang'], array($id/*$user['unit_kerja_id'], $user['unit_kerja_id']*/));
   }

   function GetListItemPengadaanById ($id, $doMstId="")
   {
      //return $this->Open($this->mSqlQueries['get_item_pengadaan_by_id'], array($id, $idUnit, $idUnit));
      $sql = $this->mSqlQueries['get_item_pengadaan_by_id'];
      /* sembunyikan jumlah yang tersedia yang bernilai 0 saat proses insert */
      if ($doMstId <> '') $sql = str_replace('[SHOW_AVAILABLE]', '', $sql);
      else $sql = str_replace('[SHOW_AVAILABLE]', 'HAVING pengadaanDetJmlAset > 0', $sql);
   	  return $this->Open($sql, array($id));
   }
	
   function GetCount(){
   	$result = $this->Open($this->mSqlQueries['get_count'],array());
   	return $result[0]['total'];
   }
   
   function GetDataGridCount ($filter)
   {
      extract($filter);

      $tglAwal = ($tglAwal) ? date('Y-m-d', $tglAwal) : '';
      $tglAkhir = ($tglAkhir) ? date('Y-m-d',$tglAkhir ) : '';
      if (!$unit) $unit = 'all';

      if ($this->roleId != 1)
      {
         $User = $this->GetDataUserByUsername($_SESSION['username']);
         $unit = $User['unit_kerja_id'];
      }

      $arg = array
      (
         "%$pengadaanNoSPK%",
         "%$doNoDO%",
         $tglAwal,$tglAwal,
         $tglAkhir,$tglAkhir,
         $unit, $unit,
         "%$kode%", "%$kode%"/*, "%$kode%"*/
      );

      $result = $this->Open($this->mSqlQueries['get_data_grid_count'], $arg);
      return $result[0]['total'];
   }

   # multiunit
   function GetDataGrid ($filter, $start = null, $limit = null)
   {
   	  $aksesPusat = $this->GetModuleAccess('delivery_order','DOListPusat');
      extract($filter);

      $tglAwal = ($tglAwal) ? date('Y-m-d', $tglAwal) : '';
      $tglAkhir = ($tglAkhir) ? date('Y-m-d',$tglAkhir ) : '';
	  $user = $this->GetDataUserByUsername($_SESSION['username']);
	  
	  $sql = $this->mSqlQueries['get_data_grid'];
	  $arg = array();
	  
	  if((int)$aksesPusat == 0){
	  	$sql = str_replace('[UNIT_FILTER]', 'WHERE (unitkerjaKodeSistem = %s OR unitkerjaKodeSistem LIKE %s)', $sql);
	  	array_push($arg,$user['unitkerjaKodeSistem'],$user['unitkerjaKodeSistem'].'.%');
	  }else $sql = str_replace('[UNIT_FILTER]', '', $sql);
	  
	  array_push($arg,"%$pengadaanNoSPK%","%$doNoDO%");
	  
	  if($tglAwal <> '' && $tglAkhir <> ''){
	  	$sql = str_replace('[SEARCH_TGLDO]', 'AND doMstTglDO >= %s AND doMstTglDO <= (%s + INTERVAL 1 DAY) ', $sql);
	  	array_push($arg, $tglAwal, $tglAkhir);
	  }elseif($tglAwal <> '' && $tglAkhir == ''){
      	$sql = str_replace('[SEARCH_TGLDO]', 'AND doMstTglDO >= %s ', $sql);
      	array_push($arg,$tglAwal);
      }elseif($tglAwal == '' && $tglAkhir <> ''){
      	$sql = str_replace('[SEARCH_TGLDO]', 'AND doMstTglDO <= (%s + INTERVAL 1 DAY) ', $sql);
      	array_push($arg, $tglAkhir);
      }else $sql = str_replace('[SEARCH_TGLDO]', '', $sql);
      
      if($kode <> ''){
      	$sql = str_replace('[SEARCH_BARANG]', 'AND (g.barangKode LIKE %s OR g.barangNama LIKE %s) ', $sql);
      	array_push($arg, "%$kode%", "%$kode%");
      }else $sql = str_replace('[SEARCH_BARANG]', '', $sql);
      
      if($unit <> '' && $unit <> 'all'){
      	$sql = str_replace('[SEARCH_UNIT]', 'unitkerjaId LIKE %s AND ', $sql);
      	array_push($arg, "%|$unit|%");
      }else $sql = str_replace('[SEARCH_UNIT]', '', $sql);
      
      array_push($arg, "%#".$user['unitkerjaKodeSistem']."#%", "%#".$user['unitkerjaKodeSistem'].".%");

      if ($start == NULL && $limit == NULL)
         $sql = str_replace('%LIMIT%', '', $sql);
      else{
         $sql = str_replace('%LIMIT%', 'LIMIT %s, %s', $sql);
         array_push($arg, $start, $limit);
      }

      $result = $this->Open($sql, $arg);
      foreach ($result as $key=>$value){
         $result[$key]['doTglDo'] = date('d F Y', strtotime($value['doMstTglDO']));
         //if (!empty($result[$key]['doTglTerima'])) $result[$key]['doTglTerima'] = date('d F Y', strtotime($result[$key]['doTglTerima']));
      }
      return $result;
   }

   function GetDOById ($id)
   {
      $result = $this->Open($this->mSqlQueries['get_DO_by_id'],array($id));

      foreach (array_keys($result) as $key){
      	$temp = explode(',',$result[$key]['doUnit']);
      	foreach($temp as $value){
      		$temp2 = explode('|',$value);
      		$jumlahDO[$temp2[0]][$temp2[1]] = $temp2[2];
      	}
      }
      $return = $result[0];
      unset($return['invMstId'], $return['doUnit']);

      $return['jumlahDO'] = $jumlahDO;
      $return['pengadaanTglSPK'] = date('d F Y', strtotime($return['pengadaanTglSPK']));
      $return['tglDODisplay'] = date('d F Y', $return['doTglDO']);
      $return['doTglDO'] = strtotime($return['doTglDO']);

      return $return;
   }

   function GetDODetail ($id,$unitId='')
   {
   	  $aksesPusat = $this->GetModuleAccess('delivery_order','DOListPusat');
   	  $result = $this->Open($this->mSqlQueries['get_DO_header_by_id'], array($id));
   	  if(empty($result)) return false;
   	  
   	  if((int)$aksesPusat == 0 ){
   	  	$roleUnit = $this->Open($this->mSqlQueries['get_DO_item_by_id_unit'], array($id,$unitId));
   	  	$result[0]['doPICPenerima'] = $roleUnit[0]['doUnitPICPenerima'];
   	  }
      else $rolePusat = $this->Open($this->mSqlQueries['get_DO_item_by_id'], array($id));
      
      $return['header'] = $result[0];
      $return['roleUnit'] = $roleUnit;
      $return['rolePusat'] = $rolePusat;
      return $return;
   }

   # multiunit
   function GetDOListForPrint ($id)
   {
      $user = $this->GetDataUserByUsername($_SESSION['username']);
      $aksesPusat = $this->GetModuleAccess('delivery_order','DOListPusat');
      $sql = $this->mSqlQueries['get_do_list_for_print'];
      $sql = str_replace('%ID%', implode(',', $id), $sql);
      if((int)$aksesPusat == 0 ) $sql = str_replace('[UNIT_FILTER]', 'WHERE (unitkerjaKodeSistem = '.$user['unitkerjaKodeSistem'].' OR unitkerjaKodeSistem LIKE "'.$user['unitkerjaKodeSistem'].'.%%")', $sql);
      else $sql = str_replace('[UNIT_FILTER]', '', $sql);
      $result = $this->Open($sql, array('%#'.$user['unitkerjaKodeSistem'].'#%','%#'.$user['unitkerjaKodeSistem'].'.%'));
      
      return $result;
   }

   # multiunit
   function GetDODetailForPrint ($id)
   {
      $tmp = $this->GetDataUserByUsername($_SESSION['username']);
      $result = $this->Open($this->mSqlQueries['get_DO_header_by_id'], array($id));
      if(empty($result)) return false;
      $return['header'] = $result[0];

      $rolePusat = $this->Open($this->mSqlQueries['get_DO_item_by_id_for_print'], array($id,$tmp['unitkerjaKodeSistem'],$tmp['unitkerjaKodeSistem'].".%"));
//       $rolePusat = array();
//       foreach ($result as $value)
//          if (isset($rolePusat[$value['invMstId']])) $rolePusat[$value['invMstId']]['jumlah']++;
//          else
//          {
//             $rolePusat[$value['invMstId']] = $value;
//             $rolePusat[$value['invMstId']]['jumlah'] = 1;
//          }
      $return['roleUnit'] = $roleUnit;
      $return['rolePusat'] = $rolePusat;
      return $return;
   }
   
   function GetLastId(){
   	  $result = $this->Open($this->mSqlQueries['get_last_id'], array());
   	  return $result[0]['id'];
   }
   
   function GetModuleAccess($module,$subModule){
   	  $userId = Security::Instance()->mAuthentication->GetCurrentUser()->GetUserId();
   	  $result = $this->Open($this->mSqlQueries['get_module_access'], array($userId,$module,$subModule));
   	  return $result[0]['akses'];
   }

   /////////
   // Do Query
   /////////

   function Add($data)
   {
      extract($data);
      $this->StartTrans();
      $User = $this->GetDataUserByUsername($_SESSION['username']);

      // do_mst_new
      if ($_FILES['doFile']['name'] !== '')
      {
         $tmp = dechex(mt_rand(65536, 1048576));
         $doFile = "DO-".$_FILES['doFile']['name']."-$tmp.".$_FILES['doFile']['ext'];
      }

      if ($doTglDO == 0) $doTglDO = time();

      $arg = array
      (
			$pengadaanId,
			date('Y-m-d H:i:s', $doTglDO),
			$doNoDO,
			$User['unit_kerja_id'],
			$doNIP,
			$doPengguna,
      		$doPICPengirim,
			$doKeterangan,
			$doFile,
			$User['user_id']
      );

      if (!$this->Execute($this->mSqlQueries['add_do_mst'], $arg))
      {
         $this->EndTrans(false);
         return 1;
      }
      // ---------

      // do_unit_new and do_detail_new
      for ($i=0;$i<count($jumlahDO);$i++)
      {
         if ($jumlahDO[$i] < 1) continue;
         $arg = array (
         		$idUnit[$i],
         		$jumlahDO[$i],
         		$idBarang[$i],
         		$pengadaanId
         );

         if (!$this->Execute($this->mSqlQueries['add_do_unit'], $arg))
         {
            $this->EndTrans(false);
            return 2;
         }
         
         $arg2 = array(
         		$idUnit[$i],
         		$pengadaanId,
         		$idBarang[$i],
         		(int)$jumlahDO[$i]
         );
         
         if (!$this->Execute($this->mSqlQueries['add_do_detail'], $arg2))
         {
         	$this->EndTrans(false);
         	return 3;
         }
      }
      // ---------

      // upload file DO
      if ($_FILES['doFile']['name'] != '' AND !move_uploaded_file($_FILES['doFile']['tmp_name'], GTFW_APP_DIR.'/'.$this->mFilePath.'/'.$doFile))
      {
         $this->EndTrans(false);
         return 4;
      }

      $this->EndTrans(true);
      return 0;
   }

   function Update ($id, $data)
   {
      extract($data);
      $this->StartTrans();
      $User = $this->GetDataUserByUsername($_SESSION['username']);

      // do_mst
      if ($_FILES['doFile']['name'] !== '')
      {
         $tmp = dechex(mt_rand(65536, 1048576));
         $doFile = "DO-".$_FILES['doFile']['name']."-$tmp.".$_FILES['doFile']['ext'];
      }

      if ($doTglDO == 0) $doTglDO = time();

      $arg = array
      (
			date('Y-m-d H:i:s', $doTglDO),
			$doNoDO,
			$User['unit_kerja_id'],
			$doNIP,
			$doPengguna,
      		$doPICPengirim,
			$doKeterangan,
			$doFile,
			$User['user_id'],
         	$id
      );

      if (!$this->Execute($this->mSqlQueries['update_do_mst'], $arg))
      {
         $this->EndTrans(false);
         return 1;
      }
      // ---------

      for ($i=0;$i<count($jumlahDO);$i++){
      	
      	if ($jumlahDO[$i] < 1 || $jumlahDO[$i] == $jumlahDOOld[$i]) continue;
      	//update do_unit_new
      	$arg2 = array(
      			$jumlahDO[$i],
      			$idBarang[$i],
      			$idUnit[$i],
      			$pengadaanId,
      			$id
      	);
      	
      	if (!$this->Execute($this->mSqlQueries['update_do_unit'], $arg2))
      	{
      		$this->EndTrans(false);
      		return 2;
      	}
      	
      	//delete do_detail_new
      	if (!$this->Execute($this->mSqlQueries['delete_do_detail'], array($idBarang[$i],$idUnit[$i],$pengadaanId,$id)))
      	{
      		$this->EndTrans(false);
      		return 3;
      	}
      	
      	//insert new do_detail_new
      	$sql = str_replace('[UNIT_ID]', "(SELECT doUnitId 
   					FROM do_unit_new 
   					WHERE 
   						doUnitBarangId = %s AND 
						doUnitUnitIdPenerima = %s AND 
						doUnitPengadaanId = %s AND 
						doUnitMstId = %s AND 
						doUnitPICPenerima IS NULL)", $this->mSqlQueries['update_do_detail']);
      	$arg3 = array(
      			$idBarang[$i],
      			$idUnit[$i],
      			$pengadaanId,
      			$id,
      			$idUnit[$i],
      			$pengadaanId,
      			$idBarang[$i],
      			(int)$jumlahDO[$i]
      	);
      	 
      	if (!$this->Execute($sql, $arg3))
      	{
      		$this->EndTrans(false);
      		return 4;
      	}      	
      }

      // upload file DO
      if ($_FILES['doFile']['name'] != '' AND !move_uploaded_file($_FILES['doFile']['tmp_name'], GTFW_APP_DIR.'/'.$this->mFilePath.'/'.$doFile))
      {
         $this->EndTrans(false);
         return 5;
      }

      $this->EndTrans(true);
      return 0;
   }

   function Penerimaan ($id, $data)
   {
      extract($data);
      $this->StartTrans();
      $User = $this->GetDataUserByUsername($_SESSION['username']);
      $tglTerima = date('Y-m-d H:i:s', $tglTerima);

      // do_mst
      if (!$this->Execute($this->mSqlQueries['update_pic_penerimaan'], array($doPICPenerima, $User['user_id'], $id,$unitId)))
      {
         $this->EndTrans(false);
         return 1;
      }
      // ---------
      
      // do_detail, inventarisasi_detail dan lokasi_history
      foreach ($ruang as $invDetId=>$ruangId)
      {
         if (empty($ruangId)) continue;
         $arg = array
         (
            $tglTerima,
         	$unitId,
            $invDetId,
            $ruangId,
            $User['user_id']
         );

         if (!$this->Execute($this->mSqlQueries['update_data_inventarisasi'], $arg))
         {
            $this->EndTrans(false);
            exit;
            return 2;
         }

         $arg = array
         (
            $tglTerima,
            $User['user_id'],
            $invDetId
         );

         if (!$this->Execute($this->mSqlQueries['add_history_lokasi'], $arg))
         {
            $this->EndTrans(false);
            exit;
            return 3;
         }
      }
      // ---------

      $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_delivery_order']);
      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_delivery_order'], array($value))) $return++;
      return $return;
   }
}
?>
