<?php

if (!function_exists('nf_set_value')) { 

	function nf_set_value($field = '', $default = '')

	{

		//if (FALSE === ($OBJ =& _get_validation_object()))

		//{

			if (isset($_POST[$field]))

			{

				return form_prep($_POST[$field], $field);

			}

			if (isset($_GET[$field]))

			{

				return form_prep($_GET[$field], $field);

			}



			return $default;

		//}



		return form_prep($OBJ->nf_set_value($field, $default), $field);

	}

}



function adminAccess(){

	$ci = &get_instance();

	$module_id=check_module_access();

	//echo '<br>'.$ci->session->userdata('module_ids');

	if($module_id=='' || !in_array($module_id,explode(',',$ci->session->userdata('module_ids'))))

	{

		//redirect('admin/admin_master/no_access');

	}

}

function check_module_access()

{

	$ci = &get_instance();

	$url='';

	if($ci->uri->segment(1) != '')

		$url=$ci->uri->segment(1);

	if($ci->uri->segment(2) != '')

		$url.='/'.$ci->uri->segment(2);

	if($ci->uri->segment(3) != '')	

		$url.='/'.$ci->uri->segment(3);

	

	$cond=array();

	$cond[] = array('where','module_type',$ci->session->userdata('user_type'));

	$cond[] = array('where','module_function_path',$url);

	$sel_array=array(

					'table_name'=>MODULE_FUNCTIONS,

					'table_fields'=>'module_id',

					'condition'=>$cond,

					'limit'=>'',

					'offset'=>''

					);

	$result['module_list']=$ci->master_model->select_data($sel_array);

	//dump($ci->db->last_query());

	if(is_array($result['module_list']) && count($result['module_list'])>0)

		$module_id=$result['module_list'][0]['module_id'];

	else

		$module_id='';	

	return $module_id;

}

function admin_auth(){

	 $ci = &get_instance();

	// $ci->load->library('tank_auth_admin');

	 $user_session_id= $ci->session->userdata('user_id');

	 //echo $user_session_id;

	// $ci->lang->load('tank_auth_admin');

	if($user_session_id==''){

	//dumpEx($ci->session->all_userdata());

	 //if (!$ci->tank_auth_admin->is_logged_in()) {

	// 	// redirect(ADMIN_MASTER_PATH.'login/');

		//redirect('https://shagoon.nityamhygiene.in/index.php/main');
		redirect(BASE_URL);

		

	}

}

function sub_modules($id,$i,$mid,$moduleid,&$nested_mod_id,$mod_sel_id,$process)

{

	$CI =& get_instance();

	$cond[] = array('where','module_type',$process);

	$cond[] = array('where','module_parent_id',$id);

	$cond[] = array('where','is_visible','1');

	$sel_array=array(

					'table_name'=>MODULES,

					'table_fields'=>'module_id,module_name',

					'condition'=>$cond,

					'limit'=>'',

					'offset'=>''

					);

	$result['module_list']=$CI->master_model->select_data($sel_array);

	

	$nested_mod_id[$id]=array();

	foreach($result['module_list'] as $k=>$result_module)

	{

		$cond1='';

		$new_id=$result_module["module_id"];

		$nested_mod_id[$id][]=$new_id;

		$sel_cond='';

		

		if(isset($mod_sel_id[$new_id]) && $mod_sel_id[$new_id]==$new_id)

		{

			$sel_cond='checked="checked"';

		}

		

		?>

		<tr>

		  <td width="3%"><input type="checkbox" name="<?php echo "mod_sel_id_".$new_id?>" id="<?php echo "mod_sel_id_".$new_id?>" value="<?php echo $new_id?>" onClick="get_selected('<?php echo $new_id?>','no')" <?php echo $sel_cond;?>></td>

		<td width="97%" align="left"><?php echo str_repeat("&nbsp; - &nbsp;", $i).stripslashes($result_module["module_name"])?></td>

			

		</tr>

		<?php

		$i++;

		sub_modules($new_id,$i,$mid,$moduleid,$nested_mod_id,$mod_sel_id,$process);

		$i--;

		

	}

	

	

}



function get_module_list($process,$pro_id)

{

	

	$none="none";

	$nested_mod_id=array();

	$CI =& get_instance();

	$mod_sel_id='';

	if($process=='admin' || $process=='employee')

	{

		if($pro_id!=''){

			$module_ids=explode(",",$pro_id);

			foreach($module_ids as $k2=>$v2)

			{

				$mod_sel_id[$v2]=$v2;

			}

		}

	}

		

	?>

		<table class="table table-striped table-bordered" style="margin-bottom: 0px;width:70%;">

				<tr>

					<td colspan="3"><input type="checkbox" name="all_chk" id="all_chk" value="" onClick="select_all_val()"><a  onClick="select_all_val()"> <b>Select All</b></a></td>

				</tr>

				</table>

	  	<?php

			

			$j=0;

			$i=1;

			$mid=0;

			$moduleid=0;

			$cond[] = array('where','module_type',$process);

			$cond[] = array('where','module_parent_id',0);

			$cond[] = array('where','is_visible','1');

			$sel_array=array(

					'table_name'=>MODULES,

					'table_fields'=>'module_id,module_name',

					'condition'=>$cond,

					'order_by_field'=>'sort_order',

					'order'=>'ASC',

					'limit'=>'',

					'offset'=>''

					);

			$result['module_list']=$CI->master_model->select_data($sel_array);

			

			foreach($result['module_list'] as $k=>$fetch_parent_classification_id_row)

			{

				$j++;

				

				$module_parant_id = $fetch_parent_classification_id_row["module_id"];

				$all_p_val[]=$module_parant_id;

				$sel_cond='';

				if(isset($mod_sel_id[$module_parant_id]) && ($mod_sel_id[$module_parant_id]==$module_parant_id))

				{

					$sel_cond='checked="checked"';

				}

				?>

				

				<table class="table table-striped table-bordered" style="margin-bottom: 0px;width:70%;">

				<tr>

					<td width="3%"><input type="checkbox" name="<?php echo "mod_sel_id_".$module_parant_id?>" id="<?php echo "mod_sel_id_".$module_parant_id?>" value="<?php echo $module_parant_id?>" onClick="get_selected('<?php echo $module_parant_id?>','no')" <?php echo $sel_cond?>></td>

					<td width="69%"><strong><?php echo $fetch_parent_classification_id_row["module_name"]?></strong></td>

					<td width="24%"><a id="<?php echo "show_hide".$j?>" onClick="show_sub_mod('<?php echo $j?>')">Expand</a></td>

				</tr>

				</table>

				<table class="table table-striped table-bordered" style="display:<?php echo $none?>;margin-bottom: 0px;width:70%;" id="<?php echo "sub_mod".$j?>">

				<?php

					sub_modules($module_parant_id,$i,$mid,$moduleid,$nested_mod_id,$mod_sel_id,$process);

				?>

								</table>



				<?php

				

			}

			

		?>

		<input type="hidden" name="all_val" id="all_val" value="<?php echo base64_encode(serialize($nested_mod_id));?>">

				<input type="hidden" name="all_p_val" id="all_p_val" value="<?php echo implode(",",$all_p_val);?>"></td>

	

	<script type="text/javascript">

	function get_selected(mid,n_val)

	{

		var mod_arr=document.getElementById("all_val").value;

		if(n_val=='no')

		{

			if(document.getElementById("mod_sel_id_"+mid).checked==true)

			{

				n_val=true;

			}

			else

			{

				n_val=false;

			}

		}

		var a=0;

		if(n_val)

			a=1;

		

		$.post("<?php echo base_url()?>index.php/admin/admin_type/get_sub_mod", {mod_arr:mod_arr,mid:mid,n_val:a},

			 function(show_grade){

				

				var selected_rec=show_grade.split(",");

				for(i=0;i<selected_rec.length;i++)

				{

					document.getElementById("mod_sel_id_"+selected_rec[i]).checked=n_val;

				}

			 });

 

		}

		function show_sub_mod(j)

		{	

			

		  val=document.getElementById("show_hide"+j).innerHTML;

		  if(val=='Expand')

		  {

			document.getElementById("sub_mod"+j).style.display = "block";

			document.getElementById("show_hide"+j).innerHTML="Collapse"

		  }

		  else

		  {

			document.getElementById("sub_mod"+j).style.display = "none";

			document.getElementById("show_hide"+j).innerHTML="Expand"

		  }

		}

		function select_all_val()

		{

			all_p_val=document.getElementById("all_p_val").value;

			all_chk=document.getElementById("all_chk").checked;

			//alert("1st="+all_chk)

			var sel_val=all_p_val.split(",");

			for(j=0;j<sel_val.length;j++)

			{

				get_selected(sel_val[j],all_chk);

			}

			

		}

	</script>

<?php	

}



