<?php

function now(){
	return date("m.d.y, g:i:s a"); 
}
function today($default = "d-m-Y"){
	return date($default); 
}

function get_match($regex,$content) {
	    preg_match($regex,$content,$matches);
		if(!empty($matches[1]))
			return $matches[1];
	    }
function logga($dir, $content) {
		$fo=fopen($dir, "a");
		fwrite($fo, "{$content}\n");
		fclose($fo);
}

function curlize($url, $cookie=FALSE, $header=FALSE, $post=FALSE, $postnum=FALSE) {
		require_once __DIR__.'/random-user-agent.php';
		$c = curl_init($url);
		if($header){
			curl_setopt($c, CURLOPT_HEADER, 1);
		}
		if($post) {
			curl_setopt($c,CURLOPT_POST, $postnum);
			curl_setopt($c,CURLOPT_POSTFIELDS, $post);
		}
		if($cookie) {
			curl_setopt($c, CURLOPT_COOKIEFILE, $cookie); //saved cookies
			curl_setopt($c, CURLOPT_COOKIEJAR, $cookie);
			//curl_setopt($c, CURLOPT_COOKIESESSION, 1);
		}
		curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
		$page = curl_exec($c);
		if (curl_error($c)) {
		    echo curl_error($c);
		}
				
		curl_close($c);
		return $page;
}
function string_starts_with($string, $search)
{
    return (strncmp($string, $search, strlen($search)) == 0);
} 
function save_in_db($sql) {
	global $mysqli;
	$result = $mysqli->query($sql);

	  if (!$result) {
	    printf("%s\n", $mysqli->error);
	    return FALSE;
	  } else {
	    return $mysqli->insert_id;
	  }
}

function db_check_by($id, $table, $column){
	global $mysqli;
	$result=$mysqli->query("SELECT {$column} FROM {$table} WHERE {$column} = '{$id}';");
	if($result->num_rows >= 1)
		return FALSE;
	else return TRUE;
}

function nomizza($str,$a_char = array("'","-"," ")){    
    //$str contains the complete raw name string
    //$a_char is an array containing the characters we use as separators for capitalization. If you don't pass anything, there are three in there as default.
    $string = strtolower($str);
    foreach ($a_char as $temp){
        $pos = strpos($string,$temp);
        if ($pos){
            //we are in the loop because we found one of the special characters in the array, so lets split it up into chunks and capitalize each one.
            $mend = '';
            $a_split = explode($temp,$string);
            foreach ($a_split as $temp2){
                //capitalize each portion of the string which was separated at a special character
                $mend .= ucfirst($temp2).$temp;
                }
            $string = substr($mend,0,-1);
            }    
        }
    return ucfirst($string);
    }
function splitName($name)
{
    $results = array();

    $r = explode(' ', $name);
    $size = count($r);

    //check first for period, assume salutation if so
    if (mb_strpos($r[0], '.') === false)
    {
        $results['salutation'] = '';
        $results['first'] = ucfirst($r[0]);
    }
    else
    {
        $results['salutation'] = $r[0];
        $results['first'] = ucfirst($r[1]);
    }

    //check last for period, assume suffix if so
    if (mb_strpos($r[$size - 1], '.') === false)
    {
        $results['suffix'] = '';
    }
    else
    {
        $results['suffix'] = $r[$size - 1];
    }

    //combine remains into last
    $start = ($results['salutation']) ? 2 : 1;
    $end = ($results['suffix']) ? $size - 2 : $size - 1;

    $last = '';
    for ($i = $start; $i <= $end; $i++)
    {
        $last .= ' '.$r[$i];
    }
    $results['last'] = ucfirst(trim($last));

    return $results;
}


function array_to_obj($content) {
	return $object = json_decode(json_encode($content), FALSE);
}

function empty_so_zero($var) {
	
	if(is_null($var) || $var == FALSE) {
		return "0";
	} else {
		return $var;
	}
}
function empty_so_trattino($var) {
	
	if(is_null($var) || $var == FALSE) {
		return "-";
	} else {
		return $var;
	}
}
function nost($var) { //not object so trattino
	
	if(is_object($var) || $var == FALSE) {
		return "-";
	} else {
		return $var;
	}
}


function sanitate($array) {
global $mysqli;
   foreach($array as $key=>$value) {
      if(is_array($value)) { sanitate($value); }
      else { $array[$key] = mysqli_real_escape_string($mysqli, $value); }
   }
   return $array;
}

function getInputValue_FromDb($name, $db_table, $where) {
global $mysqli;

	$a=mysqli_query($mysqli, "SELECT $name FROM $db_table WHERE $where LIMIT 1");
	$b=mysqli_fetch_assoc($a);
	
	return empty_so_zero($b[$name]);
	

}

function checkSelectOnDb($select, $option, $db_table, $where) {
		
		global $mysqli;

		$a=mysqli_query($mysqli, "SELECT $select FROM $db_table WHERE $where LIMIT 1");
		$b=mysqli_fetch_assoc($a);
		
		if($b[$select] == $option) {
			return 'selected';
		} else 
			return '';
	}


function better_crypt($input, $rounds = 7)
  {
    $salt = "";
    $salt_chars = array_merge(range('A','Z'), range('a','z'), range(0,9));
    for($i=0; $i < 22; $i++) {
      $salt .= $salt_chars[array_rand($salt_chars)];
    }
    return crypt($input, sprintf('$2a$%02d$', $rounds) . $salt);
  }
  
function array_to_csv($array) {
$csv = array();
foreach ($array as $item=>$val) {
    if (is_array($val)) { 
        $csv[] = array_to_csv($val);
        $csv[] = "\n";
    } else {
        $csv[] = $val;
    }
}
return implode(',', $csv);
}
 
function price_format($string) {
  return number_format($string, 0, '.', '.');
}

function user_name_to_id($string, $nospaces = 0) {
global $mysqli;
if($nospaces) {
    $sql = mysqli_query($mysqli, "SELECT id FROM users WHERE REPLACE(name, ' ', '') LIKE '{$string}' LIMIT 1 ");
  }
  else {
    $sql = mysqli_query($mysqli, "SELECT id FROM users WHERE name LIKE '%{$string}%' LIMIT 1 ");
  }
  
$res = mysqli_fetch_object($sql);

return $res->id;
}




function upload_foto($files_array, $path_to, $force_name, $room = FALSE){
  $valid_formats = array("jpeg", "jpg", "JPG", "PNG", "png", "gif");
  $max_file_size = 10000000; 
  $path_to = $path_to.'/'; // Upload directory
  $count = 0;

  if(!file_exists($path_to)) {
    mkdir($path_to, 0777, true);
  }
  chmod($path_to, 0777);
	  
	  if(!is_array($files_array['name'])) {
	    $files_new_array['name'][0]=$files_array['name'];
	    $files_new_array['error'][0]=$files_array['error'];
	    $files_new_array['size'][0]=$files_array['size'];
	    $files_new_array['tmp_name'][0]=$files_array['tmp_name'];
	    
	    $files_array = $files_new_array;
	  }
	  
	  // Loop $_FILES to exeicute all files
	  foreach ($files_array['name'] as $f => $name) {     
	      if ($files_array['error'][$f] == 4) {
		  continue; // Skip file if any error found
	      }	       
	      if ($files_array['error'][$f] == 0) {	           
		  if ($files_array['size'][$f] > $max_file_size) {
		      $message[] = "$name is too large!.";
		      continue; // Skip large files
		  }
			  elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
				  $message[] = "$name is not a valid format";
				  continue; // Skip invalid file formats
			  }
		  else{ // No error found! Move uploaded files 
		  
		     // get extension
			$ext = pathinfo($name, PATHINFO_EXTENSION);
			
		      if($room) {
			global $mysqli;
			
			$room_id = mysqli_real_escape_string($mysqli, $room);
			$result = $mysqli->query("INSERT INTO listings_foto SET id_room = '{$room_id}', extension = '{$ext}'") or die($mysqli->error);
			$name = $mysqli->insert_id.'.'.$ext;
		      }
		      
		      if($force_name) $name = $force_name.'.'.$ext;
		      if($force_name == "cover") $name = "cover.JPG";	      
		      
		      if(move_uploaded_file($files_array["tmp_name"][$f], $path_to.$name))
			return true;
		      $count++; // Number of successfully uploaded file
		  }
	      }
	  }
}

function upload_file($files_array, $path_to, $force_name = false){
  $max_file_size = 10000000;
  $count = 0;

  if(!file_exists($path_to)) {
    mkdir($path_to, 0777, true);
  }
  chmod($path_to, 0777);

  $path_to = $path_to.'/'; // Upload directory

	  
	  if(!is_array($files_array['name'])) {
	    $files_new_array['name'][0]=$files_array['name'];
	    $files_new_array['error'][0]=$files_array['error'];
	    $files_new_array['size'][0]=$files_array['size'];
	    $files_new_array['tmp_name'][0]=$files_array['tmp_name'];
	    
	    $files_array = $files_new_array;
	  }
	  
	  // Loop $_FILES to exeicute all files
	  foreach ($files_array['name'] as $f => $name) {     

	      if ($files_array['error'][$f] == 4) {
		      continue; // Skip file if any error found
	      }	       
	      if ($files_array['error'][$f] == 0) {	           
            if ($files_array['size'][$f] > $max_file_size) {
                $message[] = "$name is too large!.";
                continue; // Skip large files
            }
			
		    else{ // No error found! Move uploaded files 
		      // get extension
		      $ext = '.'.pathinfo($files_array['name'][$f], PATHINFO_EXTENSION);
		      	
		      if($force_name) $name = $force_name.$ext;
		      if($force_name == "cover") $name = "cover.JPG";

              if(!$force_name) $name = $files_array["name"][$f];

		      if(move_uploaded_file($files_array["tmp_name"][$f], $path_to.$name))
              		return pathinfo($path_to.$name);
		      else 
			$count++; // Number of successfully uploaded file


		    }
	      }
	  }
}

function new_bootstrap_box($html, $title, $md = '10', $type = 'default', $add_class = '') {

$box=<<<EOD

<div class="col-md-{$md}">
  <div class="box box-success box-{$type} {$add_class}">
    <div class="box-header with-border">
      <h3 class="box-title">{$title}</h3>
      <div class="box-tools pull-right">
      </div><!-- /.box-tools -->
    </div><!-- /.box-header -->
    <div class="box-body">
      {$html}
    </div><!-- /.box-body -->
  </div><!-- /.box -->
</div>
EOD;

return $box;

}

function supertrim($string){
	$string = preg_replace('/\s+/', ' ', trim($string));
  $string = str_replace('=', '', $string);
return $string;
}

