// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require tether
//= require bootstrap
//= require jquery_ujs
//= require turbolinks
//= require cable
//= require jquery-ui
//= require bootstrap-datepicker

$(document).ready(function(){
	// auto refresh every 60 seconds
	// setTimeout(function(){
	//    window.location.reload(1);
	// }, 60000);

	// For selected order return
	var order_status = "";
	order_status = $(".selected-item").children().find(".orders-order-status").text().substr(0,6).trim();

	// Enable/Disable Button
	control_button(order_status);

	$(".orders").on('click', function(){
		$("#order-sub-total").text('');
        // $("#order-food").text('');
        // $("#order-beverage").text('');
        $("#order-discount").text('');
        $("#order-Tax").text('');
        $("#order-grand-total").text('');

		var zone_name=$(this).find(".orders-table").text();
		var receipt_no=$(this).find(".orders-receipt-no").text();
		var unique_id = $(this).find(".orders-id").text();
		var order_status=$(this).find(".orders-order-status").text().trim();

		// Enable/Disable Button
		control_button(order_status);

		var customer_id=$(this).find(".customer-id").text();
		show_customer_details(customer_id);

		$("#re-print").val(unique_id);

		var cashier="";
		var receipt_date="";
		var sub_total=0.0;
		var discount_amount=0;
		var tax_amount=0;
		var grand_total_amount=0;

		$("#order-title").text("ORDER DETAILS - " + zone_name);
		// clear order items
		$("#order-items-table").children("tbody").empty();

		// AJAX call for order
		$.ajax({
			type: "POST",
		    url: "/origami/" + unique_id,
		    data: { 'booking_id' : unique_id },
		    success:function(result){		    	
		    	for (i = 0; i < result.length; i++) {
		    		var data = JSON.stringify(result[i]);
        			var parse_data = JSON.parse(data);
        			var show_date = "";        			

        			// Receipt Header
        			receipt_no = result[i].receipt_no;
			        cashier = result[i].cashier_name;
			        if(result[i].receipt_date != null){
				        receipt_date = new Date(result[i].receipt_date);
				        show_date = receipt_date.getDate() + "-" + receipt_date.getMonth() + "-" + receipt_date.getFullYear() + ' ' +  receipt_date.getHours()+ ':' +  receipt_date.getMinutes()
				    }			        

			        //Receipt Charges
        			sub_total += parseFloat(parse_data.price);

        			discount_amount = parse_data.discount_amount == null? '0.0' : parse_data.discount_amount;
        			tax_amount = parse_data.tax_amount;
			        grand_total_amount = parse_data.grand_total_amount;			        

			        // Ordered Items
			        var order_items_rows = "<tr>" +
				        						"<td class='item-name'>" + parse_data.item_name + "</td>" +
				        						"<td class='item-attr'>" + parse_data.qty + "</td>" +
				        						"<td class='item-attr'>" + parse_data.price + "</td>" +
			        					   "</tr>";

			        $("#order-items-table").children("tbody").append(order_items_rows);
		    	}

		    	// Cashier Info
		    	$("#receipt_no").text(receipt_no);
		        $("#cashier").text(cashier == null ? "" : cashier);
		        $("#receipt_date").text(show_date);

		        // Payment Info
		    	$("#order-sub-total").text(sub_total);
		        // $("#order-food").text('');
		        // $("#order-beverage").text('');
		        $("#order-discount").text(discount_amount);
		        $("#order-Tax").text(tax_amount);
		        $("#order-grand-total").text(grand_total_amount);
		    }
		});
		// End AJAX Call

		$('.orders').removeClass('selected-item');
	    $(this).addClass('selected-item');
	});

	// Bill Request
	$('#request_bills').click(function() {
		var order_id=$(".selected-item").find(".orders-id").text().substr(0,16);
		if(order_id!=""){
			window.location.href = '/origami/' + order_id + '/request_bills'
		}
		else {
			alert("Please select an order!");
		}
		return false;
	});

	// Discount for Payment
	$('#discount').click(function() {
		var order_id=$(".selected-item").find(".orders-id").text().substr(0,16);
		
		if(order_id!=""){
			window.location.href = '/origami/' + order_id + '/discount'
		}
		else {
			alert("Please select an order!");
		}

		return false;
	});

	// Pay Discount for Payment
	$("#pay-discount").on('click', function(e){
		e.preventDefault();
		var sale_id = $('#sale-id').text();
		var sale_item_id = $('.selected-item').attr('id').substr(0,16);
		var sub_total = $('#order-sub-total').text();
		var grand_total = $('#order-grand-total').text();
		var discount_type = $('#discount-type').val();
		var discount_value = $('#discount-amount').val();
		var discount_amount = discount_value;
		var ajax_url = "/origami/" + sale_id + "/discount";

		if(sale_item_id != null){
			ajax_url = "/origami/" + sale_item_id + "/discount";
			sub_total =  $("#"+sale_item_id).children().find("#item-total-price").text();
		}

		// For Percentage Discount
		if(discount_type == 1){			
			discount_amount=(sub_total*discount_value)/100;
		}

		var params = {'sale_id': sale_id, 'sale_item_id': sale_item_id, 'grand_total' : grand_total, 'discount_type':discount_type, 'discount_value':discount_value, 'discount_amount':discount_amount};
		$.ajax({
			type: "POST",
		    url: ajax_url,
		    data: params,
		    success:function(result){	}
		});
	});


	// Payment for Bill
	$('#pay-bill').click(function() {
		var sale_id=$(".selected-item").find(".orders-id").text().substr(0,16);
		if(sale_id!=""){
			window.location.href = '/origami/sale/'+ sale_id  + "/payment"
		}
		else {
			alert("Please select an order!");
		}

		return false;
	});

	$('#customer').click(function() {
		var sale = $(".selected-item").find(".orders-id").text().substr(0,16);
		if (sale.substring(0, 3)=="SAL") {
			var sale_id = sale
		}else{
			var sale_id = $(".selected-item").find(".order-cid").text();
		}
		window.location.href = '/origami/'+ sale_id  + "/customers"

		return false;
	});

	$('#re-print').click(function() {
		var sale_id = $(".selected-item").find(".orders-id").text().substr(0,16);
		
		window.location.href = '/origami/'+ sale_id  + "/reprint"

		return false;
	});

	function show_customer_details(customer_id){

		if(window.location.pathname.substring(0, 12) == "/origami/SAL"){
	    	var url = customer_id+"/get_customer/"
	    }else{
	    	var url = "origami/"+customer_id+"/get_customer/"
	    }

		$('.customer_detail').removeClass('hide');

		  //Start Ajax
		  $.ajax({
		  	type: "GET",
		  	url: url,
		  	data: {},
		  	dataType: "json",
		  	success: function(data) {
		  		$("#customer_name").text(data["customer"].name);
		  		if (data["response_data"]["data"].length) {
		  			$.each(data["response_data"]["data"], function (i) {
			  			if(data["response_data"]["data"][i]["accountable_type"] == "RebateAccount"){
			  				var balance = data["response_data"]["data"][i]["balance"];
			  				if (data["response_data"]["status"]==true) {
			  					$('.rebate_amount').removeClass('hide');
				  				row =
				                 '<td class="charges-name">' + data["response_data"]["data"][i]["accountable_type"] +'</td>'
				                 +'<td class="item-attr">' + balance + '</td>';

				                 $(".rebate_amount").html(row);
			  				}

			  			}
			  		});
		  	    }else{
		  	    	$('.rebate_amount').addClass('hide');
		  	    }
		  	}
		  });
		    //End Ajax
	}

	/* For Receipt - Calculate discount or tax */
	$('.cashier_number').on('click', function(event){
	    if(event.handled !== true) {
	        var original_value=0;
	        original_value = $('#discount-amount').val();

	        var input_type = $(this).attr("data-type");

	        switch (input_type) {
	          case 'num':
					var input_value = $(this).attr("data-value");
					if (original_value == "0.0"){
						$('#discount-amount').val(input_value);
						update_balance();
					}
					else{
						$('#discount-amount').val(original_value + '' + input_value);
						update_balance();
					}
					break;

	          case 'add':
					var input_value = $(this).attr("data-value");
					amount = parseInt(input_value);
					$('#discount-amount').val(amount);
					$('#discount-type').val(1);
					update_balance();
					break;

			  case 'del' :
			  		var discount_text=$('#discount-amount').val();
			  		$('#discount-amount').val(discount_text.substr(0,discount_text.length-1));
					update_balance();
					break;

	          case 'clr':
	             $('#discount-amount').val("0.0");
	             update_balance();
	          break;
			}

	      event.handled = true;
	    } else {
	        return false;
	    }
	});

	$('.discount-item-row').on('click',function(){
		$('.discount-item-row').removeClass('selected-item');
		$(this).addClass('selected-item');
	});

});

