<?php $__env->startSection('title'); ?> <?php echo e(Config::get('shuttle.title')); ?> <?php $__env->stopSection(); ?>
<?php $__env->startSection('body'); ?>

<ul class="nav nav-tabs" role="tablist">
	<li role="presentation" class="active"><a href="#panel_1" aria-controls="panel_1" role="tab" data-toggle="tab">Load Vehicles</a></li>
	<li role="presentation"><a href="#panel_2" aria-controls="panel_2" role="tab" data-toggle="tab">Summary</a></li>
</ul>

<div class="tab-content" style="padding-top: 20px;">
	<div role="tabpanel" class="tab-pane fade in active" id="panel_1">

		<div class="row">
			<div class="wrapper" style="min-width: 800px;">
				<div class="col-xs-6 col-md-6">
					<div class="form-group">
						<label class="control-label">Select Delivery Notes</label>
						<div class="input-group">
							<select class="form-control note">
								<option>Please select an option</option>
							</select>
							<span class="input-group-addon btn btn-primary addNote">
								<i class="fa fa-level-down"></i>
							</span>
						</div>
					</div>

					<div class="noteWrapper section1"></div>

				</div>
				<div class="col-xs-6 col-md-6">
					<div class="form-group">
						<label class="control-label">Select Vehicles</label>
						<div class="input-group">
							<select class="form-control vehicle">
								<option>Please select an option</option>
							</select>
							<span class="input-group-addon btn btn-primary addVehicle">
								<i class="fa fa-level-down"></i>
							</span>
						</div>
					</div>
					
					<div class="vehicleWrapper section1"></div>

				</div>
			</div>
		</div>

		<div class="row">
			<div class="col-md-12">
				<button class="btn btn-primary save">Save</button>
			</div>
		</div>


	</div>

	<div role="tabpanel" class="tab-pane fade in" id="panel_2">

		<div class="row">
			<div class="col-md-12">
				<div class="form-group">
					<div class="table-responsive">
						<table class="table table-bordered deliverySummary">
							<thead>
								<tr>
									<th>#</th>
									<th>Vehicle</th>
									<th>Delivery Note</th>
									<th>Item</th>
									<th>Qty</th>
									<th class="text-center"><i class="fa fa-gear"></i></th>
								</tr>
							</thead>
							<tbody></tbody>
						</table>
					</div>
				</div>
			</div>
		</div>

	</div>
</div>

<?php $__env->stopSection(); ?>
<?php $__env->startSection('script'); ?>
<script type="text/javascript">

