<?php

function tr_status($value) {
	switch ($value) {
		case "1":
			return "table-warning";
		break;
		case "2":
			return "table-danger";
		break;
		default:
			return "";
		break;
	}
}

function generateRandomString($length = 20) {
    $characters = '0123456789';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

function timeAgo($time_ago)
{
    $time_ago = strtotime($time_ago);
    $cur_time   = time();
    $time_elapsed   = $cur_time - $time_ago;
    $seconds    = $time_elapsed ;
    $minutes    = round($time_elapsed / 60 );
    $hours      = round($time_elapsed / 3600);
    $days       = round($time_elapsed / 86400 );
    $weeks      = round($time_elapsed / 604800);
    $months     = round($time_elapsed / 2600640 );
    $years      = round($time_elapsed / 31207680 );
    // Seconds
    if($seconds <= 60){
        return "just now";
    }
    //Minutes
    else if($minutes <=60){
        if($minutes==1){
            return "one minute ago";
        }
        else{
            return "$minutes minutes ago";
        }
    }
    //Hours
    else if($hours <=24){
        if($hours==1){
            return "an hour ago";
        }else{
            return "$hours hrs ago";
        }
    }
    //Days
    else if($days <= 7){
        if($days==1){
            return "yesterday";
        }else{
            return "$days days ago";
        }
    }
    //Weeks
    else if($weeks <= 4.3){
        if($weeks==1){
            return "a week ago";
        }else{
            return "$weeks weeks ago";
        }
    }
    //Months
    else if($months <=12){
        if($months==1){
            return "a month ago";
        }else{
            return "$months months ago";
        }
    }
    //Years
    else{
        if($years==1){
            return "one year ago";
        }else{
            return "$years years ago";
        }
    }
}

function getClientNumber($client_id) {
	try {
	
		$core = Core::getInstance();
		$stmt = $core->dbh->prepare("SELECT client_number FROM myclients WHERE client_id = :client_id");
		$stmt -> bindParam("client_id", $client_id, PDO::PARAM_INT);
		
		$stmt -> execute();
		$results = $stmt -> fetchAll(PDO::FETCH_ASSOC);
		return $results[0]["client_number"];		
		
	} catch(PDOException $pe) {
		
		trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
		
	}
}

function pushSMS($ag, $to, $msg, $msg_id) {
	global $cf_agents, $cf_api_key, $cf_api_secret;
	// get name of the function depending on current ag!
	switch($cf_agents[$ag][0]) {
		case "nexmo":
			nexmo($cf_api_key, $cf_api_secret, $cf_agents[$ag]["from"], $to, $msg, $msg_id);
		break;
	}
}

function remove_emoji($string)
{
    // Match Enclosed Alphanumeric Supplement
    $regex_alphanumeric = '/[\x{1F100}-\x{1F1FF}]/u';
    $clear_string = preg_replace($regex_alphanumeric, ':smiley:', $string);

    // Match Miscellaneous Symbols and Pictographs
    $regex_symbols = '/[\x{1F300}-\x{1F5FF}]/u';
    $clear_string = preg_replace($regex_symbols, ':smiley:', $clear_string);

    // Match Emoticons
    $regex_emoticons = '/[\x{1F600}-\x{1F64F}]/u';
    $clear_string = preg_replace($regex_emoticons, ':smiley:', $clear_string);

    // Match Transport And Map Symbols
    $regex_transport = '/[\x{1F680}-\x{1F6FF}]/u';
    $clear_string = preg_replace($regex_transport, ':smiley:', $clear_string);
    
    // Match Supplemental Symbols and Pictographs
    $regex_supplemental = '/[\x{1F900}-\x{1F9FF}]/u';
    $clear_string = preg_replace($regex_supplemental, ':smiley:', $clear_string);

    // Match Miscellaneous Symbols
    $regex_misc = '/[\x{2600}-\x{26FF}]/u';
    $clear_string = preg_replace($regex_misc, ':smiley:', $clear_string);

    // Match Dingbats
    $regex_dingbats = '/[\x{2700}-\x{27BF}]/u';
    $clear_string = preg_replace($regex_dingbats, ':smiley:', $clear_string);

    return $clear_string;
}

function formatMsgMultiPart($string) {
	if(preg_match("/=>/", $string) && preg_match("/\|{3}/", $string) ) {
		$my_array = explode("|||", $string);
		$output_array = array();
		$output_string = "";
		foreach($my_array as $value) {
			$temp_array = explode("=>", $value);
			$output_array[trim($temp_array[0])] = trim($temp_array[1]);
		}
		ksort($output_array);
		foreach($output_array as $key => $value) {
			$output_string .= $value;
		}
		return $output_string;
	} else {
		return $string;
	}
}

function nexmo($api_key, $api_secret, $from, $to, $msg, $msg_id) {
	$data = array('api_key' => $api_key,
				'api_secret' => $api_secret,
				'from' => $from,
				'to' => $to,
				'text' => $msg);
				
	$url = 'https://rest.nexmo.com/sms/json';
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
	curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));

	if(!$file = curl_exec($curl)) {

		echo curl_error($curl);

	}

	curl_close($curl);

	$data_arr = json_decode($file);
	
	if ($data_arr -> {'message-count'} > 0) {
		if ($data_arr -> messages[0] -> status == "0") {
			// sms has been sent!!!!
			try {
				$core = Core::getInstance();
				$stmt = $core -> dbh -> prepare("UPDATE messages SET mess_status = '0' WHERE mess_id = :mess_id");
				$stmt -> bindParam("mess_id", $msg_id, PDO::PARAM_STR);
				$stmt -> execute();
				$row = $stmt -> rowCount();
				
				if ($row > 0) {
					return "true";
				} else {
					return "false";
				}
			} catch(PDOException $pe) {
				trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
			}
		} else if ($data_arr -> messages[0] -> status == "1") {
			// message is throttled
			try {
				$core = Core::getInstance();
				$stmt = $core -> dbh -> prepare("UPDATE messages SET mess_status = '1' WHERE mess_id = :mess_id");
				$stmt -> bindParam("mess_id", $msg_id, PDO::PARAM_STR);
				$stmt -> execute();
				$row = $stmt -> rowCount();
				
				return "false";
				
			} catch(PDOException $pe) {
				trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
			}
		} else {
			// there has been error in sending the message
			try {
				$core = Core::getInstance();
				$stmt = $core -> dbh -> prepare("UPDATE messages SET mess_status = '2' WHERE mess_id = :mess_id");
				$stmt -> bindParam("mess_id", $msg_id, PDO::PARAM_STR);
				$stmt -> execute();
				$row = $stmt -> rowCount();
				
				return "false";
				
				// insert into log messages!
				try {
					$core = Core::getInstance();
					$stmt_up = $core -> dbh -> prepare("INSERT INTO messages_log (mlog_mess_id, mlog_status) values (:mlog_mess_id, :mlog_status)");
					$stmt_up -> bindParam("mlog_mess_id", $msg_id, PDO::PARAM_INT);
					$stmt_up -> bindParam("mlog_status", $data_arr -> messages[0] -> status, PDO::PARAM_STR);
					$stmt_up -> execute();
					$row_up = $stmt_up -> rowCount();
					
					if ($row_up > 0) {
						echo "true";
					} else {
						echo "false";
					}
				} catch(PDOException $pe) {
					trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
				}
				
			} catch(PDOException $pe) {
				trigger_error('Could not connect to MySQL database. ' . $pe->getMessage() , E_USER_ERROR);
			}
		}
	} else {
		// poruka nije poslana!!!!
		// dont do anything
	}
}

/*if (!function_exists('array_key_first')) {
	function array_key_first(array $array) { foreach ($array as $key => $value) { return $key; } }
}*/
?>