function myb_log($log_msg, $log_filename)
{

	$log_filename = $log_filename.'__'.date('Y-m-d').'.log';	
    if (!file_exists($log_filename)) 
    {
        // create directory/folder uploads.
       	 #mkdir(__DIR__.'/../logs/'.$log_filename, 0777, true);
    }
    $log_file_data = __DIR__.'/../logs/'.$log_filename;
    file_put_contents($log_file_data, time()." - ".$log_msg . "\n\n\n", FILE_APPEND);
} 
/**
 * Return all the query result set as an array MYSQLI_BOTH (MYSQLI_ASSOC, MYSQLI_NUM)
 */
 
 
 
function my_all($sql, $cod=1000, $type = MYSQLI_ASSOC) {
	global $mysqli;
	$result = $mysqli->query($sql);
	myb_log($sql, "sql");
    if($mysqli->error) print_r($mysqli->error);
	$obj = array_to_obj($result->fetch_all($type));
	return $obj;
}


/**
 * Shortcut for if(isset($_GET['force'])){...
 * handling of zero depends on php mood
 */
function request_ifset($what,$numeric=false,$default=0) {

    if($what === FALSE) return FALSE;
	if($numeric && !isset($_REQUEST[$what])){
		return $default;
	}

	if($numeric && !is_numeric($_REQUEST[$what])){
		return $default;
	}

	if (isset($_REQUEST[$what])) {
		if ($_REQUEST[$what] === 0 || $_REQUEST[$what] == '0') {
			return (int) 0;
		} else {
            
			return my_escape($_REQUEST[$what]);
		}
	}

	if($default){
		return $default;
	}
	return false;
}

function REQUEST($what,$type='string',$default=0) {
    

	if (isset($_REQUEST[$what])) {
		if ($_REQUEST[$what] === 0 || $_REQUEST[$what] == '0') {
			return (int) 0;
		} else {
            
			return my_escape($_REQUEST[$what]);
		}
	}

	if($default){
		return $default;
	}
	return false;
}

function request_ifset_removern($what,$numeric=false,$default=0) {
    $what = str_replace(array("\r\n", "\r", "\n"), "", $what);
    if($what === FALSE) return FALSE;
	if($numeric && !isset($_REQUEST[$what])){
		return $default;
	}

	if($numeric && !is_numeric($_REQUEST[$what])){
		return $default;
	}

	if (isset($_REQUEST[$what])) {
        $_REQUEST[$what] = str_replace(array("\r\n", "\r", "\n"), "", $_REQUEST[$what]);
		if ($_REQUEST[$what] === 0 || $_REQUEST[$what] == '0') {
			return (int) 0;
		} else {
			return my_escape($_REQUEST[$what]);
		}
	}

	if($default){
		return $default;
	}
	return false;
}


function my_escape($w) {

  if($w === FALSE) return FALSE;
  global $mysqli;
	if (!is_array($w)) {
		
		return trim($mysqli->real_escape_string($w));
	}

	foreach ($w as $key => $value) {
		$w[$key] = my_escape($value);
	}
	
	return $w;
}

/**
 * hack to use function  in heredoc
 */
function call_fn($data) {
	return $data;
}

$fn = 'call_fn';
//end

function  map_values($module, $field, $sort = false) {
	global $mysqli;

	$module = my_escape($module);
	$field = my_escape($field);
	if($sort) {
        $sort = my_escape($sort);
    } else $sort = '';

    $sql = "SELECT * FROM array_map WHERE module = '{$module}' AND field = '{$field}' AND (only_for IS NULL OR only_for = '{$User->id}') {$sort}";
	$r = my_all($sql);
	
	return $r; //print_r($r);
	
}
function map_get_value($module, $field, $value, $return = 'name') {
global $mysqli;

	$module = my_escape($module);
	$field = my_escape($field);
	$value = my_escape($value);
	$sql = "SELECT * FROM array_map WHERE module = '{$module}' AND field = '{$field}' AND value = '{$value}' AND (only_for IS NULL OR only_for = '{$User->id}') LIMIT 1";
	$r = my_all($sql);
	
	return $r[0]->$return; //print_r($r);
}

function map_get_value_by_name($module, $field, $value) {
global $mysqli;

	$module = my_escape($module);
	$field = my_escape($field);
	$value = my_escape($value);

	$sql = "SELECT * FROM array_map WHERE module = '{$module}' AND field = '{$field}' AND name = '{$value}' AND (only_for IS NULL OR only_for = '{$User->id}') LIMIT 1";
	$r = my_all($sql);
	
	return $r[0]->value; //print_r($r);
}


function option_value_to_map_name($module, $field, $value){

	$module = my_escape($module);
	$field = my_escape($field);
	$value = my_escape($value);

	$sql = "SELECT * FROM array_map WHERE module = '{$module}' AND field = '{$field}' AND value = '{$value}' AND (only_for IS NULL OR only_for = '{$User->id}') LIMIT 1";
	$r = my_all($sql);
	return $r[0]->name;

}

function map_values_to_options($module, $field, $selected = FALSE, $exclude_zero = false, $sort = false) {

  $array = map_values($module, $field, $sort);
  $html="<option selected disabled> -- Scegli un'opzione -- </option>";
  //$html = '';
  foreach($array as $val){
    if($val->value == $selected) {
      $sel = 'selected';
    } else { $sel = '';}
    
    if($exclude_zero && $val->value == 0) {} else {
      $html.=<<<EOD
      
	<option value="{$val->value}" $sel>{$val->name}</option>
      
EOD;
    }
  }
 
  return $html;
}



function map_values_to_js_array($module, $field){

$array = map_values($module, $field);
  $html="";
  foreach($array as $val){
    
      $html.=<<<EOD
      
      { name: "{$val->name}", id: "{$val->value}" },
      
EOD;
  
  }
 
  return $html;
}

function input_select($name, $array_option, $check_selected_value = false, $additional_class = false, $first_option_label = 'Seleziona un\'opzione') {

    $html = "<select name='{$name}' class='form-control {$additional_class}' data-live-search='true'>";
    if($first_option_label) $html.= '<option selected disabled>'.$first_option_label.'</option>';
        foreach($array_option as $key => $element){
   
            if($check_selected_value == $key) 
                $selected = "selected";
	    else $selected = '';

            
            $html.="<option value='{$key}' {$selected}>{$element}</option>";
        }
    
    $html .= "</select>";

    return $html;
}



function generate_tags_options($module, $entity_id = FALSE, $only_primary = FALSE) {
    global $User;
    if($only_primary) $add_to_sql = "AND is_primary_tag = 1";
    else $add_to_sql = "AND is_primary_tag != 1";
    $tags_list = my_all("SELECT * FROM tags WHERE module = '{$module}' AND (only_for_user = 0 OR only_for_user = '{$User->id}') AND company_id = ".COMPANY_ID. " {$add_to_sql} ORDER BY id ASC");
    $html="<option></option>";

    $selected_tags = my_all("SELECT * FROM tags_relations WHERE entity = '{$module}' AND entity_id = '{$entity_id}' AND user_id = '{$User->id}' ORDER BY id ASC");

    foreach($tags_list as $tag){
        $sel = '';
        
        foreach($selected_tags as $sel_tag){

            if($tag->id == $sel_tag->tag_id) {
                $sel = 'selected';
              } 
        }
      
        $html.=<<<EOD
      <option value="{$tag->id}" {$sel}>#{$tag->tagname}</option>
EOD;
    }
   
    return $html;
  }
  
function onlytext($string){

  $str = preg_replace('/\s+/', '', $string);
  $str = trim($str);
  return $str;

}

function sort_on_field(&$objects, $on, $order = 'ASC') {
    $comparer = ($order === 'DESC')
        ? "return -strcmp(\$a->{$on},\$b->{$on});"
        : "return strcmp(\$a->{$on},\$b->{$on});";
    usort($objects, create_function('$a,$b', $comparer));
}
function dateDiff ($d1, $d2) {

    // Return the number of days between the two dates:    
    return round(abs(strtotime($d1) - strtotime($d2))/86400);

} 
function date_is_major($a, $b){

  if (strtotime($a) > strtotime($b)) {
     return true;
  }
  else return false;
}

function destroy_cookies(){
    // unset cookies
    if (isset($_SERVER['HTTP_COOKIE'])) {
        $cookies = explode(';', $_SERVER['HTTP_COOKIE']);
        foreach($cookies as $cookie) {
            $parts = explode('=', $cookie);
            $name = trim($parts[0]);
            setcookie($name, '', time()-1000);
            setcookie($name, '', time()-1000, '/');
        }
    }
}

function array2csv($data, $delimiter = ',', $enclosure = '"', $escape_char = "\\")
{
    $f = fopen('php://memory', 'r+');
    
    foreach ($data as $item) {
        fputcsv($f, $item, $delimiter, $enclosure, $escape_char);
    }
    rewind($f);
    return stream_get_contents($f);
}

function simplearray2csv($data, $delimiter = ',', $enclosure = '"', $escape_char = "\\")
{
    $f = fopen('php://memory', 'r+');
    
    
        fputcsv($f, $data, $delimiter, $enclosure, $escape_char);
    
    rewind($f);
    return stream_get_contents($f);
}


function sql_to_json($query,$json_header=FALSE, $data_payload=FALSE, $array_zero=false){
global $mysqli;

        if( $result = $mysqli->query($query)) {
                $data = $result->fetch_all(MYSQLI_ASSOC);
        }

        if($data_payload===TRUE){

           header('Content-Type: application/json; charset=utf-8');
        }
        
         if($array_zero===TRUE){
            $data=$data[0];
        }
        
        
        $json_data = json_encode($data);
    if($json_header){
        header('Content-type: application/json');
        echo $json_data;
    } else {
        return $json_data;
    }

}



function sql_to_obj($query){
global $mysqli;

    if( $result = $mysqli->query($query)) {
            $data = $result->fetch_all(MYSQLI_ASSOC);
    }
    return $data[0];

}

function sql_to_array($query, $zero=false){
	global $mysqli;
    if( $result = $mysqli->query($query)) {
            $data = $result->fetch_all(MYSQLI_ASSOC);
    }
    if(!$zero){
        return object_to_array($data[0]);
    } else {
        return object_to_array($data);
    }

}

function object_to_array($object) {
    return (array) $object;
}



function sql_to_xls($sql, $filename=FALSE){
    global $mysqli;
    if(!$filename){
        $filename = time().'.xls'; // File Name
    }
    // Download file
    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Content-Type: application/vnd.ms-excel");
    $user_query = $mysqli->query($sql);
    // Write data to file
    $flag = false;
    foreach ($user_query->fetch_all(MYSQLI_ASSOC) as $row) {
        if (!$flag) {
            // display field/column names as first row
            echo implode("\t", array_keys($row)) . "\r\n";
            $flag = true;
        }
        echo implode("\t", array_values($row)) . "\r\n";
    }
}

