<?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 activity_sales extends CI_Controller {
	
		var $utama ='activity_sales';
		var $title ='Activity';
	function __construct()
	{
		parent::__construct();permissionz();
		$this->load->library('flexigrid');
                $this->load->helper('flexigrid');
                error_reporting(0);
                $this->output->set_header('Last-Modified: ' . gmdate("D, d M Y H:i:s") . ' GMT');('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
$this->output->set_header('Pragma: no-cache');
$this->output->set_header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
	}
	
	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['marketing']) && $_POST['marketing']!=NULL ? $_POST['marketing']:'--');
                $by2=(isset($_POST['activity']) && $_POST['activity']!=NULL ? $_POST['activity']:'--');
                $by3=(isset($_POST['customer']) && $_POST['customer']!=NULL ? $_POST['customer']:'--');
                $data['col']=$this->listcol();  
		
			$div=divisinya();
                        $anaknya=anaknya();
                        
            $this->db->select("sv_a.id id,sv_a.nilai_quo AS nilai_quo,sv_a.nilai_po AS nilai_po,b.nama_lengkap sales,d.notes aktivitas,c.title pelanggan,sv_a.tanggal tanggal,e.title status,FORMAT(`sv_a`.`nilai`,'0') AS nilai,c.id pelanggan_id,sv_a.platform platform,sv_a.created_on created_on,sv_a.latitude latitude,sv_a.longitude longitude,b.divisi divisi,sv_a.catatan catatan,f.title pelanggan_divisi",FALSE)->from("$this->utama sv_a");
            $this->db->join('master_sales b', "sv_a.sales=b.id", 'left');
            $this->db->join('master_pelanggan c', "sv_a.pelanggan=c.id", 'left');
            $this->db->join('ref_activity d', "sv_a.jenis_aktivitas=d.id", 'left');
            $this->db->join('ref_activity_status e', "sv_a.status=e.id", 'left');
            $this->db->join('master_pelanggan_divisi f', "sv_a.pelanggan_divisi=f.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.sales', $by);
            if($by2 !='--')$this->db->where('sv_a.jenis_aktivitas', $by2);
            if($by3 !='--')$this->db->where('sv_a.pelanggan', $by3);
             //if($by=='' ){
                $anaknya=implode(',',$anaknya);
            if(!diaadmin()){
                $this->db->where("(b.leader IN($anaknya) OR sv_a.created_by='".$this->session->userdata('webmaster_id')."')");
             }
			$this->db->get();
			//lastq();
		$data['lastq']=$this->db->last_query(); 
                $isisearch=array();
                if(dialeader()){
                                   $isisearch= array('divisi'=>'where/'.divisinya());
                }
		$data['opt_search']=GetOptAll('master_sales','-Nama-',$isisearch,'nama_lengkap');
                $anaknya=anaknya();
            
            if(diaadmin()){
                
		$data['opt_search']=GetOptAll('master_sales','-Nama-',array(),'nama_lengkap','id',NULL,array());
            }
            else{
            $anak=implode(',',$anaknya);
            $q=" SELECT * FROM (`sv_master_sales`) WHERE `id` =  '".$this->session->userdata('webmaster_marketing')."' OR `leader` IN ($anak) ORDER BY `nama_lengkap` asc";
                $data['opt_search']=GetOptQuery($q,'-Nama-',array(),'nama_lengkap');
            }
                $mar=  webmastermarketing();
                $div=GetValue('divisi','sv_master_sales',array('id'=>'where/'.$mar));
                $jenisaktifitas=array();
                if(!diaadmin()){
                    $jenisaktifitas=array('type'=>'where/'.$div,'notes'=>'order/asc');
                }
		$data['opt_activity']=GetOptAll('ref_activity','-Jenis Aktifitas-',$jenisaktifitas,'notes');
		$data['opt_customer']=GetOptAll('master_pelanggan','-Customer-',array(),'title');
		$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($from,$to,$by,$by2,$by3);
		//$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['sales'] = array('Nama',110,TRUE,'left',2);
			$colModel['tanggal'] = array('Tanggal',110,TRUE,'left',2,TRUE);
			$colModel['nilai_quo'] = array('Nilai Quotation',110,TRUE,'left',2,TRUE);
			$colModel['nilai_po'] = array('Nilai PO',110,TRUE,'left',2,TRUE);
			$colModel['nilai'] = array('Nilai KPI',110,TRUE,'left',2,TRUE);
			$colModel['created_on'] = array('Tanggal input',110,TRUE,'left',2);
			$colModel['aktivitas'] = array('Jenis Aktivitas',110,TRUE,'left',2);
			$colModel['pelanggan'] = array('Customer',150,TRUE,'left',2);
			$colModel['pelanggan_divisi'] = array('Divisi',150,TRUE,'left',2);
			$colModel['produk'] = array('Produk',150,TRUE,'left',2);
			$colModel['status'] = array('Status',60,TRUE,'left',2);
			$colModel['catatan'] = array('Catatan',180,TRUE,'left',2);
			//$colModel['nilai'] = array('Nilai',110,TRUE,'left',2);
			$colModel['platform'] = array('Platform',60,TRUE,'left',2);
			return $colModel;
	} 
	function maps($lat,$long){
		$data['content'] = 'contents/'.$this->utama.'/map';
		$data['lat']=$lat;
		$data['lng']=$long;
		$this->load->view('layout/main',$data);
	}
	
	function get_column($from,$to,$by,$by2,$by3){
	
			$colModel=$this->listcol();
			$colModel['input_location'] = array('Lokasi',150,TRUE,'left',2);
        
            $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');
            $buttons[] = array('export to xls','delete','btn');
            $buttons[] = array('export to pdf','delete','btn');
		
            return $grid_js = build_grid_js('flex1',site_url($this->utama."/get_record/$from/$to/$by/$by2/$by3"),$colModel,'id','desc',$gridParams,$buttons);
	}
	
	function get_flexigrid($from,$to,$by,$by2,$by3)
        {
            //Build contents query
            //$this->db->where('status','Aktif');
			$div=divisinya();
                        $anaknya=anaknya();
                        
            $this->db->select("sv_a.id id,FORMAT(`sv_a`.`nilai_quo`,'0') AS nilai_quo,FORMAT(`sv_a`.`nilai_po`,'0')  AS nilai_po,b.nama_lengkap sales,d.notes aktivitas,c.title pelanggan,sv_a.tanggal tanggal,e.title status,FORMAT(`sv_a`.`nilai`,'0') AS nilai,c.id pelanggan_id,sv_a.platform platform,sv_a.created_on created_on,sv_a.latitude latitude,sv_a.longitude longitude,b.divisi divisi,sv_a.catatan catatan,f.title pelanggan_divisi",FALSE)->from("$this->utama sv_a");
            $this->db->join('master_sales b', "sv_a.sales=b.id", 'left');
            $this->db->join('master_pelanggan c', "sv_a.pelanggan=c.id", 'left');
            $this->db->join('ref_activity d', "sv_a.jenis_aktivitas=d.id", 'left');
            $this->db->join('ref_activity_status e', "sv_a.status=e.id", 'left');
            $this->db->join('master_pelanggan_divisi f', "sv_a.pelanggan_divisi=f.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.sales', $by);
            if($by2 !='--')$this->db->where('sv_a.jenis_aktivitas', $by2);
            if($by3 !='--')$this->db->where('sv_a.pelanggan', $by3);
            
            if($this->session->userdata('divisi')){
                $this->db->where('b.divisi', $this->session->userdata('divisi'));
            }
            if($this->session->userdata('groups')){
                $this->db->where('b.groups', $this->session->userdata('groups'));        
            };
             //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.created_by='".$this->session->userdata('webmaster_id')."')");
             }
             
           // }
            //if(diasales()){$this->db->or_where('sv_a.created_by',$this->session->userdata('webmaster_id'));}
            //if(dialeader()){$this->db->where('b.divisi',$div);}
            $this->flexigrid->build_query();                                                        

            //Get contents
            $return['records'] = $this->db->get(); 
            //lastq();
            //Build count query
            $this->db->select("count(sv_a.id) record_count,sv_a.id id,b.nama_lengkap sales,d.notes aktivitas,c.title pelanggan,c.id pelanggan_id,sv_a.tanggal tanggal,e.title status,sv_a.nilai nilai,sv_a.platform platform,sv_a.created_on created_on,sv_a.latitude latitude,sv_a.longitude longitude,b.divisi divisi")->from("$this->utama sv_a");
            $this->db->join('master_sales b', "sv_a.sales=b.id", 'left');
            $this->db->join('master_pelanggan c', "sv_a.pelanggan=c.id", 'left');
            $this->db->join('ref_activity d', "sv_a.jenis_aktivitas=d.id", 'left');
            $this->db->join('ref_activity_status e', "sv_a.status=e.id", 'left');
            
            //;//if(diasales()){$this->db->where_in('b.leader',$anaknya);}
            if($from!='--')$this->db->where('sv_a.tanggal >=', $from);
            if($to!='--')$this->db->where('sv_a.tanggal <=', $to);
            if($by!='--' )$this->db->where('sales', $by);
            if($by2 !='--')$this->db->where('jenis_aktivitas', $by2);
            if($by3 !='--')$this->db->where('sv_a.pelanggan', $by3);
            
            if($this->session->userdata('divisi')){ 
                $this->db->where('b.divisi', $this->session->userdata('divisi'));
            }
            if($this->session->userdata('groups')){
                $this->db->where('b.groups', $this->session->userdata('groups'));        
            };
             //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.created_by='".$this->session->userdata('webmaster_id')."')");
             }
             
            //}
             
            $this->flexigrid->build_query(FALSE);
            $record_count = $this->db->get();
            $row = $record_count->row();
             //lastq();
            //Get Record Count
            $return['record_count'] = $row->record_count;

            //Return all
            return $return;
        }
	
	function get_record($from,$to,$by,$by2,$by3){
            error_reporting(E_ALL ^ E_NOTICE);
			$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($from,$to,$by,$by2,$by3);

            $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=='sales'){
                                    $record_items[$a][$b]="<a href='".base_url()."activity_sales/view/$row->id' >".$row->sales."</a>";
                                } 
                                  
                                elseif($key=='catatan'){
                                    $record_items[$a][$b]="<a href='#' title='$row->catatan' >".$row->catatan."</a>";
                                } 
                                elseif($key=='pelanggan'){
                                    $record_items[$a][$b]="<a href='".base_url()."master_pelanggan/view/$row->pelanggan_id' >".$row->pelanggan."</a>";
                                } 
                                elseif($key=='produk'){
                                    $pr=GetAll('activity_sales_detail',array('activity'=>'where/'.$row->id));
                                    $produkz=array();
                                    foreach($pr->result_array() as $prdk){
                                        $produkz[]=GetValue('title','master_produk',array('id'=>'where/'.$prdk['produk']));
                                    }
                                    $produk=implode(',',$produkz);
                                    $record_items[$a][$b]=$produk;
                                }
				elseif($key!='idnya' && $key!='sales' && $key!='produk'){
                                $record_items[$a][$b]=$row->$key;}
				$b++;
				}
				if($row->latitude!=NULL && $row->longitude!=NULL  ){
				$record_items[$a][$b+1]="<a href='https://maps.google.com/maps?ll=$row->latitude,$row->longitude&z=15&t=m&hl=en-GB&gl=US&mapclient=embed&q=6%C2%B025%2738.0%22S%20106%C2%B049%2748.7%22E@$row->latitude,$row->longitude' >Show Location</a>";}else{$record_items[$a][$b+1]='';}
				//$record_items[$a][$b+1]="<a href='".base_url()."activity_sales/maps/$row->latitude/$row->longitude' >Show Location</a>";}else{$record_items[$a][$b+1]='';}
				$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){
		$mar=  webmastermarketing();
                $div=GetValue('divisi','sv_master_sales',array('id'=>'where/'.$mar));
                $jenisaktifitas=array();
                if(!diaadmin()){
                    $jenisaktifitas=array('type'=>'where/'.$div,'notes'=>'order/asc');
                }
                if($div=='4'){
                    $tipe_activity='support';
                }else{
                    $tipe_activity='sales';
                }
		if($id!=NULL){
		permissionz('u');
			$filter=array('id'=>'where/'.$id);
			$data['type']='Edit';
			$data['list']=GetAll($this->utama,$filter);
                        $data['detail']=GetAll('sv_activity_sales_detail',array('activity'=>'where/'.$id));
		}
		else{
			
		permissionz('c');
			$data['type']='New';
		}  
		$data['opt_pelanggan']=GetOptAll('master_pelanggan','-Pelanggan-',array('title'=>'order/asc'));
                
		$data['opt_aktivitas']=GetOptAll('ref_activity','-Aktivitas-',$jenisaktifitas,'notes','id',NULL,array(),array('id'=>array(24,25,8,31)));
                if($id>0)
		$data['opt_aktivitas']=GetOptAll('ref_activity','-Aktivitas-',$jenisaktifitas,'notes','id',NULL,array(),array());
                
		$data['opt_jenis_produk']=GetOptAll('master_jenis_produk','-Jenis Produk-',array('title'=>'order/asc'));
		$data['opt_aktivitas_status']=GetOptAll('ref_activity_status','-Status-',array('title'=>'order/asc'));
                $data['opt_brand']=GetAll('sv_master_brand',array('status'=>'where/Aktif','title'=>'order/asc'))->result_array();
                if($this->session->userdata('webmaster_grup')=='3'){
                    $userdetails=GetAll('sv_admin',array('id'=>'where/'.$this->session->userdata('webmaster_id')))->row_array();
                    $data['opt_sales'][$userdetails['marketing']]=GetValue('nama_lengkap','sv_master_sales',array('id'=>'where/'.$userdetails['marketing']));
                }else{
		$data['opt_sales']=GetOptAll('master_sales','-Sales-',array('nama_lengkap'=>'order/asc'),'nama_lengkap');
                }
                $data['content'] = 'contents/'.$this->utama.'/edit';
		//End Global 
		 
		//Attendance
		
		$this->load->view('layout/main',$data);
	}  
	function form_po($id=null){
                $data['title']='Input PO';
		$mar=  webmastermarketing();
                $div=GetValue('divisi','sv_master_sales',array('id'=>'where/'.$mar));
                $jenisaktifitas=array();
                if(!diaadmin()){
                    $jenisaktifitas=array('type'=>'where/'.$div,'notes'=>'order/asc');
                }
                if($div=='4'){
                    $tipe_activity='support';
                }else{
                    $tipe_activity='sales';
                }
		if($id!=NULL){
		permissionz('u');
			$filter=array('id'=>'where/'.$id);
			$data['type']='Edit';
			$data['list']=GetAll($this->utama,$filter);
                        $data['detail']=GetAll('sv_activity_sales_detail',array('activity'=>'where/'.$id));
		}
		else{
			
		permissionz('c');
			$data['type']='New';
		} 
		$data['opt_pelanggan']=GetOptAll('master_pelanggan','-Pelanggan-',array('title'=>'order/asc'));
		$data['opt_aktivitas']=GetOptAll('ref_activity','-Aktivitas-',array(),'notes');
                
		$data['opt_jenis_produk']=GetOptAll('master_jenis_produk','-Jenis Produk-',array('title'=>'order/asc'));
		$data['opt_aktivitas_status']=GetOptAll('ref_activity_status','-Status-',array('title'=>'order/asc'));
                $data['opt_brand']=GetAll('sv_master_brand',array('status'=>'where/Aktif','title'=>'order/asc'))->result_array();
                if($this->session->userdata('webmaster_grup')=='3'){
                    $userdetails=GetAll('sv_admin',array('id'=>'where/'.$this->session->userdata('webmaster_id')))->row_array();
                    $data['opt_sales'][$userdetails['marketing']]=GetValue('nama_lengkap','sv_master_sales',array('id'=>'where/'.$userdetails['marketing']));
                }else{
		$data['opt_sales']=GetOptAll('master_sales','-Sales-',array('nama_lengkap'=>'order/asc'),'nama_lengkap');
                }
                $data['content'] = 'contents/'.$this->utama.'/edit';
                $data['poquo']='po';
		//End Global 
		 
		//Attendance
		
		$this->load->view('layout/main',$data);
	} 
        
	function form_po_new($id=null){
                $data['title']='Input PO (New)';
		$mar=  webmastermarketing();
                $div=GetValue('divisi','sv_master_sales',array('id'=>'where/'.$mar));
                $jenisaktifitas=array();
                if(!diaadmin()){
                    $jenisaktifitas=array('type'=>'where/'.$div,'notes'=>'order/asc');
                }
                if($div=='4'){
                    $tipe_activity='support';
                }else{
                    $tipe_activity='sales';
                }
		if($id!=NULL){
		permissionz('u');
			$filter=array('id'=>'where/'.$id);
			$data['type']='Edit';
			$data['list']=GetAll($this->utama,$filter);
                        $data['detail']=GetAll('sv_activity_sales_detail',array('activity'=>'where/'.$id));
		}
		else{
			
		permissionz('c');
			$data['type']='New';
		} 
		$data['opt_pelanggan']=GetOptAll('master_pelanggan','-Pelanggan-',array('title'=>'order/asc'));
		$data['opt_aktivitas']=GetOptAll('ref_activity','-Aktivitas-',array(),'notes');
                
		$data['opt_jenis_produk']=GetOptAll('master_jenis_produk','-Jenis Produk-',array('title'=>'order/asc'));
		$data['opt_aktivitas_status']=GetOptAll('ref_activity_status','-Status-',array('title'=>'order/asc'));
                $data['opt_brand']=GetAll('sv_master_brand',array('status'=>'where/Aktif','title'=>'order/asc'))->result_array();
                if($this->session->userdata('webmaster_grup')=='3'){
                    $userdetails=GetAll('sv_admin',array('id'=>'where/'.$this->session->userdata('webmaster_id')))->row_array();
                    $data['opt_sales'][$userdetails['marketing']]=GetValue('nama_lengkap','sv_master_sales',array('id'=>'where/'.$userdetails['marketing']));
                }else{
		$data['opt_sales']=GetOptAll('master_sales','-Sales-',array('nama_lengkap'=>'order/asc'),'nama_lengkap');
                }
                $data['content'] = 'contents/'.$this->utama.'/edit';
                $data['poquo']='po';
		//End Global 
		 
		//Attendance
		
		$this->load->view('layout/main',$data);
	} 
	function form_quotation($id=null){
                $data['title']='Input Quotation';
		$mar=  webmastermarketing();
                $div=GetValue('divisi','sv_master_sales',array('id'=>'where/'.$mar));
                $jenisaktifitas=array();
                if(!diaadmin()){
                    $jenisaktifitas=array('type'=>'where/'.$div,'notes'=>'order/asc');
                }
                if($div=='4'){
                    $tipe_activity='support';
                }else{
                    $tipe_activity='sales';
                }
		if($id!=NULL){
		permissionz('u');
			$filter=array('id'=>'where/'.$id);
			$data['type']='Edit';
			$data['list']=GetAll($this->utama,$filter);
                        $data['detail']=GetAll('sv_activity_sales_detail',array('activity'=>'where/'.$id));
		}
		else{
			
		permissionz('c');
			$data['type']='New';
		} 
		$data['opt_pelanggan']=GetOptAll('master_pelanggan','-Pelanggan-',array('title'=>'order/asc'));
		$data['opt_aktivitas']=GetOptAll('ref_activity','-Aktivitas-',array(),'notes');
		$data['opt_jenis_produk']=GetOptAll('master_jenis_produk','-Jenis Produk-',array('title'=>'order/asc'));
		$data['opt_aktivitas_status']=GetOptAll('ref_activity_status','-Status-',array('title'=>'order/asc'));
                $data['opt_brand']=GetAll('sv_master_brand',array('status'=>'where/Aktif','title'=>'order/asc'))->result_array();
                if($this->session->userdata('webmaster_grup')=='3'){
                    $userdetails=GetAll('sv_admin',array('id'=>'where/'.$this->session->userdata('webmaster_id')))->row_array();
                    $data['opt_sales'][$userdetails['marketing']]=GetValue('nama_lengkap','sv_master_sales',array('id'=>'where/'.$userdetails['marketing']));
                }else{
		$data['opt_sales']=GetOptAll('master_sales','-Sales-',array('nama_lengkap'=>'order/asc'),'nama_lengkap');
                }
                $data['content'] = 'contents/'.$this->utama.'/edit';
		//End Global 
		 
                $data['poquo']='quo';
		//Attendance
		
		$this->load->view('layout/main',$data);
	} 
        function load_sales(){
            $oi= GetValue('divisi','master_sales',array('id'=>'where/'.$_POST['s']));
            //lastq();
            if($oi==1 && $_POST['t']=='form_po'){
                echo '24';
            }
            elseif($oi==2 && $_POST['t']=='form_po'){
                echo '25';
            }
            elseif($oi==1 && $_POST['t']=='form_quotation'){
                echo '8';
            }
            elseif($oi==2 && $_POST['t']=='form_quotation'){
                echo '31';
            }
            elseif($_POST['t']=='form_po_new'){
                echo '37';
            }else{
                echo $oi;
            }
        }
	function sum($id=null){
		
		if($id!=NULL){
		permissionz('u');
                        $data['view']=TRUE;
			$filter=array('id'=>'where/'.$id);
			$data['type']='Edit';
			$data['list']=GetAll($this->utama,$filter);
                        $data['detail']=GetAll('sv_activity_sales_detail',array('activity'=>'where/'.$id));
		}
		else{
			
		permissionz('c');
			$data['type']='New';
		}
		$data['opt_pelanggan']=GetOptAll('master_pelanggan','-Pelanggan-');
		$data['opt_aktivitas']=GetOptAll('ref_activity','-Aktivitas-',array(),'title','id','notes');
		$data['opt_jenis_produk']=GetOptAll('master_jenis_produk','-Jenis Produk-',array(),'code','id','title');
		$data['opt_aktivitas_status']=GetOptAll('ref_activity_status','-Status-',array());
                $data['opt_brand']=GetAll('sv_master_brand')->result_array();
                if($this->session->userdata('webmaster_grup')=='3'){
                    $userdetails=GetAll('sv_admin',array('id'=>'where/'.$this->session->userdata('webmaster_id')))->row_array();
                    $data['opt_sales'][$userdetails['marketing']]=GetValue('nama_lengkap','sv_master_sales',array('id'=>'where/'.$userdetails['marketing']));
                }else{
		$data['opt_sales']=GetOptAll('master_sales','-Sales-',array(),'nama_lengkap');
                }
                $data['content'] = 'contents/'.$this->utama.'/sum';
		//End Global 
		 
		//Attendance
		
		$this->load->view('layout/main',$data);
	}  
	
	function view($id=null){
		
		if($id!=NULL){
		//permissionz('u');
                    $webmaster=$this->session->userdata('webmaster_id');
                    $this->db->query("UPDATE sv_notif SET status='Y' WHERE type='1' AND prospek='$id' AND `to`='$webmaster'");
			$filter=array('id'=>'where/'.$id);
			$data['type']='Edit';
                        $data['view']=TRUE;
			$data['list']=GetAll($this->utama,$filter);
                        $data['detail']=GetAll('sv_activity_sales_detail',array('activity'=>'where/'.$id));
		
		$data['opt_pelanggan']=GetOptAll('master_pelanggan','-Pelanggan-');
		$data['opt_aktivitas']=GetOptAll('ref_activity','-Aktivitas-',array(),'title','id','notes');
		$data['opt_jenis_produk']=GetOptAll('master_jenis_produk','-Jenis Produk-',array(),'code','id','title');
		$data['opt_aktivitas_status']=GetOptAll('ref_activity_status','-Status-',array());
                if($this->session->userdata('webmaster_grup')=='3'){
                    $userdetails=GetAll('sv_admin',array('id'=>'where/'.$this->session->userdata('webmaster_id')))->row_array();
                    $data['opt_sales'][$userdetails['marketing']]=GetValue('nama_lengkap','sv_master_sales',array('id'=>'where/'.$userdetails['marketing']));
                }else{
		$data['opt_sales']=GetOptAll('master_sales','-Sales-',array(),'nama_lengkap');
                }
                $data['content'] = 'contents/'.$this->utama.'/sum';
		//End Global 
		 
		//Attendance
		
		$this->load->view('layout/main',$data);
	
                }
        }  
        
        
        
	function submit(){
            error_reporting(E_ALL);
		$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(!isset($data['nilai_po']))$data['nilai_po']=0;
                if(!isset($data['nilai_quo']))$data['nilai_quo']=0;
                $data['nilai_po']=  str_replace('.','',$data['nilai_po']);
                $data['nilai_quo']=  str_replace('.','',$data['nilai_quo']);
                $data['nilai_po']=  ($data['nilai_po']=='0'?null:$data['nilai_po']);
                $data['nilai_quo']=  ($data['nilai_quo']=='0'?null:$data['nilai_quo']);
		/* if(!$this->input->post('is_active')){$data['is_active']='InActive';}
		else{$data['is_active']='Active';} */
               // print_mz($data);
		
		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');
                        notif($id,'activity_sales');
                        
                        }
			else{
				$this->session->set_flashdata("message", 'Anda Tidak Diizinkan Menambah Data');
			}
		}
                $id_detail=$this->input->post('id_detail');
		$jenis=$this->input->post('jenis_produk');
		$produk=$this->input->post('produk');
		$a=0;
		foreach($jenis as $jen){
			if($_POST['brand'][$a]!=''){
				
					$divs['activity']=$id;
					$divs['brand']=$_POST['brand'][$a];
					$divs['jenis_produk']=$jen;
					$divs['produk']=$produk[$a];
				
				if($id_detail[$a]!=''){
					//$divs['id']=$iddivisi[$a];
					$divs['modify_by'] = $webmaster_id;
					$divs['modify_on']=date("Y-m-d H:i:s");
					$this->db->where('id',$id_detail[$a]);
					$this->db->update('sv_activity_sales_detail',$divs);

				}
				else{
			$divs['created_by'] = $webmaster_id;
			$divs['created_on'] = date("Y-m-d H:i:s");
			$this->db->insert('sv_activity_sales_detail', $divs);}
			}
			$a++;
		}
		
		redirect($this->utama);
		
	}
        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' 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 loadivisi(){
            $ids=rand(111,9999);
            echo form_dropdown('pelanggan_divisi',GetOptAll('master_pelanggan_divisi','-Divisi-',array('pelanggan'=>'where/'.$_POST['v'],'title'=>'order/asc')),(isset($val[$nm_f]) ? $val[$nm_f] : ''),"class='select2' id='pelanggan_divisi'");
            echo"<script>
                    $(document).ready(function(e){ 
                        $('#pelanggan_divisi').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 carinilai(){
            $v=$_POST['v'];
            echo GetValue('nilai','sv_ref_activity',array('id'=>'where/'.$v));
        }
        function loadjenis(){
            $v=$_POST['v'];
            $id=$_POST['id'];
            $opt_brand=GetOptAll('master_jenis_produk','-Jenis Produk-',array('brand'=>'where/'.$v,'title'=>'order/asc'),'title','id');
            echo form_dropdown_('jenis_produk[]',$opt_brand,'',"id='jenis_produk-$id' onchange='gantijenis(this.value,$id)'");
        }
        function loadprodukz(){
            $v=$_POST['v'];
            $id=$_POST['id'];
            $opt_brand=GetOptAll('master_produk','-Produk-',array('jenis_produk'=>'where/'.$v,'title'=>'order/asc'),'title','id');
            echo form_dropdown_('produk[]',$opt_brand,'',"id='produk-$id' onchange='gantiproduk(this.value,$id)'");
            echo "Part Number : <span id='part_number_$id'></span>";
        }
        function to_xls(){
            error_reporting(E_ALL);
		$op = explode(",",$this->input->post('items'));
                foreach($op as $or){
                    $inz[]="$or";
                }
                $oops=implode($inz,'%');
               // print_mz($op);
               // array_pop($op); 
		//array_pop($countries_ids_post_array);
           // $from=$_POST['from_y'].'-'.$_POST['from_m'].'-'.$_POST['from_d'];
            //    $to=$_POST['to_y'].'-'.$_POST['to_m'].'-'.$_POST['to_d'];
              //  $by=$_POST['marketing'];
//		
//		$div=divisinya(); 
//                $anaknya=anaknya();
//            $this->db->select("sv_a.id id,b.nama_lengkap sales,d.notes aktivitas,c.title pelanggan,sv_a.tanggal tanggal,e.title status,sv_a.nilai nilai,sv_a.platform platform,sv_a.created_on created_on,sv_a.latitude latitude,sv_a.longitude longitude,b.divisi divisi")->from("$this->utama sv_a");
//            $this->db->join('master_sales b', "sv_a.sales=b.id", 'left');
//            $this->db->join('master_pelanggan c', "sv_a.pelanggan=c.id", 'left');
//            $this->db->join('ref_activity d', "sv_a.jenis_aktivitas=d.id", 'left');
//            $this->db->join('ref_activity_status e', "sv_a.status=e.id", 'left');
             //$this->db->select('*')->from('sv_activity_view');
             $q="SELECT * FROM sv_activity_view WHERE id IN (".$oops.")";
            //this->db->where_in('id',$op);
            //if(!diaadmin()){$this->db->where_in('b.leader',$anaknya);}
            //if(diasales()){$this->db->or_where('sv_a.created_by',$this->session->userdata('webmaster_id'));}
           //if($from!='--')$this->db->where('sv_a.tanggal >=', $from);
          //  if($to!='--')$this->db->where('sv_a.tanggal <=', $to);
           // if($by!='' )$this->db->where('sales', $by);
			//$oaaa=$this->db->query($q);
			//lastq();
		//$data['lastq']=$this->db->last_query();
                
                
                //$isisearch=array();
                //if(dialeader()){
               //                    $isisearch= array('divisi'=>'where/'.divisinya());
               // }
		//$data['opt_search']=GetOptAll('master_sales','-Sales-',$isisearch,'nama_lengkap');
		//$data['content'] = 'contents/'.$this->utama.'/view';
		
		//$data['lastq']=$oaaa->result_array();
               // lastq();
 
			// Mendefinisikan nama file ekspor "hasil-export.xls"
 
			// Tambahkan table
				//include 'table.html';
                redirect('activity_sales/render_xls/'.$oops);
            
        }
        function render_xls($lastq=null){
            
                $data['col']=$this->listcol();  
		header("Content-type: application/vnd-ms-excel");
		header("Content-Disposition: attachment; filename=hasil-export".date('YmdHis').".xls");
		$op = explode("%",$lastq);
                foreach($op as $or){
                    $inz[]="'$or'";
                }
                $oops=implode($inz,',');
             $q="SELECT * FROM sv_activity_view WHERE id IN (".$oops.")";
                
		$data['lastq']=$this->db->query($q)->result_array();
            $this->load->view('contents/'.$this->utama.'/export',$data);
        }
        function render_pdf($lastq=null){
  //die("ok");
  $this->load->helper('dompdf');
  
                $data['col']=$this->listcol();  
            error_reporting(E_ALL);
		$op = explode("%",$lastq);
                foreach($op as $or){
                    $inz[]="$or";
                }
                $oops=implode($inz,',');
             $q="SELECT * FROM sv_activity_view WHERE id IN (".$oops.")";
                
		$data['lastq']=$this->db->query($q)->result_array();
               // lastq();
    //load content html
    $html = $this->load->view('contents/activity_sales/export',$data,TRUE);
    // create pdf using dompdf
    $filename = "hasil-export";
    $paper = 'A4'; 
    $orientation = 'potrait';
   // .//ECHO "OK";
    pdf_create($html, $filename, $paper, $orientation);
 // $this->load->library('pdf');
 // $this->pdf->load_view('contents/activity_sales/export',$data);
 // $this->pdf->render();
 // $this->pdf->stream("hasil-export.pdf");
        }
        
	function encryptq($data, $size){
		$length = $size - strlen($data) % $size;
		return $data . str_repeat(chr($length), $length);
	}
	function decryptq($data){
		return substr($data, 0, -ord($data[strlen($data) - 1]));
	}
	
}
?>