
var baseURL=$('meta[name="base_url"]').attr('content');
var token_key=$('#token_key').val();

$(function() {
	getProducts();
	getInList();
});



function getProducts() {

	//var parameter = '&csrf_secure_name=' + token_key;
	$.ajax({
		url: baseURL + "dataHandling/allProductJson",
		type: 'GET',
		/* data: parameter,*/
		dataType:'json',
		success: function(response) {
			console.log(response);
			items="";
			check="";
			$.each(response,function(index,item)
			{
				if(item.presentation_status=='2'){
					check='checked';
				}
				else if(item.presentation_status=='1,2'){
					check='checked';
				}
				else{
					check='';
				}
				items+="<tr><td>"+item.product_name+"</td><td>"+item.product_model+"</td><td>"+item.size+"</td><td><input type='checkbox' class='custom-checkbox' name='product_id[]' value='"+item.product_id+"' "+check+"></td></tr>";
			});
			$(".product_table_data").html(items);
		}
	})
}

function getInList() {

	//var parameter = '&csrf_secure_name=' + token_key;
	$.ajax({
		url: baseURL + "dataHandling/allTopSaleProductJson",
		type: 'GET',
		/* data: parameter,*/
		dataType:'json',
		success: function(response) {
			console.log(response);
			items="";
			check="";
			$.each(response,function(index,item)
			{
				items+="<tr><td>"+item.product_name+"</td><td>"+item.product_model+"</td><td>"+item.size+"</td></tr>";
			});
			$(".list_data").html(items);
		}
	})
}

$("#addForm").validate({
	submitHandler: function(form) {

		$('.submit_button').css('cursor', 'wait');
		$('.submit_button').attr('disabled', true);

		$.ajax({
			url: baseURL + "topSaleProductAdd",
			type: 'POST',
			data: $('#addForm').serialize(),
			dataType:'json',
			success: function(res) {
				var response_brought = res.response.indexOf('Top Sale Product Added!');

				if (response_brought != -1)
				{
					swal({
						title: "Top Sale Product Added!",
						type: "success",
						timer: 1500,
						showConfirmButton: false,
						customClass: 'swal-height'
					});

					$("#addForm").trigger("reset");
					getProducts();
					getInList();
				}

				$('.submit_button').css('cursor', 'pointer');
				$('.submit_button').removeAttr('disabled');

			}
		});
	},                                                // Do not change code below
	errorPlacement: function(error, element)
	{
		error.insertAfter(element.parent());
	}

});

var limit = 8;
$(document).on("change", ".custom-checkbox", function () {
	if($('.custom-checkbox').filter(':checked').length >= limit) {
		this.checked = false;
		swal({
			title: "Can't add more than 8 ",
			type: "error",
			timer: 1500,
			showConfirmButton: false,
			customClass: 'swal-height'
		});
	}
});
