<?php
global $hooks;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
$hooks->add_action('silex_action','the_so'); 
function so_title(){
    echo "Shipping Order";
}

function create_so_css() {
    ?>
	<link href="/assets/global/plugins/bootstrap-fileinput/bootstrap-fileinput.css" rel="stylesheet" type="text/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/bootstrap-sweetalert/sweetalert.css" rel="stylesheet" type="text/css" />
	<link href="/assets/global/plugins/fancybox/source/jquery.fancybox.css" rel="stylesheet" type="text/css" />
	<link href="/assets/modul-css/profile/profile.min.css" rel="stylesheet" type="text/css">	
	<link href="/assets/global/plugins/typeahead/typeahead.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_so_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/html2canvas/html2canvas.min.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/html2canvas/base64.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/html2canvas/canvas2image.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/plugins/bootstrap-sweetalert/sweetalert.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/modul-js/orders/shipping-order/create.min.js?v=<?php echo rand(); ?>" type="text/javascript"></script>
 <?php
}
function so_js() {
    ?>
	<script src="/assets/global/plugins/jquery-validation/js/jquery.validate.min.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-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/jspdf.js"></script>
	<script src="/assets/global/plugins/html2canvas/html2canvas.min.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/html2canvas/base64.js" type="text/javascript"></script>
	<script src="/assets/global/plugins/html2canvas/canvas2image.js" type="text/javascript"></script>
	
	<script src="/assets/modul-js/orders/shipping-order/so.min.js"></script>
<?php }

function so_details_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/plugins/bootstrap-sweetalert/sweetalert.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>
	
<?php }

