<?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_sales extends CI_Controller {
	
		var $utama ='master_sales';
		var $title ='Master Solution Force';
	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['nama_lengkap'] = array('Nama',110,TRUE,'left',2);
            $colModel['divisi'] = array('Divisi',110,TRUE,'left',2);
            $colModel['groups'] = array('Group',110,TRUE,'left',2);
            $colModel['leader'] = array('Leader',110,TRUE,'left',2);
            $colModel['username'] = array('Username',110,TRUE,'left',2);
            $colModel['status'] = array('Status',110,TRUE,'left',2);
            $colModel['auth'] = array('Auth Menu',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,'nama_lengkap','asc',$gridParams,$buttons);
	}
	
	function get_flexigrid()
        {

            //Build contents query
            $this->db->select("sv_a.id id,sv_a.nama_lengkap nama_lengkap,c.title divisi,b.nama_lengkap leader,sv_a.status status,d.title groups")->from("$this->utama sv_a");
            $this->db->join('sv_master_sales b', "sv_a.leader=b.id", 'left');
            $this->db->join('sv_ref_divisi c', "sv_a.divisi=c.id", 'left');
            $this->db->join('sv_ref_group d', "sv_a.groups=d.id", 'left');
            if(!diaadmin())$this->db->where_in('sv_a.leader',$anaknya);
            $this->flexigrid->build_query();
			

            //Get contents
            $return['records'] = $this->db->get();
			//lastq();
            //Build count query
            $this->db->select("count(id) as record_count");
            if(!diaadmin())$this->db->where_in('leader',$anaknya);
            $this->db->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','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();

            $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 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->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']=GetOptAll('menu','-Parents-');
                $data['opt_leader']=GetOptAll('sv_master_sales','-Leader-',array(),'nama_lengkap');
                $data['opt_leader'][0]='-Tidak Ada Leader';
                //array_push($data['opt_leader'],$def);
		$data['content'] = 'contents/'.$this->utama.'/edit';
                
		//End Global
		
		//Attendance
		
		$this->load->view('layout/main',$data);
	}
	function auth($id=null){
		
		error_reporting(0);
		/* permissionz();
		if($id!=NULL){
			$filter=array('id'=>'where/'.$id);
			$data['type']='Edit';
		$data['list']=GetAll($this->utama,$filter);
		}
		else{
			$data['type']='New';
		} */
		
		$data['modul']=GetAll('menu',array('id_parents'=>'where/0','is_active'=>'where/Active'));
		//lastq();
		$data['id_user']=$id;
		//$this->data['id_grup']=GetValue('id','admin_grup',array('user_id'=>'where/'.$id));
		$data['opt']=GetOptAll('master_sales');
		$data['content'] = 'contents/'.$this->utama.'/auth';
		//End Global
		
		
		$this->load->view('layout/main',$data);
	}
	function auth_submit(){
            error_reporting(0);
		$menu=$this->input->post('menu');
		
		$m_c=$this->input->post('m_c');
		$m_v=$this->input->post('m_v');
		$m_u=$this->input->post('m_u');
		$m_d=$this->input->post('m_d');
		
		$submenu=$this->input->post('submenu');
		$s_c=$this->input->post('s_c');
		$s_v=$this->input->post('s_v');
		$s_u=$this->input->post('s_u');
		$s_d=$this->input->post('s_d');
		$s_p=$this->input->post('s_p');
		
		$user=$this->input->post('user_group');
		foreach($menu as $m){
				$cek=GetAll('users_permission_sf',array('user_id'=>'where/'.$user,'menu_id'=>'where/'.$m))->num_rows();
				$data['menu_id']=$m;
				$data['create']=($m_c[$m] ? '1':'0');
				$data['view']=($m_v[$m] ? '1':'0');
				$data['update']=($m_u[$m] ? '1':'0');
				$data['delete']=($m_d[$m] ? '1':'0');
				//$data['user_id']=$user;
				//$data['user_id']=GetValue('group_id','users_groups',array('user_id'=>'where/'.$user));
				$data['user_id']=$user;
				if($cek==0){
						$this->db->insert('users_permission_sf',$data);
				}
				else{
						$this->db->where(array('user_id'=>$user,'menu_id'=>$m));
						$this->db->update('users_permission_sf',$data);
				}
                }
		foreach($submenu as $sm){
				$cek=GetAll('users_permission_sf',array('user_id'=>'where/'.$user,'menu_id'=>'where/'.$sm))->num_rows();
				$data['menu_id']=$sm;
				$data['create']=($s_c[$sm] ? '1':'0');
				$data['view']=($s_v[$sm] ? '1':'0');
				$data['update']=($s_u[$sm] ? '1':'0');
				$data['delete']=($s_d[$sm] ? '1':'0');
				$data['print']=($s_p[$sm] ? '1':'0');
				//$data['user_id']=$user;
				//$data['user_id']=GetValue('group_id','users_groups',array('user_id'=>'where/'.$user));
				
				$data['user_id']=$user;
				if($cek==0){
						$this->db->insert('users_permission_sf',$data);
				}
				else{
						$this->db->where(array('user_id'=>$user,'menu_id'=>$sm));
						$this->db->update('users_permission_sf',$data);
				}
                }
                redirect($this->utama);
        }
	
	function submit(){
           // print_mz($this->input->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('leader')=='0'||$this->input->post('leader')==NULL){
                    $data['leader']=0;
                }
		
		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);
                        
                        $cek=$this->db->query("SELECT * FROM sv_admin WHERE marketing='$id'");
                        if($cek->num_rows()==0){
                             if($this->input->post('password')){$dataz['password']=md5($this->config->item('encryption_key').$this->input->post("password"));}else{$dataz['password']=md5($this->config->item('encryption_key').'12345');}
                        $dataz['avatar']='default.png';
                        $dataz['name']=$data['nama_lengkap'];
                        
                        $dataz['id_admin_grup']=$data['roles'];

                        $dataz['username']=  $this->input->post('username');

                        $dataz['marketing']=$id;

			$dataz['create_user_id'] = $webmaster_id;
			$dataz['create_date'] = date("Y-m-d H:i:s");
			$this->db->insert('sv_admin', $dataz);
			$idz = $this->db->insert_id();
			$profil['useradmin']=$idz;
			$profil['name']=$data['nama_lengkap'];
			$profil['avatar']=$dataz['avatar'];
			$profil['create_user_id'] = $webmaster_id;
			$profil['create_date'] = $data['modify_on'];
			$this->db->insert('sv_admin_profile',$profil);
                        }else{
                        
                        if($this->input->post('password')!=NULL){$dataz['password']=md5($this->config->item('encryption_key').$this->input->post("password"));}
                        $dataz['name']=$data['nama_lengkap'];
                        $dataz['username']=  $this->input->post('username');
			$dataz['modify_user_id'] = $webmaster_id;
			$dataz['modify_date']=date("Y-m-d");
			$this->db->where("marketing", $id);
			$this->db->update('sv_admin', $dataz);
                        }
			$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();
                        
                        if($this->input->post('password')){$dataz['password']=md5($this->config->item('encryption_key').$this->input->post("password"));}else{$dataz['password']=md5($this->config->item('encryption_key').'12345');}
                        $dataz['avatar']='default.png';
                        $dataz['name']=$data['nama_lengkap'];
                        //$dataz['username']=  str_replace(' ','_',strtolower($data['nama_lengkap']));
                        
                        $dataz['username']=  $this->input->post('username');
                        $dataz['id_admin_grup']=$data['roles'];

                        $dataz['marketing']=$id;

			$dataz['create_user_id'] = $webmaster_id;
			$dataz['create_date'] = date("Y-m-d H:i:s");
			$this->db->insert('sv_admin', $dataz);
			$idz = $this->db->insert_id();
			$profil['useradmin']=$idz;
			$profil['name']=$data['nama_lengkap'];
			$profil['avatar']=$dataz['avatar'];
			$profil['create_user_id'] = $webmaster_id;
			$profil['create_date'] = $data['created_on'];
			$this->db->insert('sv_admin_profile',$profil);
                        
                        
			$this->session->set_flashdata("message", 'Sukses ditambahkan');}
			else{
				$this->session->set_flashdata("message", 'Anda Tidak Diizinkan Menambah Data');
			}
		}
		//divisi
		
		
		redirect($this->utama);
		
	}
	
}
?>