function sub_modules_confirm($id,$i,$mid,$moduleid,&$nested_mod_id,$arr,$process)

{

	$CI =& get_instance();



	$cond[] = array('where','module_type',$process);

	$cond[] = array('where','module_parent_id',$id);

	$cond[] = array('where','is_visible','1');

	$sel_array=array(

					'table_name'=>MODULES,

					'table_fields'=>'module_id,module_name',

					'condition'=>$cond,

					'limit'=>'',

					'offset'=>''

					);

	$result['module_list']=$CI->master_model->select_data($sel_array);

	

	$nested_mod_id[$id]=array();

	if(count($result['module_list']) > 0){

		foreach($result['module_list'] as $k=>$result_module)

		{

			$cond1='';

			$new_id=$result_module["module_id"];

			

			

			if($id==$moduleid)

				$cond1="selected='selected'";

			

			if(isset($arr["mod_sel_id_".$new_id]))

			{

				$nested_mod_id[$id][]=$new_id;

				

				?>

					<input type="hidden" name="<?php echo "mod_sel_id_".$new_id?>" id="<?php echo "mod_sel_id_".$new_id?>" value="<?php echo $arr["mod_sel_id_".$new_id]?>">

					<tr>

					 <td width="100%" align="left" ><?php echo str_repeat("&nbsp; - &nbsp;", $i).stripslashes($result_module["module_name"])?></td>

						

					</tr>

					

				<?php

			}

			$i++;

			sub_modules_confirm($new_id,$i,$mid,$moduleid,$nested_mod_id,$arr,$process);

			$i--;

		}

	}

}



function get_module_list_confirm($process,$arr)

{

	//dump($arr);

	$none="none";

	$nested_mod_id=array();

	$CI =& get_instance();

	

	$j=0;

	$i=1;

	$mid=0;

	$moduleid=0;

	$cond[] = array('where','module_type',$process);

	$cond[] = array('where','module_parent_id',0);

	$cond[] = array('where','is_visible','1');

	$sel_array=array(

			'table_name'=>MODULES,

			'table_fields'=>'module_id,module_name',

			'condition'=>$cond,

			'order_by_field'=>'sort_order',

			'order'=>'ASC',

			'limit'=>'',

			'offset'=>''

			);

	$result['module_list']=$CI->master_model->select_data($sel_array);

	foreach($result['module_list'] as $k=>$fetch_parent_classification_id_row)

	{

		$j++;

		

		$module_parant_id = $fetch_parent_classification_id_row["module_id"];

		$all_p_val[]=$module_parant_id;

		if(isset($arr["mod_sel_id_".$module_parant_id]))

		{ 

		?>

		<table class="table table-striped table-bordered" style="margin-bottom: 0px;width:70%;">

		<tr>

		

			<input type="hidden" name="<?php echo "mod_sel_id_".$module_parant_id?>" id="<?php echo "mod_sel_id_".$module_parant_id?>" value="<?php echo $arr["mod_sel_id_".$module_parant_id]?>">

			<td width="69%"><strong><?php echo $fetch_parent_classification_id_row["module_name"]?></strong></td>

			

		</tr>

		</table>

		<table class="table table-striped table-bordered" style="margin-bottom: 0px;width:70%;">

		<?php

			sub_modules_confirm($module_parant_id,$i,$mid,$moduleid,$nested_mod_id,$arr,$process);

		?>

		</table>



		<?php

		}

		

	}

	

	?>

	<input type="hidden" name="all_val" id="all_val" value="<?php echo base64_encode(serialize($nested_mod_id));?>">

	<!--<input type="hidden" name="all_p_val" id="all_p_val" value="<?php echo implode(",",$all_p_val);?>"></td>-->

	</td></tr>

	</table>

<?php	

}



function dump($arr){

	echo '<pre>';print_r($arr);echo '</pre>';

}

function dumpex($arr){

	echo '<pre>';print_r($arr);echo '</pre>';exit;

}



function get_func_comp($admin_type_id)

{

	$arr=get_data_arr(ADMIN_TYPE,"function_type_ids,company_ids,module_ids","admin_type_id",$admin_type_id,'where');

	echo implode('%%',$arr);

}

function get_data_value($table,$value,$field_name,$id,$operator)

{

	$CI =& get_instance();

	$cond[] = array($operator,$field_name,$id);

	$sel_array=array(

			'table_name'=>$table,

			'table_fields'=>$value,

			'condition'=>$cond,

			'limit'=>'',

			'offset'=>''

			);

	$result['data_list']=$CI->master_model->select_data($sel_array);

	//dump($CI->db->last_query());

	$val=array();

	if(count($result['data_list']) > 0)

	{

		foreach($result['data_list'] as $ke=>$va)

			$val[]=$va[$value];

	}

	return implode(',',$val);

}

function get_data_arr($table,$value,$field_name,$id,$operator)

{

	$CI =& get_instance();

	$cond[] = array($operator,$field_name,$id);

	$sel_array=array(

			'table_name'=>$table,

			'table_fields'=>$value,

			'condition'=>$cond,

			'limit'=>'',

			'offset'=>''

			);

	$result['data_list']=$CI->master_model->select_data($sel_array);

	//dump($CI->db->last_query());

	$val=array();

	if(count($result['data_list']) > 0)

	{

		foreach($result['data_list'] as $ke=>$va)

		{

			foreach($va as $k=>$v)

				$val[$k]=$v;

		}

	}

	return $val;

}

function get_data_arr_key($table,$value,$field_name,$id,$operator)