function so_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 the_so(){
	global $app;global $csrf;  

	$app->get('/shipping-order', function() use($csrf) { 
		global $hooks;
		global $app;
		
		$hooks->add_action('global_css', "so_css");
        $hooks->add_action('global_js', "so_js");
		$hooks->add_action('the_title',"so_title");
		the_head();
		include 'so.tpl.php';
				
		the_footer();
		
		return "";
	}); 
		
	$app->post('/shipping-order/getModalSuccess', function(Request $request) {	
		global $db;
		
		$so_id = $request->get('so_id');
		$marking_no = getSOData($so_id, "marking_no");
		$order_no = substr($marking_no, -5);
		$html = '
				<div class="row text-center"><div class="col-sm-6 col-sm-offset-3"><h2 style="margin-top:10px" class="font-green-meadow">Order '.$order_no.' Created</h2>
				<i class="fa fa-check-circle fa-6 font-green-meadow" style="margin-top:30px;font-size: 80px;" aria-hidden="true"></i>
						
				<p>Your order <strong>'.$order_no.'</strong> have successfully created. Please procees to action below : </p>
				<a href="/shipping-order" style="border-radius:12px !Important" class="btn btn-sm btn-warning">Close</a>&nbsp;
				<a href="/shipping-order/create"  style="border-radius:12px !Important" class="btn btn-lg btn-sm btn-success">Create New</a>&nbsp;
				<a href="/messenger/order/'.getRoomIDFromSO($so_id).'" style="background-color: #134f5c;border-color: #134f5c;border-radius:12px !Important" class="btn btn-lg btn-sm btn-success">Chat</a></div></div>';
		$html .= "<span id='SOmarking'>" .getModalMarking($so_id) . "</span><div id='img-out'></div>";
				
		
		return $html;
	}); 
	$app->post('/shipping-order/getWarehouse', function(Request $request) {		
		global $db;
		$forwarder_id = $request->get('forwarder_id');
		$db->bind("company_id",$forwarder_id);
		
		$data = $db->query("SELECT * FROM warehouses WHERE company_id = :company_id");
		$html = "<option value=''>Please choose warehouse</option>";
		foreach ($data as $key => $value) {
			$html .= "<option value='".$value['warehouse_id']."'>".$value['name']."</option>";
		}
		return $html;
		
	}); 
	$app->post('/shipping-order/getDeliveryAddress', function(Request $request) {		
		global $db;
		$branch_id =  $_SESSION['branch_id'];
		$db->bind("branch_id",$branch_id);
		
		$data = $db->query("SELECT * FROM warehouses WHERE branch_id = :branch_id");
		$html = "<option value=''>Please choose / add new delivery address</option>";
		foreach ($data as $key => $value) {
			$html .= "<option value='".$value['warehouse_id']."'>".$value['name']."</option>";
		}
		return $html;
	}); 
	$app->post('/shipping-order/getWarehouseFromPO', function(Request $request) {		
		global $db;
		$po_id = $request->get('po_id');
		$forwarder_id =  getPOData($po_id, "forwarder_id");
		$db->bind("company_id",$forwarder_id);
		
		$data = $db->query("SELECT * FROM warehouses WHERE company_id = :company_id");
		$html = "<option value=''>Please choose warehouse</option>";
		foreach ($data as $key => $value) {
			$html .= "<option value='".$value['warehouse_id']."'>".$value['name']."</option>";
		}
		return $html;
		
	}); 
	$app->post('/shipping-order/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('/shipping-order/getdeliverydata', function(Request $request) {		
		global $db;
		$delivery_id = $request->get('delivery_id');
		$db->bind("delivery_id",$delivery_id);
		
		$data = $db->query("SELECT * FROM warehouses WHERE warehouse_id = :delivery_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('/shipping-order/list', function(Request $request)  {
        $curpage = $request->get('page');
        include 'so.list.php';
        return '';
    });
	$app->post('/shipping-order/contact', function(Request $request)  {
        $curpage = $request->get('page');
        include 'companies.list.php';
        return '';
    });
	
	$app->get('/shipping-order/create', function(){ 
		global $hooks;
		global $app;
		
        $hooks->add_action('global_css', "create_so_css");
        $hooks->add_action('global_js', "create_so_js");
		$hooks->add_action('the_title',"so_title");
		
		the_head();
		include 'create.tpl.php';
		the_footer();
		
		typeAhead();
		return "";
	}); 
	$app->post('/shipping-order/add-shipping-order', function (Request $request) {
		global $db;
		
		$user_id = $_SESSION['user_id'];
		$order_type = $request->get('order_type');
		$forwarder_id = $request->get('forwarder_id');
		$supplier = $request->get('supplier');
		$supplier_contact_person = $request->get('supplier_contact_person');
		$supplier_contact_person_no = $request->get('supplier_contact_person_no');
		$warehouse_name = $request->get('warehouse_name');
		$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');
		$delivery_name = $request->get('delivery_name');
		$delivery_address = $request->get('delivery_address');
		$delivery_city = $request->get('delivery_city');
		$delivery_zip = $request->get('delivery_zip');
		$delivery_state = $request->get('delivery_state');
		$delivery_country = $request->get('delivery_country');
		$delivery_contact_person = $request->get('delivery_contact_person');
		$delivery_contact_person_no = $request->get('delivery_contact_person_no');
		$delivery_id = $request->get('delivery_id');
		$company_id = $_SESSION['company_id'];
		$branch_id = $_SESSION['branch_id'];
		$shippingorderitems = $request->get('shippingorderitems');
		
		if($delivery_id == "" || $delivery_id == null){
			$db->bind("delivery_name", $delivery_name);
			$db->bind("delivery_address", $delivery_address);
			$db->bind("delivery_city", $delivery_city);
			$db->bind("delivery_zip", $delivery_zip);
			$db->bind("delivery_state", $delivery_state);
			$db->bind("delivery_country", $delivery_country);
			$db->bind("branch_id", $_SESSION['branch_id']);
			$db->bind("company_id", $_SESSION['company_id']);
			
			$checkDeliveryAddress = $db->query("SELECT * FROM warehouses WHERE name = :delivery_name and address = :delivery_address and city = :delivery_city and zip = :delivery_zip and state = :delivery_state and country = :delivery_country and branch_id = :branch_id and company_id = :company_id");
			
			if(count($checkDeliveryAddress) > 0){
				$delivery_id = $checkDeliveryAddress[0]['warehouse_id'];
			}else{
				$db->bind("delivery_name", $delivery_name);
				$db->bind("delivery_address", $delivery_address);
				$db->bind("delivery_city", $delivery_city);
				$db->bind("delivery_zip", $delivery_zip);
				$db->bind("delivery_state", $delivery_state);
				$db->bind("delivery_country", $delivery_country);
				$db->bind("delivery_contact_person", $delivery_contact_person);
				$db->bind("delivery_contact_person_no", $delivery_contact_person_no);
				$db->bind("branch_id", $_SESSION['branch_id']);
				$db->bind("company_id", $_SESSION['company_id']);
				
				$deliveryCreate = $db->query("INSERT INTO warehouses ( name, address, city, zip, state, country, contact_person, contact_person_no, branch_id, company_id) VALUES (:delivery_name, :delivery_address, :delivery_city, :delivery_zip, :delivery_state, :delivery_country, :delivery_contact_person, :delivery_contact_person_no ,:branch_id, :company_id);");
			}
		}
		
		$db->bind("forwarder_id", $forwarder_id);
		$db->bind("marking_no", "");
		$db->bind("supplier_company_name", $supplier);
		$db->bind("supplier_contact_person", $supplier_contact_person);
		$db->bind("supplier_contact_person_no", $supplier_contact_person_no);
		$db->bind("warehouse_name", $warehouse_name);
		$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);
		$db->bind("warehouse_id", $warehouse_id);
		$db->bind("delivery_name", $delivery_name);
		$db->bind("delivery_address", $delivery_address);
		$db->bind("delivery_zip", $delivery_zip);
		$db->bind("delivery_city", $delivery_city);
		$db->bind("delivery_state", $delivery_state);
		$db->bind("delivery_country", $delivery_country);
		$db->bind("delivery_contact_person", $delivery_contact_person);
		$db->bind("delivery_contact_person_no", $delivery_contact_person_no);
		$db->bind("delivery_id", $delivery_id);
		$db->bind("company_id", $company_id);
		$db->bind("branch_id", $branch_id);
		$soCreate = $db->query("INSERT INTO shipping_orders ( marking_no, supplier_company_name, supplier_contact_person, supplier_contact_person_no, warehouse_name, warehouse_address, warehouse_city, warehouse_zip, warehouse_state, warehouse_country, warehouse_contact_person, warehouse_contact_person_no, delivery_name, delivery_address, delivery_city, delivery_zip, delivery_state, delivery_country,delivery_contact_person,delivery_contact_person_no, branch_id, warehouse_id, delivery_id, company_id, forwarder_id) VALUES (:marking_no, :supplier_company_name, :supplier_contact_person, :supplier_contact_person_no, :warehouse_name, :warehouse_address, :warehouse_city, :warehouse_zip, :warehouse_state, :warehouse_country, :warehouse_contact_person, :warehouse_contact_person_no, :delivery_name, :delivery_address, :delivery_city, :delivery_zip, :delivery_state, :delivery_country, :delivery_contact_person, :delivery_contact_person_no, :branch_id, :warehouse_id, :delivery_id, :company_id, :forwarder_id);");
	
		$so_id = $db->lastInsertId();
		if ($soCreate) {
			
			$ordercountCreate = $db->query("INSERT INTO order_count (id) VALUES (NULL);");
			$order_no = sprintf('%05d', $db->lastInsertId());
			$marking = getMarkingNo($company_id, $forwarder_id, $branch_id);
			$marking_no = getMarkingNo($company_id, $forwarder_id, $branch_id). "/" .$order_no;
				
			$db->bind("order_no", $order_no);
			$db->bind("marking", $marking);
			$db->bind("marking_no", $marking_no);
			$db->bind("so_id", $so_id);
			$soUpdate = $db->query("UPDATE `shipping_orders` SET `marking_no`=:marking_no, `marking`=:marking, `order_no` = :order_no WHERE so_id = :so_id");
			
			
			foreach ($shippingorderitems as $key => $shippingorderitem) {
				
				# check reqired description and quantity 
				
				if ( $shippingorderitem['description'] == "" ){
					return new Response("Please make sure all your item have a description", 403);
				}
				
				if ( $shippingorderitem['packaging_quantity'] == "") {
					return new Response("Please make sure all your item have a quantity", 403);
				}

				$db->bind("description", $shippingorderitem['description']);
				$db->bind("model_no", $shippingorderitem['model_no']);
				$db->bind("brand_no", $shippingorderitem['brand_no']);
				$db->bind("item_code", $shippingorderitem['item_code']);
				$db->bind("uom", $shippingorderitem['uom']);
				$db->bind("quantity", $shippingorderitem['quantity']);
				$db->bind("packaging_quantity", $shippingorderitem['packaging_quantity']);
				$db->bind("packaging_cbm", $shippingorderitem['packaging_cbm']);
				if($shippingorderitem['packaging_type1'] == "new"){
					$db->bind("packaging_type", $shippingorderitem['packaging_type2']);
				}else{
					$db->bind("packaging_type", $shippingorderitem['packaging_type1']);
				}
				$db->bind("packaging_height", $shippingorderitem['packaging_height']);
				$db->bind("packaging_width", $shippingorderitem['packaging_width']);
				$db->bind("packaging_depth", $shippingorderitem['packaging_depth']);
				$db->bind("packaging_gross", $shippingorderitem['packaging_gross']);
				$db->bind("packaging_nett", $shippingorderitem['packaging_nett']);
				$db->bind("image", ($shippingorderitem['image'] <> "" ? $shippingorderitem['image']  : NULL));
				$db->bind("image2", ($shippingorderitem['image2'] <> "" ? $shippingorderitem['image2']  : NULL));
				$db->bind("image3", ($shippingorderitem['image3'] <> "" ? $shippingorderitem['image3']  : NULL));
				$db->bind("image4", ($shippingorderitem['image4'] <> "" ? $shippingorderitem['image4']  : NULL));
				$db->bind("so_id", $so_id);
				
				$soItemCreate = $db->query("INSERT INTO shipping_order_items ( item_code, model_no, brand_no, description, quantity, uom, packaging_quantity, packaging_type, packaging_cbm, packaging_height, packaging_width, packaging_depth, packaging_gross, packaging_nett, image, image2, image3, image4, so_id) VALUES (:item_code, :model_no, :brand_no, :description, :quantity, :uom, :packaging_quantity, :packaging_type, :packaging_cbm, :packaging_height, :packaging_width, :packaging_depth, :packaging_gross, :packaging_nett, :image, :image2, :image3, :image4, :so_id);");
			}
		}			
		
		if ($soItemCreate) {	
			$chat_name = $order_no;
			
			//create messages
			$db->bind("message", "Your shipping order have been created.");
			$db->bind("chat_type", "6");
			$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("chat_name",$chat_name);
			$db->bind("owner_id", $user_id);
			$db->bind("order_id", $so_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();
			
			//create members for room (current user)
			$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 unread notification
			$db->bind("room_id", $room_id);
			$db->bind("message_id", $message_id);
			$db->bind("user_id", $user_id);
			$createMembers  = $db->query("INSERT INTO notice_unread(room_id,message_id,user_id, status) VALUES (:room_id, :message_id,:user_id, 0)");
			
			$db->bind("forwarder_id", $forwarder_id);
			$companyStaffs = $db->query("SELECT * FROM user_company WHERE company_id = :forwarder_id and position = 1");
			foreach($companyStaffs as $key => $value){
				$db->bind("user_id", $value['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 unread notification for admin staffs
				$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)");

				
				$db->bind("user_id", $value['user_id']);
				$db->bind("so_id", $so_id);
				$createSOUnread  = $db->query("INSERT INTO shipping_order_unread(user_id,so_id) VALUES (:user_id,: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)");
				
			return new Response($so_id, 200);
		} else {			
			return new Response($so_id, 201);
		}
	});

	$app->get('/shipping-order/details/{id}', function ($id) use ($app) {
        global $db;
        global $hooks;
        global $po_id;
        global $so_id;
        $so_id = $id;
        $po_id = getSOData($id, "po_id");
        if (!isset($id) || !isSOMine($id)) {
            return $app->redirect('/shipping-order');
        }

        $hooks->add_action('global_css', "create_so_css");
        $hooks->add_action('global_js', "so_details_js");
		$hooks->add_action('the_title',"so_title");
		
        the_head();
        include 'so.details.php';
        the_footer();
        return "";
    });	
	
	$app->post('/shipping-order/get-packing-list', function (Request $request) {
		global $db;
		$id = $request->get('id');
		
		$html = getModalPackingList($id);
		return $html;
    });	
	
	$app->post('/shipping-order/get-marking', function (Request $request) {
		global $db;
		$id = $request->get('id');
		
		$html = "<span id='SOmarking'>" .getModalMarking($id) . "</span><div id='img-out'></div>";
		return $html;
    });	
}

include 'so.func.php';