<?php
class Usulan extends Database
{

   protected $mSqlFile= 'module/approval_usulan_barang/business/Usulan.sql.php';
   public $mFilePath = 'file/';
   
   function __construct ($connectionNumber=0) {
      parent::__construct($connectionNumber);    
	  #$this->setDebugOn();	
   }
   
   function GetDataUserById ($userId)
   {
      $result = $this->Open($this->mSqlQueries['get_data_user_by_id'], array($userId));  
      return $result[0];
   }
   
   function GetDataUserByUsername ($name)
   {
      $result = $this->Open($this->mSqlQueries['get_data_user_by_username'], array($name));  
      return $result[0];
   }
   
   function GetComboUnit ()
   {
      $tmp = $this->GetDataUserByUsername($_SESSION['username']);
      return $this->Open($this->mSqlQueries['get_combo_unit'], array($tmp['unitkerjaKodeSistem'],$tmp['unitkerjaKodeSistem'].'.%'));  
   }
   
   function GetDataGridCount ($filter)
   {
      extract($filter);
      $tglUsulanAwal = ($tglUsulanAwal) ? date('Y-m-d', $tglUsulanAwal) : '';
      $tglUsulanAkhir = ($tglUsulanAkhir) ? date('Y-m-d',$tglUsulanAkhir ) : '';
      if (!$unit) $unit = 'all';
      if ($status=='all') $status = '';
      
      $arg = array
      (
			"%$status%",
         $tglUsulanAwal,$tglUsulanAwal,
         $tglUsulanAkhir,$tglUsulanAkhir,
         $unit, $unit,
         "%$kode%", "%$kode%"
      );
      
      $result = $this->Open($this->mSqlQueries['get_data_grid_count'], $arg);
      return $result[0]['total'];
   }
   
   function GetDataGrid ($filter, $start = NULL, $limit = NULL)
   {
      extract($filter);
      $tglUsulanAwal = ($tglUsulanAwal) ? date('Y-m-d', $tglUsulanAwal) : '';
      $tglUsulanAkhir = ($tglUsulanAkhir) ? date('Y-m-d',$tglUsulanAkhir ) : '';
      if (!$unit) $unit = 'all';
      if ($status=='all') $status = '';
      
      $arg = array
      (
			"%$status%",
         $tglUsulanAwal,$tglUsulanAwal,
         $tglUsulanAkhir,$tglUsulanAkhir,
         $unit, $unit,
         "%$kode%", "%$kode%"
      );

      $sql = $this->mSqlQueries['get_data_grid'];
      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);
		