/* Button Control by Status */
function control_button(order_status){
	if(order_status=="billed"){
		$("#customer").prop('disabled', false);
		$("#request_bills").prop('disabled', true);
		$("#discount").prop('disabled', false);
		$("#pay-bill").prop('disabled', false);
		$("#re-print").prop('disabled', true);
	}
	else if(order_status=="new") {
		$("#customer").prop('disabled', false);
		$("#request_bills").prop('disabled', false);
		$("#discount").prop('disabled', true);
		$("#pay-bill").prop('disabled', true);
		$("#re-print").prop('disabled', true);
	}else if(order_status=="completed"){
		$("#re-print").prop('disabled', false);
	}
	else {
		$("#customer").prop('disabled', true);
		$("#request_bills").prop('disabled', true);
		$("#discount").prop('disabled', true);
		$("#pay-bill").prop('disabled', true);
		$("#re-print").prop('disabled', true);
	}

}

/* For Receipt - Update Balance */
function update_balance(){
	var discount_type = $('#discount-type').val();
	var discount_amount = $('#discount-amount').val();
	var sub_total = $('#order-sub-total').text();
	var tax = $('#order-Tax').text();

	// For Percentage Discount
	if(discount_type == 1){
		discount_amount=(sub_total*discount_amount)/100;
	}

	var total = (parseFloat(sub_total) + parseFloat(tax)) - discount_amount;
	$('#order-discount').text(discount_amount);
	$('#order-grand-total').text(total);
}
