<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Administrator extends CI_Controller {
	public function __construct(){
		parent::__construct();
		$this->load->model('common_model');
		if(get_cookie('admin_id'))
		{
			$this->session->set_userdata('admin_id',get_cookie('admin_id'));
		}
		if(!$this->session->userdata('admin_id'))
		{
			redirect('admin/login');
		}
	}

	public function index(){
		$content_data = array();
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$qry = "SELECT *,usr_users.id FROM `usr_users` LEFT JOIN `feu_userdetails` ON `feu_userdetails`.`user_id` = `usr_users`.`id` JOIN `usr_roles_users` ON `usr_roles_users`.`user_id` = `usr_users`.`id` WHERE `usr_users`.`id` != 19624 ORDER BY `usr_users`.`id` ASC";
		$res = $this->db->query($qry);
		$content_data['admin'] = $res->result_array();
		//echo $this->db->last_query(); die;
		$data['content'] = $this->load->view('admin/administrator/list', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function add(){
		$content_data = array();
		if($this->input->post())
		{//print_r($this->input->post('couple')); die;
			$email=$this->utility->info_cleanQuery($this->input->post('useremail'));
			$username=$this->utility->info_cleanQuery($this->input->post('userusername'));
			$password=$this->common_model->generateHash($this->utility->info_cleanQuery($this->input->post('userpassword')));
			$emailExist = $this->common_model->getAllRow('usr_users',array('email'=>$email));	
			$usernameExist = $this->common_model->getAllRow('feu_userdetails',array('username'=>$username));	
			if(empty($emailExist) && empty($usernameExist))
			{
				$usr_con=array(
						'email'=>$email,
						'created'=>time(),
						'password'=>$password,
						'email_confirmed'=>1,
				);
				$userId = $this->common_model->insertData('usr_users',$usr_con);

				$usrDetails_con=array(
							'user_id'=>$userId,
							'created'=>time(),
							'username'=>$username,
							'alias'=>str_replace("'","-",str_replace('&','-',str_replace(' ','-',trim($username)))),
							'accounttype'=>'Gentleman',
							'userlanguage'=>2
					);
				$this->common_model->insertData('feu_userdetails',$usrDetails_con);

				$this->common_model->insertData('usr_roles_users',array('role_id'=>1,'user_id'=>$userId));

				$this->utility->setMsg('Administrator added','SUCCESS');	
				redirect(base_url().'admin/administrator');
			}
			$this->utility->setMsg('Email or username exist','ERROR');
		}
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$data['content'] = $this->load->view('admin/administrator/add', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function delete($admin_id='')
	{
		//echo $cat_id;die;
		if($admin_id!='')
		{
			$adminId=base64_decode($admin_id);
			$this->common_model->deleteData('usr_users',array('id'=>$adminId));
			$this->common_model->deleteData('feu_userdetails',array('user_id'=>$adminId));
			$this->common_model->deleteData('usr_roles_users',array('user_id'=>$adminId));
			$this->utility->setMsg('Administrator deleted','SUCCESS');	
			redirect(base_url().'admin/administrator');
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/administrator');
		}
	}
	public function deleteAccess($access_id='',$admin_id ='')
	{
		//echo $cat_id;die;
		if($access_id!='')
		{
			$accessId=base64_decode($access_id);
			$this->common_model->deleteData('usr_modules',array('id'=>$accessId));
			$this->utility->setMsg('Administrator access deleted','SUCCESS');	
			redirect(base_url().'admin/administrator/permission/'.$admin_id);
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/administrator');
		}
	}
	public function permission($admin_id='')
	{
		if($admin_id!='')
		{
			$id=base64_decode($admin_id);
			
	        if($this->input->post())
	        {
	            $this->allotModule($id);
	        }
	        $userModulesData=$this->common_model->getAll('modules',array('user_id'=>$id),array('usr_modules','usr_modules.module_id = modules.id'),'module_name ASC','*,module_id','modules.id') ;
	        //echo $this->db->last_query(); die;
	        $userModules = array();
	        if(!empty($userModulesData))
	        {
	            foreach($userModulesData as $value)
	            {
	                array_push($userModules,$value['module_id']);
	            }
	        }
	        else
	        {
	            $userModules=array();
	        }
	        //print_r(implode(',',$userModules)); die;
	        $where = "1 = 1";
	        if(!empty($userModules))
	        {
	        	$where = "id not in (".implode(',',$userModules).")";
	        }
	        
	        $modules=$this->common_model->getAll('modules',$where,'','module_name ASC') ;
	        //echo $this->db->last_query(); die;
	        $content_data['user']=$user;
	        $content_data['user_modules']=$userModulesData;
	        $content_data['user_module_ids']=$userModules;
	        $content_data['id']=base64_encode($id);
	        $content_data['modules']=$modules;
	        
			$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
			$data['content'] = $this->load->view('admin/administrator/permission', $content_data, TRUE);
			$this->load->view('admin/layout', $data);
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/administrator');
		}
	}
	public function change_permission()
    {
        $id=base64_decode($this->input->post('id'));
        
        $data=array();
        if($this->input->post('read_access'))
        {
            if($this->input->post('read_access')==1)
                $data['read_access']=1;
            else
                $data['read_access']=0;
        }

        if($this->input->post('write_access'))
        {
            if($this->input->post('write_access')==1)
            {
                $data['read_access']=1;
                $data['write_access']=1;
            }
            else
                $data['write_access']=0;
        }

        $this->common_model->UpdateData('usr_modules',$data,array('id'=>$id));
        //$this->output('Success','SUCCESS');
    }
    private function allotModule($id)
    {
        $time=(int)time();
        $insertBatch=array();
        
        if($this->input->post('selected_modules'))
        {//print_r($this->input->post('selected_modules')); die;
            foreach($this->input->post('selected_modules') as $value)
            {
                //$chk=$this->model_video->getAllRow('user_permissions',array('user_id'=>$id,'module_id'=>base64_decode($value)));
                $chk=$this->common_model->getAll('usr_modules',array('user_id'=>$id,'module_id'=>base64_decode($value)));
                //print_r($chk); die;
                if(empty($chk))
                {
                    $data=array(
                    'user_id'=>$id,
                    'module_id'=>base64_decode($value),
                    'read_access'=>1,
                    'write_access'=>1,
                    'created'=>$time
                    );
                    array_push($insertBatch,$data);
                }
                else
                {
                    $data=array(
                    'user_id'=>$chk['user_id'],
                    'module_id'=>$chk['module_id'],
                    'read_access'=>$chk['read_access'],
                    'write_access'=>$chk['write_access'],
                    'created'=>$chk['created'],
                    );
                    array_push($insertBatch,$data);
                }
            }
            
            if($insertBatch)
            {
            	//$this->common_model->deleteData('usr_modules',array('user_id'=>$id));
            	foreach ($insertBatch as $key => $val) {
            		$this->common_model->insertData('usr_modules',$val);
                	//echo $this->db->last_query(); die;
            	}
                $this->utility->setMsg(count($insertBatch).' Module(s) has been updated');
                redirect(base_url().'admin/administrator/permission/'.  base64_encode($id));
            }
        }
        else
        {
            $this->utility->setMsg('Please enter some module','ERROR');
            redirect(base_url().'admin/administrator/permission/'.  base64_encode($id));
        }
    }
}