function obj_to_xls($obj, $filename=FALSE){
    if(!$filename){
        $filename = time().'.xls'; // File Name
    }
    // Download file
    header("Content-Disposition: attachment; filename=\"$filename\"");
    header("Content-Type: application/vnd.ms-excel");
    $out = fopen("php://output", 'w');
    foreach ($obj as $data)
    {
        fputcsv($out, $data,"\t");
    }
    fclose($out);
    
/*
    foreach ($obj as $row) {
        // display field/column names as first row
        echo implode("\t", array_keys($row)) . "\r\n";
        echo implode("\t", array_values($row)) . "\r\n";
    }
    */
}

function downloadCSV($data, $filename=false)
{
    if(!$filename){
        $filename = date("Y-m-d")."_".time().".csv";
    }

    header('Content-type: application/csv');
    header('Content-Disposition: attachment; filename=' . $filename);
    header("Content-Transfer-Encoding: UTF-8");

    $f = fopen('php://output', 'a');
    fputcsv($f, array_keys($data[0]));

    foreach ($data as $row) 
    {
        fputcsv($f, $row);
    }
    fclose($f);
}


function is_admin(){
    
    global $User;
    if($User->role == 'admin'){
	  return true;
	} else {
        return false;
    }

}

function is_backoffice(){
    
    global $User;
    if($User->role == 'admin' || $User->role == 'backoffice' || $User->role == 'frontoffice'){
	  return true;
	} else {
        return false;
    }

}


function clean_string($string){

    return $string = trim(preg_replace('/\s+/', ' ', $string));

}


function this_url(){
return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
}

function Get_User_Info($by, $value, $company_check = true){
    global $mysqli;
    
    $filter = my_escape($by);
    $value  = my_escape($value);
    
    if($company_check){
    $sql_add = "AND company_id = ".COMPANY_ID;
    } else {
    $sql_add = "";
    }
    
    $sql = "SELECT * FROM users WHERE {$by} = '{$value}' {$sql_add}";
	$r = my_all($sql);
	if(!$r) return false;
	return array_to_obj($r[0]);

}

function Get_User_List($by = 1, $value = 1){
    global $mysqli;
    
    $filter = my_escape($by);
    $value  = my_escape($value);
    
    $sql = "SELECT * FROM users WHERE {$filter} = '{$value}' AND email NOT LIKE '%superadmin%' AND company_id = ".COMPANY_ID;
	$r = my_all($sql);
	return array_to_obj($r);

}

function GetListWhere($table = '', $where = false, $company_filter = false, $order_by = 'id ASC'){
    global $mysqli;
    
    if(!$where) $where = "1=1";
    if($company_filter) $where .= ' AND company_id = '.COMPANY_ID;
    
    $sql = "SELECT * FROM {$table} WHERE {$where} ORDER BY {$order_by}";
	$r = my_all($sql);
	return array_to_obj($r);

}

function GetList($table = '', $by = 1, $value = 1, $company_filter = false){
    global $mysqli;
    
    $filter = my_escape($by);
    $value  = my_escape($value);
    if($company_filter === true) $where .= ' AND company_id = '.COMPANY_ID;
    
    $sql = "SELECT * FROM {$table} WHERE {$filter} = '{$value}'";
	$r = my_all($sql);
	return array_to_obj($r);

}

function Generate_WA_Link($n_cell, $text = FALSE, $force_wa_web = FALSE){
 
  if(!$text) $text='';
  
    $PhoneNumberE164  = ConvertPhoneNumber($n_cell);

  $text = urlencode($text);

  $link = "https://wa.me/{$PhoneNumberE164}?text={$text}";
  if($force_wa_web && !CheckIsMobile() ){
    $link = "https://web.whatsapp.com/send?phone={$PhoneNumberE164}&text={$text}&app_absent=0";
  }
  return $link;
}


function Generate_Chat_Btn($n_cell=false, $text = FALSE, $btn_text = FALSE){
  global $detect;
  global $fn;
  
  $btn_text_WA = 'Scrivi su WhatsApp';
  $btn_text_Chat = 'Scrivi in Chat';
  if($btn_text) {
    $btn_text_WA = $btn_text;
    $btn_text_Chat = $btn_text;
  }
    if(!$n_cell) $n_cell = '3926175392';
    if($detect->isMobile()) {
        $html = <<<EOD
        <a class="btn" href="{$fn(Generate_WA_Link($n_cell, $text))}">
                <span class="btn__text">$btn_text_WA</span>
                <i class="ion-social-whatsapp"></i>
        </a>
EOD;
    } else {
    $html = <<<EOD
        <a class="btn" href="javascript:void(Tawk_API.toggle())">
                <span class="btn__text">$btn_text_Chat</span>
                <i class="ion-social-whatsapp"></i>
        </a>
EOD;
    }
    
    return $html;
}


function CheckIsMobile(){

$isMob = is_numeric(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), "mobile"));
return $isMob;

}

function Generate_Call_Btn($tel=false, $text = false, $class="btn gradient--active bg--red "){
  global $detect;
  global $fn;
  global $N_TEL;
  
    if(!$tel) $tel = $N_TEL;
    if(!$text) $text = $tel;
    if($detect->isMobile()) {
        $html = <<<EOD
        <a class="btn $class" href="tel:$tel">
                <span class="btn__text">{$text}</span>
                <i class="ion-social-whatsapp"></i>
        </a>
EOD;
    } else {
    $html = <<<EOD
        <div class="btn $class"  >
                <span class="btn__text">{$text}</span>
                <i class="ion-social-whatsapp"></i>
        </a>
EOD;
    }
    
    return $html;
}


function replace_placeholder($string, $buyerlead_id = false, $listing_id = false, $potential_id = false, $contact_id = false){
global $User;


require_once __DIR__.'/MYB.Class.php';

$MYB = new MYBrokerage();

$string = str_replace('[TEAM_ID]', $User->team_id, $string);
$string = str_replace('[AGENT_NAME]', $User->name, $string);
$string = str_replace('[AGENT_CELL]', $User->cell, $string);
$string = str_replace('[AGENT_EMAIL]', $User->email, $string);
$string = str_replace('[COMPANY_NAME]', COMPANY_NAME, $string);

if($buyerlead_id){

    $today = today('Y-m-d');
    $buyerlead       = $MYB->GetBuyerLead($buyerlead_id, 'obj');
    $listing         = $MYB->GetPropertyByRif($buyerlead->id_immobile, 'obj');
    $listing_full_data = json_decode($listing->full_data);
    $meeting = $MYB->GetCalendarEvents("entity = 'buyerlead' AND entity_id = '{$buyerlead_id}' AND event_startdate >= '{$today}'", 'obj');
    if($meeting->event_startdate){

    $meeting_date = strtotime($meeting->event_startdate);
    $meeting_date_midnight = date('Y-m-d 00:00:00', $meeting_date);


    $diff =  dateDiff(today('Y-m-d'), $meeting_date_midnight);
       switch($diff){
        case 0:
            $formatted_next_meeting_date = 'oggi '.DateFormatter($meeting->event_startdate, 'dd/MM/yy').' alle ore '.DateFormatter($meeting->event_startdate, 'HH:mm');
        break;
        case 1:
            $formatted_next_meeting_date = 'domani '.DateFormatter($meeting->event_startdate, 'dd/MM/yy').' alle ore '.DateFormatter($meeting->event_startdate, 'HH:mm');
        break;
        default:
            $formatted_next_meeting_date = DateFormatter($meeting->event_startdate, 'EEEE dd/MM/yy').' alle ore '.DateFormatter($meeting->event_startdate, 'HH:mm');

        break;
       }
    } else {

        $formatted_next_meeting_date = '___________ alle ore ___________';
    }

    $string = str_replace('[ID]', $buyerlead_id, $string);
    $string = str_replace('[ENCODED_ID]', hashid($buyerlead_id, 'encode', 6), $string);
    $string = str_replace('[BUYERLEAD_ID]', $buyerlead_id, $string);
    $string = str_replace('[BUYERLEAD_NAME]', $buyerlead->name, $string);
    $string = str_replace('[LISTING_VIDEO_URL]', $listing->url_video, $string);
    $string = str_replace('[LISTING_BROCHURE_URL]', $listing_full_data->immobili_allegati->allegato->file, $string);
    $string = str_replace('[LISTING_CITY]', $listing->city, $string);
    $string = str_replace('[LISTING_ADDRESS]', $listing->address.' '.$listing->number, $string);
    $string = str_replace('[LISTING_AGENT_NAME]', $listing->consulente, $string);
    $string = str_replace('[LISTING_AGENT_CELL]', $listing->consulente_cell, $string);
    $string = str_replace('[LISTING_AGENT_EMAIL]', $listing->consulente_email, $string);
    $string = str_replace('[MEETING_DATE]', $formatted_next_meeting_date, $string);

}
if($potential_id){

    $PotentialInfo = $MYB->GetPotential($potential_id, 'obj');
    $string = str_replace('[ID]', $PotentialInfo->id, $string);
    $string = str_replace('[ENCODED_ID]', hashid($buyerlead_id, 'encode', 6), $string);
    $string = str_replace('[OPPORTUNITY_NAME]', $PotentialInfo->opportunity_name, $string);
    $string = str_replace('[ZONE]', $PotentialInfo->zone_text, $string);
    $string = str_replace('[SOURCE]', $PotentialInfo->source_text, $string);
    $string = str_replace('[OPPORTUNITY_TYPE]', $PotentialInfo->opportunity_type_text, $string);
    $string = str_replace('[CLIENT_FULLNAME]', $PotentialInfo->contact_fullname, $string);
    $string = str_replace('[OPPORTUNITY_URL]', $PotentialInfo->source_url, $string);

}
if($contact_id){

    $ContactInfo = $MYB->GetContact($contact_id, false, 'obj');
    $string = str_replace('[ID]', $contact_id, $string);
    $string = str_replace('[ENCODED_ID]', hashid($contact_id, 'encode', 6), $string);
    $string = str_replace('[CONTACT_FULLNAME]', $ContactInfo->fullname, $string);
    $string = str_replace('[MOBILE]', $ContactInfo->mobile, $string);
    $string = str_replace('[EMAIL]', $ContactInfo->email, $string);
}
return $string;

}


function CDN_Permalink($media, $folder = 'MediaUploads', $FCID_prefix = true){
    $FCID = FCID;
    if($FCID_prefix)  return "https://mybrokerage.app/{$folder}/{$FCID}/{$media}";
    else return "https://mybrokerage.app/{$folder}/{$media}";

}

