<?php 

function alert()
{
	$CI =& get_instance();
  if($CI->session->flashdata('alert_success')){
    echo '<div class="alert alert-success alert-auto-close"><button data-dismiss="alert" class="close" type="button">x</button> '.$CI->session->flashdata('alert_success')."</div>";
    $CI->session->unset_userdata('alert_success');
  }
  if($CI->session->flashdata('alert_error')){
    echo '<div class="alert alert-danger alert-auto-close"><button data-dismiss="alert" class="close" type="button">x</button>'.$CI->session->flashdata('alert_error')."</div>";
    $CI->session->unset_userdata('alert_error');
  }
  if($CI->session->flashdata('alert_warning')){
    echo '<div class="alert alert-warning alert-auto-close"><button data-dismiss="alert" class="close" type="button">x</button>'.$CI->session->flashdata('alert_warning')."</div>";
    $CI->session->unset_userdata('alert_warning');
  }
}

function user_loggedin()
{
	$CI =& get_instance();
	return (bool)$CI->session->userdata('UserId');
}

function date_string_to_timestamp($date)
{
	return DateTime::createFromFormat('M d,Y', $date)->getTimestamp();
}

function time_string_to_timestamp($time)
{
	return DateTime::createFromFormat('h:i A', $time)->getTimestamp();
}

function time_elapsed_string($ptime)
{
	$etime = time() - $ptime;

	if ($etime < 1)
	{
		return '0 seconds';
	}

	$a = array( 365 * 24 * 60 * 60  =>  'year',
		30 * 24 * 60 * 60  =>  'month',
		24 * 60 * 60  =>  'day',
		60 * 60  =>  'hour',
		60  =>  'minute',
		1  =>  'second'
  );
	$a_plural = array( 'year'   => 'years',
		'month'  => 'months',
		'day'    => 'days',
		'hour'   => 'hours',
		'minute' => 'minutes',
		'second' => 'seconds'
  );

	foreach ($a as $secs => $str)
	{
		$d = $etime / $secs;
		if ($d >= 1)
		{
			$r = round($d);
			return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ago';
		}
	}
}

function admin_profile_picture()
{
	$CI =& get_instance();
	$admin_id = $CI->session->userdata("admin_id");

	$condition[] = array('name'=>'admin_id','value'=>$admin_id);
	// $user_info = $CI->admin_model->admin($admin_id);
	$res = $CI->setting_model->get_setting('admin',$condition,false,true);
	if(!empty($res['img']))
		return base_url(ADMIN_USER_IMG_PATH.$res['admin_id'].'/'.$res['img']);
	else
		return base_url('assets/img/admin.jpg');        
}

function admin_detail($field)
{
	$CI =& get_instance();
	$admin_id = $CI->session->userdata("admin_id");

	$condition[] = array('name'=>'admin_id','value'=>$admin_id);
	$user_info = $CI->setting_model->get_setting('admin',$condition,false,true);
	return $user_info[$field];
}
function url_params_to_url()
{
	$get_params = '';
	if(!empty($_GET)){
		$i = 0;
		foreach ($_GET as $key => $value) {
			if($key=='start' && empty($value))
				{}else{
					$get_params .= ($i==0?"?":"&").$key."=".$value;
					$i++;
				}
			}
		}
		return $get_params;
	}

	function import_xl($filePath, $header=true){
    error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);

    $CI = get_instance();
    $CI->load->library('PHPExcel');

//Create excel reader after determining the file type
    $inputFileName = $filePath;
    /** Identify the type of $inputFileName **/
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    /** Create a new Reader of the type that has been identified **/
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    /** Set read type to read cell data onl **/
    $objReader->setReadDataOnly(true);
    /** Load $inputFileName to a PHPExcel Object **/
    $objPHPExcel = $objReader->load($inputFileName);
//Get worksheet and built array with first row as header
    $objWorksheet = $objPHPExcel->getActiveSheet();
