<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/*************************************
  * Created : May 2015
  * Creator : Fauzan Rabbani
  * Email   : jhanojan@gmail.com
  * Framework ver. : CI ver.2.0
*************************************/	

class stok_booking extends CI_Controller {
	
		var $utama ='stok_booking';
		var $title ='Stok Booking';
	function __construct()
	{
		parent::__construct();permissionz();
		$this->load->library('flexigrid');
                $this->load->helper('flexigrid');
                error_reporting(0);
	}
	
	function index()
	{
		$this->main();
	}
	
	function main()
	{
		//Migrasi 1 Feb 14
		//permissionz();
		//Set Global
		//permission();
		//$data = GetHeaderFooter();
		$data['content'] = 'contents/'.$this->utama.'/view';
		
		$data['js_grid']=$this->get_column();
		//$data['list']=GetAll($this->utama);
		//End Global
		
		//Attendance
		
		$this->load->view('layout/main',$data);
	}
	
	function listcol(){
		
            $colModel['idnya'] = array('ID',50,TRUE,'left',2,TRUE);
            $colModel['id'] = array('ID',100,TRUE,'left',2,TRUE);
            $colModel['code'] = array('Code',110,TRUE,'left',2,TRUE);
            $colModel['brands'] = array('Merk',110,TRUE,'left',2);
            $colModel['jenis_produks'] = array('Jenis Produk',110,TRUE,'left',2);
            $colModel['produks'] = array('Produk',110,TRUE,'left',2);
            $colModel['total'] = array('Jumlah Booking',110,TRUE,'left',2);
            $colModel['petugas'] = array('Petugas',110,TRUE,'left',2);
            $colModel['pelanggan'] = array('Customer',110,TRUE,'left',2);
            $colModel['status'] = array('Status',110,TRUE,'left',2);
            return $colModel;
	}
	
	function get_column(){
            $colModel=$this->listcol(); 
	
        
            $gridParams = array(
                'rp' => 25,
                'rpOptions' => '[10,20,30,40]',
                'pagestat' => 'Displaying: {from} to {to} of {total} items.',
                'blockOpacity' => 0.5,
                'title' => '',
                'showTableToggleBtn' => TRUE
		);
        
           $buttons[] = array('select','check','btn');
            $buttons[] = array('deselect','uncheck','btn');
            $buttons[] = array('separator');
            if(izin('c'))$buttons[] = array('add','add','btn');
            $buttons[] = array('separator');
            if(izin('u'))$buttons[] = array('edit','edit','btn');
            if(izin('d'))$buttons[] = array('delete','delete','btn');
            $buttons[] = array('separator');
		
            return $grid_js = build_grid_js('flex1',site_url($this->utama."/get_record"),$colModel,'title','asc',$gridParams,$buttons);
	}
	
	function get_flexigrid()
        {

            //Build contents query
		//	$this->db->where("sv_a.param",'in');
            $this->db->select("sv_a.*,b.title jenis_produks,c.title brands,d.title lokasi_gudang,e.title produks,f.title pelanggan")->from($this->utama.' sv_a');
            $this->db->join('sv_master_jenis_produk b', "sv_a.jenis_produk=b.id", 'left');
            $this->db->join('sv_master_brand c', "sv_a.brand=c.id", 'left');
            $this->db->join('sv_master_gudang d', "sv_a.gudang=d.id", 'left');
            $this->db->join('sv_master_produk e', "sv_a.produk=e.id", 'left');
            $this->db->join('sv_master_pelanggan f', "sv_a.customer=f.id", 'left');
            $this->flexigrid->build_query();

            //Get contents
            $return['records'] = $this->db->get();

            //Build count query
            //$this->db->where("param",'in');
            $this->db->select("count(id) as record_count")->from($this->utama);
            $this->flexigrid->build_query(FALSE);
            $record_count = $this->db->get();
            $row = $record_count->row();

            //Get Record Count
            $return['record_count'] = $row->record_count;

            //Return all
            return $return;
        }
	