function DateFormatter($date, $format = false, $timezone = 'Europe/Rome'){

    $fmt = new IntlDateFormatter('it_IT', IntlDateFormatter::LONG, IntlDateFormatter::NONE, $timezone);
    if($format) $fmt->setPattern($format);
    $date = strtotime($date);
    return $fmt->format($date);

}

function BuildGCalendarEventID($event_id, $calendar_id){

     $calendar_id = str_replace('@group.calendar.google.com', '', $calendar_id);
     return base64_encode($event_id.' '.$calendar_id);
    
}

function HTML2WAFormat($content){

    $content = str_replace("<b>", "*", $content);
    $content = str_replace("</b>", "*", $content);
    $content = str_replace("<i>", "_", $content);
    $content = str_replace("</i>", "_", $content);
    return $content;
}

function WAConnector_Send($n_cell, $text, $forceUser = false, $type = 'text',  $media_url = false){

        global $User;

        if($forceUser) { 
            $UserInfo = Get_User_Info('id', $forceUser);
            $GetWAConnector_Info = my_all("SELECT wa_access_token, wa_instance_id FROM users WHERE id = '{$UserInfo->id}'");
            $WA_INSTANCE_ID = $GetWAConnector_Info[0]->wa_instance_id;
        } 
        
        if(!$WA_INSTANCE_ID) {
            $GetWAConnector_Info = my_all("SELECT wa_access_token, wa_instance_id FROM users WHERE id = '".WACONNECTOR_MAIN_ACCOUNT."'");
            $WA_INSTANCE_ID = $GetWAConnector_Info[0]->wa_instance_id;
        }

        $text = HTML2WAFormat($text);

        $curl = curl_init();
        $PhoneNumberE164  = ConvertPhoneNumber($n_cell);
        $PhoneNumberE164_withouth_plus  = str_replace("+","", $PhoneNumberE164);

        $WAC_Info = $GetWAConnector_Info[0];

        if($type == 'media') $post['media_url']  =  $media_url;

        $post = array(
            "access_token" => $WAC_Info->wa_access_token,
            "instance_id" => $WAC_Info->wa_instance_id,
            "type"  => $type,
            "number"     => $PhoneNumberE164_withouth_plus,
            "message"   => $text,
	);

        if($type == 'media') $post['media_url']  =  $media_url;
        $post_json = json_encode($post);
	
	#print_r($post);
        $params = http_build_query($post);

        #echo("https://app.waconnector.it/api/send?$params");
        $cur = curlize("https://app.waconnector.it/api/send?$params");
	$response = json_decode($cur);
	#print_r($response);
	if($response->status == 'error' || !$response->message){

            $REMOTE_LOG['waconnector_request'] = $post_json;
            $REMOTE_LOG['message'] = "{$User->email} | WHATSAPP WACONNECTOR ERROR - SENDING TO {$PhoneNumberE164_withouth_plus} {$cur}";
            MYB_EH_Remote("rbESVHqPo4of7giFd64k2ciE", $REMOTE_LOG);
            return false;
        } else {
            return $response->message;
        }

}
function Send_WA($n_cell, $text){

        global $User;

        $curl = curl_init();
        $PhoneNumberE164  = ConvertPhoneNumber($n_cell);
        $PhoneNumberE164_withouth_plus  = str_replace("+","", $PhoneNumberE164);

        
        $post = array(
            "access_token" => SENTWA_ACCESS_TOKEN,
            "instance_id" => SENTWA_MAIN_NUMBER_INSTANCE_ID,
            "type"  => "text",
            "number"     => $PhoneNumberE164_withouth_plus,
            "message"   => $text,
        );
        
        $post_json = json_encode($post);
        #print_r($post);
        $params = http_build_query($post);
       # echo "https://dash.sentwa.com/api/send.php?$params";

        $cur = curlize("https://dash.sentwa.com/api/send.php?$params", false, false, $post, 5);
        
        $response = json_decode($cur);
        if($response->status == 'error'){

            $REMOTE_LOG['message'] = "{$User->email} | WHATSAPP SENTWA ERROR - SENDING TO {$PhoneNumberE164_withouth_plus} {$cur}";
            MYB_EH_Remote("rbESVHqPo4of7giFd64k2ciE", $REMOTE_LOG);
        } else {
            return true;
        }
        
}
function SentWA_Generate_QR_Code(){

        global $User;

        $curl = curl_init();


        $post = array(
            "access_token" => SENTWA_ACCESS_TOKEN,
            "instance_id" => SENTWA_MAIN_NUMBER_INSTANCE_ID,
        );

        $post_json = json_encode($post);
        $params = http_build_query($post);

        $cur = curlize("https://dash.sentwa.com/api/getqrcode.php?$params", false, false, $post, 5);

        $response = json_decode($cur);
        if($response->status == 'error'){
		return false;
        } else {
            return $response;
        }

}


function check_admin_token(){
global $admin_token;
    $request_token = request_ifset('admin_token');
    if($request_token == $admin_token)
    return true;
}

function array_to_td($array){

    foreach($array as $v){
        $html.= "<tr>";
        foreach($v as $vv){
            $html.= "<td>{$vv}</td>";
        }
        $html.= "<tr>";
    }
return $html;
}

function dec_enc($action, $string) {
    $output = false;
 
    $encrypt_method = "AES-256-CBC";
    $secret_key = 'bamboo_is_eco_and_cool';
    $secret_iv = 'bamboo_is_eco_and_cool';
 
    // 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 GetTotals($module, $filter = false, $operator = 'COUNT(*)', $company_id_filter = false){

    if($filter) $sql_add = "AND {$filter}";
    if($company_id_filter) $sql_add .= " AND company_id = ".COMPANY_ID;
    
    
    $sql = "SELECT {$operator} as tot FROM {$module} WHERE 1=1 {$sql_add}";
    #echo $sql;
	$r = my_all($sql);
	if(!$r) return false;
	return array_to_obj($r[0]);
}

function GetTopList($string, $limit = 5, $filter = false, $company_id_filter = true){

    if($filter) $sql_add = "AND {$filter}";
    if($company_id_filter) $sql_add .= " AND company_id = ".COMPANY_ID;
    
    switch($string){
        case 'trending-listings':
		 $sql_add = " AND {$filter} AND rif_id IS NOT NULL AND lv.company_id = ".COMPANY_ID;
          $sql = "SELECT rif_id as item, COUNT(*) as tot, city as data1, address as data2, consulente as data3 FROM richieste AS r LEFT JOIN listings_view  AS lv ON r.id_immobile = lv.rif_id WHERE 1=1 {$sql_add} GROUP BY rif_id ORDER BY tot DESC LIMIT {$limit} ";
        break;
        case 'top-appointments':
            $sql = "SELECT first_name, last_name, COUNT(*) as tot FROM ".CRM_DB_NAME.".custom_potmodtracker_view
 WHERE postvalue = 'Appuntamento fissato' {$sql_add} GROUP BY smownerid ORDER BY tot DESC LIMIT {$limit} ";
        break;
        case 'top-listings':
            $sql = "SELECT consulente, COUNT(*) as tot FROM listings_view
 WHERE offer_type = 'Vendita' {$sql_add} GROUP BY consulente ORDER BY tot DESC, consulente ASC LIMIT {$limit} ";
        break;
        case 'top-buyerleads':
            $sql = "SELECT consulente, COUNT(*) as tot FROM richieste_view LEFT JOIN listings_view ON listings_view.rif_id = richieste_view.id_immobile
 WHERE 1=1 {$sql_add} GROUP BY consulente ORDER BY tot DESC, consulente_name ASC LIMIT {$limit} ";
        break;


    }
  #  echo $sql."\n\n";
	$r = my_all($sql);
	if(!$r) return false;
	return array_to_obj($r);
}


function GeneratePositiveOrNegative($first_value, $second_value, $return){

    if($first_value > $second_value){
        $class = 'stats-change-success';
        $badge = <<<EOD
        <div class="stats-icon change-success">
            <i class="material-icons">trending_up</i>
        </div>
EOD;
    } elseif($first_value < $second_value){
        $class = 'stats-change-danger';
        $badge = <<<EOD
        <div class="stats-icon change-danger">
            <i class="material-icons">trending_down</i>
        </div>
EOD;
    }
    
    return $$return;

}

function DeltaCalc($a, $b, $format='percent'){

    $a = (float)$a;
    $b = (float)$b;
    if($format == 'percent') $delta = number_format((fdiv(($a-$b),$b)*100),2);
    if($format == 'relative') $delta = $a-$b;
    if($delta == 'inf') $delta = '0.00';
    return $delta;
}

function GetSqlTimeFilter($string){

    switch($string){
    
        case 'lastweek':
            return "between date_sub(now(),INTERVAL 1 WEEK) and now()";
        break;
        case 'previousweek':
            return "between date_sub(now(),INTERVAL 2 WEEK) and date_sub(now(),INTERVAL 1 WEEK)";
        break;
        case 'last30days':
            return "between date_sub(now(),INTERVAL 30 DAY) and now()";
        break;
        case 'previous30days':
            return "between date_sub(now(),INTERVAL 60 DAY) and date_sub(now(), INTERVAL 30 DAY)";
        break;
    }

}


function SendEmailWAttachments($subject, $message, $to, $from_display = COMPANY_NAME, $from_address = COMPANY_EMAIL, $attachments = FALSE){
	
	require_once __DIR__.'/PHPMailer.php';
    $mail=new PHPMailer\PHPMailer\PHPMailer();
    $mail->IsSMTP();   
    $mail->SMTPDebug = 0; 
    $mail->Port = SMTP_PORT;
    $mail->SMTPAuth   = true;
    $mail->SMTPSecure = "tls";
    $mail->Username=SMTP_USER;
    $mail->Password = SMTP_PSWD;                     // SMTP password
    $mail->Host = SMTP_SERVER;  // Specify main and backup SMTP servers
    $mail->From = $from_address;
    $mail->FromName = $from_display;
    
    if(is_array($to)){
        foreach($to as $recipient){
            $mail->addAddress($recipient);
        }
    } else {
        $mail->addAddress($to);
    }
	
    $mail->isHTML(true);
    $mail->Body    = $message;
    $mail->Subject = $subject;
    $mail->CharSet = 'UTF-8';
    
    if(is_countable($_FILES['task_files']['tmp_name'])) {

        for($ct=0;$ct<count($_FILES['task_files']['tmp_name']);$ct++){
            $mail->AddAttachment($_FILES['task_files']['tmp_name'][$ct],$_FILES['task_files']['name'][$ct]);
        }
    }
	
	if(!$mail->send()) {
        echo 'Mailer Error: ' . $mail->ErrorInfo;
        return FALSE;
        } else {
        return TRUE;
        }
        
         

}

