<?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 ref_exp extends CI_Controller {
	 
		var $utama ='ref_exp';
		var $title ='Alert Expired Stok';
	function __construct() 
	{
		parent::__construct();permissionz();
		$this->load->library('flexigrid');
                $this->load->helper('flexigrid'); 
                error_reporting(0);
	} 
	 
	function index() 
	{
		$this->main();
	}
	
	function main()
	{
                //redirect('customer_plan/form');
		//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);
		$colModel['merk'] = array('Merk',100,TRUE,'left',2);
		$colModel['jp'] = array('Jenis Produk',100,TRUE,'left',2);
		$colModel['produks'] = array('Produk',250,TRUE,'left',2);
		$colModel['part_number'] = array('Part Number',100,TRUE,'left',2);
		//$colModel['from'] = array('From',110,TRUE,'left',2);
		//$colModel['to'] = array('To',110,TRUE,'left',2);
		$colModel['tgl'] = array('Target Tgl Expired',110,TRUE,'left',2);
		$colModel['pembuat'] = array('Diset Oleh',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');
            if(izin('u'))$buttons[] = array('edit','edit','btn');
            $buttons[] = array('separator');
            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()
        {

            $anaknya=implode(',',anaknya()); 
            //Build contents query
            $this->db->select("sv_a.id id,b.title produks,sv_a.tgl tgl,c.title merk,d.title jp,b.part_number part_number,e.username pembuat",FALSE)->from("$this->utama sv_a");
            $this->db->join('sv_master_produk b', "sv_a.produk=b.id", 'left');
            $this->db->join('sv_master_brand c', "b.brand=c.id", 'left');
            $this->db->join('sv_master_jenis_produk d', "b.jenis_produk=d.id", 'left');
            $this->db->join('sv_admin e', "sv_a.create_user_id=e.id", 'left');
            
             //if($by=='' ){
                // $anaknya=implode(',',$anaknya);
            //if(!diaadmin()){
                //$this->db->where_in('b.leader',$anaknya);
                //$this->db->or_where('sv_a.created_by',$this->session->userdata('webmaster_id'));
             //   $this->db->where("(b.leader IN($anaknya) OR sv_a.sales_id='".$this->session->userdata('webmaster_marketing')."')");
           //  }

            //Get contents
            $return['records'] = $this->db->get();
             
            //Build count query
            $this->db->select("count(sv_a.id) as record_count",FALSE)->from("$this->utama sv_a");
            //$this->db->join('ref_divisi b', "sv_a.divisi=b.id", 'left');
            
            $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','title','code','link','catatan','tag');
			$z=0;
				foreach($colModel as $key=>$cm){
				$valid_fields[$z]=$key;
				$z++;
				}

            $this->flexigrid->validate_post('sv_a.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_array() 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'];
				$b=2;
				foreach($colModel as $key=>$cm){
					if($key!='idnya')
				$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));				
		}
			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);
		}
		else{
			
		permissionz('c');
			$data['type']='New';
		}
		$data['opt_brand']=GetOptAll('sv_ref_brand','-Tag-');
		$data['opt_produk']=GetOptAll('sv_master_produk','-Produk-');
		$data['content'] = 'contents/'.$this->utama.'/edit';
		$div=divisinya();
                $anaknya=  anaknya(); 
                if(diaadmin()){
                
        //$wherez['status']='where/Aktif';$qbz='';
                if($this->session->userdata('divisi') && $this->session->userdata('groups')){                
                    $qbz=" WHERE (divisi='".$this->session->userdata('divisi')."' AND groups='".$this->session->userdata('groups')."' )";
                }
                else{
                    if($this->session->userdata('divisi')){
                    $qbz=" WHERE divisi='".$this->session->userdata('divisi')."'";
                    }
                    elseif($this->session->userdata('groups')){
                        $qbz=" WHERE groups='".$this->session->userdata('groups')."'";
                    }
                }
                
            $anak=implode(',',$anaknya);
            $q=" SELECT * FROM (`sv_master_sales`) $qbz ORDER BY `nama_lengkap` asc";
            if($this->session->userdata('divisi')) $and.=" AND `divisi`='".$this->session->userdata('divisi')."'";
                $data['opt_sales']=GetOptQuery($q,'-Name-',array(),'nama_lengkap');
               // $data['opt_sales']=GetOptAll('sv_ref_divisi','-Divisi-',array('status'=>'where/Aktif'),'title');
            }
            else{
                $qbz='';
            if($this->session->userdata('divisi') && $this->session->userdata('groups')){                
                    $qbz=" AND (divisi='".$this->session->userdata('divisi')."' AND groups='".$this->session->userdata('groups')."' )";
                }
                else{
                    if($this->session->userdata('divisi')){
                    $qbz=" AND divisi='".$this->session->userdata('divisi')."'";
                    }
                    elseif($this->session->userdata('groups')){
                        $qbz=" AND groups='".$this->session->userdata('groups')."'";
                    }
                }
                
            $anak=implode(',',$anaknya);
            $q=" SELECT * FROM (`sv_master_sales`) WHERE (`id` =  '".$this->session->userdata('webmaster_marketing')."' OR `leader` IN ($anak)) $qbz ORDER BY `nama_lengkap` asc";
                if($this->session->userdata('divisi')) $and.=" AND `divisi`='".$this->session->userdata('divisi')."'";
                $data['opt_sales']=GetOptQuery($q,'-Name-',array(),'nama_lengkap');
               // $data['opt_sales']=GetOptAll('sv_ref_divisi','-Divisi-',array('status'=>'where/Aktif'),'title');
            }
            $ty=date('Y')+2;
            for($a=date('Y')-2;$a<=$ty;$a++){
            $data['opt_yeari'][$a]=$a;}
		//End Global
		//Attendance
            $this->load->view('layout/main',$data);
	}
	
	function submit_bak(){
		$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']] = str_replace('.','',$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';} */
                //$cek=GetAll('sv_customer_plan',array('sales_id'=>'where/'.$data['sales_id'],'year'=>'where/'.$data['year']))->num_rows();
		
		if($id>0)
		{
			/* 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(array("sales_id"=>$data['sales_id'],'year'=>$data['year']));
                        $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');
			}
		}
		
		redirect($this->utama);
		
	}
        function submit(){
            error_reporting(E_ALL);
		$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']] = str_replace('.','',$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';} */
                //$cek=GetAll('sv_customer_plan',array('sales_id'=>'where/'.$data['sales_id'],'year'=>'where/'.$data['year']))->num_rows();
               // print_mz($this->input->post());
                    
                //echo $activity[$a];
                //die();
                    $q="SELECT * FROM sv_".$this->utama." WHERE produk='".$data['produk']."'";
                   // echo $q;
                    $cari=$this->db->query($q)->num_rows();
                   // lastq();
                     
		if($cari>0)
		{
                    //$sales['sales']=$this->input->post('sales');
                    //$sales['activity']=$this->input->post('activity')[$a];
                   // $sales['target']=$target;
			/* 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_user_id'] = $webmaster_id;
			$data['modify_date']=date("Y-m-d");
			//$this->db->where(array("sales_id"=>$data['sales_id'],'year'=>$data['year']));
                        $cariz=array('produk'=>$data['produk']);
                        $this->db->where($cariz);
			$this->db->update($this->utama, $data);
			
			$this->session->set_flashdata("message", 'Expired Date Sukses Di Update');}
			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['create_user_id'] = $webmaster_id;
			$data['create_date'] = date("Y-m-d H:i:s");
			$this->db->insert($this->utama, $data);
			$id = $this->db->insert_id();
			$this->session->set_flashdata("message", 'Expired Date Sukses Di Update');}
			else{
				$this->session->set_flashdata("message", 'Anda Tidak Diizinkan Menambah Data');
			}
                }
		
		redirect($this->utama.'/');
		
	}
        function loadactivity(){
            $divisi=GetValue('divisi','master_sales',array('id'=>'where/'.$_POST['s']));
            $activity=  GetOptAll('ref_activity', '-Jenis Activity-', array('type'=>'where/'.$divisi), 'notes', 'id');
            $query=GetAll('sv_major_customer', array('sales'=>'where/'.$_POST['s']));
            $data['activity']=  $query->result_array();
            $this->load->view('contents/'.$this->utama.'/activity_resume',$data);
            
           // echo form_dropdown('activity',$activity,(isset($val[$nm_f]) ? $val[$nm_f] : ''),'class="select2" onchange="" id="'.$nm_f.'"');
           echo "<script>"
            . "$(document).ready(function(e){"
            . "$('.select2').css('width','200px').select2({matcher: function(params,data){
               return matchStart(params, data);
               },});});"
            . "</script>";
        }
        function loadisi(){
            $sales=$this->input->post('s');
            $year=$this->input->post('y');
            $data['val']=$this->db->query("SELECT * FROM sv_customer_plan WHERE sales_id='$sales' AND year='$year'")->row_array();
            $this->load->view('contents/alert_stok/monthly',$data);
        }
	
}
?>