	function get_record(){
		$colModel=$this->listcol();
		$valid_fields = array('id','code','jenis_produk','brand',);

            $this->flexigrid->validate_post('id','ASC',$valid_fields);
            $records = $this->get_flexigrid();

            $this->output->set_header($this->config->item('json_header'));

            $record_items = array();
            $a=0;
            foreach ($records['records']->result() as $row)
            {/*
			if($row->status=='y'){$status='Aktif';}
			elseif($row->status=='n'){$status='Tidak Aktif';}
			elseif($row->status=='s'){$status='Suspended';}*/ 
			
				$record_items[$a][]=$row->id;
				$record_items[$a][]=$row->id;
				$record_items[$a][]=$row->id;
				$b=2;
				foreach($colModel as $key=>$cm){
					if($key=='auth'){
                                        $record_items[$a][$b]="<a href='".base_url()."master_sales/auth/$row->id'>Menu</a>";
                                        
                                        }
					elseif($key=='username'){
                                        $record_items[$a][$b]=GetValue('username','sv_admin',array('marketing'=>'where/'.$row->id));
                                        
                                        }
					elseif($key!='idnya' && $key!='id' && $key!='username'){
                                        $record_items[$a][$b]=$row->$key;}
				$b++;
				}
						$a++;
            }
            return $this->output->set_output($this->flexigrid->json_build($records['record_count'],$record_items));;
	}  

	function deletec()
	{		
		//return true;
		if(izin('d')){
		$countries_ids_post_array = explode(",",$this->input->post('items'));
		array_pop($countries_ids_post_array);
		foreach($countries_ids_post_array as $index => $country_id){
			/*if (is_numeric($country_id) && $country_id > 0) {
				$this->delete($country_id);}*/
				//$data['status']='InAktif';
				//$this->db->where('id',$country_id);
				//$this->db->update($this->utama,$data);
			$this->db->delete($this->utama,array('id'=>$country_id));	
                        //stok_trx('out', $country_id,null,null,null,null,null,null,null,null,null,'del');
		}
			echo 'ok';
		}
		else{
			echo 'error';
		}
		//$error = "Selected countries (id's: ".$this->input->post('items').") deleted with success. Disabled for demo";
		//echo "Sukses!";
	}
	
	function form($id=null){
		
		if($id!=NULL){
		permissionz('u');
			$filter=array('id'=>'where/'.$id);
			$data['type']='Edit';
			$data['list']=GetAll($this->utama,$filter)->row_array();
                        $data['opt_jenis']=GetOptAll('master_jenis_produk','-Jenis Produk-',array('brand'=>'where/'.$data['list']['brand']));
                        $data['opt_produk']=GetOptAll('master_produk','-Produk-',array('brand'=>'where/'.$data['list']['brand'],'jenis_produk'=>'where/'.$data['list']['jenis_produk']));
		}
		else{
			
		permissionz('c');
			$data['type']='New';
                        $data['opt_jenis']=GetOptAll('master_jenis_produk','-Jenis Produk-',array('status'=>'where/abcdefghijkl'));
                        $data['opt_produk']=GetOptAll('master_produk','-Produk-',array('status'=>'where/abcdefghijkl'));
		}
		$data['opt_brand']=GetOptAll('master_brand','-Merk-',array('status'=>'where/Aktif'));
		$data['opt_currency']=GetOptAll('master_currency','-Currency-',array('status'=>'where/Aktif'),'code');
		$data['opt_metric']=GetOptAll('master_metric','-Metric-',array('status'=>'Aktif'),'code');
		$data['opt_klasifikasi']=GetOptAll('sv_ref_produk_klas','-Klasifikasi-');
		$data['opt_satuan']=GetOptAll('sv_ref_satuan','-Satuan-');
		$data['opt_gudang']=GetOptAll('master_gudang','-Gudang-');
		$data['opt_customer']=GetOptAll('master_pelanggan','-Customer-',array('status'=>'where/Aktif'));
		$data['opt_sales']=GetOptAll('master_sales','-Sales-',array('status'=>'where/Aktif'),'nama_lengkap');
		$data['opt_booking']=GetOptAll('sv_stok_booking','-Booking-',array('status'=>'where/unfinished'),'code');
                //print_mz($data['opt_booking']);                
//lastq();
		$data['content'] = 'contents/'.$this->utama.'/edit';
		//End Global
		
		//Attendance
		
		$this->load->view('layout/main',$data);
	}
	
