<?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_pengiriman extends CI_Controller {
	
		var $utama ='stok_pengiriman';
		var $title ='Proses Pengiriman';
	function __construct()
	{
            header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
            // always modified right now
            header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
            // HTTP/1.1
            header("Cache-Control: private, no-store, max-age=0, no-cache, must-revalidate, post-check=0, pre-check=0");
            // HTTP/1.0
            header("Pragma: no-cache");
		parent::__construct();permissionz();
		$this->load->library('flexigrid');
                $this->load->helper('flexigrid');
                error_reporting(0);
	}
	
	function index()
	{
		$this->main();
	}
	
	function main($cat)
	{
		//Migrasi 1 Feb 14
		//permissionz();
		//Set Global
		//permission();
		//$data = GetHeaderFooter();
		$data['content'] = 'contents/'.$this->utama.'/view';
		
		$data['js_grid']=$this->get_column($cat);
		//$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['nama_forwarder'] = array('Nama Forwarder',110,TRUE,'left',2);
            $colModel['kode_order'] = array('PO Number',110,TRUE,'left',2);
            $colModel['pabriks'] = array('Pabrik',110,TRUE,'left',2);
            $colModel['est_tiba_gudang'] = array('Estimasi Tiba Gudang',110,TRUE,'left',2);
            $colModel['posisi'] = array('Posisi',110,TRUE,'left',2);
            $colModel['status'] = array('Status',110,TRUE,'left',2);
            $colModel['tgl_tiba'] = array('Tanggal Tiba',110,TRUE,'left',2);
            $colModel['act'] = array('Action',110,TRUE,'left',2);
            $colModel['keterangan'] = array('Keterangan',110,TRUE,'left',2);
            return $colModel;
	}
	
	function get_column($cat){
            $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($cat==null){
            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/".$cat),$colModel,'title','asc',$gridParams,$buttons);
	}
	
	function get_flexigrid($cat)
        {

            //Build contents query
			//$this->db->where("sv_a.param",'in');
            
        if($cat==null){$this->db->where("sv_a.status",null);}else{
            $this->db->where("sv_a.status",'tiba gudang');
        }
            $this->db->select("sv_a.*,b.title pabriks,c.title produks,d.username nama_forwarder")->from($this->utama.' sv_a');
            $this->db->join('sv_master_pabrik b', "sv_a.pabrik=b.id", 'left');
            $this->db->join('sv_master_produk c', "sv_a.produk=c.id", 'left');
            $this->db->join('sv_admin d', "sv_a.forwarder=d.id", 'left');
            $this->flexigrid->build_query();

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

            //Build count query
            //$this->db->where("param",'in');
            if($cat==null){$this->db->where("status",null);}else{
            $this->db->where("status",'tiba gudang');
        }
            $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($cat){
		$colModel=$this->listcol();
		$valid_fields = array('id','code','jenis_produk','brand',);

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

            $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=='act'){
                                            $record_items[$a][$b]="<a href='".base_url()."stok_pengiriman/masuk/$row->id'>Masuk Stok</a>";
                                        }
					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);}*/
				
			$this->db->delete($this->utama,array('id'=>$country_id));
			$this->db->delete('sv_stok_pengiriman_detail',array('pengiriman_id'=>$country_id));				
		}
			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']));
                        $data['opt_produk']=GetOptAll('master_produk','-Produk-',array('status'=>'where/Aktif'));
                        $data['opt_pabrik']=GetOptAll('master_pabrik','-Pabrik-');
		}
		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/Aktif'));
                        $data['opt_pabrik']=GetOptAll('master_pabrik','-Pabrik-');
		}
		$data['opt_brand']=GetOptAll('master_brand','-Merk-',array('status'=>'Aktif'));
		$data['opt_currency']=GetOptAll('master_currency','-Currency-',array('status'=>'Aktif'),'code');
		$data['opt_metric']=GetOptAll('master_metric','-Metric-',array('status'=>'Aktif'),'code');
		$data['opt_klasifikasi']=GetOptAll('sv_ref_produk_klas','-Klasifikasi-');
		$data['opt_gudang']=GetOptAll('master_gudang','-Gudang-');
		$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(!$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);
			
			$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();
			$this->session->set_flashdata("message", 'Sukses ditambahkan');}
			else{
				$this->session->set_flashdata("message", 'Anda Tidak Diizinkan Menambah Data');
			}
		}
                if($data['status']=='selesai'){
                    if(GetValue('id', 'sv_stok_pengiriman',array('pabrikasi_id'=>$id))==0){
                    $pengiriman['pabrikasi_id']=$id;
                    $pengiriman['kode_order']=$data['kode_order'];
                    $pengiriman['pabrik']=$data['pabrik'];
                    $pengiriman['produk']=$data['produk'];
			$pengiriman['created_by'] = $webmaster_id;
			$pengiriman['created_on'] = date("Y-m-d H:i:s");
			$this->db->insert('sv_stok_pengiriman', $pengiriman);
                    
                    }
                    
                }
		
		redirect($this->utama);
		
	}
        function submit_masuk(){
		$webmaster_id=$this->session->userdata('webmaster_id');
		$id = $this->input->post('id');
		$GetColumns = GetColumns('sv_'.$this->utama);
                //print_mz($this->input->post());
		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(!$this->input->post('is_active')){$data['is_active']='InActive';}
		else{$data['is_active']='Active';} */
                $index=0;
                $pengiriman_detail=$this->input->post('id_pengiriman_detail');
                $pengiriman_id=$this->input->post('id_pengiriman');
                $kode_order=$this->input->post('kode_order');
                $so_number=$this->input->post('so_number');
                $brand=$this->input->post('brand');
                $jenis_produk=$this->input->post('jenis_produk');
                $produk=$this->input->post('produk');
                $total=$this->input->post('total');
                $satuan=$this->input->post('satuan');
                $gudang=$this->input->post('gudang');
                $tanggal_tiba=$this->input->post('tanggal_tiba');
                
                $stok_in_code='STK'.$pengiriman_id[0].rand(11111,99999).date('His');
                    $cek_kode_order=$this->db->query("SELECT count(*) as hitung FROM(SELECT id FROM sv_stok_in WHERE pengiriman_id='".$pengiriman_id[$index]."' GROUP BY stok_in_code) b")->row_array();
                        $tambah=$cek_kode_order['hitung']+1;
                        $kode_orders=$kode_order[$index].'_#'.$tambah;
                foreach($_POST['kode_order'] as $ko){
                    //}
                    $this->db->where('id',$pengiriman_detail[$index]);
                    $this->db->update('sv_stok_pengiriman_detail',array('gudang'=>$gudang[$index],'tgl_tiba'=>$tanggal_tiba[$index]));
                    $masuk=array(
                        'kode_order'=>$kode_orders,
                        'stok_in_code'=>$stok_in_code,
                        'pengiriman_id'=>$pengiriman_id[$index],
                        'pengiriman_detail_id'=>$pengiriman_detail[$index],
                        'so_number'=>$so_number[$index],
                        'brand'=>$brand[$index],
                        'jenis_produk'=>$jenis_produk[$index],
                        'produk'=>$produk[$index],
                        'total'=>$total[$index],
                        'satuan'=>$satuan[$index]
                    );
//                    $this->db->select('id')->from('sv_stok_in')->where($masuk);
//                    $cari=$this->db->get();
//                    if($cari->num_rows()==0){
                        $masuk['gudang']=$gudang[$index];
                        $masuk['tgl_tiba']=$tanggal_tiba[$index];
                    if($masuk['total']>0){
                        $this->db->insert('sv_stok_in',$masuk);
                        $in_id=$this->db->insert_id();
                    stok_trx('in', $in_id, $masuk['brand'], $masuk['jenis_produk'],$masuk['produk'], '0', $masuk['total'],  $masuk['satuan'], $masuk['tgl_tiba'],'0000-00-00', $masuk['gudang'],'ins');
                    
                    }
//                    }
//                    else{
//                        $dapet=$cari->row_array();
//                        $where=$masuk;
//                    $masuk['gudang']=$gudang[$index];
//                    $masuk['tgl_tiba']=$tanggal_tiba[$index];
//			$this->db->where($where);
//			$this->db->update('sv_stok_in', $masuk);
//                        stok_trx('in', $dapet['id'], $masuk['brand'], $masuk['jenis_produk'],$masuk['produk'], '0', $masuk['total'],  $masuk['satuan'], $masuk['tgl_tiba'],'0000-00-00', $masuk['gudang'],'upd');
//                     //echo "Update data";
//                     //die();
//                    }
//                    
                   
                    $index++;
                }
		 $completed=1;
                $cek_pabrikasi=$this->db->query("SELECT * FROM sv_stok_pengiriman_detail WHERE pengiriman_id='".$id."'")->result_array();
                foreach($cek_pabrikasi as $cp){
                    $total_dikirim=$this->db->query("SELECT SUM(total) AS total FROM sv_stok_in WHERE pengiriman_detail_id='".$cp['id']."'")->row_array();
                    if($total_dikirim['total']!=$cp['total']){
                        $completed=0;
                    }
                }
                if($completed==1){
                       $this->session->set_flashdata("message", 'Semua Produk Sukses Dimasukkan ke Stok');
                       $this->db->query("UPDATE sv_stok_pengiriman SET status='tiba gudang' WHERE id='".$id."'");
                      // lastq();
                }
                else{
                    $this->session->set_flashdata("message", 'Sukses Dimasukkan ke Stok');
                }
		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 masuk($id=null){
		
		if($id!=NULL){
		permissionz('u');
                        $data['id']=$id;
			$filter=array('pengiriman_id'=>'where/'.$id);
			$data['type']='Edit';
			$data['list']=GetAll('sv_stok_pengiriman_detail',$filter)->result_array();
                        //print_mz($data['list']);
                        //lastq();
                        //$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']));
                        $data['opt_produk']=GetOptAll('master_produk','-Produk-',array('status'=>'where/Aktif'));
                        $data['opt_pabrik']=GetOptAll('master_pabrik','-Pabrik-');
		}
		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/Aktif'));
                        $data['opt_pabrik']=GetOptAll('master_pabrik','-Pabrik-');
		}
		$data['opt_brand']=GetOptAll('master_brand','-Merk-',array('status'=>'Aktif'));
		$data['opt_currency']=GetOptAll('master_currency','-Currency-',array('status'=>'Aktif'),'code');
		$data['opt_metric']=GetOptAll('master_metric','-Metric-',array('status'=>'Aktif'),'code');
		$data['opt_klasifikasi']=GetOptAll('sv_ref_produk_klas','-Klasifikasi-');
		$data['opt_gudang']=GetOptAll('master_gudang','-Gudang-');
		$data['content'] = 'contents/'.$this->utama.'/masuk';
		//End Global
		
		//Attendance
		
		$this->load->view('layout/main',$data);
	}
}
?>