function CreateOptions($array, $selected_value=false, $field_value = false){
	
	
    foreach($array as $item) {

    
    $selected = '';
    if($selected_value && $field_value){
        if($selected_value == $item->$field_value){
            $selected = 'selected';
        } 
    }
    
    $options.=<<<EOD
    <option $selected value="{$item->value}">{$item->item}</option>
EOD;
    }
    
    return $options;

}

function Generate_Users_Options($selected_value=false, $force_view = false, $disable_first_option = true){
    global $User;
    $disabled = '';
    if($disable_first_option) $disabled = 'disabled';
    $options = "<option selected {$disabled}>-- Seleziona un Consulente --</option>";
    
    if(is_backoffice() || is_manager()){
        
        if($User->org_units_permissions) {
            if($User->org_units_permissions == 'group'){
                $s_where = '';
            } else {
                $s_where = " AND FIND_IN_SET('{$User->org_units_permissions}', org_unit_id) OR id = '{$User->id}'";
            }
        } else {
            $s_where = '';
        }

    } else{
	    if(is_team_leader()){

        $s_where = " AND team_leader_id = '{$User->id}' OR id = '{$User->id}'";
		} else {
        $s_where = " AND id = '{$User->id}'";
		} 
        if($force_view == 'all'){
            $s_where = '';
        }
    }
    if($User->is_superadmin == 1) { 
        $exclude_superadmin = '';
    } else {
        $exclude_superadmin = 'AND is_superadmin = 0 ';
    }
    
    $users_list = my_all("SELECT * FROM users WHERE 1=1 {$s_where} {$exclude_superadmin} AND role IN ('admin', 'consulente', 'staff', 'backoffice', 'frontoffice', 'team_leader', 'manager') AND company_id = ".COMPANY_ID." ORDER BY status DESC");
    foreach($users_list as $UserData) {

        if($selected_value == $UserData->id){
            $selected = 'selected';
        } else {
            $selected = '';
        }
        $UserData->status_text = '';
        if($UserData->status == 0) $UserData->name = "-- {$UserData->name} | DISABILITATO ";
    $options.=<<<EOD
    <option $selected value="{$UserData->id}">{$UserData->name}</option>
EOD;
    }
    
    return $options;

}

function GetValueMap($name, $value){
        if(!is_string($name) OR !is_string($value)) return false;
        
        $value_1        =  map_get_value_by_name('maximizer', 'campo', $name);
        $value_2        =  map_get_value('maximizer', 'valore_campi', "{$value_1}__{$value}");
        
        return $value_2;
}
function extract_zip_subdir($zipfile, $subpath, $destination, $temp_cache, $traverse_first_subdir=true){
	$zip = new ZipArchive;
	if(substr($temp_cache, -1) !== DIRECTORY_SEPARATOR) {
		$temp_cache .= DIRECTORY_SEPARATOR;
	}
	$res = $zip->open($zipfile);
	if ($res === TRUE) {
	    if ($traverse_first_subdir==true){
	        $zip_dir = $temp_cache . $zip->getNameIndex(0);
	    }
	    else {
	    	$temp_cache = $temp_cache . basename($zipfile, ".zip");
	    	$zip_dir = $temp_cache;
	    }
	    $zip->extractTo($temp_cache);
	    $zip->close();
	   
	    exec("mv {$zip_dir}{$subpath}  $destination");
	   	//echo "ok\n";
	
	    rmdir($zip_dir);
	    //echo "ok\n";
	} else {
	    echo "failed\n";
	    die();
	}
}

 function chmod_r($dir, $dirPermissions, $filePermissions) {
      $dp = opendir($dir);
       while($file = readdir($dp)) {
         if (($file == ".") || ($file == ".."))
            continue;

        $fullPath = $dir."/".$file;

         if(is_dir($fullPath)) {
            chmod($fullPath, $dirPermissions);
            chmod_r($fullPath, $dirPermissions, $filePermissions);
         } else {
            chmod($fullPath, $filePermissions);
         }

       }
     closedir($dp);
  }

function Send_SMS($number, $body){
    /*
        $ID = 'ACc791a8e78d517a5c35e06e3b86b9d8e1';
        $token = '2eaf0f471f5ca1a93c194aead17e4587';
        $service = TWILIO_SMS_SID;
        $url = 'https://api.twilio.com/2010-04-01/Accounts/' . $ID . '/Messages.json';
    */

    
    $number = ConvertPhoneNumber($number, 'full');
    $openapi_formatted_recipent = "+".$number->getCountryCode().'-'.$number->GetNationalNumber();
    //$url = 'https://api.sms.to/sms/send?api_key='.SMSTO_API_KEY.'&bypass_optout=true&to='.$number.'&message='.rawurlencode($body).'&sender_id='.SMS_SENDER_ID;
    $url = 'https://ws.messaggisms.com/messages/';

    $data = array(
        "test" => false,
        "sender" => SMS_SENDER_ID,
        "recipients" => $openapi_formatted_recipent,
        "body" => $body
        );
        
        $postdata = json_encode($data);


	#$number = str_replace("+","",$number);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);

        //curl_setopt($ch, CURLOPT_HTTPAUTH,CURLAUTH_BASIC);
        //curl_setopt($ch, CURLOPT_USERPWD,$ID . ':' . $token);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Authorization: Bearer ' . OPENAPI_SMS_TOKEN
            ));

        curl_setopt($ch, CURLOPT_POST,true);
       curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);

        $resp = curl_exec($ch);

        curl_close($ch);
        return json_decode($resp,true);
    
    
    }

     function isValidEmail($email) {
        if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
           return true;
          } else {
            return false;
          }
      }

    function ValidatePhoneNumber($number){

        //$number = '3926389086';
    
        $ID = 'ACc791a8e78d517a5c35e06e3b86b9d8e1';
        $token = '2eaf0f471f5ca1a93c194aead17e4587';
        $url = 'https://lookups.twilio.com/v1/PhoneNumbers/' . $number.'?CountryCode=IT';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);

        curl_setopt($ch, CURLOPT_HTTPAUTH,CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD,$ID . ':' . $token);

        $resp = curl_exec($ch);
        curl_close($ch);

        $resp = json_decode($resp,true);
        return $resp;
    
    }

    function PhoneNumberLookup($number, $response = 'obj'){

        //$number = '3926389086';
    
        $ID = 'ACc791a8e78d517a5c35e06e3b86b9d8e1';
        $token = '2eaf0f471f5ca1a93c194aead17e4587';
        $url = 'https://lookups.twilio.com/v1/PhoneNumbers/' . $number;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);

        curl_setopt($ch, CURLOPT_HTTPAUTH,CURLAUTH_BASIC);
        curl_setopt($ch, CURLOPT_USERPWD,$ID . ':' . $token);

        $resp = curl_exec($ch);
        curl_close($ch);

        if($response == 'json'){
            return $resp;
        } 
        if($response == 'obj'){
            $resp = json_decode($resp,true);
            return $resp;
        }
    
    }

    
function Send_Telegram($chatID, $messaggio, $inline_buttons=false, $reply_to_msg=false, $bot_token = TELEGRAM_BOT_TOKEN){
    #echo "Sending message to " . $chatID . " from BOT ID ". TELEGRAM_BOT_TOKEN . "\n";
    global $User;
    $REMOTE_LOG['message'] = "{$User->email} | MESSAGE START --> CHAT_ID $chatID";	
    $REMOTE_LOG['content'] = $messaggio;
    MYB_EH_Remote("X6bc7WUhxmvb2zyg23RXg3oE", $REMOTE_LOG);
    
    $url = "https://api.telegram.org/bot" . $bot_token . "/sendMessage?chat_id=" . $chatID;
    $url = $url . "&text=" .urlencode($messaggio);
    $url = $url . "&parse_mode=html";
    if($reply_to_msg) {
	$url = $url . "&reply_to_message_id=".$reply_to_msg;
    }
    if($inline_buttons) $url = $url.="&reply_markup=".urlencode(json_encode($inline_buttons));
    $ch = curl_init();
    
    $optArray = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true
    );
    curl_setopt_array($ch, $optArray);
    $result = curl_exec($ch);
    curl_close($ch);
    
    $REMOTE_LOG['content'] = $messaggio;
    $REMOTE_LOG['message'] = "{$User->email} | MESSAGE START --> CHAT_ID $chatID --> SENT!";	
    $REMOTE_LOG['telegram_response'] = $result;	
    MYB_EH_Remote("X6bc7WUhxmvb2zyg23RXg3oE", $REMOTE_LOG);
    
    #myb_log($result, "telegram");
    return $result;

}

function Edit_Msg_Telegram($chatID, $messageID, $text, $inline_buttons=false, $bot_token = TELEGRAM_BOT_TOKEN){
    #echo "Sending message to " . $chatID . " from BOT ID ". TELEGRAM_BOT_TOKEN . "\n";


 global $User;
    $REMOTE_LOG['message'] = "{$User->email} | MESSAGE START --> CHAT_ID $chatID";
    $REMOTE_LOG['content'] = $messaggio;
    MYB_EH_Remote("X6bc7WUhxmvb2zyg23RXg3oE", $REMOTE_LOG);


    $url = "https://api.telegram.org/bot" . $bot_token . "/editMessageText?chat_id=" . $chatID."&message_id=".$messageID;
    $url = $url . "&text=" .urlencode($text);
    $url = $url . "&parse_mode=html";
    if($inline_buttons) $url = $url.="&reply_markup=".urlencode(json_encode($inline_buttons));
$ch = curl_init();
    
    $optArray = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true
    );
    curl_setopt_array($ch, $optArray);
    $result = curl_exec($ch);


	$REMOTE_LOG['content'] = $messaggio;
    $REMOTE_LOG['message'] = "{$User->email} | MESSAGE START --> CHAT_ID $chatID --> SENT!";
    $REMOTE_LOG['telegram_response'] = $result; 
    MYB_EH_Remote("X6bc7WUhxmvb2zyg23RXg3oE", $REMOTE_LOG);

//print_r($result);
    curl_close($ch);
    return $result;

}


function Delete_Msg_Telegram($chatID, $messageID, $bot_token = TELEGRAM_BOT_TOKEN){
    #echo "Sending message to " . $chatID . " from BOT ID ". TELEGRAM_BOT_TOKEN . "\n";
    
    $url = "https://api.telegram.org/bot" . $bot_token . "/deleteMessage?chat_id=" . $chatID."&message_id=".$messageID;
  
$ch = curl_init();
    
    $optArray = array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true
    );
    curl_setopt_array($ch, $optArray);
    $result = curl_exec($ch);
    //print_r($result);
    curl_close($ch);
    return $result;

}