{

	$CI =& get_instance();

	$cond[] = array($operator,$field_name,$id);

	$sel_array=array(

			'table_name'=>$table,

			'table_fields'=>$value,

			'condition'=>$cond,

			'limit'=>'',

			'offset'=>''

			);

	$result['data_list']=$CI->master_model->select_data($sel_array);

	//dump($CI->db->last_query());

	$val=array();

	if(count($result['data_list']) > 0)

	{

		foreach($result['data_list'] as $ke=>$va)

		{

			foreach($va as $k=>$v)

				$val[$ke]=$v;

		}

	}

	return $val;

}



function get_current_financial_year()

{

	$CI =& get_instance();

	$cond[] = array('where','start_date <=',date('Y-m-d'));

	$cond[] = array('where','end_date >=',date('Y-m-d'));

	$cond[] = array('where','is_enable','1');

	$sel_array=array(

			'table_name'=>FINANCIAL_YEAR,

			'table_fields'=>'financial_year_id',

			'condition'=>$cond,

			'limit'=>'',

			'offset'=>''

			);

	

	$result['fin_year_data']=$CI->master_model->select_data($sel_array);

	

	if(count($result['fin_year_data'])>0)

	{

		foreach($result['fin_year_data'] as $k=>$v)

			return $v['financial_year_id'];

	}

	else

		return '';

}



function get_financial_year()

{

	$CI =& get_instance();

	$cond[] = array('where','is_enable','1');

	$sel_array=array(

			'table_name'=>FINANCIAL_YEAR,

			'table_fields'=>'financial_year_id,financial_year',

			'condition'=>$cond,

			'order_by_field'=>'financial_year',

			'order'=>'DESC',

			'limit'=>'',

			'offset'=>''

			);

	

	$result['fin_year_data']=$CI->master_model->select_data($sel_array);

	//dump($CI->db->last_query());

	if(count($result['fin_year_data'])>0)

	{

		return $result['fin_year_data'];

	}

	else

		return '';

}

function key_generate()

{

	$len = 6;

	$base='ABCDEFGHKLMNOPQRSTWXYZ123456789';

	$max=strlen($base)-1;

	$key="";

	mt_srand((double)microtime()*1000000);

	while (strlen($key)<$len+1)

	$key.=$base[mt_rand(0,$max)];

	return $key;

}

function generate_code($table,$field,$id,$initial)

{

	$CI =& get_instance();

	$cond = array();

	$sel_array=array(

			'table_name'=>$table,

			'table_fields'=>$field,

			'condition'=>$cond,

			'order_by_field'=>$id,

			'order'=>'DESC',

			'limit'=>'1',

			'offset'=>'0'

			);

	$result['data_list']=$CI->master_model->select_data($sel_array);

	

	if (count($result['data_list']) > 0) {

		foreach($result['data_list'] as $k=>$v){

			$code=$v[$field];

		}

		$letters = preg_replace('/[^a-zA-Z]/', '', $code);

		$numbers = preg_replace('/[^0-9]/', '', $code);

		

		$numbers=sprintf("%04d",($numbers+1));

		if($initial=='E')

			$code_val=$numbers;

		else	

			$code_val=$letters.'_'.$numbers;

	}

	else

	{

		if($initial=='E')

			$code_val='800001';

		else	

			$code_val=$initial.'_0001';

	}

	

	return $code_val;

}

function getlistmodules($id){		

	$CI = &get_instance();

	$result=array();

	

	$cond[] = array('where','module_parent_id',$id);

	$cond[] = array('where','is_visible','1');

	$sel_array=array(

			'table_name'=>MODULES,

			'table_fields'=>'module_id,module_name,is_visible,module_parent_id',

			'condition'=>$cond,

			'order_by_field'=>'sort_order',

			'order'=>'ASC',

			'limit'=>'',

			'offset'=>''

			);

	$result=$CI->master_model->select_data($sel_array);	

	return $result;		

}

function module_list($id,$i,$append_sql,$x0=0,$x1=0,$x2=0,$x3=0,$x4=0,$x5=0)

{

	$CI = &get_instance();

	$j =1;

	$k=1;

	$cond=array();

	$cond=$append_sql;

	$cond[] = array('where','module_parent_id',$id);

	//$cond[] = array('where','is_visible','1');

	$sel_array1=array(

			'table_name'=>MODULES,

			'table_fields'=>'*',

			'condition'=>$cond,

			'order_by_field'=>'sort_order',

			'order'=>'ASC',

			'limit'=>'',

			'offset'=>''

			);

	$result_new['data']=$CI->master_model->select_data($sel_array1);	

	//dump($CI->db->last_query());

	$not_append='';							

	foreach($result_new['data'] as $k=>$result_module)

	{

		$id=$result_module["module_id"];

		echo "<tr><td  valign='top' class='td_white'><p>";								

		$cnt=$i;

			

		if($cnt==0)

		{

			$x0++;

			$x1=0;

			echo $x0;

		}

		if($cnt==1)

		{

			$x1++;											

			$x2=0;

		}

		

		if($cnt==2)

		{

			$x2++;									

		}

		

		if($cnt==3)

		{

			$x3++;									

		}

		

		if($cnt==4)

		{

			$x4++;									

		}

		

		if($cnt==5)

		{

			$x5++;									

		}

			

		echo "</p></td>";

		echo "<td height='25' valign='top' class='td_white'><p>";

			echo str_repeat("&nbsp;&nbsp;", $i);

			if($i>0)

			{

				echo str_repeat("&nbsp;-&nbsp;", $i);

			}									

			echo stripslashes($result_module["module_name"]);									

		echo "</p></td>";

		echo "<td valign='top' class='td_white'><p>";

			echo ucfirst(stripslashes($result_module["module_type"]));									

		echo "</p></td>";

	?>

	<?php

		echo "<td valign='top' class='td_white'><p>";

	?>

		<a href="<?php echo base_url().'index.php/'.MODULE_MASTER_PATH.'manage_module/'.$result_module["module_id"];?>/<?php echo $result_module["module_parent_id"];?>"><b>Edit</b></a> | 

	<?php

		if($result_module["is_visible"]=='1') {  

				echo anchor(MODULE_MASTER_PATH.'toggle_module/'.$id.'/'.$result_module["is_visible"],'<b>Disable</b>','class="link_s"'); 

		 } else {

			

			$cond2[] = array('where','module_parent_id',$result_module["module_parent_id"]);

			$sel_array1=array(

					'table_name'=>MODULES,

					'table_fields'=>'is_visible,module_name',

					'condition'=>$cond2,

					'limit'=>'1',

					'offset'=>'0'

					);

			$result_new['data1']=$CI->master_model->select_data($sel_array1);

			foreach($result_new['data1'] as $ke=>$result_sql){

				if($result_sql["is_visible"]=="1")

				{

					echo anchor(MODULE_MASTER_PATH.'toggle_module/'.$id.'/'.$result_module["is_visible"],'<b>Enable</b>','class="link_s"'); 

				}

				else

				{

					if($result_module["module_parent_id"]=="0")

					{											

						echo anchor(MODULE_MASTER_PATH.'toggle_module/'.$id.'/'.$result_module["is_visible"],'<b>Enable</b>','class="link_s"');

					}

					else

					{											

						echo anchor(MODULE_MASTER_PATH.'toggle_module/'.$id.'/'.$result_module["is_visible"],'<b>Enable</b>','class="link_s"');

					} 

				}

			}

		}

	

	?>

	

	<?php	echo "</p></td>";

		echo "</tr>";

		

		$i++;

		module_list($id,$i,$not_append,$x0,$x1,$x2,$x3,$x4,$x5);

		$i--;								

	}

}	

