<?php
global $hooks;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

$hooks->add_action('silex_action','the_messenger'); 
function general_title(){
    echo "General Notification";
}
function help_title(){
    echo "Help Notification";
}
function order_title(){
    echo "Order Notification";
}

 
// Define the CSS 
function general_css() {
    ?>
	<link href="/assets/global/plugins/jstree/dist/themes/default/style.min.css" rel="stylesheet" type="text/css" />
    <?php
}
// Define the JS 
function general_js() {
    ?>
	<script src="/assets/global/plugins/jstree/dist/jstree.min.js" type="text/javascript"></script>
	<script src="/assets/modul-js/common/messenger/ui-tree.min.js" type="text/javascript"></script>
	<script src="/assets/modul-js/common/messenger/general.min.js" type="text/javascript"></script>
    <?php
}

// Define the CSS 
function help_css() {
    ?>
	<link href="/assets/global/plugins/jstree/dist/themes/default/style.min.css" rel="stylesheet" type="text/css" />
    <?php
}
// Define the JS 
function help_js() {
    ?>
	<script src="/assets/global/plugins/jstree/dist/jstree.min.js" type="text/javascript"></script>
	<script src="/assets/modul-js/common/messenger/ui-tree.min.js" type="text/javascript"></script>
	<script src="/assets/modul-js/common/messenger/help.min.js" type="text/javascript"></script>
    <?php
}
// Define the CSS 
function order_css() {
    ?>
	<link href="/assets/modul-js/common/messenger/emoji/css/jquery.emojipicker.css" rel="stylesheet" type="text/css" >
	<link href="/assets/modul-js/common/messenger/emoji/css/jquery.emojipicker.tw.css" rel="stylesheet" type="text/css" >
	<link href="/assets/global/plugins/dropzone/dropzone.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/dropzone/basic.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/bootstrap-wysihtml5/bootstrap-wysihtml5.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/bootstrap-datetimepicker/css/bootstrap-datetimepicker.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/bootstrap-editable/bootstrap-editable/css/bootstrap-editable.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/bootstrap-editable/inputs-ext/address/address.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/jstree/dist/themes/default/style.min.css" rel="stylesheet" type="text/css" />
    <?php
}
// Define the JS 
function order_js() {
    ?>
	<script src="/assets/global/plugins/jstree/dist/jstree.min.js" type="text/javascript"></script>
	<script src="/assets/modul-js/common/messenger/ui-tree.min.js" type="text/javascript"></script>
	<script src="/assets/modul-js/common/messenger/emoji/js/jquery.emojipicker.min.js" type="text/javascript" ></script>
    <script src="/assets/modul-js/common/messenger/emoji/js/jquery.emojis.min.js" type="text/javascript" ></script>
	<script src="/assets/global/plugins/bootstrap-editable/bootstrap-editable/js/bootstrap-editable.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/bootstrap-datetimepicker/js/bootstrap-datetimepicker.min.js" type="text/javascript"></script>
	<script src="/assets/global/scripts/components-date-time-pickers.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/bootstrap-editable/inputs-ext/address/address.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/bootstrap-editable/inputs-ext/wysihtml5/wysihtml5.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/jspdf.min.js"></script>
	<script src="/assets/modul-js/common/messenger/order.min.js?v=<?php echo rand();?>" type="text/javascript"></script>
    <?php
}

