 <div class="row">
  <!-- Column One -->
  <div class="col-lg-6 col-md-6 col-sm-6">
    <!-- Order Details -->
    <div class="card"  >
        <!-- <div class="card-header">
          <div><strong id="order-title">ORDER DETAILS</strong></div>
        </div> -->
        <div class="card-block">
          <div class="card-title row">
            <div class="col-lg-6 col-md-6 col-sm-6">
              <p id="sale-id" class="hidden"><%=@sale_data.sale_id %></p>
              <p>Receipt No: <span id="receipt_no"><%=@sale_data.receipt_no rescue ' '%></span></p>
              <!-- <p>Cashier:  <span id="cashier"><%=@sale_data.cashier_name rescue ' '%></span></p> -->
            </div>
            <div class="col-lg-6 col-md-6 col-sm-6 text-right">
              <p>Date:  <span id="receipt_date"> <%=@sale_data.receipt_date.strftime("%d/%m/%Y - %I:%M %p") rescue '-'%></span></p>
            </div>
          </div>
          <div class="card-text">
            <table class="table table-default" id="order-items-table">
              <thead>
                <tr>
                  <th class="item-name">Items</th>
                  <th class="item-attr">QTY</td>
                  <th class="item-attr">Price</td>
                </tr>
              </thead>
              <tbody>
                <% sub_total = 0 %>
	            <% @sale_data.sale_items.each do |sale_item| %>
	          		<% 
		          		sub_total += sale_item.qty*sale_item.unit_price 
		          		unless sale_item.price == 0
	          		%>
	            	<tr class="item-row" id=<%= sale_item.sale_item_id %> >
	                    <td style="width:60%; text-align:left">
	                       <span id="item-account-type" class="hidden"><%=sale_item.account_id%></span>
	                       <span id="item-name-price"><%=sale_item.product_name%>@<%=sale_item.unit_price%></span>
	                    </td>
	                    <td style="width:20%; text-align:right">
	                      <span id="item-qty"><%=sale_item.qty%></span>
	                    </td>
	                    <td style="width:20%; text-align:right">
	                       <span id="item-total-price"><%=(sale_item.qty*sale_item.unit_price)%></span>
	                    </td>
	                  </tr>
	            <%
	            	   	end
	            	end 
	            %>
              </tbody>
            </table>
          </div>
          <div class="card-footer">
            <table class="table" id="order-charges-table" border="0">
              <tr>
                <td class="charges-name"><strong>Sub Total:</strong></td>
                <td class="item-attr"><strong id="order-sub-total"><%=sub_total%></strong></td>
              </tr>
              <!-- <tr>
                <td class="charges-name"><strong>Food:</strong></td>
                <td class="item-attr"><strong id="order-food"></strong></td>
              </tr>
              <tr>
                <td class="charges-name"><strong>Beverage:</strong></td>
                <td class="item-attr"><strong id="order-beverage"></strong></td>
              </tr> -->
              <tr>
                <td class="charges-name"><strong>Discount:</strong></td>
                <td class="item-attr">(<strong id="order-discount"><%=@sale_data.total_discount rescue 0%></strong>)</td>
              </tr>
              <tr class="hidden">
                <td class="charges-name"><strong>Tax:</strong></td>
                <td class="item-attr"><strong id="order-Tax"><%=@sale_data.total_tax rescue 0%></strong></td>
              </tr>
              <tr class="hidden">
                <td class="charges-name"><strong>Grand Total:</strong></td>
                <td class="item-attr"><strong id="order-grand-total"><%=@sale_data.grand_total rescue 0%></strong></td>
              </tr>
            </table>
          </div>
        </div>
    </div>
  </div>
  <!-- Column One -->

  <!-- Column Two -->
  <div class="col-lg-5 col-md-5 col-sm-5">
	<!-- Discount Amount -->
    <div class="card">
        <div class="card-header">
          <div><strong id="order-title">Discount Control</strong></div>
        </div>
        <div class="card-block">
			<div class="card-title">
				<div class="form-horizontal">
					<div class="col-md-12">	
						<div class="form-group">											
							<input type="text" id="discount-amount" name="discount-amount" value="<%= @sale_data.total_discount rescue 0 %>" class="form-control" />
						</div>
						<div class="form-group">			
							<%
								@accounts.each do |acc|								
							%>
							<button id="account-<%= acc.id %>" class="accounts-type btn btn-default"><%= acc.title %></button>
							<% end %>
						</div>
					</div>					
				</div>
			</div>

			<hr />

	      	<div class="row">
	      		<div class="col-md-9">
		         <div class="row bottom">
		           <div class="col-md-3">
		              <div class="fluid cashier_number" data-value="5" data-type="add">5%</div>
		           </div>
		           <div class="col-md-9">
		                 <div class="col-md-4 cashier_number" data-value="1" data-type="num">1</div>
		                 <div class="col-md-4 left cashier_number" data-value="2" data-type="num">2</div>
		                 <div class="col-md-4 left cashier_number" data-value="3" data-type="num">3</div>
		            </div>
		         </div>

		         <div class="row bottom">
		           <div class="col-md-3">
		             <div class="fluid cashier_number" data-value="10" data-type="add">10%</div>
		           </div>
		           <div class="col-md-9">
		                <div class="col-md-4 cashier_number" data-value="4" data-type="num">4</div>
		                <div class="col-md-4 left cashier_number" data-value="5" data-type="num">5</div>
		                <div class="col-md-4 left cashier_number" data-value="6" data-type="num">6</div>
		           </div>
		         </div>

		         <div class="row bottom">
		            <div class="col-md-3">
		                <div class="fluid cashier_number" data-value="20" data-type="add">15%</div>
		            </div>
		            <div class="col-md-9">
		                 <div class="col-md-4 cashier_number" data-value="7" data-type="num">7</div>
		                 <div class="col-md-4 left cashier_number" data-value="8" data-type="num">8</div>
		                 <div class="col-md-4 left cashier_number" data-value="9" data-type="num">9</div>
		            </div>
		         </div>

		          <div class="row bottom">
		          	 <div class="col-md-3">
		                <div class="fluid cashier_number" data-value="30" data-type="add">20%</div>
		             </div>
		             <div class="col-md-9">
		                  <div class="col-md-4 cashier_number" data-value="0" data-type="num">0</div>
		                  <div class="col-md-4 left cashier_number" data-value="." data-type="num">.</div>
		                  <div class="col-md-4 left cashier_number" data-value="00" data-type="num">00</div>
		             </div>
		          </div>

		          <div class="row">
		          	 <div class="col-md-3">
		                <div class="fluid cashier_number" data-value="50" data-type="add">30%</div>
		             </div>
		             <div class="col-md-9">
		                 <div class="col-md-4 cashier_number"></div>
		                 <div class="col-md-4 left cashier_number red" data-type="del">DEL</div>
		                 <div class="col-md-4 left cashier_number green" data-type="clr">CLR</div>
		             </div>
		          </div>
		      	</div>

		      	<div class="col-md-3">
		      		<div class="form-group">
						<button id="net" class="btn btn-info fluid action-btn">Nett</button>
						<button id="percentage" class="btn btn-primary fluid action-btn">Percentage</button>	
						<button id="remove-item" class="btn btn-default fluid action-btn">Clear Discount</button>
		      		</div>
	        	</div>
	      	</div>	
        </div>
    </div>
  </div>

  <!-- Column Three -->
  <div class="col-lg-1 col-md-1 col-sm-1">
	<!-- Action Panel -->
    <div>
	    <button type="button" class="btn btn-primary btn-block" onclick="window.location.href = '/origami';"><i class="fa fa-arrow-left"></i> Back </button>
	    <button id="remove-item-discount" class="btn btn-warning btn-block action-btn">RemoveItem Discount</button>
	    <button id="remove-all" class="btn btn-warning btn-block action-btn">Remove All</button>
		<button id="pay-discount" class="btn btn-danger btn-block action-btn">Enter</button>
    </div>
  </div>