function get_module_data($field_value,$module_parent_id,$module_id,$module_type)

{

	

	if($field_value=="child")

	{

?>	

		<label class="col-sm-5 control-label" for="form-field-2" ><?php echo 'Parent Module ';?></label>

		<div class="col-sm-7">	

			<select name='module_parent_id' style="width:200px;" >

				<?php 

					echo submodule(0,0,$module_parent_id,$module_id,$module_type);	

				?>	

			</select>

			<?php echo form_error('module_parent_id'); ?>

		</div>

<?php 

	}

	else

	{

	  echo "";

	}

	



}



function submodule($id,$i,$mid,$moduleid,$module_type)

{

	$CI = &get_instance();

	$cond[] = array('where','module_type',$module_type);

	$cond[] = array('where','module_parent_id',$id);

	$cond[] = array('where','is_visible','1');

	$sel_array1=array(

			'table_name'=>MODULES,

			'table_fields'=>'*',

			'condition'=>$cond,

			'order_by_field'=>'module_name',

			'order'=>'ASC',

			'limit'=>'',

			'offset'=>''

			);

	$result_new['data']=$CI->master_model->select_data($sel_array1);	

										

	foreach($result_new['data'] as $k=>$result_module)

	{

		$cond1='';

		$id=$result_module["module_id"];

		

		if($id==$mid)

			$cond1="selected='selected'";

			

		echo "<option value=".$id." $cond1>".str_repeat("&nbsp; - &nbsp;", $i).stripslashes($result_module["module_name"])."</option>";

		$i++;

		submodule($id,$i,$mid,$moduleid,$module_type);

		$i--;

	}

}

function is_parent($parent_id,$CI)

{

	$cond[] = array('where','module_parent_id',$parent_id);

	$cond[] = array('where_in','module_id',explode(',',$CI->session->userdata('module_ids')));

	$cond[] = array('where','is_visible','1');

	$sel_array1=array(

			'table_name'=>MODULES,

			'table_fields'=>'module_id,module_name',

			'condition'=>$cond,

			'limit'=>'',

			'offset'=>''

			);

	$result_new['data']=$CI->master_model->select_data($sel_array1);

											

	if (count($result_new['data']) > 0)

	return true;

	else return false;

}

function get_parent_id($parent_id,$CI)

{

	$cond[] = array('where','module_id',$parent_id);

	$cond[] = array('where','is_visible','1');

	$sel_array1=array(

			'table_name'=>MODULES,

			'table_fields'=>'module_id,module_parent_id,module_name',

			'condition'=>$cond,

			'limit'=>'',

			'offset'=>''

			);

	$result_new['data']=$CI->master_model->select_data($sel_array1);

	if (count($result_new['data']) > 0)

	{

		foreach($result_new['data'] as $k=>$v)

			$parent_id=$v['module_parent_id'];

	}

	return $parent_id;

}

function get_children_module($id,$module_id_array,$CI,$type)

{

	global $constants_array;

	

	//$CI = get_instance();

	$result_new['data']='';

	$cond=array();

	//$cond[] = array('where','module_type',$type);

	$cond[] = array('where','module_parent_id',$id);

	$cond[] = array('where','is_visible','1');

	$sel_array1=array(

			'table_name'=>MODULES,

			'table_fields'=>'module_name,module_id,module_url,module_parent_id,sort_order',

			'condition'=>$cond,

			'order_by_field'=>'sort_order',

			'order'=>'ASC',

			'limit'=>'',

			'offset'=>''

			);

	$result_new['data']=$CI->master_model->select_data($sel_array1);	

	//dump($CI->db->last_query());

	//dump($result_new['data']);

	foreach($result_new['data'] as $m_key=>$m_val)

	{

		if(in_array($result_new['data'][$m_key]["module_id"],$module_id_array))

		{

			if($result_new['data'][$m_key]["module_parent_id"]==0)

			{

				$a_class='';

				if((is_parent($result_new['data'][$m_key]["module_id"],$CI))){

					$a_class='class="dropdown-toggle" data-toggle="dropdown"';

				}

				// echo '<li class="dropdown">';

				echo '<li class="dropdown">';

				// echo anchor($result_new['data'][$m_key]['module_docroot_path'], $result_new['data'][$m_key]['module_name'].((is_parent($result_new['data'][$m_key]["module_id"],$CI))?'<b class="caret"></b>':''),$a_class);

				if($type=='employee')

					echo anchor('/employee/'.$result_new['data'][$m_key]['module_url'], $result_new['data'][$m_key]['module_name'].((is_parent($result_new['data'][$m_key]["module_id"],$CI))?'<b class="caret"></b>':''),$a_class);

				else

					echo anchor($result_new['data'][$m_key]['module_url'], $result_new['data'][$m_key]['module_name'].((is_parent($result_new['data'][$m_key]["module_id"],$CI))?'<b class="caret"></b>':''),$a_class);

				if(is_parent($result_new['data'][$m_key]["module_id"],$CI)){

					echo '<ul class="dropdown-menu">';

					// get_children_module($result_new['data'][$m_key]["module_id"],$module_id_array,$CI,$type);	

					get_children_module($result_new['data'][$m_key]["module_id"],$module_id_array,$CI,$type);

					echo '</ul>';

				}

				echo '</li>';	

			}

			else

			{

				if(is_parent($result_new['data'][$m_key]["module_id"],$CI))

				{

					$class="";

					$flag="false";

					$a_class='';

					$li_class='';

					if(get_parent_id($result_new['data'][$m_key]["module_id"],$CI) > 0)

					{

						$li_class=' class="dropdown-submenu" ';

						// $li_class=' class="dropdown-menu" ';

						// $a_class=' class="dropdown-toggle" data-toggle="dropdown" ';

						$flag="true";

					}

					echo '<li '.$li_class.'>';

					// echo '<li>';

					echo '<a href="javascript:void(0);" >'.$result_new['data'][$m_key]['module_name'].'</a>';

					echo '<ul class="dropdown-menu">';

					get_children_module($result_new['data'][$m_key]["module_id"],$module_id_array,$CI,$type);

					echo '</ul>';

					echo '</li>';

				}

				else

				{

					echo '<li>';

					echo anchor($result_new['data'][$m_key]["module_url"], $result_new['data'][$m_key]['module_name']);

					echo '</li>';

				}

			}

		}

	}

	return '';

}



function check_directory($filepath)

{

	if (!file_exists($filepath)) {

			

		try{

			$create = mkdir($filepath, 0777, TRUE);

		}catch(Exception $e)

		{

			echo 'Caught exception: ',  $e->getMessage(), "\n";exit;

		}

	}

}



function get_admin_data($function_type_id,$company_id,$admin_type_id=NULL)

