$query = 'SELECT fl.user_id, fl.friend_id, fl.status frnstatus, fl.date_created, fl.status-1 as frnstatus2,
(CASE WHEN (u.logintime < (SELECT datecreated
FROM tbl_message
WHERE (receiver_id = '.$parameters[0]->user_id.' AND sender_id=fl.friend_id) ORDER BY datecreated DESC LIMIT 1)) THEN "1" ELSE "0" END) as LiveChatTime,
(SELECT COUNT(*) FROM tbl_message WHERE (receiver_id = '.$parameters[0]->user_id.' AND sender_id=fl.friend_id) AND is_read="0") AS TotalUnreadMsg,
u.user_name, u.imageurl, u.date_birth,u.status, u.status_field,
(1.60934*(3959 * ACOS(COS(RADIANS('.$parameters[0]->latitude.')) * COS(RADIANS(u.curlat)) * COS(RADIANS(u.curlon) - RADIANS('.$parameters[0]->longitude.')) +
SIN(RADIANS('.$parameters[0]->latitude.')) * SIN(RADIANS(u.curlat)) ))) AS distance
FROM tbl_friendlist fl
INNER JOIN users u ON (fl.friend_id=u.user_id)
WHERE fl.user_id = '.$parameters[0]->user_id.' AND fl.is_block<>1
AND u.invisible NOT IN (2, 3)'.$search.'
UNION
SELECT f2.user_id, f2.friend_id, f2.status AS frnstatus, f2.date_created, f2.status AS frnstatus2,
(CASE WHEN (u.logintime < (SELECT datecreated
FROM tbl_message
WHERE (receiver_id = '.$parameters[0]->user_id.' AND sender_id=f2.user_id) ORDER BY datecreated DESC LIMIT 1)) THEN "1" ELSE "0" END) as LiveChatTime,
(SELECT COUNT(*) FROM tbl_message WHERE (receiver_id = '.$parameters[0]->user_id.' AND sender_id=f2.user_id) AND is_read="0") AS TotalUnreadMsg,
u.user_name, u.imageurl, u.date_birth,u.status AS online, u.status_field,
(1.60934*(3959 * ACOS(COS(RADIANS('.$parameters[0]->latitude.')) * COS(RADIANS(u.curlat)) * COS(RADIANS(u.curlon) - RADIANS('.$parameters[0]->longitude.')) +
SIN(RADIANS('.$parameters[0]->latitude.')) * SIN(RADIANS(u.curlat)) ))) AS distance
FROM tbl_friendlist f2
INNER JOIN users u ON (f2.user_id=u.user_id)
WHERE f2.friend_id = '.$parameters[0]->user_id.' AND f2.is_block<>1
AND u.invisible NOT IN (2, 3)'.$search.'
ORDER BY frnstatus2 DESC, TotalUnreadMsg DESC, LiveChatTime DESC, distance ASC
LIMIT ' . $limit . '
OFFSET ' . $offset;