	function submit(){
		$webmaster_id=$this->session->userdata('webmaster_id');
		$id = $this->input->post('id');
		$GetColumns = GetColumns('sv_'.$this->utama);
		foreach($GetColumns as $r)
		{
			$data[$r['Field']] = $this->input->post($r['Field']);
			$data[$r['Field']."_temp"] = $this->input->post($r['Field']."_temp");
			
			if(!$data[$r['Field']] && !$data[$r['Field']."_temp"]) unset($data[$r['Field']]);
			unset($data[$r['Field']."_temp"]);
		}	
                //if($data['booked']=='yes'){
                 //   $this->db->query("UPDATE sv_stok_booking SET status='finished' WHERE id='".$data['booking_id']."'");
              //  }
		/* if(!$this->input->post('is_active')){$data['is_active']='InActive';}
		else{$data['is_active']='Active';} */
		
		if($id != NULL && $id != '')
		{
			/* if(!$this->input->post('password')){unset($data['password']);}
			else{$data['password']=md5($this->config->item('encryption_key').$this->input->post("password"));} */
			
			if(izin('u')){
			$data['modify_by'] = $webmaster_id;
			$data['modify_on']=date("Y-m-d");
			$this->db->where("id", $id);
			$this->db->update('sv_'.$this->utama, $data);
			//stok_trx('out', $id, $data['brand'], $data['jenis_produk'],$data['produk'], $data['part_number'], '-'.$data['total'],  $data['satuan'], $data['tgl_tiba'],$data['exp'], $data['gudang'],'upd');
			$this->session->set_flashdata("message", 'Sukses diedit');}
			else{
				$this->session->set_flashdata("message", 'Anda Tidak Diizinkan Mengedit Data');
			}
		}
		else
		{
			//if($this->input->post('password')){$data['password']=md5($this->config->item('encryption_key').$this->input->post("password"));}
			//if(!$this->input->post('avatar')){$data['avatar']='default.png';}
			
			if(izin('c')){
			$data['created_by'] = $webmaster_id;
			$data['created_on'] = date("Y-m-d H:i:s");
			$this->db->insert('sv_'.$this->utama, $data);
			$id = $this->db->insert_id();
                       // stok_trx('out', $id, $data['brand'], $data['jenis_produk'],$data['produk'], $data['part_number'], '-'.$data['total'],  $data['satuan'], $data['tgl_tiba'],$data['exp'], $data['gudang'],'ins');
			$this->session->set_flashdata("message", 'Sukses ditambahkan');}
			else{
				$this->session->set_flashdata("message", 'Anda Tidak Diizinkan Menambah Data');
			}
		}
		
		redirect($this->utama);
		
	}
        function loadjenis(){
            $ids=rand(111,9999);
            echo form_dropdown('jenis_produk',GetOptAll('master_jenis_produk','-Jenis Produk-',array('brand'=>'where/'.$_POST['v'])),(isset($val[$nm_f]) ? $val[$nm_f] : ''),"class='select2' onchange='gantijenis(this.value)' id='produk$ids'");
            echo"<script>
                    $(document).ready(function(e){ 
                        $('#produk$ids').css('width','200px').select2({allowClear:true});
				$('#select2-multiple-style .btn').on('click', function(e){
					var target = $(this).find('input[type=radio]');
					var which = parseInt(target.val());
					if(which === 2) $('.select2').addClass('tag-input-style');
					 else $('.select2').removeClass('tag-input-style');
				});});</script>";
        }
        function loadproduk(){
            $ids=rand(111,9999);
            echo form_dropdown('produk',GetOptAll('master_produk','-Produk-',array('jenis_produk'=>'where/'.$_POST['v'])),(isset($val[$nm_f]) ? $val[$nm_f] : ''),"class='select2' onchange='cariexpired()' id='produk'");
            
            echo"<script>
                    $(document).ready(function(e){ 
                        $('#produk').css('width','200px').select2({allowClear:true});
				$('#select2-multiple-style .btn').on('click', function(e){
					var target = $(this).find('input[type=radio]');
					var which = parseInt(target.val());
					if(which === 2) $('.select2').addClass('tag-input-style');
					 else $('.select2').removeClass('tag-input-style');
				});});</script>";
        }
	function load_expired(){
            echo GetValue('tgl','ref_exp',array('produk'=>'where/'.$this->input->post('p')));
        }
        function cari_tanggal($tgl=null){
            $pr=$this->input->post('v');
            $gdg=$this->input->post('g');
            $a=$this->db->query("SELECT SUM(total) as stok,produk,gudang,tgl FROM `sv_stok_trx` WHERE produk='$pr' AND gudang='$gdg' GROUP BY produk,gudang,tgl")->result_array();
            $opt[]='-Tanggal Tiba-';
            foreach($a as $b){
                $opt[$b['tgl']]=$b['tgl'];
            }
            echo form_dropdown('tgl_tiba',$opt,$tgl,'class="select2" onchange="caristok()" id="tgl_tiba"');
            echo"<script>
                    $(document).ready(function(e){ 
                        $('#produk').css('width','200px').select2({allowClear:true});
				});</script>";
        }
        function cari_stok(){
            $pr=$this->input->post('v');
            $tgl=$this->input->post('t');
            $gdg=$this->input->post('g');
            $booked=$this->input->post('b');
            $a=$this->db->query("SELECT SUM(total) as stok,produk,gudang,tgl,satuan FROM `sv_stok_trx` WHERE produk='$pr' AND tgl='$tgl' AND gudang='$gdg' GROUP BY produk,gudang,tgl")->row_array();
            $b=$this->db->query("SELECT SUM(total) as stok,satuan FROM `sv_stok_booking` WHERE produk='$pr' AND status='unfinished' GROUP BY produk")->row_array();
            if($booked=='yes'){
                $b['stok']=0;
            }
            $data=array(
                'stok'=>$a['stok']-$b['stok'],
                'produk'=>$a['produk'],
                'gudang'=>$a['gudang'],
                'satuan'=>$a['satuan'],
                'tgl'=>$a['tgl'] 
            );
            echo json_encode($data);
        }function loadbrand(){
                $nm_f='brand';
		$opt_brand=GetOptAll('master_brand','-Merk-',array('status'=>'Aktif'));
            echo form_dropdown($nm_f,$opt_brand,(isset($val[$nm_f]) ? $val[$nm_f] : ''),'class="select2" id="'.$nm_f.'" onchange="gantiproduk(this.value)" ');
            echo"<script>
                    $(document).ready(function(e){ 
                        $('#brand').css('width','200px').select2({allowClear:true});
				});</script>";
        }function loadbrandb(){
                $nm_f='brand';
                $bkg=$this->input->post('v');
                $bdata=GetAll('sv_stok_booking',array('id'=>'where/'.$bkg))->row_array();
		$opt_brand=GetOptAll('master_brand','-Merk-',array('status'=>'Aktif'));
            echo form_input($nm_f,$bdata['brand'],'class="select2" id="'.$nm_f.'" onchange="gantiproduk(this.value)"  style="display:none"');
            echo GetValue('title','master_brand',array('id'=>'where/'.$bdata['brand']));
           
        }
        