{

	$CI = &get_instance();

	

	$cond_admin[]=array('where',"FIND_IN_SET($function_type_id,function_type_ids) AND 1",NULL,FALSE);

	$cond_admin[]=array('where',"FIND_IN_SET($company_id,company_ids) AND 1",NULL,FALSE);

	if($admin_type_id!='') {

		$cond_admin[]=array('where','`admin_type_id` IN ('.$admin_type_id.')',NULL,FALSE);

	}

	$emp_data_array=array(

						'table_name'=>ADMIN,

						'table_fields'=>'email',

						'condition'=>$cond_admin,

						'limit'=>'',

						'offset'=>'',

						);

	$admin_data=$CI->master_model->select_data($emp_data_array);

	return $admin_data;

}



function get_data_func_comp($alias)

{

	$funct_compa_ids=get_rel_func_comp_arr();

	$query_data='';

	if(count($funct_compa_ids) > 0)

	{

		$i=0;

		$operator='';

		$query_data='(';

		foreach($funct_compa_ids as $ke=>$va)

		{

			$i++;

			// $cond[]=array($operator,$alias.'.function_type_id',$ke);

			// $cond[]=array('where_in',$alias.'.company_id',$va);

			if($alias=='admin' || $alias=='admin_type')

			{

				

				$query_data.=$operator." (FIND_IN_SET('".$ke."',".$alias.".function_type_ids)) ";

				$j=0;

				$c_operator='AND';

				//$query_data.='(';

				foreach($va as $c=>$ce)

				{

					$j++;

					$query_data.=$c_operator;

					if($j==1)

						$query_data.='(';

					$query_data.=" (FIND_IN_SET('".$ce."',".$alias.".company_ids)) ";

					if($j < count($va))

						$c_operator=' OR';

				}

				$query_data.=')';

				//AND ".$alias.".company_ids ='".implode(",",$va)."')

				if($i < count($funct_compa_ids))

					$operator=' OR';

			}

			else

			{

				$query_data.=$operator." (".$alias.".function_type_id IN('".$ke."') AND ".$alias.".company_id IN('".implode("','",$va)."'))";

				if($i < count($funct_compa_ids))

					$operator=' OR';

			}		

		}

		$query_data.=')';

	}

	return $query_data;

}



function get_data_func($alias)

{

	$funct_compa_ids=get_rel_func_comp_arr();



	$cond='';

	if(count($funct_compa_ids) > 0)

	{

		foreach($funct_compa_ids as $ke=>$va)

		{

			$func[]=$ke;

		}

		$cond[]=array('where_in',$alias.'.function_type_id',$func);

	}

	return $cond;

}



function get_data_comp($alias)

{

	$funct_compa_ids=get_rel_func_comp_arr();

	$func=array();

	if(count($funct_compa_ids) > 0)

	{

		foreach($funct_compa_ids as $ke=>$va)

		{

			foreach($va as $k=>$v)

			{

				$comp[]=$v;

			}

		}

		$cond[]=array('where_in',$alias.'.company_id',$comp);

	}

	return $cond;

}



function get_rel_func_comp_arr()

{	

	$CI = &get_instance();

	//admin func and comp ids

	if($CI->session->userdata('user_type')=='employee'){

		$func_ids=explode(',',$CI->session->userdata('function_type_id'));

		$comp_ids=explode(',',$CI->session->userdata('company_id'));

	}

	else

	{

		$func_ids=explode(',',$CI->session->userdata('function_type_ids'));

		$comp_ids=explode(',',$CI->session->userdata('company_ids'));

	}

	$func_comp_ids=array();

	foreach($func_ids as $k=>$v)

	{

		$comp_data=get_data_arr_key(COMPANY,'company_id','function_type_id',$v,'where');

		//$comp_data=explode(',',$comp_data_val);

		if(count($comp_data) > 0)

		{

			foreach($comp_data as $ke=>$va)

			{

				if(in_array($va,$comp_ids))

					$func_comp_ids[$v][]=$va;

			}

		}

	}

	return $func_comp_ids;

}



function get_where_data($tbl,$arr)

{

	$CI = &get_instance();

	$tbl_query = $CI->db->get_where($tbl, $arr);

	$tbl_result = $tbl_query->row_array();

	return $tbl_result;

}



function getUserType()

{

	$CI = &get_instance();

	return $CI->session->userdata('user_type');

}



function isLoggedIn()

{

	$CI = &get_instance();

	return $CI->session->userdata('status');

}



function get_date_dmy_format($date)

{

	return date('d/m/Y H:i:s',strtotime($date));

}

function get_date_ymd_format($date)

{

	return date('Y-m-d H:i:s',strtotime($date));

}



function get_date_dmy_format_wo_time($date)

{

	return date('d-m-Y',strtotime($date));

}

function get_date_ymd_format_wo_time_new($date)

{

	return date('Y-m-d',strtotime($date));

}



function get_date_by_add_days($date,$no_of_days)

{

	return date('Y-m-d',strtotime(date("Y-m-d", strtotime($date)) . " +".$no_of_days."days"));

}



function get_date_by_add_months($date,$no_of_days)

{

	return date('Y-m-d',strtotime(date("Y-m-d", strtotime($date)) . " +".$no_of_days."months"));

}



function get_date_by_sub_days($date,$no_of_days)