</div>

<script type="text/javascript">
$(document).ready(function(){
	$(".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);						
					}
					else{
						$('#discount-amount').val(original_value + '' + input_value);						
					}
					break;

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

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

	          case 'clr':
	             $('#discount-amount').val("0.0");	            
	          break;
		    }
	      	event.handled = true;
	    } else {
	        return false;
	    }
	});

	// Select Sale Item
	$('.item-row').on('click',function(){
		if($(this).hasClass('selected-item') == true){
			$(this).removeClass('selected-item');
		}
		else {
	    	$(this).addClass('selected-item');
	    }
	});

	// Select discount-item
	$('#order-items-table tbody').on('click', '.discount-item-row',function(){
		if($(this).hasClass('selected-item') == true){
			$(this).removeClass('selected-item');
		}
		else {
	    	$(this).addClass('selected-item');
	    }
	});

	// Select for account types
	$(".accounts-type").on('click', function(e){
		var account_id = $(this).attr('id').substr(8);

		if($(this).hasClass('selected-account') == true){
			$(this).removeClass('selected-account');
			$(".item-row").each(function(i){
	        	if($(this).children().find("#item-account-type").text() == account_id){
	        		$(this).removeClass("selected-item");
	        	}
	        });
		}
		else {
	    	$(this).addClass('selected-account');
	    	$(".item-row").each(function(i){
	        	if($(this).children().find("#item-account-type").text() == account_id){
	        		$(this).addClass("selected-item");
	        	}
	        });
	    }        
	});

	// Calculate Net Discount for Payment
	$("#net").on('click', function(e){
		e.preventDefault();
		var sale_id = $('#sale-id').text();
		var discount_value = $('#discount-amount').val();
		var ajax_url = "/origami/" + sale_id + "/discount";

		// Selected Items
		var sale_items = get_selected_sale_items();					

		// Selected Account
		var account_types = get_selected_account_types();

		if(sale_items.length == 0 && account_types.length == 0){
			calculate_overall_discount(0, discount_value);
		}
		else {
			calculate_item_discount(0, discount_value, sale_items, account_types);	
		}	

		// Remove Selection
		selection_remove();						
	});

	// Calculate Percentage Discount for Payment
	$("#percentage").on('click', function(e){
		e.preventDefault();
		var sale_id = $('#sale-id').text();
		var discount_value = $('#discount-amount').val();
		var ajax_url = "/origami/" + sale_id + "/discount";

		// Selected Items
		var sale_items = get_selected_sale_items();					

		// Selected Account
		var account_types = get_selected_account_types();
		
		if(sale_items.length == 0 && account_types.length == 0){
			calculate_overall_discount(1, discount_value);
		}
		else {
			calculate_item_discount(1, discount_value, sale_items, account_types);	
		}

		// Remove Selection
		selection_remove();			
	});

	// Remove selected discount items
	$("#remove-item").on('click', function(e){
		e.preventDefault();

		$('.discount-item-row.selected-item').each(function(i){
			$(this).remove();
		});
	});

	// Pay Discount for Payment
	$("#pay-discount").on('click', function(e){
		e.preventDefault();
		var sale_id = $('#sale-id').text();
		var discount_items = JSON.stringify(get_discount_item_rows());
		var overall_discount = $("#order-discount").text();
		var sub_total = $('#order-sub-total').text();		
		var ajax_url = "/origami/" + sale_id + "/discount";	

		var params = { 'sale_id': sale_id, 'sub_total': sub_total, 'discount_items': discount_items, 'overall_discount': overall_discount };

		$.ajax({
			type: "POST",
		    url: ajax_url,
		    data: params,
		    success:function(result){			    		    			    
		    	alert("Successfully Discount!");
		    	if(result.table_type == "Table"){
		    		window.location.href = "/origami/table/" + result.table_id
		    	}
		    	else {
		    		window.location.href = "/origami/room/" + result.table_id
		    	}		    	
		    }
		});
	});

	// Remove selected given discount item
	$("#remove-item-discount").on('click', function(e){
		e.preventDefault();
		var sale_id = $('#sale-id').text();
		var discount_items = [];

		// Selected Items		
		var sale_items = get_selected_sale_items();	
		if(sale_items.length == 0){
			alert("You have no selected item!");
			return;
		}

		for(var i=0;i < sale_items.length;i++){
			if(sale_items[i].price < 0){
				discount_items.push(sale_items[i]);
			}
			else {
				alert("You have selected no discount item!");
				return;
			}
		}

		var params = { 'sale_id': sale_id, 'discount_items': JSON.stringify(discount_items) };
		$.ajax({
			type: "POST",
			url: "/origami/" + sale_id + "/remove_discount_items",
			data: params,
			success: function(result){
				alert('Removed Discount');
				if(result.table_type == "Table"){
		    		window.location.href = "/origami/table/" + result.table_id
		    	}
		    	else {
		    		window.location.href = "/origami/room/" + result.table_id
		    	}
			}
		});
	});

	$("#remove-all").on('click', function(e){
		e.preventDefault();
		var sale_id = $('#sale-id').text();
		$.ajax({
			type: "GET",
			url: "/origami/" + sale_id + "/remove_all_discount",
			success: function(result){
				alert('Removed All Discount');
				if(result.table_type == "Table"){
		    		window.location.href = "/origami/table/" + result.table_id
		    	}
		    	else {
		    		window.location.href = "/origami/room/" + result.table_id
		    	}
			}
		});
	});
});

