<div class="form-horizontal">
	<div class="col-md-12">
		<h4> Punto de venta: <%= @pointsale.name %> </h4>
		<table class="table table-striped table-bordered table-hover" id="table_assign_or_delete">
			<thead>
				<tr>
					<th> Producto </th>
					<th> Stock inicial </th>
				</tr>
			</thead>
			<tbody>
				<% @products.each do |product| %>
					<tr id="product_<%= product.id %>">
						<td> 
							<strong><%= product.name %></strong> <br>
							SKU: <%= product.sku %> <br>
							<% if product.display_attributes.present? %>
								<%= product.display_attributes %> <br>
							<% end %>
							<%= product.description if product.description.present? %>
						</td>
						<td> 
    						<input type="number" min="0" class="form-control" value="0" pattern="^[0-9]*[1-9][0-9]*$" title="Stock con el que se agregará el producto al punto de venta">
						</td>
					</tr>
				<% end %>
			</tbody>
		</table>
	</div>
	<div class="form-actions">
		<div class="row">
			<div class="col-md-9">
  				<button type="button" title="Asignar los productos seleccionados al punto de venta" 		class="btn blue" onclick="assignOrDeleteProducts($(this))"> 
  					<i class="fa fa-long-arrow-right"></i> Asignar productos
				</button>
				<button class="btn default" onclick="closeModal()">Cancelar</button>
			</div>
		</div>
	</div>	
</div>

<script>
	function closeModal() {
		$('#dialog').modal('toggle');
	}

	function assignOrDeleteProducts(button) {
		button.attr('disabled', true);
		var products = [];
		$('#table_assign_or_delete tbody tr').each(function(row) {
			var idText = $(this).attr('id');
    		var product_id = idText.substring(idText.lastIndexOf('_') + 1, idText.length);
    		var obj = { id: product_id, stock: $(this).find('input').val() };			
	      	products.push(obj);  
	    });	

	    $.ajax({
	      type: "POST",
	      url: "/pointsales/"+ <%= @pointsale.id %> + "/assign_products_to_pointsale",
	      dataType: "json",
	      data: {
	      	products: JSON.stringify(products) 
	      },
	      success: function(xhr, status, error) {
	      	button.attr('disabled', false);
	      	toastr["success"]("Productos asignados correctamente.");
	      	$('#dialog').modal('toggle');
	      	$(class_1).DataTable().draw(); 
	      	$(class_2).DataTable().draw();

	      }
	    });	 
	}
</script>