{

	return date('Y-m-d',strtotime(date("Y-m-d", strtotime($date)) . " -".$no_of_days."days"));

}





	

	function dealer_code($str) {

		if (! preg_match("\/^([a-zA-Z0-9 ])+$\/i", $str)) {

			$CI->form_validation->set_message('dealer_code', 'The %s field can only be alpha numeric');

			return false;

		} else {

			return true;

		}

	}

	



	function send_notification_to_admin($email_type,$emp_name,$date_of_confirmation,$designation_name,$date_of_promotion)

	{

		$CI=&get_instance();

		$email_data=get_data_arr(TBL_EMAIL_CONTENT,'email_subject,email_message','email_type',$email_type,'where');

		$application_url=base_url();	

		$to=get_data_value(ADMIN,'email','admin_id',$CI->session->userdata('user_id'),'where');

		

		$admin_display_name=get_data_value(ADMIN_TYPE,'admin_display_name','admin_type_id',$CI->session->userdata('admin_type'),'where');

		$email_message=$email_data['email_message'];

		

		eval("\$email_message = \"$email_message\";");

		

		$email_data_array = array('to_email_ids'=>array($to),

			  'email_subject'=>$email_data['email_subject'],

			  'email_message'=>$email_message

			);

			

		//echo "<pre>";print_r($email_data_array);echo "</pre>";

		if($to != '')

			customized_email($email_data_array);

	}

	



	function daysDifference($endDate, $beginDate)

	{



	   $date_parts1 = explode("-", $beginDate);

	   $date_parts2 = explode("-", $endDate);

	   $start_date = gregoriantojd($date_parts1[1], $date_parts1[2], $date_parts1[0]);

	   $end_date = gregoriantojd($date_parts2[1], $date_parts2[2], $date_parts2[0]);

	   $diff = abs($end_date - $start_date);

	   $years = floor($diff / 365.25);

	   return $years;

	}

	

	function get_asset() {

		

		$CI =& get_instance();

		$cond=array();

		$asset_data='';

		$cond[]=array('join',ASSET_TYPE,ASSET_TYPE.'.asset_type_id='.ASSET.'.asset_type','left');

		

		$select_array=array(

							'table_name'=>ASSET,

							'table_fields'=>ASSET_TYPE.'.asset_type_name,serial_no,asset_id',

							'condition'=>$cond,

							'order_by_field'=>'asset_id',

							'order'=>'',

							'limit'=>'',

							'offset'=>''

							);

		$result_data['get_asset_log_list']=$CI->master_model->select_data($select_array);

		if(!empty($result_data['get_asset_log_list']) && is_array($result_data['get_asset_log_list']))

		{

			foreach($result_data['get_asset_log_list'] as $k=>$row)

			{

				$asset_data['']='Select Asset';

				$asset_data[$row['asset_id']]=$row['asset_type_name'].'-'.$row['serial_no'];

			}

		}

		else

			$asset_data['']='Select Asset';

		return $asset_data;

	} 

	

	function get_autocomplete_data($name)

	{

		$CI = &get_instance();

		$disp_name="(CONCAT_WS(' ',title,first_name,middle_name,last_name`)) emp_name`";

		

		$condition=array();

		$condition[] = array('where','activated','1');

		$condition[] = array('where','emp_exit_date','0000-00-00');

		$condition[] = array('where','(title LIKE "%'.$name.'%" OR first_name LIKE "%'.$name.'%" OR middle_name LIKE "%'.$name.'%" OR last_name LIKE "%'.$name.'%")',NULL,FALSE);

				

		$select_array=array(

						'table_name'=>EMPLOYEE,

						'table_fields'=>$disp_name.',emp_id',

						'condition'=>$condition,	

						'limit'=>'',

						'offset'=>''

								);

		$result_data['get_emp_list']=$CI->master_model->select_data($select_array);

		

		$str='';

		foreach ($result_data['get_emp_list'] as $k=>$rs) {

			$str.= '<li onclick="set_item(\''.str_replace("'", "\'", $rs['emp_name']).'\',\''.str_replace("'", "\'", $rs['emp_id']).'\')">'.$rs['emp_name'].'</li>';

		}

		echo $str;

	}

	

	// function get_autocomplete_data_and_code($name)

	function get_autocomplete_data_and_code($name,$company_id=null)

	{

		$CI = &get_instance();		

		$disp_name="(CONCAT_WS(' ',title,first_name,middle_name,last_name`)) emp_name`";

		

		$condition=array();

		$condition[] = array('join',DESIGNATION,EMPLOYEE.'.designation_id ='.DESIGNATION.'.designation_id');

		$condition[] = array('join',COMPANY,EMPLOYEE.'.company_id ='.COMPANY.'.company_id');

		$condition[] = array('where','activated','1');

		// $condition[] = array('where','function_type_id','1');

		$condition[] = array('where','emp_exit_date','0000-00-00');

		if(isset($company_id)){

		$condition[] = array('where',EMPLOYEE.'.company_id',$company_id);

		}

		// $condition[] = array('where_in',DESIGNATION.'.designation_short_code',array('RA','SA'));

		$condition[] = array('where','(title LIKE "%'.$name.'%" OR first_name LIKE "%'.$name.'%" OR middle_name LIKE "%'.$name.'%" OR last_name LIKE "%'.$name.'%" OR emp_code LIKE "%'.$name.'%")',NULL,FALSE);

				

		$select_array=array(

						'table_name'=>EMPLOYEE,

						'table_fields'=>$disp_name.',emp_id,emp_code,'.DESIGNATION.'.designation_short_code,'.COMPANY.'.company_name,'.COMPANY.'.function_type_id',

						'condition'=>$condition,	

						'order_by_field'=>'emp_name',

						'order' => 'ASC',

						'limit'=>'',

						'offset'=>''

								);

		$result_data['get_emp_list']=$CI->master_model->select_data($select_array);

		// dump($CI->db->last_query());

		$str='';

		foreach ($result_data['get_emp_list'] as $k=>$rs) {

			// $str.= '<li onclick="set_item(\''.str_replace("'", "\'", $rs['emp_name'].' ('. $rs['emp_code'].')').'\',\''.str_replace("'", "\'", $rs['emp_id']).'\','.$rs['designation_short_code'].')">'.$rs['emp_name'].' ('. $rs['emp_code'].')</li>';

			// $str.= '<li onclick="set_item(\''.str_replace("'", "\'", $rs['emp_name']).'\',\''.str_replace("'", "\'", $rs['emp_id']).'\',\''.$rs['designation_short_code'].'\')",">'.$rs['emp_name'].' ('. $rs['emp_code'].')</li>';			

			$str.= '<li onclick="set_item(\''.str_replace("'", "\'", $rs['emp_name']).' ('.$rs['emp_code'].')\',\''.str_replace("'", "\'", $rs['emp_id']).'\',\''.$rs['designation_short_code'].'\',\''.$rs['function_type_id'].'\')",">'.$rs['emp_name'].' ('. $rs['emp_code'].')</li>';			

			// $str.= '<li onclick="set_item(\''.$rs['emp_name'].' ('.$rs['emp_code'].'),\''.str_replace("'", "\'", $rs['emp_id']).'\',\''.$rs['designation_short_code'].'\',\''.$rs['function_type_id'].'\')",">'.$rs['emp_name'].' ('. $rs['emp_code'].')</li>';

		}

		echo $str;

	}

	

	function get_no_of_days($startDate,$endDate)

	{

		$day = 86400; // Day in seconds



		$sTime = strtotime($startDate); // Start as time

		$eTime = strtotime($endDate); // End as time

		$numDays = round(($eTime - $sTime) / $day) + 1;

		

		return $numDays;

	}

	 function check_injections_filter($data)

	{

	// remove whitespaces from begining and end

    $data = trim($data);

    $data = htmlspecialchars($data);

    

    // apply stripslashes to pevent double escape if magic_quotes_gpc is enabled

/*     if(get_magic_quotes_gpc())

    {
 */
        $data = stripslashes($data);

   // }

    // connection is required before using this function

   // $data = mysql_real_escape_string($data);

    return $data;

	}



	function fetch_cities($city_ids)

	{

		$CI =& get_instance();

    	$city =  explode( ',',$city_ids);



    	$condition[] = array('where','is_active','1');

    	//$condition[] = array('where_in','city_id',$city);

        $selected_array=array(

                              'table_name'=>TABLE_CITY,

                              'table_fields'=>'city_name,city_id',

                               'condition'=>$condition,

                               'limit'=>'',

                               'offset'=>''

                              );

          

           $city['city'] = $CI->master_model->select_data($selected_array);

          foreach ($city['city'] as  $value) {

			  $selected='';

             if (in_array($value['city_id'],$city)) 

			 {

				$selected='selected="selected"';

			 }

			 $output .= '<option value='.$value['city_id'].' '.$selected.'>'.$value['city_name'].'</option>';

		

          }

         echo $output;      

    }

	

	function get_cities($city_ids)

	{

		$CI =& get_instance();

    	$city =  explode( ',',$city_ids);

		$condition[] = array('where_in','city_id',$city);

    	$selected_array=array(

                              'table_name'=>TABLE_CITY,

                              'table_fields'=>'GROUP_CONCAT(city_name)',

                               'condition'=>$condition,

                               'limit'=>'',

                               'offset'=>''

                              );

          

           $city['city'] = $CI->master_model->select_data($selected_array);

          foreach ($city['city'] as  $value) {

             $city=$value['GROUP_CONCAT(city_name)'];

          }

         return $city;    

    }

