<?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 master_pelanggan extends CI_Controller {
	
		var $utama ='master_pelanggan';
		var $title ='Master Customer';
	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();
		
                       // $anaknya=anaknya();
                       // print_mz($anaknya);
		
//                $from=(isset($_POST['from']) && $_POST['from']!=NULL ? $_POST['from']:'--');
//                $to=(isset($_POST['to']) && $_POST['to']!=NULL ? $_POST['to']:'--');
                $by=(isset($_POST['pelanggan']) && $_POST['pelanggan']!=NULL ? $_POST['pelanggan']:'--');
                $by2=(isset($_POST['bidang']) && $_POST['bidang']!=NULL ? $_POST['bidang']:'--');
                $data['col']=$this->listcol();  
		
            $this->db->select("sv_a.id as id, sv_a.title as title, b.title as perusahaan, sv_a.alamat as alamat, sv_a.telp1 as telp1, sv_a.pelanggan_sejak as pelanggan_sejak,d.title status_pelanggan")->from("$this->utama sv_a");
            $this->db->join('sv_ref_bidang_pelanggan b', "sv_a.perusahaan=b.id", 'left');
            $this->db->join('sv_ref_pelanggan d', "sv_a.status_pelanggan=d.id", 'left');
           // if($from!='--')$this->db->where('sv_a.tanggal >=', $from);
           // if($to!='--')$this->db->where('sv_a.tanggal <=', $to);
            if($by!='--' )$this->db->where('sv_a.id', $by);
            if($by2 !='--')$this->db->where('sv_a.perusahaan', $by2);
			$this->db->get();
			//lastq();
		$data['lastq']=$this->db->last_query(); 
                $isisearch=array();
                //if(dialeader()){
                //                   $isisearch= array('divisi'=>'where/'.divisinya());
               // }
		$data['opt_search']=GetOptAll('master_pelanggan','-Nama Pelanggan-',$isisearch,'nama_lengkap');
               // $anaknya=anaknya();
            
            if(diaadmin()){
                
		$data['opt_search']=GetOptAll('master_pelanggan','-Pelanggan-',array());
            }
            else{
            $anak=implode(',',$anaknya);
            $q=" SELECT * FROM (`sv_master_pelanggan`) ORDER BY title ASC";
                $data['opt_search']=GetOptQuery($q,'-Nama-',array());
            }
            $q=" SELECT * FROM (`sv_master_pelanggan`) ORDER BY title ASC";
                $data['opt_search']=GetOptQuery($q,'-Nama-',array());
                
            $q=" SELECT * FROM (`sv_ref_bidang_pelanggan`) ORDER BY title ASC";
		$data['opt_activity']=GetOptQuery($q,'-Bidang Pelanggan-',array());
		$data['content'] = 'contents/'.$this->utama.'/view';
		
	if(isset($_POST['export'])){
		$data['lastq']=$this->db->query($_POST['lastq'])->result_array();
		header("Content-type: application/vnd-ms-excel");
 
			// Mendefinisikan nama file ekspor "hasil-export.xls"
				header("Content-Disposition: attachment; filename=hasil-export.xls");
 
			// Tambahkan table
				//include 'table.html';
			$this->load->view('contents/'.$this->utama.'/export',$data);
	}
		else{
		$data['js_grid']=$this->get_column($by,$by2);
		//$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['title'] = array('Nama Customer',150,TRUE,'left',2);
            $colModel['perusahaan'] = array('Bidang',110,TRUE,'left',2);
            $colModel['divisi'] = array('Divisi',150,TRUE,'left',2);
            $colModel['kontak'] = array('Kontak',400,TRUE,'left',2);
            $colModel['alamat'] = array('Alamat',210,TRUE,'left',2);
            $colModel['telp1'] = array('Telepon',110,TRUE,'left',2,TRUE);
            $colModel['pelanggan_sejak'] = array('Customer Sejak',110,TRUE,'left',2);
            $colModel['status_pelanggan'] = array('Status',110,TRUE,'left',2);
			return $colModel;
	}
	
	function get_column($by,$by2){
			$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/$by/$by2"),$colModel,'title','asc',$gridParams,$buttons);
	}
	
	function get_flexigrid($by,$by2)
        {

            //Build contents query
            //$this->db->where($this->utama.'.status','Aktif');
            $this->db->select("sv_a.id as id, sv_a.title as title, b.title as perusahaan, sv_a.alamat as alamat, sv_a.telp1 as telp1, sv_a.pelanggan_sejak as pelanggan_sejak,d.title status_pelanggan")->from("$this->utama sv_a");
            $this->db->join('sv_ref_bidang_pelanggan b', "sv_a.perusahaan=b.id", 'left');
            $this->db->join('sv_ref_pelanggan d', "sv_a.status_pelanggan=d.id", 'left');
            if($by!='--' )$this->db->where('sv_a.id', $by);
            if($by2 !='--')$this->db->where('sv_a.perusahaan', $by2);
            $this->flexigrid->build_query();
			

            //Get contents
            $return['records'] = $this->db->get();
            //lastq();
            //Build count query
            $this->db->select("count(id) as record_count")->from($this->utama);
            if($by!='--' )$this->db->where('id', $by);
            if($by2 !='--')$this->db->where('perusahaan', $by2);
            $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($by,$by2){
		
			$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('id','ASC',$valid_fields);
            $records = $this->get_flexigrid($by,$by2);

            $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;
				$b=2;
				foreach($colModel as $key=>$cm){
                                if($key=='title'){
                                    
                                        $record_items[$a][$b]="<a href='".base_url()."master_pelanggan/form/$row->id'>".$row->$key."</a>";
                                        $b++;
                                }
					elseif($key=='divisi'){
                                    $pr=GetAll('sv_master_pelanggan_divisi',array('pelanggan'=>'where/'.$row->id));
                                    //lastq();
                                    $produkz=array();
                                    foreach($pr->result_array() as $prdk){
                                        $produkz[]=$prdk['title'];
                                    }
                                    $produk=implode(',',$produkz);
                                    $record_items[$a][$b]=$produk;
                                            
				$b++;}
					elseif($key=='kontak'){
                                    $pr=GetAll('sv_master_pelanggan_divisi_kontak',array('pelanggan'=>'where/'.$row->id));
                                    //lastq();
                                    $produkz=array();
                                    foreach($pr->result_array() as $prdk){
                                        $produkz[]=$prdk['kontak']." <b>(".$prdk['telp1'].")</b> ";
                                    }
                                    $produk=implode(',',$produkz);
                                    $record_items[$a][$b]=$produk;
                                            
				$b++;}
					elseif($key!='idnya'){
                                        $record_items[$a][$b]=$row->$key;
				$b++;}
				}
                /* $record_items[] = array(
                $row->id,
                $row->id,
			$row->id,
			$row->code,
			$row->perusahaan,
			$row->title,
			$row->kota,
			$row->situs,
			$row->pelanggan_sejak,
			$row->status_pelanggan,
                        ); */
						$a++;
            }

            return $this->output->set_output($this->flexigrid->json_build($records['record_count'],$record_items));;
	}  
	function ok(){
		print_r($GLOBALS['colModel']);
	}

	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->delete($this->utama);
                                
				$this->db->where('pelanggan',$country_id);
				$this->db->delete('sv_master_pelanggan_divisi');
                                
                                
				$this->db->where('pelanggan',$country_id);
				$this->db->delete('sv_master_pelanggan_divisi_kontak');
			//$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_pelanggan']=GetOptAll('sv_ref_pelanggan','-Status-');
		$data['opt_brand']=GetOptAll('master_brand','-Brand-');
		$data['opt_sales']=GetOptAll('master_sales','-Sales-',array(),'nama_lengkap');
		$data['content'] = 'contents/'.$this->utama.'/edit';
		//End Global
		
		//Attendance
		
		$this->load->view('layout/main',$data);
	}
	
	
	function view($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_pelanggan']=GetOptAll('sv_ref_pelanggan','-Status-');
		$data['opt_brand']=GetOptAll('master_brand','-Brand-');
		$data['opt_sales']=GetOptAll('master_sales','-Sales-',array(),'nama_lengkap');
		$data['content'] = 'contents/'.$this->utama.'/seee';
		//End Global
		
		//Attendance
		
		$this->load->view('layout/main',$data);
	}
	function submit(){
            //print_mz($_POST);
		$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';} */
		unset($data['unique']);
		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');
			}
		}
		//divisi
		$iddivisi=$this->input->post('id_divisi');
		$divisi=$this->input->post('divisi');
		$unique=$this->input->post('unique');
		$a=0;
		foreach($unique as $uni){
                    $div=$divisi[$a];
			if($div!=''){
				
					$divs['pelanggan']=$id;
					$divs['title']=$div;
                                        $divs['unique']=$uni;
				
				if($iddivisi[$a]!=''){
					//$divs['id']=$iddivisi[$a];
					$data['modify_by'] = $webmaster_id;
					$data['modify_on']=date("Y-m-d");
					$this->db->where('id',$iddivisi[$a]);
					$this->db->update('sv_master_pelanggan_divisi',$divs);

				}
				else{
                                    $data['created_by'] = $webmaster_id;
                                    $data['created_on'] = date("Y-m-d H:i:s");
                                    $this->db->insert('sv_master_pelanggan_divisi', $divs);
                                    $iddivisi[$a]=$this->db->insert_id();
                                   // lastq();
                                }
                                
                                    
                                        //$divs['brand']=$_POST['d_brand'][$divs['unique']][$a];
                                        //$divs['sales']=$_POST['d_sales'][$divs['unique']][$a];
                                $b=0;
                                      foreach($_POST['d_kontak'][$divs['unique']] as $oi){
                                     
                                     $id_kontak[$b]=$_POST['id_kontak'][$divs['unique']][$b];
                                        //$divz['id']=$divs['id_kontak'];
                                        $divz['divisi']=$iddivisi[$a];
                                        $divz['unique']=$divs['unique'];
                                        $divz['pelanggan']=$id;
                                        $divz['kontak']=$oi;
                                        $divz['telp1']=$_POST['d_telp1'][$divs['unique']][$b];
                                        $divz['telp2']=$_POST['d_telp2'][$divs['unique']][$b];
                                        $divz['fax']=$_POST['d_fax'][$divs['unique']][$b];
                                        $divz['email']=$_POST['d_email'][$divs['unique']][$b];
                                        $divz['status']='Aktif';
                                        $divz['catatan']=$_POST['d_catatan'][$divs['unique']][$b];
                                    
				if($id_kontak[$b]!=''){
					//$divs['id']=$iddivisi[$a];
					$data['modify_by'] = $webmaster_id;
					$data['modify_on']=date("Y-m-d");
					$this->db->where('id',$id_kontak[$b]);
					$this->db->update('sv_master_pelanggan_divisi_kontak',$divz);

				}
				else{
                                    $data['created_by'] = $webmaster_id;
                                    $data['created_on'] = date("Y-m-d H:i:s");
                                    $this->db->insert('sv_master_pelanggan_divisi_kontak', $divz);
                                    $idkontak[$b]=$this->db->insert_id();
                                }    
                                        
                                        $b++;
                                      }
                             }
			$a++;
		}
		
		redirect($this->utama);
		
	}
        function load_div(){
            $data['unique']=rand('1111111','9999999');
            $data['v']=$_POST['v'];
		$data['opt_pelanggan']=GetOptAll('sv_ref_pelanggan','-Status-');
		$data['opt_brand']=GetOptAll('master_brand','-Brand-');
		$data['opt_sales']=GetOptAll('master_sales','-Sales-',array(),'nama_lengkap');
            $this->load->view('contents/'.$this->utama.'/bagiandivisi.php',$data);
        }
        function load_kontak($unique){
            $data['unique']=$unique;
            $data['v']=$_POST['v'];
		$data['opt_pelanggan']=GetOptAll('sv_ref_pelanggan','-Status-');
		$data['opt_brand']=GetOptAll('master_brand','-Brand-');
		$data['opt_sales']=GetOptAll('master_sales','-Sales-',array(),'nama_lengkap');
            $this->load->view('contents/'.$this->utama.'/kontak_pelanggan.php',$data);
        }
        function hapusdiv(){
            $val=$this->input->post('v');
            $ok=$this->db->query("DELETE FROM sv_master_pelanggan_divisi WHERE id='$val'");
            if($ok){
                echo 'Y';
            }
        }
        function hapuskontak(){
            $val=$this->input->post('v');
            $ok=$this->db->query("DELETE FROM sv_master_pelanggan_divisi_kontak WHERE id='$val'");
            if($ok){
                echo 'Y';
            }
        }
	
}
?>