<?php
function p($data, $exit = 1)
{
    echo "<pre>";
    print_r($data);
    echo "</pre>";
    if ($exit == 1) {
        exit;
    }
}

function jsonResponse($data=[]){
	header('Content-Type:application/json');
	echo json_encode($data);exit;
}

function jsonUnauthorizedResponse(){
	jsonResponse(['status'=>0,'message'=>'Unauthorized']);;
}


function renderView($ci,$view,$data=[],$output=false){
	$data['view']=$view;
	$ci->load->view('layouts/main',$data);
}
function apiCall($api_name,$get=[],$post=[],$files=[]){
    if(isset($_SESSION['device_id']) && $_SESSION['device_id']){
        $device_id=$_SESSION['device_id'];
    }else{
        $device_id= random_string('alnum',32);
        $_SESSION['device_id']=$device_id;
    }
   if(empty($post))
   {
       $post = [];
   }
   if(empty($get))
   {
       $get = [];
   }
 
    $post['api_key']=$get['api_key']=api_key;
    $post['device_id']=$get['device_id']=$device_id;
    $post['device_uiid']=$get['device_uiid']='user_'.$device_id;
    $post['device_platform']=$get['device_platform']=device_platform;
    $post['code_version']=$get['code_version']=code_version;
    $post['lang']=$get['lang']=lang;
    // $post['restaurant_slug']=$get['restaurant_slug']=restaurant_slug;
    $post['merchant_id']=$get['merchant_id']=merchant_id;

    if(isset($_SESSION['token']) && $_SESSION['token']){
        $get['user_token']=$_SESSION['token'];
    }
   $data='';
    $i=0;
    foreach ($get as $key=>$row){
        if(is_array($row)){
            foreach($row as $k=>$v){
                $data.=$key.'['.$k.']='.$v;
            }
        }else{
            $row = str_replace(" ", "%20",$row);
            $data.=$i?'&':'?';
            $data.=$key.'='.$row;
            $i++;
        }
    }
    foreach($post as $key=>$row){
        if(is_array($row)){
            unset($post[$key]);
            foreach($row as $k=>$v){
                $k=$k?$k:'';
                if(is_array($v)){
                    foreach($v as $k1=>$v1){
                        $k1=$k1?$k1:'';
                        $post[$key.'['.$k.']'.'['.$k1.']']=$v1;
                    }
                }else{
                    $post[$key.'['.$k.']']=$v;
                }
            }
        }
    }
   
    $curl = curl_init();
    if($files) {
        if (function_exists('curl_file_create')) { // php 5.5+
            $cFile = curl_file_create($files['tmp_name']);
        } else { //
            $cFile = '@' . realpath($files['tmp_name']);
        }
        $post['file']=$cFile;
    }
//   echo API_URL.$api_name.$data;
//   echo '<br />';
    curl_setopt_array($curl, array(
        CURLOPT_URL => API_URL.$api_name.$data,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $post,
    ));
    $response = curl_exec($curl);
  //p($response);
    curl_close($curl);
   return @json_decode($response,true);
}


function getFilePath($type=1){
	return 'assets/upload/chat/';
}

function fileUpload($fieldName, $type = 1)
{
	$file = $_FILES[$fieldName];
	$name = explode('.', $file['name']);
	$ext = $name[count($name) - 1];
	$fileName = time() . rand(1000, 9999) . '.' . $ext;
	$uploadPath = getFilePath($type);
	if (move_uploaded_file($file['tmp_name'], $uploadPath . $fileName)) {
		return ['status' => 1, 'data' => ['name' => $file['name'], 'file_name' => $fileName, 'extension' => $ext, 'size' => $file['size'], 'type' => $file['type']]];
	}
	return ['status' => 0, 'message' => 'File upload Error'];
}

function validateFile($data){
	foreach($data as $rule){
		$field=$rule[0];$title=$rule[1];$allowExt=$rule[2];
		$isRequired=(isset($rule[3]) && $rule[3])?true:false;
		if(isset($_FILES[$field]) && $_FILES[$field]['tmp_name']!=''){
			$file=$_FILES[$field];
			$name=explode('.',$file['name']);
			$ext=$name[count($name)-1];
			if(!empty($allowExt) && !in_array($ext,$allowExt)){
				return ['status'=>0,'message'=>$title.' File not valid.','field'=>$field,'title'=>$title];
			}
		}else{if($isRequired){
			return ['status'=>0,'message'=>$title.' File is required.','field'=>$field,'title'=>$title];}
		}
	} return ['status'=>1];
}

function sendMail($ci,$to,$subject,$body){
	$ci->config->load('email');
	$ci->email->set_mailtype('html');
	$ci->email->to($to);
	$ci->email->from(FROM_EMAIL,FROM_NAME);
	$ci->email->subject($subject);
	$ci->email->message($body);
	return $ci->email->send();
}

function tokenIsExpired($token){
	$tokenData=explode('_',$token);
	return isset($tokenData[1]) && $tokenData[1]>(time()-(1*60*60) )?false:true;
}