function new_state($state_id){

		$CI =& get_instance();

    	//$city =  explode( ',',$city_ids);



    	$condition[] = array('where','is_active','1');

    	$condition[] = array('where_in','state_id',$state_id);

        $selected_array=array(

                              'table_name'=>TABLE_STATE,

                              'table_fields'=>'state_name,state_id',

                               'condition'=>$condition,

                               'limit'=>'',

                               'offset'=>''

                              );

          

           $state['state'] = $CI->master_model->select_data($selected_array);

          foreach ($state['state']  as  $value) {

			 $output= $value['state_id'];
				
			 }

		
         echo $output;    
}	

	

    function fetch_states($state_ids){

    	$CI =& get_instance();

    	$state =  explode( ',' ,$state_ids);

    	// /echo $state;

 

    	$condition[] = array('where_in','state_id',$state);

        $selected_array=array(

                              'table_name'=>TABLE_STATE,

                              'table_fields'=>'GROUP_CONCAT(state_name)',

                               'condition'=>$condition,

                               'limit'=>'',

                               'offset'=>''

                              );





          $state['state'] = $CI->master_model->select_data($selected_array);

          foreach ($state['state'] as  $value) {

             $state=$value['GROUP_CONCAT(state_name)'];

          }

          return $state;



 

    }

      function fetch_accessible_branch($branch_id){

    	$CI =& get_instance();

    	$access_branch =  explode( ',' ,$branch_id);

    	// /echo $state;

 

    	$condition[] = array('where_in','company_branch_id',$access_branch);

        $selected_array=array(

                              'table_name'=>TABLE_COMPANY_BRANCH,

                              'table_fields'=>'GROUP_CONCAT(company_branch_name),GROUP_CONCAT(company_branch_id)',

                               'condition'=>$condition,

                               //'group_by_field'=>'company_branch_name',

                               'limit'=>'',

                               'offset'=>''

                              );





          $accessible_branch['accessible_branch'] = $CI->master_model->select_data($selected_array);

          foreach ($accessible_branch['accessible_branch'] as  $value) {

                    $access_branch=$value['GROUP_CONCAT(company_branch_name)'];

                    $access_branch_id=$value['GROUP_CONCAT(company_branch_id)'];

          }

          return $access_branch;



 

    }

    function add_customer_address($parameters){

       $customer_id=$parameters['customer_id'];

       $contact_person_name=$parameters['contact_person_name'];

       $mobile_no=$parameters['mobile_no'];

       $email_id=$parameters['email_id'];

       $designtation=$parameters['designtation'];

       

       $add_customer_data=array(

								'customer_id' => $customer_id,

								'contact_person_name' => $contact_person_name,

								'mobile_no' => $mobile_no,

								'email_id' => $email_id,

								'designation' =>$designtation,

								'created_on' => date("Y-m-d H:i:s"),

								'created_by' =>'',

								'modified_by' => '',	

								'modified_on' => date("Y-m-d H:i:s")

								

					        );

        $condition[] = array('where','customer_id',$customer_id);

		$selected_array=array(

								'table_name' =>TABLE_CUSTOMER_CONTACT,					

								'table_fields'=>'customer_id',

								'limit'=>'',

								'offset'=>'',

								'condition'=>$condition							

					        );

		$customer['customer'] = $this->master_model->select_data($selected_array);

		    if(!empty($customer['customer'])){

					echo "Contact details already present";



			}else{			

				$this->master_model->insert_record(TABLE_CUSTOMER_CONTACT,$add_customer_data);

		    }

		 

    }

    function Module_checked(){

     	admin_auth();

    	$selected_array = array( 

			                   'table_name' =>MODULES,

			                   'table_fields' => 'module_id,module_name,module_parent_id',

			                   'order_by_field'=>'Asc'

		);



		return $this->master_model->get_table_data($selected_array);		         

    }

    function module_view($module_id){

     	admin_auth();

     	$CI =& get_instance();

    	$module_ids =  explode( ',' ,$module_id);

     	$condition[] = array('where_in','module_id',$module_ids);
     	$condition[] = array('where','is_visible','1');
     	$condition[] = array('where','module_parent_id','0');

    	$selected_array = array( 

			                   'table_name' =>MODULES,

			                   'table_fields' => 'module_id,module_name,module_parent_id',

			                   'order_by_field'=>'Asc',

			                   'condition'=>$condition,

			                   'limit'=>'',

			                   'offset'=>''

		);



		return $CI->master_model->select_data($selected_array);		         

    }
	
	function get_sub_module_view($module_id){

     	admin_auth();

     	$CI =& get_instance();

    	//$module_ids =  explode( ',' ,$module_id);

     	$condition[] = array('where_in','module_parent_id',$module_id);
     	$condition[] = array('where','is_visible','1');

    	$selected_array = array( 

			                   'table_name' =>MODULES,
			                   'table_fields' => 'module_id,module_name,module_parent_id',
			                   'order_by_field'=>'Asc',
			                   'condition'=>$condition,
			                   'limit'=>'',
			                   'offset'=>''
		);

		return $CI->master_model->select_data($selected_array);		         
		//dump($CI->db->last_query());
    }

    function set_change_refill_date($dues){

   	admin_auth();

    $CI =& get_instance();

    $CI->load->library('session');

	$CI->session->set_userdata('link_due',$dues);

   }

   function get_change_refill_date(){

   	$CI =& get_instance();

    $CI->load->library('session');

    $date = $CI->session->userdata('link_due'); 

   

    return $date;

   }

	

	function get_current_possessed($possessed,$status){

		$CI =& get_instance();



	    if ($status=='Customer') {

	    $customer_name=get_data_value(TABLE_CUSTOMER,'customer_name','customer_id',$possessed,'where');	

	    return $customer_name;

	    }else if($status=='Company'){

	     $company_name=get_data_value(TABLE_COMPANY_BRANCH,'company_branch_name','company_branch_id',$possessed,'where');	

	    return $company_name;

	    }else{

	    	$not='Not Allocated';

	    	return $not;

	    }



	}

	function get_cust_count($condition)

	{

		$CI =& get_instance();

		$cond[] = $condition;

		$sel_array=array(

				'table_name'=>TABLE_CUSTOMER.' as a',

				'table_fields'=>'a.customer_id',

				'condition'=>$condition,

				'order_by_field'=>'a.customer_id',

				'group_by_field'=>'a.customer_id',

				'order'=>'DESC',

				'limit'=>'',

				'offset'=>''

				);

		

		$result['fin_year_data']=$CI->master_model->select_data($sel_array);

	

		if(count($result['fin_year_data'])>0)

		{

			return count($result['fin_year_data']);

		}

		else

			return count($result['fin_year_data']);

	}



	function get_list_refill_sale_data_count($condition)

	{

		$CI =& get_instance();

		$cond[] = $condition;

		$sel_array=array(

				'table_name'=>TABLE_DISPENSER_SALES.' as b',

				'table_fields'=>'b.dispenser_sales_id',

				'condition'=>$condition,

				'order_by_field'=>'b.dispenser_sales_id',

				'group_by_field'=>'b.dispenser_sales_id',

				'order'=>'DESC',

				'limit'=>'',

				'offset'=>''

				);

		

		$result['fin_year_data']=$CI->master_model->select_data($sel_array);

	

		if(count($result['fin_year_data'])>0)

		{

			return count($result['fin_year_data']);

		}

		else

			return count($result['fin_year_data']);

	}

	function fetch_products($product_id){

    	$CI =& get_instance();

    	//if ($product_type=='Dispenser') {
    		$refill_id_get =  explode( ',' ,$product_id);
    		$condition[] = array('where_in','product_id',$refill_id_get);
    	//}
    	

    	// /echo $state;

    	// /$condition[] = array('where_in','company_branch_id',$access_branch);

        $selected_array=array(

                              'table_name'=>TABLE_PRODUCT,

                              'table_fields'=>'GROUP_CONCAT(product_name),GROUP_CONCAT(product_id)',

                               'condition'=>$condition,

                               //'group_by_field'=>'company_branch_name',

                               'limit'=>'',

                               'offset'=>''

                              );





          $product_name['product_name'] = $CI->master_model->select_data($selected_array);

          foreach ($product_name['product_name'] as  $value) {

                    $product_name=$value['GROUP_CONCAT(product_name)'];

                    $product_id=$value['GROUP_CONCAT(product_id)'];

          }

          return $product_name;

    }
    function fetch_product_dispenser($product_id){

    	$CI =& get_instance();

    	//$p_id=explode(',',$product_id);
       //$cond_set='FIND_IN_SET('.$product_id.',refill_ids)';
        $where_cond = 'FIND_IN_SET('.$product_id.',refill_ids ) AND 1=1 ';			
		 //$condition[] = array('where','refill_ids IN ('.$p_id.')',null,false);
		//$condition[] = array('where_in','refill_ids',$product_id);
		$condition[] = array('where',$where_cond,'',false);
        $selected_array=array(

                              'table_name'=>TABLE_PRODUCT,

                              'table_fields'=>'GROUP_CONCAT(product_name),GROUP_CONCAT(product_id),refill_ids',

                               'condition'=>$condition,

                               //'group_by_field'=>'product_id',

                               'limit'=>'',

                               'offset'=>''

                              );

          $dispenser_name['dispenser_name'] = $CI->master_model->select_data($selected_array);
          //dump($CI->db->last_query());
          foreach ($dispenser_name['dispenser_name'] as  $value) {
          	
                    $product_name=$value['GROUP_CONCAT(product_name)'];

                    $product_id=$value['GROUP_CONCAT(product_id)'];

          }

          return $product_name;

    }
    function get_data_value_return_result($table,$value,$field_name,$id,$operator)
	{
	$CI =& get_instance();
	$cond[] = array($operator,$field_name,$id);
	$sel_array=array(

			'table_name'=>$table,
			'table_fields'=>$value,
			'condition'=>$cond,
			'limit'=>1,
			'offset'=>'',
			'order_by_field'=>'dispenser_refill_details_id',
			'order'=>'DESC'
			);
	$result['data_list']=$CI->master_model->select_data($sel_array);

		//dump($CI->db->last_query());

	$val=array();

	if(count($result['data_list']) > 0)
	{
		foreach($result['data_list'] as $ke=>$va){
		
			$val[]=$va[$value];
		}		
	}
	return implode(',',$val);

}

	
function encrypt_decrypt_parameters($string, $action)
{

		$key = 'shgoon@2024';
		
		$output = false;
		$encrypt_method = "AES-256-CBC";
		$secret_key = $key;
		$secret_iv = $key;
		// hash
		$key = hash('sha256', $secret_key);
		// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
		$iv = substr(hash('sha256', $secret_iv), 0, 16);
		if( $action == 'encrypt' ) {
			$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
			$output = base64_encode($output);
		}
		else if( $action == 'decrypt' ){
			$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
		}
		
		return $output;
	
}

