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

function create_warehouse_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" />
	<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-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" />
    <?php
}

function create_warehouse_arrangement_js() {
    ?>
	<script src="/assets/global/plugins/jquery-validation/js/jquery.validate.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/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-datepicker/js/bootstrap-datepicker.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/modul-js/arrangements/warehouse-arrangement/create.js" type="text/javascript"></script>
 <?php
} 
function warehouse_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>
	
 <?php
} 

function the_warehouse_arrangement(){
	global $app;

	$app->get('/warehouse-arrangements', function(){  
		global $hooks;
		global $app;
		$company_id = getCompany($_SESSION['user_id']);
		$_SESSION['company_id'] = $company_id;
		$hooks->add_action('global_css',"create_warehouse_arrangement_css");
		$hooks->add_action('global_js',"create_warehouse_arrangement_js");
		$hooks->add_action('the_title',"create_warehouse_arrangement_title");
	
		the_head();
		include 'warehouse.tpl.php';
		the_footer();
	
	
		return "";
	}); 
	$app->post('/warehouse-arrangements/getSOWarehouse', function(Request $request) {
		global $db;
		$so_id = $request->get('so_id');

		return getSOData($so_id, "warehouse_name");
		
		
	}); 	
	$app->post('/warehouse-arrangements/getSOItems', function(Request $request) {		
		global $db;
		$so_id = $request->get('so_id');
		
		$db->bind("so_id", $so_id);
		$shipping_order_items = $db->query("SELECT * FROM shipping_order_items WHERE so_id = :so_id");
		$table = "";
		$count = 1;
		foreach ($shipping_order_items as $key => $shipping_order_item){
			$table .= "<tr>"
							."<td>". $count. "</td>"
							."<td>". $shipping_order_item['description']. "</td>"
							."<td>". $shipping_order_item['packaging_quantity']. "</td>"
							."<td><input name='warehouse_arrangement_items[".$count."][actual_ctn]' id='warehouse_arrangement_items[".$count."][actual_ctn]' class='form-control input-sm warehouse_arrangement_items ctn ' /></td>"
							."<td>". $shipping_order_item['packaging_height']. " x ". $shipping_order_item['packaging_width']. " x ". $shipping_order_item['packaging_depth']. "</td>"
							."<td><input placeholder='Height' name='warehouse_arrangement_items[".$count."][actual_height_ctn]' id='warehouse_arrangement_items[".$count."][actual_height_ctn]' class='form-control input-sm warehouse_arrangement_items height' /> x <input placeholder='Width' name='warehouse_arrangement_items[".$count."][actual_width_ctn]' id='warehouse_arrangement_items[".$count."][actual_width_ctn]' class='form-control input-sm warehouse_arrangement_items width' /> x <input placeholder='Depth' name='warehouse_arrangement_items[".$count."][actual_depth_ctn]' id='warehouse_arrangement_items[".$count."][actual_depth_ctn]' class='form-control input-sm warehouse_arrangement_items depth' /></td>"
							."<td>". $shipping_order_item['packaging_nett']. "</td>"
							."<td><input name='warehouse_arrangement_items[".$count."][actual_weight_ctn]' id='warehouse_arrangement_items[".$count."][actual_weight_ctn]' class='form-control input-sm warehouse_arrangement_items weight' /></td>"
							."<td>".getItemBalance($shipping_order_item['id'], $so_id)."</td>"
							."<td></td>"
							."<td><label class='mt-checkbox mt-checkbox-single mt-checkbox-outline'><input name='warehouse_arrangement_items[".$count."][isDamaged]' id='warehouse_arrangement_items[".$count."][isDamaged]' type='checkbox' class='checkboxes' onchange='toggleCheckbox(this)' value='1'><span></span></label></td>"
							."<td>
							<div class='fileinput fileinput-new' data-provides='fileinput'>
								<div class='fileinput-new thumbnail' style='width: 100px; height: auto;'>												
									<img id='uploadPreview[".$count."]' src='".($shipping_order_item['image'] <> '' ? $shipping_order_item['image'] : "http://www.placehold.it/200/EFEFEF/AAAAAA&text=no+image") ."' alt='' /> 
								</div>
								
								<div>
									<span class='btn default btn-file'>
										<span class='fileinput-new'> Select image </span>
										<span class='fileinput-exists'> Change </span>
										<input type='file' name='image[".$count."]' id='image[".$count."]' onchange='PreviewImage(".$count.");'> </span>
										<input type='text' name='warehouse_arrangement_items[".$count."][image]' id='warehouse_arrangement_items[".$count."][image]' style='display:none;'>
									<a href='javascript:;' class='btn default fileinput-exists' data-dismiss='fileinput'> Remove </a>
								</div>
							</div>
							<input style='display: none' name='warehouse_arrangement_items[".$count."][balance]' id='warehouse_arrangement_items[".$count."][balance]' value='".getItemBalance($shipping_order_item['id'], $so_id)."'>
							<input style='display: none' name='warehouse_arrangement_items[".$count."][so_item_id]' id='warehouse_arrangement_items[".$count."][so_item_id]' value='".$shipping_order_item['id']."'><input style='display: none' name='warehouse_arrangement_items[".$count."][status]' id='warehouse_arrangement_items[".$count."][status]'></td>"
						."</tr>";
			$count++;
		}
		
		return $table;
	}); 
	
	 $app->post('/warehouse-arrangements/checkConsignmentNote', function(Request $request) {
        global $db;
		$company_id = $_SESSION['company_id'];
        $consignment_note_no = $request->get('consignment_note_no');
        $db->bind('company_id', $company_id);
        $db->bind('consignment_note_no', $consignment_note_no);
        $row = $db->query("SELECT consignment_note_no FROM warehouse_arrangements WHERE consignment_note_no = :consignment_note_no and company_id = :company_id");
        if (count($row) > 0) {
            $status = 'false';
        } else {
            $status = 'true';
        }
        echo $status;
        return '';
    });
	
	 $app->post('/warehouse-arrangements/checkReceiveNote', function(Request $request) {
        global $db;
        $company_id = $_SESSION['company_id'];
        $warehouse_receive_note_no = $request->get('warehouse_receive_note_no');
        $db->bind('company_id', $company_id);
		$db->bind('warehouse_receive_note_no', $warehouse_receive_note_no);
        $row = $db->query("SELECT warehouse_receive_note_no FROM warehouse_arrangements WHERE warehouse_receive_note_no = :warehouse_receive_note_no and company_id = :company_id");
        if (count($row) > 0) {
            $status = 'false';
        } else {
            $status = 'true';
        }
        echo $status;
        return '';
    });
	
	$app->post('/warehouse-arrangements/list', function(Request $request)  {
        $curpage = $request->get('page');
        include 'warehouse.list.php';
        return '';
    }); 
	
	$app->post('/warehouse-arrangements/add-warehouse-arrangements', function (Request $request) {
        global $db;
		
		$user_id = $_SESSION['user_id'];
		$company_id = $_SESSION['company_id'];
		$so_id = $request->get('so_id');
		$receive_on = date('Y-m-d', strtotime($request->get('receive_on')));
		$transport_company_name = $request->get('transport_company_name');
		$consignment_note_no = $request->get('consignment_note_no');
		$warehouse_receive_note_no = $request->get('warehouse_receive_note_no');
		$receiving_person = $request->get('receiving_person');
		$type = $request->get('type');
		if($type == "decision_request"){
			$title = "Unmatched Quantity";
			$remarks = $request->get('instruction');
			$status = "1";
		}elseif($type == "decision_reject"){
			$remarks = $request->get('reason');
			$status = "3";
		}else{
			$status = "0";
		}
		$warehouse_arrangement_items = $request->get('warehouse_arrangement_items');
		
		$db->bind("user_id", $user_id);
		$db->bind("company_id", $company_id);
		$db->bind("so_id", $so_id);
		$db->bind("receive_on", $receive_on);
		$db->bind("transport_company_name", $transport_company_name);
		$db->bind("consignment_note_no", $consignment_note_no);
		$db->bind("warehouse_receive_note_no", $warehouse_receive_note_no);
		$db->bind("receiving_person", $receiving_person);
		$db->bind("remarks", $remarks);
		$db->bind("status", $status);
				
		$warehousearrangementsCreate = $db->query("INSERT INTO warehouse_arrangements (receive_on, transport_company_name, consignment_note_no, warehouse_receive_note_no, receiving_person, remarks, status, so_id, user_id, company_id) VALUES (:receive_on, :transport_company_name, :consignment_note_no, :warehouse_receive_note_no, :receiving_person, :remarks, :status, :so_id, :user_id, :company_id);");
		$warehouse_arrangement_id = $db->lastInsertId();
		$unmatch_count = 0;
		if($warehousearrangementsCreate){
			foreach ($warehouse_arrangement_items as $key => $warehouse_arrangement_item) {
				$db->bind("actual_ctn", $warehouse_arrangement_item['actual_ctn']);
				$db->bind("actual_measurement_ctn", $warehouse_arrangement_item['actual_height_ctn'] * $warehouse_arrangement_item['actual_width_ctn'] * $warehouse_arrangement_item['actual_depth_ctn'] );
				$db->bind("actual_weight_ctn", $warehouse_arrangement_item['actual_weight_ctn']);
				$db->bind("actual_height_ctn", $warehouse_arrangement_item['actual_height_ctn']);
				$db->bind("actual_width_ctn", $warehouse_arrangement_item['actual_width_ctn']);
				$db->bind("actual_depth_ctn", $warehouse_arrangement_item['actual_depth_ctn']);
				$db->bind("status", $warehouse_arrangement_item['status']);
				$db->bind("isDamaged", ($warehouse_arrangement_item['isDamaged'] ? $warehouse_arrangement_item['isDamaged'] : 0));
				$db->bind("image", $warehouse_arrangement_item['image']);
				$db->bind("so_item_id", $warehouse_arrangement_item['so_item_id']);
				$db->bind("warehouse_arrangement_id", $warehouse_arrangement_id);
				
				$warehouse_arrangement_itemsCreate = $db->query("INSERT INTO warehouse_arrangement_items (actual_ctn, actual_measurement_ctn, actual_weight_ctn, actual_height_ctn, actual_width_ctn, actual_depth_ctn, status, isDamaged, image, so_item_id, warehouse_arrangement_id) VALUES (:actual_ctn, :actual_measurement_ctn, :actual_weight_ctn, :actual_height_ctn, :actual_width_ctn, :actual_depth_ctn, :status, :isDamaged, :image, :so_item_id, :warehouse_arrangement_id);");
				
				if($warehouse_arrangement_item['status'] == 1 || $warehouse_arrangement_item['isDamaged'] == 1){
					$unmatch_count++;
				}
			}
		}
		
		
		
		if ($warehouse_arrangement_itemsCreate) {	
			
			//update so status
			$db->bind("status", "1");
			$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 Warehouse Receive Note have been created.");
			$db->bind("chat_type", "7");
			$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($type == "decision_request"){
				//create messages
				$db->bind("message", "Decision Requested.");
				$db->bind("chat_type", "11");
				$db->bind("decision", 0);
				$db->bind("decision_type", 1);
				$db->bind("warehouse_arrangement_id", $warehouse_arrangement_id);
				$db->bind("from_id", $user_id);
				$createMessage  = $db->query("INSERT INTO notice_messages(message,chat_type,from_id, decision, decision_type, warehouse_arrangement_id) VALUES (:message,:chat_type,:from_id, :decision, :decision_type, :warehouse_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)");
			}
			if($soUpdate){
				return new Response("SUCCESS", 200);
			}else{
				return new Response('FAILED', 201);				
			}
		} else {			
			return new Response('FAILED', 201);
		}

	});
	
	$app->post('/get-unread', function(Request $request)  {
		if(getOrderUnread() + getGeneralUnread() + getHelpUnread() > 0){
			$unread_order = getOrderUnread()+ getGeneralUnread() + getHelpUnread();
		}else{
			$unread_order = "";
		}
		if(getStatusCompanyFriend($_SESSION['company_id']) > 0 && $_SESSION['group_id'] == 1){ 
			$unread_contact = getStatusCompanyFriend($_SESSION['company_id']) + getContactUnread();
		}else{
			$unread_contact = getContactUnread();
		}
		if(getSOUnread() > 0){
			$unread_so = getSOUnread();
		}else{
			$unread_so = "";
		}
		$output_array = array();
		$output_array[] = array('unread_order' => $unread_order, 'unread_contact' => $unread_contact, 'unread_so' => $unread_so);
		
		return json_encode( $output_array );
	});
	$app->get('/warehouse-arrangements/details/{id}', function ($id) use ($app) {
		global $db;
        global $hooks;
        global $WAID;
		
        $WAID = $id;
		
		
        if (!isset($id) || !isSOMine(getWADatafromWAID($id, "so_id"))) {
            return $app->redirect('/warehouse-arrangements');
        }
		
		$hooks->add_action('global_css', "create_warehouse_arrangement_css");
        $hooks->add_action('global_js', "create_warehouse_arrangement_js");
		$hooks->add_action('the_title',"create_warehouse_arrangement_title");
		
		the_head();
        include 'warehouse.details.php';
        the_footer();
        return "";
	
	}); 
}
	
include 'warehouse.func.php';