        function loadjenisb(){
                $ids=rand(111,9999);
                $bkg=$this->input->post('v');
                $bdata=GetAll('sv_stok_booking',array('id'=>'where/'.$bkg))->row_array();
            echo form_input('jenis_produk',$bdata['jenis_produk'],"class='select2' onchange='gantijenis(this.value)' id='produk$ids' style='display:none'");
            echo GetValue('title','master_jenis_produk',array('id'=>'where/'.$bdata['jenis_produk']));
        }
        function loadprodukb(){
                $ids=rand(111,9999);
                $bkg=$this->input->post('v');
                $bdata=GetAll('sv_stok_booking',array('id'=>'where/'.$bkg))->row_array();
            echo form_input('produk',$bdata['produk'],"class='select2' onchange='cariexpired()' id='produk' style='display:none'");
            echo GetValue('title','master_produk',array('id'=>'where/'.$bdata['produk']));
            
        }
        function loadsatuan(){
            
		$opt_satuan=GetOptAll('sv_ref_satuan','-Satuan-');
                $ids=rand(111,9999);
                $bkg=$this->input->post('v');
                $satuan= GetValue('satuan','sv_stok_booking',array('id'=>'where/'.$bkg));
                echo form_dropdown('satuan',$opt_satuan,$satuan,'class="" id="'.$nm_f.'" ');
        }
        function loadjumlah(){
                $bkg=$this->input->post('v');
            echo GetValue('total','sv_stok_booking',array('id'=>'where/'.$bkg));
        }
}
?>