<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Accident Management
*
* @package   	Accident Management
* @subpackage   Manage Controller 
* @author		Himanshu Charegaonkar
* @copyright	Copyright (c) 2013 - 2014 
* @since		Version 1.0
* @purpose      Manage functionality
**/

class Manage extends CI_Controller {


	/**
	* construct
	*
	* @author	Himanshu Charegaonkar
	* @access	public
	* @params	null
	* @return	void
	**/
	
	public function __construct() 
	{
		parent::__construct();
		$this->ci = & get_instance();
        if (!isset($this->CI->session))  //Check if session lib is loaded or not
            $this->ci->load->library('session');
        $this->load->model('manage_permissions','model');
		//Load Dependencies

	}
	
	/**
	* between
	*
	* gives string between entered strings
	* 
	* @author	Himanshu Charegaonkar
	* @access	int $this1, str $that, str $inthat
	* @params	null
	* @return	string
	*/
	function between ($this1, $that, $inthat)
    {
        return $this->before ($that, $this->after($this1, $inthat));
    }
	
	/**
	* after
	*
	* gives string after entered string
	* 
	* @author	Himanshu Charegaonkar
	* @access	int $this1, str $inthat
	* @params	null
	* @return	string
	*/
	function after ($this1, $inthat)
    {
        if (!is_bool(strpos($inthat, $this1)))
        return substr($inthat, strpos($inthat,$this1)+strlen($this1));
    }
	
	/**
	* before
	*
	* gives string before entered string
	* 
	* @author	Himanshu Charegaonkar
	* @access	int $this1, str $inthat
	* @params	null
	* @return	string
	*/
	function before ($this1, $inthat)
    {
        return substr($inthat, 0, strpos($inthat, $this1));
    }
	
	/**
	* add_modules
	*
	* Display page to add modules
	* 
	* @author	Himanshu Charegaonkar
	* @params	null
	* @return	void
	*/
	function add_modules()
    {
        $arrData['middle'] = 'admin/scan_modules';
        $this->load->view('admin/templates/template', $arrData);
    }
	
	/**
	* scanmodules
	*
	* This used to scan new modules
	* 
	* @author	Himanshu Charegaonkar
	* @access	public
	* @params	null
	* @return	void
	*/
	function scanmodules()
	{		
		$error_counter = $success_counter = 0;
		$controllers    =  $arrInsertData = array();

        $dir            = APPPATH.'/controllers/';
        $files          = scandir($dir);

        $controller_files = array_filter($files, function($filename) {
            return (substr(strrchr($filename, '.'), 1)=='php') ? true : false;
        });
		foreach ($controller_files as $filename)
        {
			$ctrl_methods = array();
			//echo $filename."<br>";
			$arr_filename = explode('.', $filename);
			$file = $arr_filename[0];
			$searchthis = "function ";
			$handle = @fopen('./application/controllers/'.$filename, "r");
			if ($handle)
			{
				while (!feof($handle))
				{
					$buffer = fgets($handle);
					if(strpos($buffer, $searchthis) !== FALSE)
						$ctrl_methods[] = $this->between('function ', '(', $buffer);
				}
				fclose($handle);
			}

			//echo('<pre>');print_r($ctrl_methods);exit;
			
			if(sizeof($ctrl_methods) > 0)
			{
				foreach($ctrl_methods as $key=>$val)
				{
					if($val != '' && $val != '\', \'')
					{
						$status_module = array();
						$status_module = $this->model->checkIfExists(trim($file), trim($val)); //check if the module exists
                        //echo "<pre>";print_r($status_module);exit;
						if(empty($status_module) )
						{
                            #echo "in";exit;
							
							
							for($i=1; $i<6; $i++)
							{

								$arrInsertData[]	= array(
															'module_name' => trim($file),
															'method_name'	=> trim($val),
															'user_level_id' => $i,
															'permission'	=> 0
															); 
                            }
						}
					}
				
				}
                //echo "<pre>";print_r($arrInsertData);exit;
			}
			
        }

        /*echo('<pre>');
        print_r($controllers);
        echo('</pre>');*/
    	
		/*echo('<pre>');
        print_r($arrInsertData);
        echo('</pre>');
		
		exit;
		die;*/
		
		if(!empty($arrInsertData))
			$status = $this->model->add($arrInsertData);
		else
			$status = 0; 
			
		if($status)
		{
			$this->session->set_flashdata('message', 'Modules added Successfully !!');
			$success_counter++;
		}else{
			$this->session->set_flashdata('message', 'Failed to add Modules !!');
			$error_counter++;
		}
						
		if($error_counter > 0)
		{
			$arrData = array('error' => $error_counter);
		}
		else{
			//if($success_counter > 0)
			{
				$arrData = array('success' => $success_counter);				
			}
		}
		//echo json_encode($arrData);exit;
		
		if($success_counter > 0)
			{
				$this->session->set_flashdata('success', 'Modules added successfully.');
				redirect('manage/add_modules/');
			}else{
				$this->session->set_flashdata('error', 'Failed to add modules.');
				redirect('manage/add_modules/');
			}
		
	}
	
	/**
	* permission
	*
	* manages permissions of module according to user level
	* 
	* @author	Himanshu Charegaonkar
	* @access	public
	* @params	int $role_id
	* @return	void
	*/
	function permission($role_id = 0)
    {
        if ((int)$role_id == 0) {
            $this->ci = & get_instance();
            $arr_session = $this->ci->session->all_userdata();
            $role_id = $arr_session['level'];
        }
        $this->load->model('user');
        # Get the previous allotted ids.
        $arr_session = $this->ci->session->all_userdata();
        $intSessionUserRole = $arr_session['level'];
        # Get the Posted Data and get the selected role id.
        if (isset($_POST['role_id'])) {
            $arrPostedData = $_POST;
            $role_id = $arrPostedData['role_id'];
        }

        # Updated the access for given role only when form is submitted by clicking submit button form.
        if(isset($_POST['permission']))
		{	
			$arrSelectedAccess = $arrPostedData['access_methods'];
            $arrUpdateRecords['alloted_access'] = implode(",", $arrSelectedAccess);
            $this->user->fnUpdateUsersAccess($role_id, $arrUpdateRecords);

            $this->session->set_flashdata('success', 'Access has been updated successfully');
            redirect('manage/permission/'.$role_id);
		}

        # First Get the list of all available access roles.
        $arrCheckResult = $this->user->fnGetAccessRoles();
        $arrData['users'] = $arrCheckResult;

        # Get the all available methods.
        $arrMethodInfo =  $this->user->fnGetAllMethods();
        $arrFinalMethod = array();
        foreach($arrMethodInfo as $method) {
            $arrFinalMethod[$method['category']][$method['action_id']] = $method;
        }
        $arrData['all_methods'] = $arrFinalMethod;

        # Get the previously allotted access to this user level.
        $arrPreviousAccess = $this->user->fnGetPreviousAccess($role_id);
        $strPreviousAccess = $arrPreviousAccess[0]['alloted_access'];
        $arrPreviousAccess = explode(",", $strPreviousAccess);
        $arrData['middle'] = 'admin/manage_permission';
		$arrData['selected_id'] = $role_id;
		$arrData['previous_access'] = $arrPreviousAccess;
		$arrData['session_level_id'] = $intSessionUserRole;
        $this->load->view('admin/templates/template', $arrData);
    }
	
}