//excel with first row header, use header as key
    if($header){
      $highestRow = $objWorksheet->getHighestRow();
      $highestColumn = $objWorksheet->getHighestColumn();
      $headingsArray = $objWorksheet->rangeToArray('A1:'.$highestColumn.'1',null, true, true, true);
      $headingsArray = $headingsArray[1];

      $r = -1;
      $namedDataArray = array();
      for ($row = 2; $row <= $highestRow; ++$row) {
        $dataRow = $objWorksheet->rangeToArray('A'.$row.':'.$highestColumn.$row,null, true, true, true);
        if ((isset($dataRow[$row]['A'])) && ($dataRow[$row]['A'] > '')) {
          ++$r;
          foreach($headingsArray as $columnKey => $columnHeading) {
            $namedDataArray[$r][$columnHeading] = $dataRow[$row][$columnKey];
          }
        }
      }
    }
    else{
//excel sheet with no header
      $namedDataArray = $objWorksheet->toArray(null,true,true,true);
    }
    return $namedDataArray;
  } 

  function validate_ext($file_name,$ext)
  {
    return pathinfo($file_name, PATHINFO_EXTENSION)==$ext;
  }
  function get_xl_header($filePath, $header=true){
    error_reporting(E_ALL);
    ini_set('display_errors', TRUE);
    ini_set('display_startup_errors', TRUE);

    $CI = get_instance();
    $CI->load->library('PHPExcel');
// echo $filePath;die;
//Create excel reader after determining the file type
    $inputFileName = $filePath;
    /** Identify the type of $inputFileName **/
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
    /** Create a new Reader of the type that has been identified **/
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    /** Set read type to read cell data onl **/
    $objReader->setReadDataOnly(true);
    /** Load $inputFileName to a PHPExcel Object **/
    $objPHPExcel = $objReader->load($inputFileName);
//Get worksheet and built array with first row as header
    $objWorksheet = $objPHPExcel->getActiveSheet();
//excel with first row header, use header as key
    if($header){
      $highestRow = $objWorksheet->getHighestRow();
      $highestColumn = $objWorksheet->getHighestColumn();
      $headingsArray = $objWorksheet->rangeToArray('A1:'.$highestColumn.'1',null, true, true, true);
      $headingsArray = $headingsArray[1];
    }

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

    return $headingsArray;
  } 
  function get_admin_perms(){ 
    // $CI =& get_instance();    
    // $condition=array();
    // $select=array('add_perm','edit_perm','view_perm','del_perm','admin.user_group_id');
    // $join[] = array('table_name' => 'user_group' ,'condition' => 'user_group.user_group_id =admin.user_group_id' ,'join_type' => 'left');

    // $condition[] = array('name'=>'admin_id','value'=>$CI->session->userdata("admin_id"));
    // $res = $CI->setting_model->get_setting('admin',$condition,false,false,$select,$join);
    // $perms['add_perm'] = $res['add_perm'];
    // $perms['edit_perm'] = $res['edit_perm'];
    // $perms['view_perm'] = $res['view_perm'];
    // $perms['del_perm'] = $res['del_perm'];
    // $perms['user_group_id']= $res['user_group_id'];

    $perms['add_perm'] =',1,2,3,4,5,';
    $perms['edit_perm'] =',1,2,3,4,5,';
    $perms['view_perm'] =',1,2,3,4,5,';
    $perms['del_perm'] =',1,2,3,4,5,';

    return $perms;
  }

  function api_header(){ 
    $name = base64_decode("d2VpZ2hicmlkZ2VhZG1pbg==");
    $pass= base64_decode("d2VpZ2hicmlkZ2VhZG1pbkA0bQ==");

    $req_user = $_SERVER['PHP_AUTH_USER'];
    $req_pass = $_SERVER['PHP_AUTH_PW'];

    if (!($name ==$req_user && $pass ==$req_pass)) {
     header('WWW-Authenticate: Basic realm="My Realm"');
     header('HTTP/1.0 401 Unauthorized');
     die ("Not authorized");
   }
   header('Content-type: application/json');
 }

 function token_verify(){
  $resp=array(); 

  if(!empty($_POST['admin_id']) && !empty($_POST['api_token'])){
   $CI =& get_instance();
   $admin_id = $_POST['admin_id'];
   $api_token = $_POST['api_token'];

   $condition[] = array('name'=>'admin_id','value'=>$admin_id);
   $condition[] = array('name'=>'api_token','value'=>$api_token); 
   $res = $CI->setting_model->get_setting('wb_admin',$condition); 
  
   if (!$res) {
    $resp['status'] = 'error'; 
    $resp['code'] = 401;  
    $resp['message'] = 'Invalid mandatory fields!';    
    echo json_encode($resp);
    exit;
  }
}
else{
  $resp['status'] = 'error'; 
  $resp['code'] = 401;  
  $resp['message'] = 'Please fill mandatory fields!';    
  echo json_encode($resp);
  exit;
} 

}
?>