function Send_Webhook($payload, $url)
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    return curl_exec($curl);
}

function PrepSQLValues($array, $escape = false){
    $i = 0;
    foreach($array as $field => $value){
    
        if($escape){
            $field = my_escape($field);
            $value = my_escape($value);
        }
        if($value !== FALSE){
        if($i == 0){
                $sql = "{$field} = '{$value}'";
        } else {
            if(!empty($field)){
                $sql .= ", {$field} = '{$value}'";
            }
        }
        $i++;
        }
    }
    return $sql;
}
function GenRandomString($length_of_string) 
{ 
  
    // String of all alphanumeric character 
    $str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; 
  
    // Shufle the $str_result and returns substring 
    // of specified length 
    return substr(str_shuffle($str_result),  
                       0, $length_of_string); 
} 
function hide_mail($email) {
    $mail_segments = explode("@", $email);
    $mail_segments[0] = str_repeat("*", strlen($mail_segments[0]));

    return implode("@", $mail_segments);
}

function hide_phone($phone) {
    return substr($phone, 0, -4) . "****";
}

function extract_email_from_string($string){
    preg_match_all("/[\._a-zA-Z0-9-]+@[\._a-zA-Z0-9-]+/i", $string, $matches);
    return $matches[0][0];
  }

function check_password_hash($user,$pswd){
        
        $pswd_hashed = better_crypt($pswd); 

		$sql = 	"SELECT * FROM users WHERE email = '{$user}' AND status = 1  LIMIT 1";
		$user = my_all($sql);

		//print_r($user);die();
		if (!isset($user[0]->id)) {
			return(false);
		} else {
            if(crypt($pswd, $user[0]->pswd) == $user[0]->pswd) 
                return $user[0];
		}
		
}
/**
 * Get header Authorization
 * */
function getAuthorizationHeader(){
    $headers = null;
    if (isset($_SERVER['Authorization'])) {
        $headers = trim($_SERVER["Authorization"]);
    }
    else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { //Nginx or fast CGI
        $headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
    } elseif (function_exists('apache_request_headers')) {
        $requestHeaders = apache_request_headers();
        // Server-side fix for bug in old Android versions (a nice side-effect of this fix means we don't care about capitalization for Authorization)
        $requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
        //print_r($requestHeaders);
        if (isset($requestHeaders['Authorization'])) {
            $headers = trim($requestHeaders['Authorization']);
        }
    }
    return $headers;
}

/**
 * get access token from header
 * */
function getBearerToken() {
    $headers = getAuthorizationHeader();
    // HEADER: Get the access token from the header
    if (!empty($headers)) {
        if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
            return $matches[1];
        }
    }
    return null;
}


function UserInit(){


    if(request_ifset('apikey')) {
    
        $user_apikey = request_ifset('apikey');
        $User = Get_User_Info('apikey', $user_apikey, false);
        if($User->status == 0) {
           echo 'NON AUTORIZZATO';
           die();
        } else {
            return $User;
        }
    }


	if(getBearerToken()){
		$token =  getBearerToken();
		$User = Get_User_Info('apikey', $token, false);
		if($User->status == 0){
			echo 'NON AUTORIZZATO';
			die();
		} else {
			return $User;
		}
	}


    if(check_admin_token()) {
    
      
        $User = Get_User_Info('is_superadmin', '1', false);
        if($User->status == 0) {
           echo 'NON AUTORIZZATO';
           die();
        } else {
            return $User;
        }
    }

    
    
    session_start();
    if(!isset($_COOKIE['user_session'])) {
        // die('NOT AUTHTORIZED');
        header("Location: {$BASE_URL_HTTPS}/auth?redirect_to={$_SERVER['REQUEST_URI']}");
        die();

    } else {
    
        $User = Get_User_Info('id', $_COOKIE['user_session'], false);
        if($User->status == 0) {
            header("Location: {$BASE_URL_HTTPS}/auth?logout=1");
        }
        if(!empty($_COOKIE['user_superadmin'])){
        
            if($_COOKIE['user_superadmin'] == md5($User->email)){
            
                $User->is_superadmin = true;
                
                 if($_POST['superadmin_embody']){
            
                        setcookie("user_session",$_POST['superadmin_embody'],time()+ (365 * 24 * 60 * 60),"/", false);
                    }
            
            }
        
        }
    }
    
    
    $now = time();

    if (isset($_SESSION['discard_after']) && $now > $_SESSION['discard_after']) {
        // this session has worn out its welcome; kill it and start a brand new one
        session_unset();
        session_destroy();
        session_start();
        
        header("Location: {$BASE_URL_HTTPS}/auth?redirect_to={$_SERVER[REQUEST_URI]}");
    }
    
    // either new or old, it should live at most for ....
    $_SESSION['discard_after'] = $now + 86400;
    
    
    //print_r($_SESSION);
    return $User;
}

function EuroFormat($number){
#return money_format('%.2n',$number);
	
	return '€ '.number_format($number, 2);
}

if (!function_exists('money_format')){
 function money_format($formato, $valor) {

    if (setlocale(LC_MONETARY, 0) == 'C') { 
        return number_format($valor, 2); 
    }

    $locale = localeconv(); 

    $regex = '/^'.             // Inicio da Expressao 
             '%'.              // Caractere % 
             '(?:'.            // Inicio das Flags opcionais 
             '\=([\w\040])'.   // Flag =f 
             '|'. 
             '([\^])'.         // Flag ^ 
             '|'. 
             '(\+|\()'.        // Flag + ou ( 
             '|'. 
             '(!)'.            // Flag ! 
             '|'. 
             '(-)'.            // Flag - 
             ')*'.             // Fim das flags opcionais 
             '(?:([\d]+)?)'.   // W  Largura de campos 
             '(?:#([\d]+))?'.  // #n Precisao esquerda 
             '(?:\.([\d]+))?'. // .p Precisao direita 
             '([in%])'.        // Caractere de conversao 
             '$/';             // Fim da Expressao 

    if (!preg_match($regex, $formato, $matches)) { 
        trigger_error('Formato invalido: '.$formato, E_USER_WARNING); 
        return $valor; 
    } 

    $opcoes = array( 
        'preenchimento'   => ($matches[1] !== '') ? $matches[1] : ' ', 
        'nao_agrupar'     => ($matches[2] == '^'), 
        'usar_sinal'      => ($matches[3] == '+'), 
        'usar_parenteses' => ($matches[3] == '('), 
        'ignorar_simbolo' => ($matches[4] == '!'), 
        'alinhamento_esq' => ($matches[5] == '-'), 
        'largura_campo'   => ($matches[6] !== '') ? (int)$matches[6] : 0, 
        'precisao_esq'    => ($matches[7] !== '') ? (int)$matches[7] : false, 
        'precisao_dir'    => ($matches[8] !== '') ? (int)$matches[8] : $locale['int_frac_digits'], 
        'conversao'       => $matches[9] 
    ); 

    if ($opcoes['usar_sinal'] && $locale['n_sign_posn'] == 0) { 
        $locale['n_sign_posn'] = 1; 
    } elseif ($opcoes['usar_parenteses']) { 
        $locale['n_sign_posn'] = 0; 
    } 
    if ($opcoes['precisao_dir']) { 
        $locale['frac_digits'] = $opcoes['precisao_dir']; 
    } 
    if ($opcoes['nao_agrupar']) { 
        $locale['mon_thousands_sep'] = ''; 
    } 

    $tipo_sinal = $valor >= 0 ? 'p' : 'n'; 
    if ($opcoes['ignorar_simbolo']) { 
        $simbolo = ''; 
    } else { 
        $simbolo = $opcoes['conversao'] == 'n' ? $locale['currency_symbol'] 
                                               : $locale['int_curr_symbol']; 
    } 
    $numero = number_format(abs($valor), $locale['frac_digits'], $locale['mon_decimal_point'], $locale['mon_thousands_sep']); 


    $sinal = $valor >= 0 ? $locale['positive_sign'] : $locale['negative_sign']; 
    $simbolo_antes = $locale[$tipo_sinal.'_cs_precedes']; 

    $espaco1 = $locale[$tipo_sinal.'_sep_by_space'] == 1 ? ' ' : ''; 

    $espaco2 = $locale[$tipo_sinal.'_sep_by_space'] == 2 ? ' ' : ''; 

    $formatado = ''; 
    switch ($locale[$tipo_sinal.'_sign_posn']) { 
    case 0: 
        if ($simbolo_antes) { 
            $formatado = '('.$simbolo.$espaco1.$numero.')'; 
        } else { 
            $formatado = '('.$numero.$espaco1.$simbolo.')'; 
        } 
        break; 
    case 1: 
        if ($simbolo_antes) { 
            $formatado = $sinal.$espaco2.$simbolo.$espaco1.$numero; 
        } else { 
            $formatado = $sinal.$numero.$espaco1.$simbolo; 
        } 
        break; 
    case 2: 
        if ($simbolo_antes) { 
            $formatado = $simbolo.$espaco1.$numero.$sinal; 
        } else { 
            $formatado = $numero.$espaco1.$simbolo.$espaco2.$sinal; 
        } 
        break; 
    case 3: 
        if ($simbolo_antes) { 
            $formatado = $sinal.$espaco2.$simbolo.$espaco1.$numero; 
        } else { 
            $formatado = $numero.$espaco1.$sinal.$espaco2.$simbolo; 
        } 
        break; 
    case 4: 
        if ($simbolo_antes) { 
            $formatado = $simbolo.$espaco2.$sinal.$espaco1.$numero; 
        } else { 
            $formatado = $numero.$espaco1.$simbolo.$espaco2.$sinal; 
        } 
        break; 
    } 

    if ($opcoes['largura_campo'] > 0 && strlen($formatado) < $opcoes['largura_campo']) { 
        $alinhamento = $opcoes['alinhamento_esq'] ? STR_PAD_RIGHT : STR_PAD_LEFT; 
        $formatado = str_pad($formatado, $opcoes['largura_campo'], $opcoes['preenchimento'], $alinhamento); 
    } 

    return $formatado; 
}
}

function menu_check_priv($condition, $true = true, $href, $icon, $name){
if($condition == $true){
return <<<EOD

<li class="nav-item ">
    <a class="nav-link" href="{$href}">
        <div class="parent-icon"><i class='bx {$icon}'></i>
        </div>
        <div class="menu-title d-flex align-items-center">{$name}</div>
    </a>
</li>
EOD;
}
}