      return $result;
   }
   
   function GetUsulanById ($id)
   {
      $result = $this->Open($this->mSqlQueries['get_data_by_id'], array($id));
      if (empty($result)) return false;
      $return = $result[0];
      $return['usulanBrgMstTglUsulan'] = strtotime($return['usulanBrgMstTglUsulan']);
      $return['tglUsulan1Display'] = date('d F Y', $return['usulanBrgMstTglUsulan']);
      
      // get detail barang list
      $result = $this->Open($this->mSqlQueries['get_detail_barang'], array($id));
      if (!empty($result)) foreach ($result as $key=>$value)
         $return['detail_barang']["item_$key"] = $value;
      // ---------
      
      return $return;
   }
   
   function GetUsulanDetailById ($id)
   {
      $result = $this->Open($this->mSqlQueries['get_detail_by_id'], array($id));
      if (empty($result)) return false;
      $return = $result[0];
      $return['usulanBrgMstTglUsulan'] = strtotime($return['usulanBrgMstTglUsulan']);
      $return['tglUsulan1Display'] = date('d F Y', $return['usulanBrgMstTglUsulan']);
      
      // get detail barang list
      $result = $this->Open($this->mSqlQueries['get_detail_barang'], array($id));
      if (!empty($result)) $return['detail_barang'] = $result;
      // ---------
      
      return $return;
   }
   
   function GetLastMstId ()
   {
      $result = $this->Open($this->mSqlQueries['get_last_mst_id'], array());
      return (int) $result[0]['id'];
   }
   
   function GetListBarangToApprove ($brgId)
   {
      $result = $this->Open($this->mSqlQueries['get_list_barang_to_approve'], array($brgId));
      if (empty($result)) return array();
      
      $return = array();
      foreach ($result as $value)
      {
         $value['usulanBrgMstTglUsulan'] = date('d F Y', strtotime($value['usulanBrgMstTglUsulan']));
         $value['hargaLama'] = $value['usulanBrgTotal1'] / $value['usulanBrgDetJml'];
         $value['hargaBaru'] = $value['usulanBrgTotal2'] / $value['usulanBrgDetJml'];
         $return[$value['id']] = $value;
      }
      return $return;
   }
   
   function GetDataGridForPrint ($id)
   {
      if (!is_array($id)) {$id = array($id); $sql = $this->mSqlQueries['get_data_grid_for_print'];}
      else $sql = str_replace('%s', implode(',', array_fill(0, count($id), "%s")), $this->mSqlQueries['get_data_grid_for_print']);
      $result = $this->Open($sql, $id);
      if ($result == false) return array('dataGrid'=>array(), 'barangUsulan'=>array());
      $return['dataGrid'] = $result;
      
      $sql = str_replace('%s', implode(',', array_fill(0, count($id), "%s")), $this->mSqlQueries['get_data_barang_usulan_for_print']);
      $result = $this->Open($sql, $id);
      if ($result !== false) foreach ($result as $value)
         $return['barangUsulan'][$value['usulanBrgDetMstId']][] = $value;
      else $return['barangUsulan'] = array();
      
      return $return;
   }
	
	function GetDataGridForPrintRtf ()
   {
      $result = $this->Open($this->mSqlQueries['get_data_grid_for_print_rtf'], array());  
      return $result;
   }
   
   /////////
   // Do Query
   /////////
   
   function Add ($data)
   {
      $this->StartTrans();
      extract($data);
      if ($_FILES['fileUsulan']['name'] !== '')
      {
         $tmp = dechex(mt_rand(65536, 1048576));
         $usulanBrgMstFile = "usulan-".$_FILES['fileUsulan']['name']."-$tmp.".$_FILES['fileUsulan']['ext'];
      }
      
      // tabel usulan_brg_mst
      $arg = array
      (
         date('Y-m-d', $usulanBrgMstTglUsulan),
         $usulanBrgMstNoUsulan,
         $usulanBrgMstUnitId,
         $usulanBrgMstPIC,
         $usulanBrgMstKet,
         $usulanBrgMstFile,
         $_SESSION['username']
      );
      
      if (!$this->Execute($this->mSqlQueries['add_usulan'], $arg))
      {
         $this->EndTrans(false);
         return 1;
      }
      // ---------
      
      // tabel usulan_brg_det
      $mstId = $this->GetLastMstId();
      if (!empty($detail_barang)) foreach ($detail_barang as $value)
      {
         extract($value);
         
         $arg = array
         (
            $mstId,
            $usulanBrgDetBrgId,
            $usulanBrgDetJml,
            ($brgHargaLama*$usulanBrgDetJml),
            ($brgHps*$usulanBrgDetJml)
         );
      
         if (!$this->Execute($this->mSqlQueries['add_detail_barang'], $arg))
         {
            $this->EndTrans(false);
            return 2;
         }
      }
      // ---------
      
      // uploading file
      if
      (
         $_FILES['fileUsulan']['name'] !== '' AND
         !move_uploaded_file($_FILES['fileUsulan']['tmp_name'], GTFW_APP_DIR.'/'.$this->mFilePath.$usulanBrgMstFile)
      )
      {
         $this->EndTrans(false);
         return 3;
      }
      // ---------
      
      $this->EndTrans(true);
      return 0;
   }
   
   function Update ($data, $mstId)
   {
      $this->StartTrans();
      extract($data);
      if ($_FILES['fileUsulan']['name'] !== '')
      {
         $tmp = dechex(mt_rand(65536, 1048576));
         $usulanBrgMstFile = "usulan-".$_FILES['fileUsulan']['name']."-$tmp.".$_FILES['fileUsulan']['ext'];
      }
      
      // tabel usulan_brg_mst
      $arg = array
      (
         date('Y-m-d', $usulanBrgMstTglUsulan),
         $usulanBrgMstNoUsulan,
         $usulanBrgMstUnitId,
         $usulanBrgMstPIC,
         $usulanBrgMstKet,
         $usulanBrgMstFile,
         $_SESSION['username'],
         $mstId
      );
      
      if (!$this->Execute($this->mSqlQueries['update_usulan'], $arg))
      {
         $this->EndTrans(false);
         return 1;
      }
      // ---------
      
      // tabel usulan_brg_det
      if (!$this->Execute($this->mSqlQueries['delete_detail_barang'], array($mstId)))
      {
         $this->EndTrans(false);
         return 2;
      }
      
      if (!empty($detail_barang)) foreach ($detail_barang as $value)
      {
         extract($value);
         
         $arg = array
         (
            $mstId,
            $usulanBrgDetBrgId,
            $usulanBrgDetJml,
            ($brgHargaLama*$usulanBrgDetJml),
            ($brgHps*$usulanBrgDetJml)
         );
      
         if (!$this->Execute($this->mSqlQueries['add_detail_barang'], $arg))
         {
            $this->EndTrans(false);
            return 2;
         }
      }
      // ---------
      
      // uploading file
      if
      (
         $_FILES['fileUsulan']['name'] !== '' AND
         !move_uploaded_file($_FILES['fileUsulan']['tmp_name'], GTFW_APP_DIR.'/'.$this->mFilePath.$usulanBrgMstFile)
      )
      {
         $this->EndTrans(false);
         return 3;
      }
      // ---------
      
      $this->EndTrans(true);
      return 0;
   }
   
   function Delete ($id)
   {
      $sql = str_replace('%VALUE%', implode(',', array_fill(0, count($id), "%s")), $this->mSqlQueries['delete_usulan']);
      if ($this->Execute($sql, $id)) return 0;
      
      // delete one by one
      $return = 0;
      $sql = str_replace('%VALUE%', '%s', $this->mSqlQueries['delete_usulan']);
      foreach ($id as $value) if (!$this->Execute($sql, array($value))) $return++;
      return $return;
   }
   
   function Approve ($data)
   {
      $this->StartTrans();
      extract($data);
      
      // insert barang rekap
      $arg = array
      (
         $usulanRkpNoRkp,
         $usulanRkpPicApprove,
         date('Y-m-d', $usulanRkpTglApprove)
      );
      
      if (!$this->Execute($this->mSqlQueries['add_approval'], $arg))
      {
         $this->EndTrans(false);
         return 1;
      }
      // ---------
      
      foreach ($listBarang as $key=>$value)
      {
         // insert barang rekap detail 
         $arg = array
         (
            $key,
            $value['usulanUnitId']
         );
         
         if (!$this->Execute($this->mSqlQueries['add_rekap_detail'], $arg))
         {
            $this->EndTrans(false);
            return 2;
         }
         // ---------
         
         //update usulan barang detail
         $arg = array
         (
            $value['usulanBrgDetJmlApprove'],
            $value['usulanBrgStjTotal1'],
            $value['usulanBrgStjTotal2'],
            $key
         );
         
         if (!$this->Execute($this->mSqlQueries['update_detail_barang'], $arg))
         {
            $this->EndTrans(false);
            return 3;
         }
         // ---------
      }
      
      $this->EndTrans(true);
      return 0;
   }
}
?>