/* Remove Selection */
function selection_remove(){
	$(".item-row").removeClass("selected-item");
	$(".discount_item_row").removeClass("selected-item");
	$(".accounts-type").removeClass("selected-account");
}

/* Get Item rows but not discount*/
function get_item_rows(){
	var sale_items = [];	
	$('.item-row').not('.discount-item-row').each(function(i){
		var sale_item = {};
		sale_item.id = $(this).attr('id').substr(0,16);
		sale_item.name = $(this).find('#item-name-price').text().split('@')[0];
		sale_item.account_id = $(this).find('#item-account-type').text();
		sale_item.price = $(this).find('#item-total-price').text();
		sale_items.push(sale_item);
	});	
	return sale_items;
}

/* Get discount Item rows */
function get_discount_item_rows(){
	var sale_items = [];	
	$('.discount-item-row').each(function(i){
		var sale_item = {};
		sale_item.id = $(this).attr('id');
		sale_item.name = $(this).find('#item-name-price').text();
		sale_item.account_id = $(this).find('#item_account_type').text();
		sale_item.price = $(this).find('#item-total-price').text();
		sale_items.push(sale_item);
	});	
	return sale_items;
}

/* Get discount Item rows */
// function get_selected_discount_items(){
// 	var sale_items = [];	
// 	$('.discount-item-row').hasClass('.selected-item').each(function(i){
// 		var sale_item = {};
// 		sale_item.id = $(this).attr('id');
// 		sale_item.name = $(this).find('#item-name-price').text();
// 		sale_item.account_id = $(this).find('#item_account_type').text();
// 		sale_item.price = $(this).find('#item-total-price').text();
// 		sale_items.push(sale_item);
// 	});	
// 	return sale_items;
// }