function check_if_value_is_in_csv($search_string, $csv){
	$csv = rtrim($csv);

        if(strpos($csv, ',')){
            $temp = explode(',', $csv);
        } else {
            $temp[0] = trim($csv);
        }
        
        foreach($temp as $val){
		if ($val == $search_string) {
            		$return = true;
        	}
	}
       return $return;
        
    
}
function formatPhone($num) {
    $num = preg_replace('/[^0-9]/', '', $num);
    $len = strlen($num);

    if($len == 7) $num = preg_replace('/([0-9]{2})([0-9]{2})([0-9]{3})/', '$1 $2 $3', $num);
    elseif($len == 8) $num = preg_replace('/([0-9]{3})([0-9]{2})([0-9]{3})/', '$1 - $2 $3', $num);
    elseif($len == 9) $num = preg_replace('/([0-9]{3})([0-9]{2})([0-9]{2})([0-9]{2})/', '$1 - $2 $3 $4', $num);
    elseif($len == 10) $num = preg_replace('/([0-9]{3})([0-9]{2})([0-9]{2})([0-9]{3})/', '$1 - $2 $3 $4', $num);

    return $num;
}
function slugify ($text) {

    $replace = [
        '&lt;' => '', '&gt;' => '', '&#039;' => '', '&amp;' => '',
        '&quot;' => '', 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä'=> 'Ae',
        '&Auml;' => 'A', 'Å' => 'A', 'Ā' => 'A', 'Ą' => 'A', 'Ă' => 'A', 'Æ' => 'Ae',
        'Ç' => 'C', 'Ć' => 'C', 'Č' => 'C', 'Ĉ' => 'C', 'Ċ' => 'C', 'Ď' => 'D', 'Đ' => 'D',
        'Ð' => 'D', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ē' => 'E',
        'Ę' => 'E', 'Ě' => 'E', 'Ĕ' => 'E', 'Ė' => 'E', 'Ĝ' => 'G', 'Ğ' => 'G',
        'Ġ' => 'G', 'Ģ' => 'G', 'Ĥ' => 'H', 'Ħ' => 'H', 'Ì' => 'I', 'Í' => 'I',
        'Î' => 'I', 'Ï' => 'I', 'Ī' => 'I', 'Ĩ' => 'I', 'Ĭ' => 'I', 'Į' => 'I',
        'İ' => 'I', 'Ĳ' => 'IJ', 'Ĵ' => 'J', 'Ķ' => 'K', 'Ł' => 'K', 'Ľ' => 'K',
        'Ĺ' => 'K', 'Ļ' => 'K', 'Ŀ' => 'K', 'Ñ' => 'N', 'Ń' => 'N', 'Ň' => 'N',
        'Ņ' => 'N', 'Ŋ' => 'N', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O',
        'Ö' => 'Oe', '&Ouml;' => 'Oe', 'Ø' => 'O', 'Ō' => 'O', 'Ő' => 'O', 'Ŏ' => 'O',
        'Œ' => 'OE', 'Ŕ' => 'R', 'Ř' => 'R', 'Ŗ' => 'R', 'Ś' => 'S', 'Š' => 'S',
        'Ş' => 'S', 'Ŝ' => 'S', 'Ș' => 'S', 'Ť' => 'T', 'Ţ' => 'T', 'Ŧ' => 'T',
        'Ț' => 'T', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'Ue', 'Ū' => 'U',
        '&Uuml;' => 'Ue', 'Ů' => 'U', 'Ű' => 'U', 'Ŭ' => 'U', 'Ũ' => 'U', 'Ų' => 'U',
        'Ŵ' => 'W', 'Ý' => 'Y', 'Ŷ' => 'Y', 'Ÿ' => 'Y', 'Ź' => 'Z', 'Ž' => 'Z',
        'Ż' => 'Z', 'Þ' => 'T', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a',
        'ä' => 'ae', '&auml;' => 'ae', 'å' => 'a', 'ā' => 'a', 'ą' => 'a', 'ă' => 'a',
        'æ' => 'ae', 'ç' => 'c', 'ć' => 'c', 'č' => 'c', 'ĉ' => 'c', 'ċ' => 'c',
        'ď' => 'd', 'đ' => 'd', 'ð' => 'd', 'è' => 'e', 'é' => 'e', 'ê' => 'e',
        'ë' => 'e', 'ē' => 'e', 'ę' => 'e', 'ě' => 'e', 'ĕ' => 'e', 'ė' => 'e',
        'ƒ' => 'f', 'ĝ' => 'g', 'ğ' => 'g', 'ġ' => 'g', 'ģ' => 'g', 'ĥ' => 'h',
        'ħ' => 'h', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'ī' => 'i',
        'ĩ' => 'i', 'ĭ' => 'i', 'į' => 'i', 'ı' => 'i', 'ĳ' => 'ij', 'ĵ' => 'j',
        'ķ' => 'k', 'ĸ' => 'k', 'ł' => 'l', 'ľ' => 'l', 'ĺ' => 'l', 'ļ' => 'l',
        'ŀ' => 'l', 'ñ' => 'n', 'ń' => 'n', 'ň' => 'n', 'ņ' => 'n', 'ŉ' => 'n',
        'ŋ' => 'n', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'oe',
        '&ouml;' => 'oe', 'ø' => 'o', 'ō' => 'o', 'ő' => 'o', 'ŏ' => 'o', 'œ' => 'oe',
        'ŕ' => 'r', 'ř' => 'r', 'ŗ' => 'r', 'š' => 's', 'ù' => 'u', 'ú' => 'u',
        'û' => 'u', 'ü' => 'ue', 'ū' => 'u', '&uuml;' => 'ue', 'ů' => 'u', 'ű' => 'u',
        'ŭ' => 'u', 'ũ' => 'u', 'ų' => 'u', 'ŵ' => 'w', 'ý' => 'y', 'ÿ' => 'y',
        'ŷ' => 'y', 'ž' => 'z', 'ż' => 'z', 'ź' => 'z', 'þ' => 't', 'ß' => 'ss',
        'ſ' => 'ss', 'ый' => 'iy', 'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G',
        'Д' => 'D', 'Е' => 'E', 'Ё' => 'YO', 'Ж' => 'ZH', 'З' => 'Z', 'И' => 'I',
        'Й' => 'Y', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O',
        'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F',
        'Х' => 'H', 'Ц' => 'C', 'Ч' => 'CH', 'Ш' => 'SH', 'Щ' => 'SCH', 'Ъ' => '',
        'Ы' => 'Y', 'Ь' => '', 'Э' => 'E', 'Ю' => 'YU', 'Я' => 'YA', 'а' => 'a',
        'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'yo',
        'ж' => 'zh', 'з' => 'z', 'и' => 'i', 'й' => 'y', 'к' => 'k', 'л' => 'l',
        'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's',
        'т' => 't', 'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch',
        'ш' => 'sh', 'щ' => 'sch', 'ъ' => '', 'ы' => 'y', 'ь' => '', 'э' => 'e',
        'ю' => 'yu', 'я' => 'ya'
    ];

    // make a human readable string
    $text = strtr($text, $replace);

    // replace non letter or digits by -
    $text = preg_replace('~[^\\pL\d.]+~u', '_', $text);

    // trim
    $text = trim($text, '-');

    // remove unwanted characters
    $text = preg_replace('~[^-\w.]+~', '', $text);

    //$text = strtolower($text);

    return $text;
}
function DateRange_to_Dates($string){

    $dates = explode('-',$string);
    return $dates;
}


function DynamicWhereField($field, $value, $operator = '='){
    
    return "{$field} {$operator} {$value}";

}

function create_permalink($string) {
	$string = strtolower($string);
	$string = preg_replace("/[^0-9A-Za-z ]/", "", $string);
	$string = str_replace(" ", "-", $string);
	while (strstr($string, "--")) {
		$string = preg_replace("/--/", "-", $string);
	}
	return($string);
}