$(function(){
	var _token = $('meta[name="_token"]').attr('content');

	loadNotes();
	loadVehicles();
	loadDeliverySummary();

	$.dragdrop({
		section: '.section1',
		ondrop: function($from, $to){
			dropItem($from, $to);
		}
	});

	$(document).on('keyup', '.pallet', function(e){
		updatePallets($(this));
	});

	$(document).on('focus', '.pallet', function(e){
		$(this).select();
	});

	$('a[href="#panel_2"]').click(function(){
		loadDeliverySummary();
	});

	$('.addNote').click(function(){
		var id = $('.note').val();
		addNote(id);
	});

	$('.addVehicle').click(function(){
		var id = $('.vehicle').val();
		addVehicle(id);
	});

	$('.save').click(function(){
		saveDelivery();
	});

	function loadDeliverySummary(){
		$.post("<?php echo e(url('/shuttle/loadDeliverySummary')); ?>", {_token: _token}, function(e){
			console.log(e);
		}, 'json');
	}

	function saveDelivery(){
		//todo check if delivery notes & vehicles added 

		validateDelivery(function(data){
			$.post("<?php echo e(url('/shuttle/saveDelivery')); ?>", {_token: _token, data: data}, function(e){
				$.highlightOrThrow(e, function(){
					$('.noteWrapper').html('');
					$('.vehicleWrapper').html('');
				});
			}, 'json');
		});

	}

	function validateDelivery(callback){
		var data = [];

		$.clearHighlights();
		var size = $('.vehicle_thumbnail', '.vehicleWrapper').length;
		$.each($('.vehicle_thumbnail', '.vehicleWrapper'), function(i){
			var $thumbnail = $(this);

			//todo : validate qty of both sides

			//check if no items added
			var itemCount = $('table tbody tr', $thumbnail).length;
			if(itemCount == 0){
				$.notify.error('<b>Some vehicles dont have items added.</b>');
				return false;
			}

			var from = $('.trip', $thumbnail).data('from');
			var to = $('.trip', $thumbnail).data('to');

			if(from == undefined || to == undefined){
				$.notify.error('<b>Some vehicles dont have destinations added</b>');
				return false;
			}

			var pallet = $('.pallet', $thumbnail).val();
			if(!$.isInt(pallet)){
				$.notify.error('<b>Invalid pallet amount</b>');
				$('.pallet', $thumbnail).highlightElement({msg: 'Invalid amoung'});
				return false;
			}

			pallet = +pallet;
			if(pallet == 0){
				$.notify.error('<b>Invalid pallet amount</b>');
				$('.pallet', $thumbnail).highlightElement({msg: 'Invalid amoung'});
				return false;
			}

			var capacity = $.trim($('.capacity', $thumbnail).html());
			if(!$.isInt(capacity)){
				$.notify.error('<b>Invalid pallet capacity</b>');
				$('.capacity', $thumbnail).closest('progress').highlightElement({msg: 'Invalid pallet capacity'});
				return false;
			}
			capacity = +capacity;

			if(capacity == 0){
				$.notify.error('<b>Invalid pallet capacity</b>');
				$('.capacity', $thumbnail).closest('progress').highlightElement({msg: 'Invalid pallet capacity'});
				return false;
			}

			if(pallet > capacity){
				$.notify.error('<b>Maximum pallets allowed ('+ capacity +') exeeded.</b>');
				$('.pallet', $thumbnail).highlightElement({msg: 'Maximum pallets allowed ('+ capacity +') exeeded'});
				return false;
			}


			var record = {
				vehicle: $thumbnail.data('vehicle'),
				pallet: pallet
			};
			
			var trLength = $('table tbody tr', $thumbnail).length;
			var notes = [];
			$('table tbody tr', $thumbnail).each(function(j){
				// notes.push();
				var id = $(this).data('item').split('_').length > 0 ? +$(this).data('item').split('_')[0] : 0;
				var delivery_item_id = +$(this).data('delivery_item_id');
				var item = $(this).data('item').split('_').length > 1 ? +$(this).data('item').split('_')[1] : 0;
				var qty = +$.trim($(this).find('.qty').html());



				notes.push({delivery_item_id: delivery_item_id, item: item, qty: qty});

				if((++j) == trLength){

					record.delivery = notes;
					data.push(record);

					if((++i) == size){
						//end of all loops
						if(callback != undefined && typeof(callback) == 'function'){
							callback(data);
						}
					}
				}
			});

		});
	}

	function updatePallets($_this){
		var pallets = $_this.val() != '' ? $_this.val() : 0;
		var $progress = $_this.closest('.vehicle_thumbnail').find('.progress .progress-bar');

		if($progress.length > 0){
			if($.isInt(pallets)){
				$.clearHighlights();
				pallets = +pallets;
				var percentage = 0;
				var capacity = +$.trim($('.capacity', $progress).html());
				if(capacity > 0){
					if(pallets <= capacity){
						percentage = ((pallets)/(capacity))*100;
					}else{
						percentage = 0;
						pallets = 0;
						$_this.highlightElement({msg: 'Maximum pallets allowed ('+ capacity +') exeeded.'});
					}
				}else{
					percentage = 0;
					pallets = 0;
					$progress.parent('div').highlightElement({msg: 'Invalid pallet capacity'});
				}
			}else{
				percentage = 0;
				pallets = 0;
				$_this.highlightElement({msg: 'Invalid amount.'});
			}

			$progress.css({width: percentage+'%'});
			$('.count', $progress).html(pallets);
		}

	}

	function getVehicleTR(data){
		var dom = '<tr data-item="'+ data.item +'" data-delivery_item_id="'+ data.delivery_item_id +'">';
		dom += '<td>'+ data.name +'</td>';
		dom += '<td class="qty">'+ data.qty +'</td>';
		dom += '<td>';
		dom += '<button class="btn btn-danger btn-xs"><i class="fa fa-close"></i></button>';
		dom += '</td>';
		dom += '</tr>';

		return dom;
	}

	function update_and_addTR($from, $to, item, originalQty, data){
		if($('[data-item="'+ item +'"]', $to).length == 0){
			//we are adding a new item
			$('table tbody', $to).append(getVehicleTR(data));
		}else{
			//item already added. we need to modify the qty
			var $updateRow = $('[data-item="'+ item +'"]');
			var currentQty = +$('.qty', $updateRow).html();
			var updatedQty = currentQty + data.qty;
			$('.qty', $updateRow).html(updatedQty);
		}
		$from.data('qty', (originalQty - data.qty));
		$('.qty', $from.closest('tr')).html(originalQty - data.qty);
		clearNoteInputs();
	}

	function dropItem($from, $to){
		$.clearHighlights();
		var item = $from.data('item');
		var from = $from.data('from');
		var to = $from.data('to');
		var originalQty = +$from.data('qty');

		var data = {
			item: $from.data('item'),
			name: $from.data('name'),
			txtFrom: $from.data('txtfrom'),
			txtTo: $from.data('txtto'),
			delivery_item_id: $from.data('delivery_item_id'),
			qty: +$('input:text', $from).val(),
		};

		//validate qty, original qty

		if(originalQty >= data.qty){

			var curFrom = $('.trip', $to).data('from');
			var curTo = $('.trip', $to).data('to');
			var destionationsAvailable = curFrom != undefined && curTo != undefined;

			if(destionationsAvailable){
				if((curFrom == from && curTo == to) || (curFrom == to && curTo == from)){
					//all good. we are inserting an item having same destinations

					update_and_addTR($from, $to, item, originalQty, data);

				}else{
					$.notify.error('<b>Destinations mismatch</b>');
				}
			}else{

				update_and_addTR($from, $to, item, originalQty, data);

				$('.trip').data('from', from);
				$('.trip').data('to', to);
				$('.trip', $to).html(data.txtFrom + ' - ' + data.txtTo);

			}
			
		}else{
			$('input:text', $from).highlightElement({msg: 'Invalid Qty.'});
		}

	}

	function clearNoteInputs(){
		$('input:text', '.noteWrapper').val('');
	}

	function addVehicle(id){
		var $wrapper = $('.vehicleWrapper');
		var elementCount = $('[data-vehicle="'+ id +'"]', $wrapper).length;

		if(elementCount == 0){
			$.post("<?php echo e(url('/shuttle/addVehicle')); ?>", {_token: _token, id: id}, function(e){
				if(e != undefined && typeof(e) == 'object'){
					var dom = '';

					dom += '<div class="form-group thumbnail vehicle_thumbnail drop" data-vehicle="'+ e.id +'" style="padding: 10px;">';
					dom += '	<h4 style="display: inline; margin: 0px;">'+ e.number +' <small class="pull-right">'+ e.transporter +'<i class="btn btn-xs text-danger fa fa-close pull-right"></i></small></h4>';
					dom += '	<hr style="margin: 15px 0px 20px 0px;">';
					dom += '	<table class="table table-bordered">';
					dom += '		<thead>';
					dom += '			<tr>';
					dom += '				<th>Name</th>';
					dom += '				<th width="80px">Qty</th>';
					dom += '				<th width="35px"></th>';
					dom += '			</tr>';
					dom += '		</thead>';
					dom += '		<tbody></tbody>';
					dom += '	</table>';
					dom += '	<div class="thumbnail trip" style="height: 30px;"></div>';
					dom += '	<div class="form-group">';
					dom += '		<label class="control-label">Pallets</label>';
					dom += '		<input type="text" class="form-control pallet" placeholder="Enter no of pallets">';
					dom += '	</div>';
					dom += '	<div class="progress" style="margin-bottom: 4px;">';
					dom += '		<div class="progress-bar progress-bar-info" role="progressbar">';
					dom += '			<div class="text-danger" style="font-weight:bold;">';
					dom += '				<span>Pallets&nbsp;</span><span class="count">0</span>&nbsp;/&nbsp;<span class="capacity">'+ e.pallet +'</span>';
					dom += '			</div>';
					dom += '		</div>';
					dom += '	</div>';
					dom += '</div>';

					$wrapper.prepend(dom);
				}
			}, 'json');
		}else{
			$.notify.error('<b>Item already added.</b>');
		}
	}

	function addNote(id){
		var $wrapper = $('.noteWrapper');
		var elementCount = $('[data-note="'+ id +'"]', $wrapper).length;
		if(elementCount == 0){
			$.post("<?php echo e(url('/shuttle/addNote')); ?>", {_token: _token, id: id}, function(e){
				if(e != undefined && typeof(e) == 'object' && e.hasOwnProperty('note') && e.hasOwnProperty('items')){
					var dom = '';
					var attributes = '';
					var note = e.note;

					dom += '<div class="form-group thumbnail" data-note="'+ note.id +'" style="padding: 10px;">';
					dom += '	<h4 style="margin: 0px;">'+ note.txtFrom +' - '+ note.txtTo +'<small><i class="btn btn-xs text-danger fa fa-close pull-right"></i></small></h4>';
					dom += '	<hr style="margin: 15px 0px 20px 0px;">';
					dom += '	<table class="table table-bordered">';
					dom += '		<thead>';
					dom += '			<tr>';
					dom += '				<th>Name</th>';
					dom += '				<th width="80px">Qty</th>';
					dom += '				<th width="120px"></th>';
					dom += '			</tr>';
					dom += '		</thead>';
					dom += '		<tbody>';
					if(typeof(e.items) == 'object' && e.items.length > 0){
						$.each(e.items, function(i, item){

							attributes += 'data-delivery_item_id="'+ item.delivery_item_id +'" ';
							attributes += 'data-item="'+ note.id +'_'+ item.id +'" ';
							attributes += 'data-from="'+ note.from + '" ';
							attributes += 'data-txtfrom="'+ note.txtFrom + '" ';
							attributes += 'data-to="'+ note.to + '" ';
							attributes += 'data-txtto="'+ note.txtTo + '" ';
							attributes += 'data-qty="'+ item.qty + '" ';
							attributes += 'data-name="'+ item.name + '" ';

							dom += '	<tr>';
							dom += '		<td>'+ item.name +'</td>';
							dom += '		<td class="qty">'+ item.qty +'</td>';
							dom += '		<td>';
							dom += '			<div class="input-group drag" draggable="true" '+ attributes +'>';
							dom += '				<input type="text" class="form-control">';
							dom += '				<span class="input-group-addon"><i class="fa fa-arrows-alt"></i></span>';
							dom += '			</div>';
							dom += '		</td>';
							dom += '	</tr>';
						});
					}
					dom += '		</tbody>';
					dom += '	</table>';
					dom += '</div>';

					$wrapper.prepend(dom);
				}
			}, 'json');
		}else{
			$.notify.error('<b>Item already added.</b>');
		}
	}

	function loadNotes(){
		var $select = $('.note');
		$.post("<?php echo e(url('/shuttle/loadNotes')); ?>", {_token: _token}, function(e){
			var dom = '';
			if(e != undefined && typeof(e) == 'object' && Object.keys(e).length > 0){
				$.each(e, function(i, k){
					dom += '<option value="'+ k.id +'">Delivery note #'+ k.id +'</option>';
				});
			}else{
				dom = '<option>No items found.</option>';
			}
			$select.html(dom);
		}, 'json');
	}

	function loadVehicles(){
		var $select = $('.vehicle');
		$.post("<?php echo e(url('/shuttle/loadVehicles')); ?>", {_token: _token}, function(e){
			var dom = '';
			if(e != undefined && typeof(e) == 'object' && Object.keys(e).length > 0){
				$.each(e, function(i, k){
					dom += '<option value="'+ k.id +'">'+ k.name +' - '+ k.number +'</option>';
				});
			}else{
				dom = '<option>No items found.</option>';
			}
			$select.html(dom);
		}, 'json');
	}

});

</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.master', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>