/* Get Selected Sale Item's ID and Price */
function get_selected_sale_items(){
	var sale_items = [];	
	$('.item-row.selected-item').each(function(i){
		var sale_item = {};
		sale_item.id = $(this).attr('id').substr(0,16);
		sale_item.name = $(this).find('#item-name-price').text().split('@')[0];
		sale_item.account_id = $(this).find('#item-account-type').text();
		sale_item.price = $(this).find('#item-total-price').text();
		sale_items.push(sale_item);
	});	
	return sale_items;
}

/* Get Selected Accounts ID and Price */
function get_selected_account_types(){	
	var account_types = [];

	$('.selected-account').each(function(i){
		var account= {};
		account.id = $(this).attr('id').substr(8);
		account.name = $(this).text();			
		account_types.push(account);
	});	
	return account_types;
}

/* Calculate Overall Discount*/
function calculate_overall_discount(type, amount){
	var origin_sub_total = parseFloat($("#order-sub-total").text());	
	var dis_amount = 0;
	var sub_total = 0;
	var total_discount = 0;

	// For Net Pay
	if(type == 0){
		total_discount = amount;
	}

	// For Percentage Pay
	if(type == 1){
		if(amount > 100 ){
			aler("Percentage Value over 100!");
			return;
		}
		total_discount = (origin_sub_total * amount)/100;
	}

	$("#order-discount").text(total_discount);
}