function mount_email_template($msg, $template = '1', $Page = false){

    switch($template){
        case 1: {
        
        $html = <<<EOD
    
<!-- start preheader -->
<div class="preheader" style="display: none; max-width: 0; max-height: 0; overflow: hidden; font-size: 1px; line-height: 1px; color: #fff; opacity: 0;"></div>
<!-- end preheader -->
<p></p>
<!-- start body -->
<table border="0" cellpadding="0" cellspacing="0" width="100%"><!-- start logo -->
<tbody>
<tr>
<td align="center" bgcolor="#e9ecef"><!-- [if (gte mso 9)|(IE)]>
        <table align="center" border="0" cellpadding="0" cellspacing="0" width="600">
        <tr>
        <td align="center" valign="top" width="600">
        <![endif]-->
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;">
<tbody>
<tr>
<td align="center" valign="top" style="padding: 36px 24px;"><a href="{$Page->BASE_URL_HTTPS}" target="_blank" style="display: inline-block;" rel="noopener"> <img src="https:{$Page->IMG_PATH_LOGO_FULL}" alt="Logo" border="0" width="100" style="display: block; width: 100px; max-width: 100px; min-width: 48px;" /> </a></td>
</tr>
</tbody>
</table>
<!-- [if (gte mso 9)|(IE)]>
        </td>
        </tr>
        </table>
        <![endif]--></td>
</tr>
<!-- end logo --> <!-- start hero -->

<tr>
<td align="center" bgcolor="#e9ecef"><!-- [if (gte mso 9)|(IE)]>
        <table align="center" border="0" cellpadding="0" cellspacing="0" width="600">
        <tr>
        <td align="center" valign="top" width="600">
        <![endif]-->
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;"><!-- start copy -->
<tbody>
<tr>
<td align="left" bgcolor="#ffffff" style="padding: 24px; font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 24px;">

{$msg}

</td>
</tr>
</tbody>
</table>
<!-- [if (gte mso 9)|(IE)]>
        </td>
        </tr>
        </table>
        <![endif]--></td>
</tr>
<!-- end copy block --> <!-- start footer -->
<tr>
<td align="center" bgcolor="#e9ecef" style="padding: 24px;"><!-- [if (gte mso 9)|(IE)]>
        <table align="center" border="0" cellpadding="0" cellspacing="0" width="600">
        <tr>
        <td align="center" valign="top" width="600">
        <![endif]-->
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;"><!-- start permission -->
<tbody>
<tr>
<td align="center" bgcolor="#e9ecef" style="padding: 12px 24px; font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 20px; color: #666;">
<p style="margin: 0;">{$Page->COMPANY_NAME}</p>
</td>
</tr>
</tbody>
</table>
<!-- [if (gte mso 9)|(IE)]>
        </td>
        </tr>
        </table>
        <![endif]--></td>
</tr>
<!-- end footer --></tbody>
</table>
<!-- end body -->
EOD;
        
        break;
    } case 2: {
        
        
        $html = <<<EOD
    
<!-- start preheader -->
<div class="preheader" style="display: none; max-width: 0; max-height: 0; overflow: hidden; font-size: 1px; line-height: 1px; color: #fff; opacity: 0;"></div>
<!-- end preheader -->
<p></p>
<!-- start body -->
<table border="0" cellpadding="0" cellspacing="0" width="100%"><!-- start logo -->
<tbody>
<tr>
<td align="center" bgcolor="#e9ecef"><!-- [if (gte mso 9)|(IE)]>
        <table align="center" border="0" cellpadding="0" cellspacing="0" width="600">
        <tr>
        <td align="center" valign="top" width="600">
        <![endif]-->
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;">
<tbody>
<tr>
<td align="center" valign="top" style="padding: 36px 24px;"><div style="display: inline-block;" rel="noopener"> <img src="https:{$Page->IMG_PATH_LOGO_FULL}" alt="Logo" border="0" width="100" style="display: block; width: 100px; max-width: 100px; min-width: 48px;" /> </div></td>
</tr>
</tbody>
</table>
<!-- [if (gte mso 9)|(IE)]>
        </td>
        </tr>
        </table>
        <![endif]--></td>
</tr>
<!-- end logo --> <!-- start hero -->

<tr>
<td align="center" bgcolor="#e9ecef"><!-- [if (gte mso 9)|(IE)]>
        <table align="center" border="0" cellpadding="0" cellspacing="0" width="600">
        <tr>
        <td align="center" valign="top" width="600">
        <![endif]-->
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;"><!-- start copy -->
<tbody>
<tr>
<td align="left" bgcolor="#ffffff" style="padding: 24px; font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; font-size: 16px; line-height: 24px;">

{$msg}

</td>
</tr>
</tbody>
</table>
<!-- [if (gte mso 9)|(IE)]>
        </td>
        </tr>
        </table>
        <![endif]--></td>
</tr>
<!-- end copy block --> <!-- start footer -->
<tr>
<td align="center" bgcolor="#e9ecef" style="padding: 24px;"><!-- [if (gte mso 9)|(IE)]>
        <table align="center" border="0" cellpadding="0" cellspacing="0" width="600">
        <tr>
        <td align="center" valign="top" width="600">
        <![endif]-->
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="max-width: 600px;"><!-- start permission -->
<tbody>
<tr>
<td align="center" bgcolor="#e9ecef" style="padding: 12px 24px; font-family: 'Source Sans Pro', Helvetica, Arial, sans-serif; font-size: 14px; line-height: 20px; color: #666;">
<p style="margin: 0;">{$Page->PLATFORM_NAME}</p>
</td>
</tr>
</tbody>
</table>
<!-- [if (gte mso 9)|(IE)]>
        </td>
        </tr>
        </table>
        <![endif]--></td>
</tr>
<!-- end footer --></tbody>
</table>
<!-- end body -->
EOD;
        
        break;
    }
    }

    return $html;
}
function is_team_leader(){
    
    global $User;
    if($User->role == 'team_leader'){
	  return true;
	} else {
        return false;
    }

}
function is_manager(){
    
    global $User;
    if($User->role == 'manager'){
	  return true;
	} else {
        return false;
    }

}

function businessHours_settings()
{
    // settings
    $start = "09:00";
    $end   = "19:00";

    // calculate amount of hours per working day
    $diff  = strtotime( $end ) - strtotime( $start );
    $hours = $diff / 3600;

    $settings = array(
        "start" => $start,
        "end"   => $end,
        "diff"  => $diff,
        "hrs"   => $hours
    );

    return $settings;
}
function findObjectByField($id, $field='id', $array){
    

    foreach ( $array as $element ) {
        if ( $id == $element->$field ) {
            return $element;
        }
    }

    return false;
}


function ConvertPhoneNumber($PhoneNumber, $return = 'E164', $DefaultCountryCode = "IT") {

    myb_log("START PROCESSING {$PhoneNumber}", "PNC");

	if($PhoneNumber == 'anonymous') return $PhoneNumber;

    $phoneUtil = \libphonenumber\PhoneNumberUtil::getInstance();
    try {
        $PhoneProto = $phoneUtil->parse($PhoneNumber, $DefaultCountryCode);
        $isValid = $phoneUtil->isValidNumber($PhoneProto);
        //print_r($PhoneProto);
    } catch (\libphonenumber\NumberParseException $e) {
        //print_r($e);
    }

    if($phoneUtil->isValidNumber($PhoneProto)){

        myb_log("--> {$PhoneNumber} -- VALID", "PNC");

        if($return == 'E164') {
            return $phoneUtil->format($PhoneProto, \libphonenumber\PhoneNumberFormat::E164);
        } else {
            return $PhoneProto;
        }
    } else {

        myb_log("--> {$PhoneNumber} -- NOT VALID", "PNC");


        if(!$phoneUtil->isValidNumber($PhoneProto) && $phoneUtil->isPossibleNumber($PhoneProto)){

            myb_log("--> {$PhoneNumber} -- TRY WITH PLUS", "PNC");

            // try international adding plus 
            $PhoneProto = $phoneUtil->parse("+".$PhoneNumber);
            return $phoneUtil->format($PhoneProto, \libphonenumber\PhoneNumberFormat::E164);
    
        } else {
            myb_log("--> {$PhoneNumber} -- ERROR", "PNC");

            $REMOTE_LOG['message'] = 'PHONE VALIDATION -> THIS NUMBER IS NOT RECOGNIZED AND VALID - '.$PhoneNumber;
            MYB_EH_Remote("rbESVHqPo4of7giFd64k2ciE", $REMOTE_LOG);
    
            return $PhoneNumber;
        }
    }

 
}
    

function GenE164Number($string){

    if(strpos($string, '+')) return $string;

    $string = str_replace(' ', '', $string);
    $string = str_replace('+39', '', $string);
    $string = str_replace('00', '', $string);
    if(strlen($string) >= 11) {
        $string = preg_replace('/39/', '', $string, 1);
    }
    $string = '+39'.$string;
    return $string;
    
}


function DeleteITACountryCodeFromNumber($string){

  
    if(strlen($string) >= 12) {
        $string = preg_replace('/39/', '', $string, 1);
    } 
    
    return $string;
    
    
}
function GenSuperAdminEmbody($User){
//print_r($User);
    $users_list =  GetListWhere("users", "1=1");
    foreach($users_list as $users){
        $options.="<option value='{$users->id}'>{$users->name}</option>";
    }

    if($User->is_superadmin == 1){

    $HTML = <<<EOD

    <form method="POST">
    <div style="margin-right:2em">
        <select name="superadmin_embody" class="select2">
            <option value="">---</option>
            $options
        </select>
        <button type="submit" class="btn btn-xs">Embody</button>
    </div>
    </form>




EOD;
    }
    return $HTML;
}

function SQLPaging_limit ( $request)
	{
		//$limit = "LIMIT ". MAX_BUYERLEADS;

		if ( isset($request['start']) && $request['length'] != -1 ) {
			$limit = "LIMIT ".intval($request['start']).", ".intval($request['length']);
		}

		return $limit;
	}
function gen_vcard($array){
    $data = <<<EOD
BEGIN:VCARD
VERSION:3.0
FN;CHARSET=UTF-8:{$fullname}
N;CHARSET=UTF-8:{$fullname};;;
EMAIL:{$email}
TITLE;CHARSET=UTF-8:{$org}
TEL:{$tel}
END:VCARD
EOD;
return $data;
}


function getDirContents($dir, $relativePath = false)
{
    $fileList = array();
    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));
    foreach ($iterator as $file) {
        if ($file->isDir()) continue;
        $path = $file->getPathname();
        if ($relativePath) {
            $path = str_replace($dir, '', $path);
            $path = ltrim($path, '/\\');
        }
        $fileList[] = $path;
    }
    return $fileList;
}

function hashid($string, $encode_or_decode, $pad = 8) {

    include_once(__DIR__.'/Hashids/Math/MathInterface.php');
    include_once(__DIR__.'/Hashids/Math/Bc.php');
    include_once(__DIR__.'/Hashids/Math/Gmp.php');
    include_once(__DIR__.'/Hashids/HashidsInterface.php');
    include_once(__DIR__.'/Hashids/HashidsException.php');
    include_once(__DIR__.'/Hashids/Hashids.php');

    $hashids = new Hashids\Hashids('', $pad);

    if($encode_or_decode == 'encode'){
        $id = $hashids->encode($string);
        return $id;
    } else {
        $result = $hashids->decode($string);
        return $result[0]; 
    }
}

function UnixTimestamp_To_Date($unix){

    $currentTime = DateTime::createFromFormat( 'U', $unix );
    $formattedString = $currentTime->format( 'Y-m-d' );
    return $formattedString;


}
function eIDinfo($eid){
    preg_match_all('/([0-9]+|[a-zA-Z]+)/',$eid,$matches);

    $info = new stdClass();
    $info->ent = $matches[1][0];
    $info->entity_id = $matches[1][1];

    switch($info->ent){
        case 'BUY':
            $info->entity = 'buyerlead';
        break;
        case 'POT':
            $info->entity = 'potential';
        break;
        case 'CON':
            $info->entity = 'contact';
        break;
    }
    return $info;
}
function GenerateOpenAI($prompt, $max_tokens) {

    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');

// Imposta i parametri della richiesta API
$data = array(
    'model' => 'gpt-3.5-turbo', // Sostituisci con il modello che desideri utilizzare
    'temperature' => 0.6, // Regola il livello di casualità delle risposte
    'max_tokens' => 50, // Limita il numero di parole nella risposta
    'stream' => true,
    'messages' => [
        [
            "role" => "user",
            "content" => "Who won the world series in 2020?"
        ],
    ],
);

// Converte i dati in formato JSON
$data_json = json_encode($data);

// Imposta la URL della risorsa API
$url = 'https://api.openai.com/v1/chat/completions';

// Imposta le opzioni di richiesta API
$options = array(
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $data_json,
    CURLOPT_HTTPHEADER => array(
        "Content-Type: application/json",
        "Authorization: Bearer ".OPENAI_API_KEY
    )
);

// Inizializza cURL
$curl = curl_init();

// Imposta le opzioni di cURL
curl_setopt_array($curl, $options);

// Effettua la richiesta API
$response = curl_exec($curl);

// Decodifica la risposta JSON
$response_data = json_decode($response, true);
print_r($response_data);
// Mostra la risposta
$answer = $response_data['choices'][0]['text'];
echo "data: " . $answer . "\n\n";

// Chiudi la sessione di cURL
curl_close($curl);
}




