<?php
global $hooks;
	
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$hooks->add_action('silex_action','the_delivery_arrangement'); 
function create_delivery_arrangement_title(){
    echo "Delivery Receive Note";
}


function create_delivery_arrangement_css() {
	?>
	<link href="/assets/global/plugins/bootstrap-daterangepicker/daterangepicker.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/bootstrap-datepicker/css/bootstrap-datepicker3.min.css" rel="stylesheet" type="text/css" />
    <link href="/assets/global/plugins/select2/css/select2.min.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/select2/css/select2-bootstrap.min.css" rel="stylesheet" type="text/css" />
    <?php
}

function create_delivery_arrangement_js() {
	?>
	<script src="/assets/global/plugins/select2/js/select2.full.min.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/jquery-validation/js/additional-methods.min.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/bootstrap-wizard/jquery.bootstrap.wizard.min.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/jquery-repeater/jquery.repeater.js" type="text/javascript"></script>
	<script src="/assets/global/scripts/datatable.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/datatables/datatables.min.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/datatables/plugins/bootstrap/datatables.bootstrap.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/bootstrap-daterangepicker/daterangepicker.min.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/bootstrap-timepicker/js/bootstrap-timepicker.min.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/plugins/clockface/js/clockface.js" type="text/javascript"></script>
	<script src="/assets/modul-js/arrangements/delivery-arrangement/create.min.js" type="text/javascript"></script>
 <?php
} 