/* Calculate Items Discount*/
function calculate_item_discount(type, amount, sale_items, account_types){
	var origin_sub_total = parseFloat($("#order-sub-total").text());	
	var dis_amount = 0;
	var sub_total = 0;
	var total_discount = 0;
	// For Net Pay
	if(type == 0){
		dis_amount = (0 - amount);
		if(sale_items.length > 0){
			for(var i=0;i < sale_items.length;i++){
				if(account_types.length > 0){
					for(var j=0; j < account_types.length; j++){
						if(sale_items[i].account_id != account_types[j].id){						
							// Discount Items
					        var discount_item_row = item_row_template(type, sale_items[i], dis_amount, amount);
					        $("#order-items-table tbody").append(discount_item_row);
					        total_discount = total_discount + amount;
						}
					}
				}
				else {
					var discount_item_row = item_row_template(type,sale_items[i], dis_amount, amount);
					$("#order-items-table tbody").append(discount_item_row);
					total_discount = total_discount + amount;
				}
			}
		}

		if(account_types.length > 0){			
			var item_rows=get_item_rows();
			if(item_rows.length > 0){
				for(var k=0; k < item_rows.length; k++){
					for(var j=0; j < account_types.length; j++){
						if(item_rows[k].account_id == account_types[j].id){
							// Discount Items
					        var discount_item_row = item_row_template(type, item_rows[k], dis_amount, amount);
					        $("#order-items-table tbody").append(discount_item_row);
					        total_discount = total_discount + amount;
						}
					}
				}
			}
			else {
				alert("No Items!");
			}						
		}

		sub_total = origin_sub_total - total_discount;
	}

	// For Percentage Pay
	if(type == 1){
		if(amount > 100 ){
			aler("Percentage Value over 100!");
			return;
		}

		// Check sale items exists
		if(sale_items.length > 0){
			for(var i=0;i < sale_items.length;i++){
				if(account_types.length > 0){
					for(var j=0; j < account_types.length; j++){
						if(sale_items[i].account_id != account_types[j].id){						
							// Discount Items
							dis_amount = 0 - ((sale_items[i].price * amount)/100);
					        var discount_item_row = item_row_template(type,sale_items[i], dis_amount, amount);
					        $("#order-items-table tbody").append(discount_item_row);
					        total_discount = total_discount + dis_amount;
						}
					}
				}
				else {
					dis_amount = 0 - ((sale_items[i].price * amount)/100);
					var discount_item_row = item_row_template(type,sale_items[i], dis_amount, amount);
					$("#order-items-table tbody").append(discount_item_row);
					total_discount = total_discount + dis_amount;

				}
			}
		}

		// Check account types exists
		if(account_types.length > 0){			
			var item_rows=get_item_rows();
			console.log(account_types);
			if(item_rows.length > 0){
				for(var k=0; k < item_rows.length; k++){
					for(var j=0; j < account_types.length; j++){
						if(item_rows[k].account_id == account_types[j].id){
							// Discount Items							
							dis_amount = 0 - ((item_rows[k].price * amount)/100);
					        var discount_item_row = item_row_template(type, item_rows[k], dis_amount, amount);
					        $("#order-items-table tbody").append(discount_item_row);
					        total_discount = total_discount + dis_amount;
						}
					}
				}
			}
			else {
				alert("No Items!");
			}						
		}

		sub_total = origin_sub_total + total_discount;
	}
	
	$("#order-sub-total").text(sub_total);
}

function item_row_template(type, item, discount_amount, amount){
	var dis_str = "-discount";
	if(type == 1){
		dis_str = dis_str + "(" + amount + "%)"
	}
	var discount_item_row = "<tr class='discount-item-row' id='" + item.id + "'>" +
        						"<td style='width: 60%; text-align: left;'>" + 
        						"<span id='item_account_type' class='hidden'>" + 
        							item.account_id +
        						"</span>" + 
        						"<span id='item-name-price'>" + 
        							item.name + dis_str +
        						"</span>" + 
        						"</td>" +
        						"<td style='width: 20%; text-align: right;'>" + 
        						"<span id='item-qty'>1</span>" +
        						"</td>" +
        						"<td style='width: 20%; text-align: right;'>" + 
        						"<span id='item-total-price'>" + 
        							discount_amount +
        						"</span>" + 
        						"</td>" +
    					   		"</tr>";
	return  discount_item_row; 					   		
}

</script>