function check_disp_returned($dispenser_sales_id)
{
		$CI =& get_instance();
		$cond=array();
		$cond[] = array('where','dispenser_sales_id',$dispenser_sales_id);
		$cond[] = array('where','stop_refill','yes');
		$select_array = array(
								'table_name'=>TABLE_DISPENSER_REFILL_DETAILS,
								'table_fields'=>'dispenser_sales_id,',
								'condition'=>$cond,
								'sort_by'=>'dispenser_sales_id',
								'order_by_field'=>'',
								'order'=>'ASC',
								'limit'=>'',
								'offset'=>''
								);
		$chk_stop_refill=$CI->master_model->select_data($select_array);
		//dump($CI->db->last_query());
		$cnt_stop_refill=count($chk_stop_refill);
		$is_returned='No';
		if($cnt_stop_refill>0)
		{
			$is_returned="Yes";
		}
	return $is_returned;
}

function get_tacking_numbers($tracking_numbers)
{
	$CI =& get_instance();
	
	$tracking_numbers_arr = explode(',', $tracking_numbers);
	$tracking_cond = array();		 
	$tracking_cond[] = array('where_in','tracking_numbers_id',$tracking_numbers_arr);
	$select_array = array(
							'table_name'=>TABLE_TRACKING_NUMBERS,
							'table_fields'=>'(tracking_number) as tracking_number',
							'condition'=>$tracking_cond,
							'sort_by'=>'tracking_numbers_id',
							'order_by_field'=>'tracking_number',
							'order'=>'ASC',
							'limit'=>'',
							'offset'=>''
							);
	$tracking_data=$CI->master_model->select_data($select_array);
			
	$output='';
	foreach($tracking_data as $row)
	{
		//$tracking_number=$this->encrypt->encode($row['tracking_number']);
		$tracking_number=encrypt_decrypt_parameters($row['tracking_number'],'encrypt');
	  $output .= ' , <a href="'.base_url().'index.php/gc/refill_track/list_refill_track/'.$tracking_number.'">'.$row['tracking_number'].'</a>';

	}
	  echo trim($output," , ");	
	
}


function get_refill($dispenser_id)
{
	$CI =& get_instance();

	$salse_person_cond = array();
	$salse_person_cond[] = array('where','dispenser_name',$dispenser_id);
	$salse_person_cond[] = array('where','is_active','1');
	$salse_person_cond[] = array('where','product_type','Refill');
	$select_array = array(
							'table_name'=>TABLE_PRODUCT,
							'table_fields'=>'product_id,product_name',
							'condition'=>$salse_person_cond,
							'sort_by'=>'product_name',
							'order_by_field'=>'product_name',
							'order'=>'ASC',
							'limit'=>'',
							'offset'=>''
							);
	$salse_person_data = $CI->master_model->select_data($select_array);
	$output='<option value="">Select Refill Name</option>';
	
	foreach($salse_person_data as $row)
	{
	  $output .= '<option value='.$row['product_id'].'>'.$row['product_name'].'</option>';

	}
	  echo $output;	
}


?>