function the_delivery_arrangement(){
	global $app;
	
	$app->get('/delivery-arrangements', function(){ 
		global $hooks;
		global $app;
		
		$hooks->add_action('global_css',"create_delivery_arrangement_css");
		$hooks->add_action('global_js',"create_delivery_arrangement_js");
		$hooks->add_action('the_title',"create_delivery_arrangement_title");
	
		the_head();
		include 'delivery.tpl.php';
		the_footer();
	
	
		return "";
	}); 
	
	$app->post('/delivery-arrangements/list', function(Request $request)  {
		$curpage = $request->get('page');
        include 'delivery.list.php';
        return '';
    }); 
	$app->post('/delivery-arrangements/getwarehousedata', function(Request $request) {		
		global $db;
		$warehouse_id = $request->get('warehouse_id');
		$db->bind("warehouse_id",$warehouse_id);
		
		$data = $db->query("SELECT * FROM warehouses WHERE warehouse_id = :warehouse_id");
		
		$output_array = array();

		foreach($data as $row) {
			$output_array[] = array( 'warehouse_id' => $row['warehouse_id'], 'name' => $row['name'], 'address' => $row['address'] , 'zip' =>  $row['zip'] , 'city' => $row['city'] , 'state' =>  $row['state'], 'country' =>  $row['country'], 'contact_person' =>  $row['contact_person'], 'contact_person_no' =>  $row['contact_person_no']);
		}

		return json_encode( $output_array );
	}); 
	
	$app->post('/delivery-arrangements/getOrderSelection', function(Request $request) {		
			global $db;
			
			$db->bind("company_id", $_SESSION['company_id']);
			$orderselections = $db->query("SELECT * FROM shipping_orders where forwarder_id = :company_id and (so_id in (select so_id from shipment_arrangement_items where 1) and so_id not in (select so_id from delivery_arrangement_items where 1))");
			$table = "";
			
			foreach ($orderselections as $key => $orderselection){
				$table .= "<tr>"
							."<td>".  date('d/m/Y', strtotime(getSAData($orderselection['so_id'], "eta"))). "</td>"
							."<td>".getSAData($orderselection['so_id'], "shipment_no")."</td>"
							."<td>".$orderselection['marking_no']."</td>"
							."<td>".get_branch($orderselection['branch_id'], "branch_address") . ",<br/> " 
								   .get_branch($orderselection['branch_id'], "branch_zip"). " " 
								   .get_branch($orderselection['branch_id'], "branch_city"). ",<br/> "
								   .get_branch($orderselection['branch_id'], "branch_state").", " 
								   .get_branch($orderselection['branch_id'], "branch_country")
						   ."</td>"
						   ."<td>CBM : ".getWATotalCBM(getWAID($orderselection['so_id'])). "<br/>Weight : ".  getWATotalWeight(getWAID($orderselection['so_id'])) ."<br/>Carton Qty : ".  getWATotalCarton(getWAID($orderselection['so_id'])) ."</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='so_ids' name='so_ids[]' value=".$orderselection['so_id']."><span></span></label></div></td>"
						 ."</tr>";
				
			}
			return $table;
		}); 
		
	$app->post('/delivery-arrangements/add-delivery-arrangements', function (Request $request) {
		global $db;
		
		$user_id = $_SESSION['user_id'];
		$company_id = $_SESSION['company_id'];
		$delivery_type = $request->get('delivery_type');
		$so_ids = $request->get('so_ids');
		if($delivery_type == "1" || $delivery_type == "3"){
			$delivery_date = date('Y-m-d', strtotime($request->get('delivery_date')));
			$driver_contact_person = $request->get('driver_contact_person');
			$driver_contact_person_no = $request->get('driver_contact_person_no');
			$vehicle_no = $request->get('vehicle_no');
			
			$db->bind("user_id", $user_id);
			$db->bind("company_id", $company_id);
			$db->bind("delivery_type", $delivery_type);
			$db->bind("delivery_date", $delivery_date);
			$db->bind("driver_contact_person", $driver_contact_person);
			$db->bind("driver_contact_person_no", $driver_contact_person_no);
			$db->bind("vehicle_no", $vehicle_no);
			$deliveryarrangementsCreate = $db->query("INSERT INTO `delivery_arrangements`(`delivery_type`, `delivery_date`, `driver_contact_person`, `driver_contact_person_no`, `vehicle_no`, `courier_service_name`, `tracking_no`, `warehouse_id`, `warehouse_address`, `warehouse_zip`, `warehouse_city`, `warehouse_state`, `warehouse_country`, `warehouse_contact_person`, `warehouse_contact_person_no`, `user_id`, `company_id`) VALUES (:delivery_type,:delivery_date,:driver_contact_person,:driver_contact_person_no,:vehicle_no,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,:user_id,:company_id)");
		}elseif($delivery_type == "2"){
			$courier_service_name = $request->get('courier_service_name');
			$tracking_no = $request->get('tracking_no');
			
			
			$db->bind("user_id", $user_id);
			$db->bind("company_id", $company_id);
			$db->bind("delivery_type", $delivery_type);
			$db->bind("courier_service_name", $courier_service_name);
			$db->bind("tracking_no", $tracking_no);
			
			$deliveryarrangementsCreate = $db->query("INSERT INTO `delivery_arrangements`(`delivery_type`, `delivery_date`, `driver_contact_person`, `driver_contact_person_no`, `vehicle_no`, `courier_service_name`, `tracking_no`, `warehouse_id`, `warehouse_address`, `warehouse_zip`, `warehouse_city`, `warehouse_state`, `warehouse_country`, `warehouse_contact_person`, `warehouse_contact_person_no`, `user_id`, `company_id`) VALUES (:delivery_type,NULL,NULL,NULL,NULL,:courier_service_name,:tracking_no,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,:user_id,:company_id)");
			
		}elseif($delivery_type == "4"){
			$warehouse_id = $request->get('warehouse_id');
			$warehouse_address = $request->get('warehouse_address');
			$warehouse_city = $request->get('warehouse_city');
			$warehouse_zip = $request->get('warehouse_zip');
			$warehouse_state = $request->get('warehouse_state');
			$warehouse_country = $request->get('warehouse_country');
			$warehouse_contact_person = $request->get('warehouse_contact_person');
			$warehouse_contact_person_no = $request->get('warehouse_contact_person_no');$warehouse_id = $request->get('warehouse_id');
			
			$db->bind("user_id", $user_id);
			$db->bind("company_id", $company_id);
			$db->bind("delivery_type", $delivery_type);
			$db->bind("warehouse_id", $warehouse_id);
			$db->bind("warehouse_address", $warehouse_address);
			$db->bind("warehouse_city", $warehouse_city);
			$db->bind("warehouse_zip", $warehouse_zip);
			$db->bind("warehouse_state", $warehouse_state);
			$db->bind("warehouse_country", $warehouse_country);
			$db->bind("warehouse_contact_person", $warehouse_contact_person);
			$db->bind("warehouse_contact_person_no", $warehouse_contact_person_no);
			
			$deliveryarrangementsCreate = $db->query("INSERT INTO `delivery_arrangements`(`delivery_type`, `delivery_date`, `driver_contact_person`, `driver_contact_person_no`, `vehicle_no`, `courier_service_name`, `tracking_no`, `warehouse_id`, `warehouse_address`, `warehouse_zip`, `warehouse_city`, `warehouse_state`, `warehouse_country`, `warehouse_contact_person`, `warehouse_contact_person_no`, `user_id`, `company_id`) VALUES (:delivery_type,NULL,NULL,NULL,NULL,NULL,NULL, :warehouse_id, :warehouse_address, :warehouse_zip, :warehouse_city, :warehouse_state, :warehouse_country, :warehouse_contact_person, :warehouse_contact_person_no,:user_id,:company_id)");
			
		}
			$delivery_arrangement_id = $db->lastInsertId();
			
			if($deliveryarrangementsCreate){
				foreach ($so_ids as $key => $so_id) {
					$db->bind("so_id", $so_id);
					$db->bind("delivery_arrangement_id", $delivery_arrangement_id);
					
					$delivery_arrangement_itemsCreate = $db->query("INSERT INTO delivery_arrangement_items (so_id, delivery_arrangement_id) VALUES (:so_id, :delivery_arrangement_id);");
					
					if($delivery_arrangement_itemsCreate){
						$db->bind("status", "3");
						$db->bind("so_id", $so_id);
						$soUpdate = $db->query("UPDATE `shipping_orders` SET `status`=:status WHERE so_id = :so_id");

						//create messages
						$db->bind("message", "Your Delivery Arrangement have been created.");
						$db->bind("chat_type", "9");
						$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();
						
						//find room for current so
						$room_id = getRoomIDFromSO($so_id);
						
						//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)");
						
						$insideRoom = getUserInRoom($room_id);
						foreach($insideRoom 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($delivery_type == 2 || $delivery_type == 4){
							$db->bind("message", "Have you received your goods?");
							$db->bind("chat_type", "13");
							$db->bind("decision", 0);
							$db->bind("decision_type", 0);
							$db->bind("delivery_arrangement_id", $delivery_arrangement_id);
							$db->bind("from_id", $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();
							
							//find room for current so
							$room_id = getRoomIDFromSO($so_id);
							
							//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)");

							$insideRoom = getUserInRoom($room_id);
							foreach($insideRoom 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)");
							}
						}else{
							$db->bind("message", "Please confirm or reschedule your delivery arrangements.");
							$db->bind("chat_type", "14");
							$db->bind("decision", 0);
							$db->bind("decision_type", 0);
							$db->bind("delivery_arrangement_id", $delivery_arrangement_id);
							$db->bind("from_id", $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();
							
							//find room for current so
							$room_id = getRoomIDFromSO($so_id);
							
							//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)");
							
							$insideRoom = getUserInRoom($room_id);
							foreach($insideRoom 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 ($delivery_arrangement_itemsCreate) {
			return new Response("SUCCESS", 200);
		} else {			
			return new Response('FAILED', 201);
		} 
	}); 
	$app->get('/delivery-arrangements/details/{id}', function ($id) use ($app) {
		global $db;
		global $hooks;
		global $so_id;
		
		$so_id = $id;
		
		if (!isset($id) || !isSOMine($id)) {
			return $app->redirect('/delivery-arrangements');
		}
		
		$hooks->add_action('global_css', "create_delivery_arrangement_css");
		$hooks->add_action('global_js', "create_delivery_arrangement_js");
		$hooks->add_action('the_title',"create_delivery_arrangement_title");
		
		the_head();
		include 'delivery.details.php';
		the_footer();
		return "";		
		
	}); 
}
	
include 'delivery.func.php';