function the_messenger(){
	global $app;

	$app->get('/messenger/general', function (Request $request) {
		global $hooks;
		
		$hooks->add_action('the_title',"general_title");
		$hooks->add_action('global_css',"general_css");
		$hooks->add_action('global_js',"general_js");
		
		the_head();
		include 'general.tpl.php';
				
		the_footer();
		return "";
	}); 

	$app->post('/messenger/get-general', function (Request $request) {
		global $db;		
		$id = $request->get('id');
		include 'general.list.php';				
		return "";
	}); 
	
	
	$app->get('/messenger/help', function (Request $request) {
		global $hooks;
		
		$hooks->add_action('the_title',"help_title");
		$hooks->add_action('global_css',"help_css");
		$hooks->add_action('global_js',"help_js");
		
		the_head();
		include 'help.tpl.php';
				
		the_footer();
		return "";
	}); 
	$app->post('/messenger/get-help', function (Request $request) {
		global $db;		
		$id = $request->get('id');
		include 'help.list.php';				
		return "";
	}); 
	$app->post('/messenger/updateGroupName', function(Request $request) {		
		global $db;
		$chat_name = $request->get('value');
		$room_id = $request->get('pk');
		
		
		$db->bind("chat_name", $chat_name);
		$db->bind("room_id", $room_id);
		
		$updateGroupName  = $db->query("UPDATE `notice_rooms` SET `chat_name` = :chat_name WHERE room_id = :room_id");
		
		if ($updateGroupName) {
			return new Response("SUCCESS", 200);
		} else {			
			return new Response('FAILED', 201);
		}
	}); 
	$app->post('/messenger/send-help', function(Request $request) {		
		global $db;

		$user_id = $request->get('user_id');
		$text = $request->get('text');

		//create messages
		$db->bind("message", $text);
		$db->bind("chat_type", "1");
		$db->bind("from_id", $user_id);
		$createMessage  = $db->query("INSERT INTO notice_messages(message,chat_type,from_id) VALUES (:message,:chat_type,:from_id)");
		$message_id = $db->lastInsertId();
		
		//create room for user_id
		$db->bind("owner_id", $user_id);
		$checkRoom = $db->query("SELECT * FROM notice_rooms WHERE owner_id = :owner_id and room_type = 'help'");
		if(count($checkRoom) == 0){				
			$db->bind("owner_id", $user_id);
			$createRoom  = $db->query("INSERT INTO notice_rooms(chat_name,owner_id,room_type) VALUES ('Help', :owner_id, 'help')");
			$room_id = $db->lastInsertId();
		}else{
			$room_id = $checkRoom[0]["room_id"];
		} 
		
		//create members for room (current user)
		$db->bind("user_id", $user_id);
		$db->bind("room_id", $room_id);
		$checkMembers = $db->query("SELECT * FROM notice_members WHERE user_id = :user_id and room_id = :room_id");
		if(count($checkMembers) == 0){	
			$db->bind("user_id", $user_id);
			$db->bind("room_id", $room_id);
			$createMembers  = $db->query("INSERT INTO notice_members(room_id,user_id,status) VALUES (:room_id, :user_id, 1)");
		}
		
		//create members for room (administrator)
		$db->bind("user_id", "1");
		$db->bind("room_id", $room_id);
		$checkMembers = $db->query("SELECT * FROM notice_members WHERE user_id = :user_id and room_id = :room_id");
		if(count($checkMembers) == 0){	
			$db->bind("user_id", "1");
			$db->bind("room_id", $room_id);
			$createMembers  = $db->query("INSERT INTO notice_members(room_id,user_id,status) VALUES (:room_id, :user_id, 1)");
		}

		//connecting messages with room
		$db->bind("room_id", $room_id);
		$db->bind("message_id", $message_id);
		$createMembers  = $db->query("INSERT INTO notice_room_message(room_id,message_id) VALUES (:room_id, :message_id)");
		
		//create unread status
		$db->bind("room_id", $room_id);
		$db->bind("message_id", $message_id);
		$db->bind("user_id", "1");
		$createUnread  = $db->query("INSERT INTO notice_unread(room_id,message_id, user_id) VALUES (:room_id, :message_id, :user_id)");
		
		
		$html .= '<li class="out" id="cc" data-id="'.$message_id.'">';
		$html .= '<br>';
		$html .= '<img class="avatar" alt="" src="'. showImage($user_id).'">';
		$html .= '<div class="message">';
		$html .= '<div class="desc">'.$text;
		$html .= '<br/><span class="datetime"><a href="javascript:;">'.($_SESSION['user_id'] == 1 ? "Bot" : (getProfileData($user_id, "first_name") <> "" ? getProfileData($user_id, "first_name") : get_data($user_id, "username")))."</a> at ".date("H:i").'</span>'.'</div>';
		$html .= '</div>';
		$html .= '</li>';
	return $html;
	}); 
	

	$app->get('/messenger/order/{id}', function ($id) use ($app) {
		global $hooks;
		global $room_id;
		global $image;
		$room_id = $id;
		$image = showImage($_SESSION['user_id']);
		if (!roomIDExist($room_id) && !userInRoom($room_id, $_SESSION['user_id'])) {	
			unset($room_id);
            return $app->redirect('/messenger/general');
        }
		$hooks->add_action('the_title',"order_title");
		$hooks->add_action('global_css',"order_css");
		$hooks->add_action('global_js',"order_js");
		the_head();
		include 'order.tpl.php';
				
		the_footer();
		return "";
	}); 
	$app->post('/messenger/get-order', function (Request $request) {
		global $db;		
		$id = $request->get('id');
		$room_id = $request->get('room_id');
		include 'order.list.php';				
		return "";
	}); 
	$app->get('/messenger/order_list', function(Request $request)  {
        include 'order_list.php';
        return '';
    });
	$app->post('/messenger/send-order', function(Request $request) {		
		global $db;

		$user_id = $request->get('user_id');
		$text = $request->get('text');
		$room_id = $request->get('room_id');
		$reply_id = $request->get('reply_id');
		if($reply_id >= 0){
		}else{
			$reply_id  = NULL;
		}


		//create messages
		if($reply_id ){
			$db->bind("message", $text);
                        $db->bind("chat_type", "1");
                        $db->bind("from_id", $user_id);
			$db->bind("reply_id", $reply_id);
			$createMessage  = $db->query("INSERT INTO notice_messages(message,chat_type,from_id,reply_id) VALUES (:message,:chat_type,:from_id, :reply_id)");
		}else{
			$db->bind("message", $text);
                        $db->bind("chat_type", "1");
                        $db->bind("from_id", $user_id);
			$createMessage  = $db->query("INSERT INTO notice_messages(message,chat_type,from_id) VALUES (:message,:chat_type,:from_id)");
		}
		$message_id = $db->lastInsertId();
		
		//connecting messages with room
		$db->bind("room_id", $room_id);
		$db->bind("message_id", $message_id);
		$createMembers  = $db->query("INSERT INTO notice_room_message(room_id,message_id) VALUES (:room_id, :message_id)");
		
		//create unread status
		$MembersInRoom = getUserInRoom($room_id);
		foreach ($MembersInRoom as $key => $value){
			if($value['user_id'] <> $_SESSION['user_id']){
				$db->bind("room_id", $room_id);
				$db->bind("message_id", $message_id);
				$db->bind("user_id", $value['user_id']);
				$createMembers  = $db->query("INSERT INTO notice_unread(room_id,message_id,user_id, status) VALUES (:room_id, :message_id,:user_id, 0)");
			}
		}
		
		
		$html .= '<li class="out" id="cc" data-id="'.$message_id.'">';
		$html .= '<div class="mt-comment" style="background: #f9f9f9;border-radius: 10px !important;">
						<div class="mt-comment-img">
							<img class="avatar" alt="" src="'. showImage($_SESSION['user_id']).'"> 
						</div>
						<div class="mt-comment-body">
							<div class="mt-comment-info">
								<span class="mt-comment-author">'.($_SESSION['user_id'] == 1 ? "Bot" : (getProfileData($user_id, "first_name") <> "" ? getProfileData($user_id, "first_name") : get_data($user_id, "username"))).'</span>
								<span class="mt-comment-date">'.date("H:i").'</span>
							</div>
							<div class="mt-comment-text">'.$text .'</div>
							<div class="mt-comment-details">
								<ul class="mt-comment-actions">
									<li>
										<a style="text-transform:capitalize;" class="reply" data-reply_id="'.$message_id.'">Reply</a>
									</li>
									<li>
										<a style="text-transform:capitalize;" class="recall" data-reply_id="'.$message_id.'">Recall</a>
									</li>
								</ul>
							</div>
						</div>
					</div>';
		$html .= '</li>';
	return $html;
	}); 
	$app->post('/messenger/recall', function(Request $request) {		
		global $db;		
		$reply_id = $request->get('reply_id');
		$username = ($_SESSION['role'] == 0 ? $_SESSION['username'] : (getProfileData($_SESSION["user_id"], "first_name") <> "" ? getProfileData($_SESSION["user_id"], "first_name") : $_SESSION['username']));
		$message = $username . " have recalled a message.";
		$db->bind("message", $message);
		$db->bind("reply_id", $reply_id);
		$data  = $db->query("UPDATE  `notice_messages` SET message = :message, chat_type = 1, isRecall = 1, file = null, file_name = null, mime = null, decision_type = null, decision = 0, warehouse_arrangement_id = null WHERE message_id = :reply_id");
		
		if ($data) {
			return new Response("SUCCESS", 200);
		} else {			
			return new Response('FAILED', 201);
		} 
	}); 
	$app->post('/messenger/get-reply-content', function(Request $request) {		
		global $db;		
		$reply_id = $request->get('reply_id');
		$db->bind("reply_id", $reply_id);
		$data  = $db->query("SELECT notice_messages.file as file, notice_messages.file_name as file_name, notice_messages.message_id as message_id, notice_messages.message_id as message_id, notice_messages.message as message, notice_messages.from_id as from_id, notice_messages.created_on as created_on, notice_messages.chat_type as chat_type, notice_messages.mime as mime FROM `notice_messages` join notice_room_message on notice_messages.message_id = notice_room_message.message_id WHERE notice_messages.message_id = :reply_id");
		if($data[0]["from_id"] == $_SESSION['user_id'] ){
			$class="out";
		}else{
			$class="in";
		}
		$html = "";
		
			$html .= '<ul class="chats" id="reply_chat" data-reply_id="'.$reply_id.'" style="margin-bottom:10px;padding-top: 20px;">';
				$html .=	'<button type="button" class="close" id="close_reply" data-dismiss="alert" aria-hidden="true"></button><li class="'.$class.'">';
					$html .=	'<div class="mt-comment" style="background: #f9f9f9;border-radius: 20px !important;">';
					$html .=		'<div class="mt-comment-img">
										<img class="avatar" alt="" src="'.showImage($data[0]['from_id']).'"> 
									</div>';
					$html .=		'<div class="mt-comment-body">
										<div class="mt-comment-info">
											<span class="mt-comment-author">'.($data[0]['from_id'] == 1 ? "Bot" : getProfileData($data[0]['from_id'], "first_name")).'</span>
											<span class="mt-comment-date">'.date("H:i", strtotime($data[0]['created_on'])).'</span>
										</div>	
										<div class="mt-comment-text">'.$data[0]['message'].'</div>
									</div>';
					$html .=	'</div>
							</li>
						</ul>';
			$html .= '</div>';
				
				
		return $html;
	}); 
	
	
	$app->post('/messenger/add-member', function(Request $request) {
		global $db;
		$room_id = $request->get('room_id');
		$user_ids = $request->get('user_ids');

		foreach ($user_ids as $key => $user_id) {
			$db->bind("user_id", $user_id);
			$db->bind("room_id", $room_id);
			$db->bind("roles", "1");

			$createMembers  = $db->query("INSERT INTO notice_members(room_id,user_id,status, roles) VALUES (:room_id, :user_id, 1, :roles)");			
		}
		if ($createMembers) {
			return new Response("SUCCESS", 200);
		} else {			
			return new Response('FAILED', 201);
		} 
	}); 
	
	$app->post('/messenger/add-group', function(Request $request) {
		global $db;
		
		
		$so_id = $request->get('order_id');
		$chat_name = getSOData($so_id,"order_no");
		$owner_id = $_SESSION['user_id'];
		$room_type = "order";
		
		$db->bind("order_id", $so_id);
		$db->bind("chat_name",$chat_name);
		$db->bind("owner_id", $_SESSION['user_id']);
		$db->bind("room_type", "order");
		$createRoom  = $db->query("INSERT INTO notice_rooms(chat_name,owner_id,order_id,room_type) VALUES ( :chat_name, :owner_id, :order_id, :room_type)");
		
		$room_id = $db->lastInsertId();
		$user_ids = $request->get('user_ids');

		foreach ($user_ids as $key => $user_id) {
			$db->bind("user_id", $user_id);
			$db->bind("room_id", $room_id);
			$db->bind("roles", "0");

			$createMembers  = $db->query("INSERT INTO notice_members(room_id,user_id,status, roles) VALUES (:room_id, :user_id, 1, :roles)");
		}
		if ($createMembers) {
			return new Response("SUCCESS", 200);
		} else {			
			return new Response('FAILED', 201);
		} 
	}); 

	$app->post('/messenger/order/decision-request-update', function(Request $request) {		
		global $db;
		$message_id = $request->get('message_id');
		$decision = $request->get('decision');
		if( $request->get('reason') && $request->get('scheduled_date')){
			$reason = $request->get('reason');
			$scheduled_date = $request->get('scheduled_date');
		}

		if($request->get('id')){
			$DAID = $request->get('id');
			
		}
		
		$db->bind("message_id", $message_id);
		
		$data  = $db->query("SELECT * FROM `notice_room_message` WHERE message_id = :message_id");
		$room_id = $data[0]["room_id"];
		
		$db->bind("message_id", $message_id);
		$db->bind("decision", $decision);
		
		$data  = $db->query("UPDATE `notice_messages` SET decision = :decision WHERE message_id = :message_id");
		
		$decision_type = getMessageData($message_id, "decision_type");
		if($decision_type == 1){
			$warehouse_arrangement_id = getMessageData($message_id, "warehouse_arrangement_id");
			if($decision == 1){
				$db->bind("status", "2");
				$db->bind("warehouse_arrangement_id", $warehouse_arrangement_id);
				$data  = $db->query("UPDATE `warehouse_arrangements` SET status = :status WHERE id = :warehouse_arrangement_id");
			}else{
				$db->bind("status", "3");
				$db->bind("warehouse_arrangement_id", $warehouse_arrangement_id);
				$data  = $db->query("UPDATE `warehouse_arrangements` SET status = :status WHERE id = :warehouse_arrangement_id");
			}

			//create messages
			if($decision == 1){
				$text = (getProfileData($_SESSION['user_id'], "first_name") <>  "" ? getProfileData($_SESSION['user_id'], "first_name") : get_data($_SESSION['user_id'], "username")) . " have agreed to accept <a class='decision-request-details' data-id='".$warehouse_arrangement_id."' data-message_id='".$message_id."' data-decision='".$decision."'>this</a> decision request.";
			}else{
				$text = (getProfileData($_SESSION['user_id'], "first_name") <>  "" ? getProfileData($_SESSION['user_id'], "first_name") : get_data($_SESSION['user_id'], "username")) . " have agreed to declined <a class='decision-request-details' data-id='".$warehouse_arrangement_id."' data-message_id='".$message_id."' data-decision='".$decision."'>this</a> decision request.";
			}
			$db->bind("message", $text);
			$db->bind("chat_type", "1");
			$db->bind("from_id", $_SESSION['user_id']);
			$createMessage  = $db->query("INSERT INTO notice_messages(message,chat_type,from_id) VALUES (:message,:chat_type,:from_id)");
			
			$message_id = $db->lastInsertId();
			
			
			
			//connecting messages with room
			$db->bind("room_id", $room_id);
			$db->bind("message_id", $message_id);
			$createMembers  = $db->query("INSERT INTO notice_room_message(room_id,message_id) VALUES (:room_id, :message_id)");
			
			//create unread status
			$MembersInRoom = getUserInRoom($room_id);
			foreach ($MembersInRoom as $key => $value){
				if($value['user_id'] <> $_SESSION['user_id']){
					$db->bind("room_id", $room_id);
					$db->bind("message_id", $message_id);
					$db->bind("user_id", $value['user_id']);
					$createMembers  = $db->query("INSERT INTO notice_unread(room_id,message_id,user_id, status) VALUES (:room_id, :message_id,:user_id, 0)");
				}
			}
		}else{
			$delivery_arrangement_id = getMessageData($message_id, "delivery_arrangement_id");
			if($decision == 1){
				$db->bind("status", "2");
				$db->bind("delivery_arrangement_id", $delivery_arrangement_id);
				$data  = $db->query("UPDATE `delivery_arrangements` SET status = :status WHERE id = :delivery_arrangement_id");
				//create messages
			
				$text = (getProfileData($_SESSION['user_id'], "first_name") <>  "" ? getProfileData($_SESSION['user_id'], "first_name") : get_data($_SESSION['user_id'], "username")) . " have agreed to accept <a class='delivery-request-details' data-id='".$delivery_arrangement_id."' data-message_id='".$message_id."' data-decision='".$decision."'>this</a> decision request.";
			
				$db->bind("message", $text);
				$db->bind("chat_type", "1");
				$db->bind("from_id", $_SESSION['user_id']);
				$createMessage  = $db->query("INSERT INTO notice_messages(message,chat_type,from_id) VALUES (:message,:chat_type,:from_id)");
				
				$message_id = $db->lastInsertId();
				
				//connecting messages with room
				$db->bind("room_id", $room_id);
				$db->bind("message_id", $message_id);
				$createMembers  = $db->query("INSERT INTO notice_room_message(room_id,message_id) VALUES (:room_id, :message_id)");
				
				//create unread status
				$MembersInRoom = getUserInRoom($room_id);
				foreach ($MembersInRoom as $key => $value){
					if($value['user_id'] <> $_SESSION['user_id']){
						$db->bind("room_id", $room_id);
						$db->bind("message_id", $message_id);
						$db->bind("user_id", $value['user_id']);
						$createMembers  = $db->query("INSERT INTO notice_unread(room_id,message_id,user_id, status) VALUES (:room_id, :message_id,:user_id, 0)");
					}
				}
				
				//create messages
				$db->bind("message", "Have you received your goods?");
				$db->bind("chat_type", "13");
				$db->bind("decision", 0);
				$db->bind("decision_type", 1);
				$db->bind("delivery_arrangement_id", $delivery_arrangement_id);
				$db->bind("from_id", $_SESSION['user_id']);
				$createMessage  = $db->query("INSERT INTO notice_messages(message,chat_type,from_id, decision, decision_type, delivery_arrangement_id) VALUES (:message,:chat_type,:from_id, :decision, :decision_type, :delivery_arrangement_id)");
				$message_id = $db->lastInsertId();
								
				//connecting messages with room
				$db->bind("room_id", $room_id);
				$db->bind("message_id", $message_id);
				$createMembers  = $db->query("INSERT INTO notice_room_message(room_id,message_id) VALUES (:room_id, :message_id)");
			}else{
				$db->bind("status", "5");
				$db->bind("delivery_arrangement_id", $delivery_arrangement_id);
				$data  = $db->query("UPDATE `delivery_arrangements` SET status = :status WHERE id = :delivery_arrangement_id");
				
				//create messages
				$text = (getProfileData($_SESSION['user_id'], "first_name") <>  "" ? getProfileData($_SESSION['user_id'], "first_name") : get_data($_SESSION['user_id'], "username")) . " have agreed to accept <a class='delivery-request-details' data-id='".$delivery_arrangement_id."' data-message_id='".$message_id."' data-decision='".$decision."'>this</a> decision request.";
				
				$db->bind("message", $text);
				$db->bind("chat_type", "1");
				$db->bind("from_id", $_SESSION['user_id']);
				$createMessage  = $db->query("INSERT INTO notice_messages(message,chat_type,from_id) VALUES (:message,:chat_type,:from_id)");
				
				$message_id = $db->lastInsertId();
				
				//connecting messages with room
				$db->bind("room_id", $room_id);
				$db->bind("message_id", $message_id);
				$createMembers  = $db->query("INSERT INTO notice_room_message(room_id,message_id) VALUES (:room_id, :message_id)");
				
				//create unread status
				$MembersInRoom = getUserInRoom($room_id);
				foreach ($MembersInRoom as $key => $value){
					if($value['user_id'] <> $_SESSION['user_id']){
						$db->bind("room_id", $room_id);
						$db->bind("message_id", $message_id);
						$db->bind("user_id", $value['user_id']);
						$createMembers  = $db->query("INSERT INTO notice_unread(room_id,message_id,user_id, status) VALUES (:room_id, :message_id,:user_id, 0)");
					}
				}
			}
			
		}
		
		
		return new Response("SUCCESS", 200);
	
	});
	$app->post('/messenger/order/get-warehouse-arrangement', function(Request $request) {		
		global $db;
		$warehouse_arrangement_id = $request->get('id');
		$message_id = $request->get('message_id');
		$html = '
		<div class="portlet light"><table class="warehouse-arrangement table table-striped table-bordered nowrap" data-message_id="'.$message_id.'" cellspacing="0" width="100%">
			<thead>
				<tr>
					<th> No   		          </th>
					<th> Description          </th>
					<th> Total Ctn (Nominal)  </th>
					<th> Total Ctn (Actual)   </th>
					<th> CBM (Nominal)		  </th>
					<th> CBM (Actual) 		  </th>
					<th> Weight (Nominal)     </th>
					<th> Weight (Actual)      </th>
					<th> Status           	  </th>
					<th> Photo           	  </th>
				</tr>
			</thead>
			<tbody>';
		$WAItems = getWAItems(getWADatafromWAID($warehouse_arrangement_id, "so_id")); $x = 1;
		foreach($WAItems as $key => $WAItem){ 
			$html .= 
			($WAItem['status'] == 1 ? "<tr class='eror'>" : "<tr>")
				."<td>".$x."</td>
				<td>".getSOItem($WAItem['so_item_id'], "description")."</td>
				<td>".getSOItem($WAItem['so_item_id'], "packaging_quantity")."</td>
				<td>".$WAItem['actual_ctn']."</td>
				<td>".getSOItem($WAItem['so_item_id'], 'packaging_height') . "x" . getSOItem($WAItem['so_item_id'], 'packaging_width') . "x" . getSOItem($WAItem['so_item_id'], 'packaging_depth')."</td>
				<td>".$WAItem['actual_height_ctn'] . "x" . $WAItem['actual_width_ctn'] . "x" . $WAItem['actual_depth_ctn']."</td>
				<td>".getSOItem($WAItem['so_item_id'], "packaging_gross")."</td>
				<td>".$WAItem['actual_weight_ctn']."</td>
				<td>".($WAItem['status'] == 1 ? "<span class='font-red bold'>Unmatched</span>" : "Matched")."</td>
				<td><img style='max-width: 100px; max-height: 100px;' src='". ($WAItem['image'] <> null ? $WAItem['image'] : "http://www.placehold.it/200/EFEFEF/AAAAAA&amp;text=no+image") ."'></td>
			</tr>";
			 $x++; 			
		 } 
		 
		 $html .=			'</tbody>
						</table></div>
						<div class="form-group">
							<label class="control-label col-md-2">Instruction :</label>
							<div class="col-md-9">
								<p class="form-control-static">'.getWADatafromWAID($warehouse_arrangement_id,"remarks").'</p>
							</div>
						</div>';
		 return($html);
	});
	$app->post('/messenger/order/get-delivery-arrangement', function(Request $request) {		
		global $db;
		$delivery_arrangement_id = $request->get('id');
		$message_id = $request->get('message_id');
		$delivery_type = getDADataFromDAID($delivery_arrangement_id, "delivery_type");
		if(getDADataFromDAID($delivery_arrangement_id, "delivery_type") == 1){ 
			$delivery_type = "Inhouse Services"; 
		}elseif(getDADataFromDAID($delivery_arrangement_id, "delivery_type") == 2){ 
			$delivery_type = "Courier Services"; 
		}elseif(getDADataFromDAID($delivery_arrangement_id, "delivery_type") == 3){ 
			$delivery_type = "Outsource Services"; 
		}elseif(getDADataFromDAID($delivery_arrangement_id, "delivery_type") == 4){
			$delivery_type = "Self Collect"; 
		}
		$html = "";
		$html .= '
		<h3 class="form-section">Delivery Arrangement Details</h3>
						<div class="row">
							<div class="col-md-6">
								<div class="form-group">
									<label class="control-label col-md-4">Delivery Type :</label>
									<div class="col-md-8">
										<p class="form-control-static">'. $delivery_type .'</p>
									</div>
								</div>
							</div>
						</div><div class="row">';
		if(getDADataFromDAID($delivery_arrangement_id, "delivery_type") == 1 || getDADataFromDAID($delivery_arrangement_id, "delivery_type") == 3 ){ 
		$html .= '
				<div class="col-md-6">
					<div class="form-group">
						<label class="control-label col-md-4">Delivery Date :</label>
						<div class="col-md-8">
							<p class="form-control-static"> '. getDADataFromDAID($delivery_arrangement_id, "delivery_date").' </p>
						</div>
					</div>
					<div class="form-group">
						<label class="control-label col-md-4">Driver Name:</label>
						<div class="col-md-8">
							<p class="form-control-static"> '. getDADataFromDAID($delivery_arrangement_id, "driver_contact_person").' </p>
						</div>
					</div>
				</div>
				<div class="col-md-6">
					<div class="form-group">
						<label class="control-label col-md-4">Driver Contact:</label>
						<div class="col-md-8">
							<p class="form-control-static"> '. getDADataFromDAID($delivery_arrangement_id, "driver_contact_person_no").' </p>
						</div>
					</div>
					<div class="form-group">
						<label class="control-label col-md-4">Vehicle No:</label>
						<div class="col-md-8">
							<p class="form-control-static"> '. getDADataFromDAID($delivery_arrangement_id, "vehicle_no").' </p>
						</div>
					</div>
				</div>';
		}elseif(getDADataFromDAID($delivery_arrangement_id, "delivery_type") == 2){
			$html .= '
				<div class="col-md-6">
					<div class="form-group">
						<label class="control-label col-md-4">Courier Service:</label>
						<div class="col-md-8">
							<p class="form-control-static"> '. getDADataFromDAID($delivery_arrangement_id, "courier_service_name").' </p>
						</div>
					</div>
				</div>
				<div class="col-md-6">
					<div class="form-group">
						<label class="control-label col-md-4">Tracking No:</label>
						<div class="col-md-8">
							<p class="form-control-static"> '. getDADataFromDAID($delivery_arrangement_id, "tracking_no").' </p>
						</div>
					</div>
				</div>';
		}elseif(getDADataFromDAID($delivery_arrangement_id, "delivery_type") == 4){ 
			$html .= '
				<div class="col-md-6">
					<div class="form-group">
						<label class="control-label col-md-4">Warehouse:</label>
						<div class="col-md-8">
							<p class="form-control-static"> '. get_warehouse(getDADataFromDAID($delivery_arrangement_id, "warehouse_id"), "warehouse_name").' </p>
						</div>
					</div>
					<div class="form-group">
						<label class="control-label col-md-4">Contact Person:</label>
						<div class="col-md-8">
							<p class="form-control-static"> '. getDADataFromDAID($delivery_arrangement_id, "warehouse_contact_person").' </p>
						</div>
					</div>
					<div class="form-group">
						<label class="control-label col-md-4">Contact Person No:</label>
						<div class="col-md-8">
							<p class="form-control-static"> '. getDADataFromDAID($delivery_arrangement_id, "warehouse_contact_person_no").' </p>
						</div>
					</div>
				</div>
				<div class="col-md-6">
					<div class="form-group">
						<label class="control-label col-md-4">Address:</label>
						<div class="col-md-8">
							<p class="form-control-static"> '. getDADataFromDAID($delivery_arrangement_id, "warehouse_address").' </p>
						</div>
					</div>
					<div class="form-group">
						<label class="control-label col-md-4">City:</label>
						<div class="col-md-8">
							<p class="form-control-static"> '. getDADataFromDAID($delivery_arrangement_id, "warehouse_zip").'  '. getDADataFromDAID($delivery_arrangement_id, "warehouse_city").' </p>
						</div>
					</div>
					<div class="form-group">
						<label class="control-label col-md-4">State:</label>
						<div class="col-md-8">
							<p class="form-control-static"> '. getDADataFromDAID($delivery_arrangement_id, "warehouse_state").' </p>
						</div>
					</div>
				</div>';
		}
		$html .= '</div>';
		return($html);
	});
	$app->post('/messenger/get-staff', function(Request $request) {		
		global $db;
		$room_id = $request->get('room_id');
		$branch_id = $_SESSION['branch_id'];
		$company_id = $_SESSION['company_id'];
		$current_user = $_SESSION['user_id'];
		$a = 0;
		
		// $db->bind("company_id", $company_id);
		// $db->bind("branch_id", $branch_id);
		$db->bind("room_id", $room_id);
		$db->bind("current_user", $current_user);
		
		// $data  = $db->query("SELECT * FROM `user_company` WHERE branch_id = :branch_id and company_id = :company_id and user_id not in (select user_id from notice_members where room_id = :room_id) and user_id <> :current_user");
		$data  = $db->query("SELECT * FROM `user_friend` WHERE friend_id not in (select user_id from notice_members where room_id = :room_id) and user_id = :current_user");
		
		if(count($data) == 0){	
			$table = "<table class='table table-striped table-bordered table-hover dataTable no-footer'>
						<thead>
							<tr>
								<th>Name</th>
								<th>Mobile Number</th>
								<th>Selection</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td colspan='3'><center>No data available</center></td>
							</tr>
						</tbody>
					  </table>";
		}else{
			$table = "<input style='display:none;' name='room_id' id='room_id' value='".$room_id."'>
					  <table class='table table-striped table-bordered table-hover dataTable no-footer'>
						<thead>
							<tr>
								<th>Name</th>
								<th>Mobile Number</th>
								<th>Selection</th>
							</tr>
						</thead>
						<tbody>";
							foreach($data as $key => $value){
								if(get_data($value['friend_id'], "group_id") == get_data($value['user_id'], "group_id")){
									$table .= "<tr>
											<td>".getProfileData($value['friend_id'], "first_name") . " " . getProfileData($value['friend_id'], "last_name")."</td>
											<td>".get_data($value['friend_id'], "username")."</td>
											<td><div style='padding-top: 0px;padding-bottom: 0px;' class='mt-checkbox-list'><label class='mt-checkbox mt-checkbox-outline' style='margin-bottom: 0px;'><input style='margin-top: 0px;' type='checkbox' id='user_ids' name='user_ids[]' value=".$value['friend_id']."><span></span></label></div></td>
											</tr>";
									$a++;
								}
							}
							if($a == 0){
								$table .= "<tr><td  colspan='3'><center>No data available</center></td></tr>"; 
							}
			$table .=   "</tbody>
					  </table>";
			
		}
		return $table;
	}); 
	
	$app->post('/messenger/get-all-staff', function(Request $request) {		
		global $db;
		
		$room_id = $request->get('room_id');
		$so_id = getRoomData($room_id, "order_id");
		if($_SESSION['role'] == 1){
			$importer_id = getSOData(getRoomData($room_id, "order_id"), "company_id");
			$importer_branch_id = getSOData(getRoomData($room_id, "order_id"), "branch_id");
			$forwarder_id = getSOData(getRoomData($room_id, "order_id"), "forwarder_id");
		}
		
		$db->bind("importer_id", $importer_id);
		$db->bind("importer_branch_id", $importer_branch_id);
		$db->bind("forwarder_id", $forwarder_id);
		
		$data  = $db->query("SELECT * FROM `user_company` WHERE company_id = :forwarder_id or (company_id = :importer_id or branch_id =:importer_branch_id)");
		
		if(count($data) == 0){	
			$table = "<table class='table table-striped table-bordered table-hover dataTable no-footer'>
						<thead>
							<tr>
								<th>Name</th>
								<th>Mobile Number</th>
								<th>Selection</th>
							</tr>
						</thead>
						<tbody>
							<tr>
								<td colspan='3'><center>No data available</center></td>
							</tr>
						</tbody>
					  </table>";
		}else{
			$table = "<input style='display:none;' name='order_id' id='order_id' value='".$so_id."'>
					  <table class='table table-striped table-bordered table-hover dataTable no-footer'>
						<thead>
							<tr>
								<th>Name</th>
								<th>Mobile Number</th>
								<th>Selection</th>
							</tr>
						</thead>
						<tbody>";
							foreach($data as $key => $value){
							$table .= "<tr>
										<td>".getProfileData($value['user_id'], "first_name") . " " . getProfileData($value['user_id'], "last_name")."</td>
										<td>".get_data($value['user_id'], "username")."</td>
										<td><div style='padding-top: 0px;padding-bottom: 0px;' class='mt-checkbox-list'><label class='mt-checkbox mt-checkbox-outline' style='margin-bottom: 0px;'><input style='margin-top: 0px;' type='checkbox' id='user_ids' name='user_ids[]' value=".$value['user_id']."><span></span></label></div></td>
									   </tr>";
							}
			$table .=   "</tbody>
					  </table>";
			
		}
		return $table;
	}); 
	
	$app->post('/messenger/send-file', function(Request $request) {		
		global $db;

		$user_id = $request->get('user_id');
		$file = $request->get('file');
		$file_name = $request->get('file_name');
		$mime = $request->get('mime');
		$room_id = $request->get('room_id');
		$text = (getProfileData($user_id, "first_name") <>  "" ? getProfileData($user_id, "first_name") : get_data($user_id, "username")) . " has uploaded " .$file_name;
		
		if($mime == "image/aces" || $mime == "image/cis-cod" || $mime == "image/x-icon" || $mime == "image/x-portable-anymap" || $mime == "image/x-portable-bitmap" || $mime == "image/x-portable-graymap" || $mime == "image/x-cmu-raster" || $mime == "image/tiff" || $mime == "image/pipeg" || $mime == "image/bmp" || $mime == "image/cgm" || $mime == "image/dicom-rle" || $mime == "image/emf" || $mime == "image/example" || $mime == "image/fits" || $mime == "image/g3fax" || $mime == "image/gif" || $mime == "image/ief" || $mime == "image/jls" || $mime == "image/jp2" || $mime == "image/jpg" || $mime == "image/jpeg" || $mime == "image/jpm" || $mime == "image/jpx" || $mime == "image/ktx" || $mime == "image/naplps" || $mime == "image/png" || $mime == "image/prs.btif" || $mime == "image/prs.pti" || $mime == "image/pwg-raster" || $mime == "image/svg+xml" || $mime == "image/t38" || $mime == "image/tiff" || $mime == "image/tiff-fx" || $mime == "image/vnd.adobe.photoshop" || $mime == "image/vnd.airzip.accelerator.azv" || $mime == "image/vnd.cns.inf2" || $mime == "image/vnd.dece.graphic" || $mime == "image/vnd-djvu" || $mime == "image/vnd.dwg" || $mime == "image/vnd.dxf" || $mime == "image/vnd.dvb.subtitle" || $mime == "image/vnd.fastbidsheet" || $mime == "image/vnd.fpx" || $mime == "image/vnd.fst" || $mime == "image/vnd.fujixerox.edmics-mmr" || $mime == "image/vnd.fujixerox.edmics-rlc" || $mime == "image/vnd.globalgraphics.pgb" || $mime == "image/vnd.microsoft.icon" || $mime == "image/vnd.mix" || $mime == "image/vnd.ms-modi" || $mime == "image/vnd.mozilla.apng" || $mime == "image/vnd.net-fpx" || $mime == "image/vnd.radiance" || $mime == "image/vnd.sealed-png" || $mime == "image/vnd.sealedmedia.softseal-gif" || $mime == "image/vnd.sealedmedia.softseal-jpg" || $mime == "image/vnd-svf" || $mime == "image/vnd.tencent.tap" || $mime == "image/vnd.valve.source.texture" || $mime == "image/vnd-wap-wbmp" || $mime == "image/vnd.xiff" || $mime == "image/vnd.zbrush.pcx" || $mime == "image/wmf" || $mime == "image/emf" || $mime == "image/wmf"){
			//image
			$chat_type = "2";
		}elseif($mime == "application/msword" || $mime == "application/pdf" || $mime == "application/vnd.ms-excel.addin.macroEnabled.12" || $mime == "application/vnd.ms-excel.sheet.binary.macroEnabled.12" || $mime == "application/vnd.ms-excel.sheet.macroEnabled.12" || $mime == "application/vnd.ms-excel.template.macroEnabled.12" || $mime == "application/vnd.ms-excel" || $mime == "application/vnd.ms-powerpoint.addin.macroEnabled.12" || $mime == "application/vnd.ms-powerpoint.presentation.macroEnabled.12" || $mime == "application/vnd.ms-powerpoint.slideshow.macroEnabled.12" || $mime == "application/vnd.ms-powerpoint" || $mime == "application/vnd.ms-word.document.macroEnabled.12" || $mime == "application/vnd.ms-word.template.macroEnabled.12" || $mime == "application/vnd.openxmlformats-officedocument.presentationml.presentation" || $mime == "application/vnd.openxmlformats-officedocument.presentationml.slideshow" || $mime == "application/vnd.openxmlformats-officedocument.presentationml.template" || $mime == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" || $mime == "application/vnd.openxmlformats-officedocument.spreadsheetml.template" || $mime == "application/vnd.openxmlformats-officedocument.wordprocessingml.document" || $mime == "application/vnd.openxmlformats-officedocument.wordprocessingml.template" || $mime == "application/x-7z-compressed" || $mime == "application/x-rar-compressed" || $mime == "application/zip" || $mime == "text/csv"){
			//document
			$chat_type = "3";
		}elseif($mime == "audio/basic" || $mime == "audio/basic" || $mime == "audio/mid" || $mime == "audio/mid" || $mime == "audio/mpeg" || $mime == "audio/x-aiff" || $mime == "audio/x-aiff" || $mime == "audio/x-aiff" || $mime == "audio/x-mpegurl" || $mime == "audio/x-pn-realaudio" || $mime == "audio/x-pn-realaudio" || $mime == "audio/x-wav"){
			//audio
			$chat_type = "4";
		}elseif($mime == "video/mpeg" || $mime == "video/mp4" || $mime == "video/quicktime" || $mime == "video/x-la-asf" || $mime == "video/x-ms-asf" || $mime == "video/x-msvideo" || $mime == "video/x-sgi-movie" || $mime == "video/x-flv" || $mime == "video/3gpp" || $mime == "video/x-ms-wmv"){
			//video
			$chat_type = "5";
		}else{
			$chat_type = "999";
		}

		//create messages
		$db->bind("message", $text);
		$db->bind("file", $file);
		$db->bind("file_name", $file_name);
		$db->bind("mime", $mime);
		$db->bind("chat_type", $chat_type);
		$db->bind("from_id", $user_id);
		
		$createMessage  = $db->query("INSERT INTO notice_messages(message,file,file_name,mime,chat_type,from_id) VALUES (:message,:file,:file_name,:mime,:chat_type,:from_id)");
		$message_id = $db->lastInsertId();
		
		//connecting messages with room
		$db->bind("room_id", $room_id);
		$db->bind("message_id", $message_id);
		$createMembers  = $db->query("INSERT INTO notice_room_message(room_id,message_id) VALUES (:room_id, :message_id)");
		
		//create unread status
		$MembersInRoom = getUserInRoom($room_id);
		foreach ($MembersInRoom as $key => $value){
			$db->bind("room_id", $room_id);
			$db->bind("message_id", $message_id);
			$db->bind("user_id", $value['user_id']);
			$createMembers  = $db->query("INSERT INTO notice_unread(room_id,message_id,user_id, status) VALUES (:room_id, :message_id,:user_id, 0)");
		}
		
		if($chat_type == "2"){
			$html .= '<li class="out" id="cc" data-id="'.$message_id.'">';
			$html .= '<div class="mt-comment" style="background: #f9f9f9;border-radius: 10px !important;">
							<div class="mt-comment-img">
								<img class="avatar" alt="" src="'. showImage($_SESSION['user_id']).'"> 
							</div>
							<div class="mt-comment-body">
								<div class="mt-comment-info">
									<span class="mt-comment-author">'.($_SESSION['user_id'] == 1 ? "Bot" : (getProfileData($user_id, "first_name") <> "" ? getProfileData($user_id, "first_name") : get_data($user_id, "username"))).'</span>
									<span class="mt-comment-date">'.date("H:i").'</span>
								</div>
								<div class="mt-comment-text">'.$text .'</div>								
								<div class="mt-comment-text">><a href="'.$file .'" download="'.$file_name.'"><img src="'.$file .'" style="max-width:300px; height: auto;" /></a></div>
								<div class="mt-comment-details">
									<ul class="mt-comment-actions">
										<li>
											<a style="text-transform:capitalize;" class="recall" data-reply_id="'.$message_id.'">Recall</a>
										</li>
									</ul>
								</div>
							</div>
						</div>';
			$html .= '</li>';
		}elseif($chat_type == "3"){
			$html .= '<li class="out" id="cc" data-id="'.$message_id.'">';
			$html .= '<div class="mt-comment" style="background: #f9f9f9;border-radius: 10px !important;">
							<div class="mt-comment-img">
								<img class="avatar" alt="" src="'. showImage($_SESSION['user_id']).'"> 
							</div>
							<div class="mt-comment-body">
								<div class="mt-comment-info">
									<span class="mt-comment-author">'.($_SESSION['user_id'] == 1 ? "Bot" : (getProfileData($user_id, "first_name") <> "" ? getProfileData($user_id, "first_name") : get_data($user_id, "username"))).'</span>
									<span class="mt-comment-date">'.date("H:i").'</span>
								</div>
								<div class="mt-comment-text">'.$text .'</div>								
								<div class="mt-comment-text"><a id="dwnldLnk" download="'.$file_name.'" href="'.$file.'"> Download </a> </div>
								<div class="mt-comment-details">
									<ul class="mt-comment-actions">
										<li>
											<a style="text-transform:capitalize;" class="recall" data-reply_id="'.$message_id.'">Recall</a>
										</li>
									</ul>
								</div>
							</div>
						</div>';
			$html .= '</li>';
		}elseif($chat_type == "4"){
			$html .= '<li class="out" id="cc" data-id="'.$message_id.'">';
			$html .= '<div class="mt-comment" style="background: #f9f9f9;border-radius: 10px !important;">
							<div class="mt-comment-img">
								<img class="avatar" alt="" src="'. showImage($_SESSION['user_id']).'"> 
							</div>
							<div class="mt-comment-body">
								<div class="mt-comment-info">
									<span class="mt-comment-author">'.($_SESSION['user_id'] == 1 ? "Bot" : (getProfileData($user_id, "first_name") <> "" ? getProfileData($user_id, "first_name") : get_data($user_id, "username"))).'</span>
									<span class="mt-comment-date">'.date("H:i").'</span>
								</div>
								<div class="mt-comment-text">'.$text .'</div>								
								<div class="mt-comment-text">
									<audio controls>
										<source src="'.$file.'" type="'.$mime.'">
										Your browser does not support the audio element.
									</audio>
								</div>
								<div class="mt-comment-details">
									<ul class="mt-comment-actions">
										<li>
											<a style="text-transform:capitalize;" class="recall" data-reply_id="'.$message_id.'">Recall</a>
										</li>
									</ul>
								</div>
							</div>
						</div>';
			$html .= '</li>';
		}elseif($chat_type == "5"){
			$html .= '<li class="out" id="cc" data-id="'.$message_id.'">';
			$html .= '<div class="mt-comment" style="background: #f9f9f9;border-radius: 10px !important;">
							<div class="mt-comment-img">
								<img class="avatar" alt="" src="'. showImage($_SESSION['user_id']).'"> 
							</div>
							<div class="mt-comment-body">
								<div class="mt-comment-info">
									<span class="mt-comment-author">'.($_SESSION['user_id'] == 1 ? "Bot" : (getProfileData($user_id, "first_name") <> "" ? getProfileData($user_id, "first_name") : get_data($user_id, "username"))).'</span>
									<span class="mt-comment-date">'.date("H:i").'</span>
								</div>
								<div class="mt-comment-text">'.$text .'</div>								
								<div class="mt-comment-text">
									<video width="320" height="240" controls>
										<source src="'.$file.'" type="'.$mime.'">
										Your browser does not support the video tag.
									</video>
								</div>
								<div class="mt-comment-details">
									<ul class="mt-comment-actions">
										<li>
											<a style="text-transform:capitalize;" class="recall" data-reply_id="'.$message_id.'">Recall</a>
										</li>
									</ul>
								</div>
							</div>
						</div>';
			$html .= '</li>';
		}
	return $html;
	}); 
}

include 'messenger.func.php';
