index.js

mail@pastecode.io avatar
unknown
javascript
a year ago
34 kB
0
Indexable
Never
$(document).ready(function(){

	var page = 1;
	var searchBrand = "";
	var searchSku = "";
	var searchModel = "";
	var searchShipper = [];
	var searchAvailable = "";
	var name = "";
	var allShippers = [];
	var list = document.getElementById("list");
	document.getElementById("resetFilterButton").addEventListener("click", resetFilter);
	document.getElementById("increaseButton").addEventListener("click", increaseSumRequest);
	document.getElementById("decreaseButton").addEventListener("click", decreaseSumRequest);

	document.getElementById("decreasePercentButton").addEventListener("click", decreasePercentSumRequest);
	document.getElementById("increasePercentButton").addEventListener("click", increasePercentSumRequest);
	
	document.getElementById("uploadFileButton").addEventListener("click", uploadFile);
	document.getElementById("ExcelUploadFileButton").addEventListener("click", uploadExcelFile);
	document.getElementById("ExcelUpdateButton").addEventListener("click", updateExcelPrice);
	document.getElementById("dippingButton").addEventListener("click", selectDippingFilter);

	document.getElementById("addSelectAllStores").addEventListener("change", selectStoresToAdd);

	var searchButton = document.getElementById("searchButton");
	searchButton.addEventListener("click", function(){
		searchSku = document.getElementById("inputSku").value;
		searchModel = document.getElementById("inputModel").value;
		searchBrand = "";
		searchShipper = "";
		searchAvailable = document.getElementById("availableFilter").value;

		var checks = document.querySelectorAll("#shipperCheck");
		for (var i = 0; i < checks.length; i++) {
			if (checks[i].checked) {
				if (searchShipper.length == 0) {
					searchShipper += checks[i].dataset.id;
				} else { 
					searchShipper += ",";
					searchShipper += checks[i].dataset.id;
				}
			}	
		}

		var brandChecks = document.querySelectorAll("#brandCheckbox");
		for (var i = 0; i < brandChecks.length; i++) {
			if (brandChecks[i].checked) {
				if (searchBrand.length == 0) {
					searchBrand += brandChecks[i].dataset.id;
				} else { 
					searchBrand += ",";
					searchBrand += brandChecks[i].dataset.id;
				}
			}	
		}




		page=1;
		getData();
	});

	$("#inputSku").on('keyup', function (e) {
		if (e.key === 'Enter' || e.keyCode === 13) {
			searchButton.click();
		}
	});
	$("#inputModel").on('keyup', function (e) {
		if (e.key === 'Enter' || e.keyCode === 13) {
			searchButton.click();
		}
	});
	$("#brand").on('keyup', function (e) {
		if (e.key === 'Enter' || e.keyCode === 13) {
			searchButton.click();
		}
	});

	checkStore();


	//Store selection event
	document.getElementById("storeSelect").addEventListener("change", function(){
		document.cookie = "store_selection="+this.value;
		page=1;
		resetFilter();
		checkStore();
	});




	// Export to XML button
	document.getElementById("downloadXML").addEventListener("click", function(){
		window.open("api/exportToXML.php", '_blank').focus();
	});

	// Export to Halyk XML button
	document.getElementById("downloadHalykXML").addEventListener("click", function(){
		window.open("api/exportToXMLHalyk.php", '_blank').focus();
	});

	// Export to Halyk XML button
	document.getElementById("downloadHomeCreditXML").addEventListener("click", function(){
		window.open("api/exportToHomeCreditXML.php", '_blank').focus();
	});
	
	getBrands();
	getData();
	

	function getBrands () {
		
		$.ajax({
			method: "GET",
			url: 'api/brand/getBrands.php',
			async: true
		}).done(function(data) {
			data = JSON.parse(data);
			insertBrandsIntoFilter(data);
		});
	}
	
	async function insertBrandsIntoFilter (data) {
		var brandSelect = document.getElementById("brand");
		brandSelect.innerHTML = '<li><label><input type="checkbox" id="brandCheckbox" data-id="0" />Все производители</label></li>';
		// for (var i = 0; i < data.length; i++) {
		// 	$("#brand").append('<option value="'+data[i].name+'">'+data[i].name+'</option>');
		// }
		var shipperFilter = document.getElementById("brand");
	    var shiplist = "";

	    var reserved = '<li><label><input type="checkbox" id="brandCheckbox" data-name="0" />Все поставщики</label></li>';

	    for (var i = 0; i < data.length; i++) {
	    	for (var j = 0; j < searchBrand.length; i++) {
	    		if (data[i].id == searchBrand[j]) {
	    			$("#brand").append('<li><label for="allShippers[i].id"><input checked type="checkbox" id="brandCheckbox" name="'+allShippers[i].id+'" data-id="'+data[0].shippers[i].name+'" />'+data[0].shippers[i].name+'</label></li>');
	    			continue;
	    		}
	    	}
	    	
	    	$("#brand").append('<li><label for="'+data[i].id+'"><input type="checkbox" id="brandCheckbox" name="'+data[i].id+'" data-id="'+data[i].name+'" />'+data[i].name+'</label></li>');
	    }

	}

	function selectStoresToAdd () {
		var inputs = document.querySelectorAll("#storeAddCheck");
		selectAllCheck = document.getElementById("addSelectAllStores");
		for (var i = inputs.length - 1; i >= 0; i--) {
			inputs[i].checked = selectAllCheck.checked;
		}
		
	}

	function increaseSumRequest () {
		var amount = document.getElementById("amountField").value;
		if (searchShipper.length > 0) {
			if (amount.length > 0) {
				$.ajax({
					method: "POST",
					url: 'api/update-data.php',
					data: {
						increaseAmount: amount,
						sku:searchSku,
						brand: searchBrand,
						model:searchModel,
						shipper: searchShipper,
						available: searchAvailable,
					}
				}).done(function(data) {
					getData();
					$.notify("Цена всех товаров увеличена на "+amount+" Тенге", "success");
				}).fail(function(response) {
					$.notify("Вы неавторизованы код: "+response.status, "error");
					if (response.status == 403) {
						location.reload();
					}
				});
			} else 
			$.notify("Укажите в поле насколько нужно увеличить цену", "error");
		} else 
		$.notify("Выберите поставщика", "error");
	}

	function decreaseSumRequest () {
		var amount = document.getElementById("amountField").value;
		console.log(typeof searchShipper)
		if (searchShipper.length > 0) {
			if (amount.length > 0) {
				$.ajax({
					method: "POST",
					url: 'api/update-data.php',
					data: {
						decreaseAmount: amount,
						sku: searchSku,
						brand: searchBrand,
						model: searchModel,
						shipper: searchShipper,
						available: searchAvailable,
					}
				}).done(function(data) {
					getData();
					$.notify("Цена всех товаров уменьшена на "+amount+" Тенге", "success");
				}).fail(function(response) {
					$.notify("Вы неавторизованы код: "+response.status, "error");
					if (response.status == 403) {
						location.reload();
					}
				});
			} else
			$.notify("Укажите в поле насколько нужно уменьшить цену", "error");
		} else 
		$.notify("Выберите поставщика", "error");
	}


	function decreasePercentSumRequest() {
		var amount = document.getElementById("amountField").value;
		console.log(typeof searchShipper)
		if (searchShipper.length > 0) {
			if (amount.length > 0) {
				$.ajax({
					method: "POST",
					url: 'api/update-data.php',
					data: {
						decreasePercentAmount: amount,
						sku: searchSku,
						brand: searchBrand,
						model: searchModel,
						shipper: searchShipper,
						available: searchAvailable,
					}
				}).done(function(data) {
					getData();
					$.notify("Цена всех товаров уменьшена на "+amount+"%", "success");
				}).fail(function(response) {
					$.notify("Вы неавторизованы код: "+response.status, "error");
					if (response.status == 403) {
						location.reload();
					}
				});
			} else
			$.notify("Укажите в поле насколько нужно уменьшить цену", "error");
		} else 
		$.notify("Выберите поставщика", "error");
	}

	function increasePercentSumRequest () {
		var amount = document.getElementById("amountField").value;
		console.log(typeof searchShipper)
		if (searchShipper.length > 0) {
			if (amount.length > 0) {
				$.ajax({
					method: "POST",
					url: 'api/update-data.php',
					data: {
						increasePercentAmount: amount,
						sku: searchSku,
						brand: searchBrand,
						model: searchModel,
						shipper: searchShipper,
						available: searchAvailable,
					}
				}).done(function(data) {
					getData();
					$.notify("Цена всех товаров увеличена на "+amount+"%", "success");
				}).fail(function(response) {
					$.notify("Вы неавторизованы код: "+response.status, "error");
					if (response.status == 403) {
						location.reload();
					}
				});
			} else
			$.notify("Укажите в поле насколько нужно уменьшить цену", "error");
		} else 
		$.notify("Выберите поставщика", "error");
	}

	var showingItemsCount = 0;

	function getData() {
		list.innerHTML = 
		'<div class="col-12 d-flex justify-content-center">'+
		'<div class="spinner-border" role="status">'+
		'<span class="visually-hidden">Loading...</span>'+
		'</div>'+
		'</div>';

		$.ajax({
			method: "GET",
			url: 'api/getData.php?page='+page+"&sku="+searchSku+"&brand="+searchBrand+"&model="+searchModel+"&shipper="+searchShipper+"&available="+searchAvailable,
		}).done(function(data) {
			data = JSON.parse(data);
			var el = "";
			var tr = "";
			allShippers = data[0].shippers;

			showingItemsCount = data[0].items.length;

			for (var i = 0; i < data[0].items.length; i++) {
				var price = (data[0].items[i].price == undefined) ? 0 : data[0].items[i].price;
				var marzh = Math.round(((data[0].items[i].price - (data[0].items[i].price * 0.13)) - data[0].items[i].purchase_price));
				var colMarzh = (marzh > data[0].items[i].price * 0.13 ? "green" : "red");
				el +=
				'<td style="vertical-align: middle; text-align: center;">'+ (data[0].itemsPrefix.length > 0 ? ""+data[0].itemsPrefix+"" : data[0].itemsPrefix) +data[0].items[i].id+'</td>'+
				'<td style="vertical-align: middle;">'+data[0].items[i].model+'</td>'+
				'<td style="vertical-align: middle; text-align: center;">'+data[0].items[i].brand+'</td>'+
				'<td style="vertical-align: middle; text-align: center;">'+data[0].items[i].purchase_price+'</td>'+
				'<td style="vertical-align: middle; text-align: center;">'+data[0].items[i].price+'</td>'+
				'<td style="vertical-align: middle; text-align: center; color:'+colMarzh+';">'+ marzh +'</td>'+
				'<td style="vertical-align: middle; text-align: center;">'+data[0].items[i].preOrder+'</td>'+
				'<td style="vertical-align: middle; text-align: center; color: '+(data[0].items[i].available == "yes" ? 'green' : 'red')+';">'+(data[0].items[i].available == "yes" ? 'Есть' : 'Нет')+'</td>'+
				'<td style="vertical-align: middle; text-align: center;">Да</td>'+
				'<td style="vertical-align: middle; text-align: center;">'+data[0].items[i].added_date+'</td>'+
				'<td style="vertical-align: middle; text-align: center;">'+(data[0].items[i].shtrih == null ? "N/A" : data[0].items[i].shtrih) +'</td>'+
				'<td style="vertical-align: middle; text-align: center;">'+(data[0].items[i].shipper.length > 0 ? data[0].items[i].shipper : "-")+'</td>'+
				'<td style="vertical-align: middle; text-align: center;"><button id="editSelectedItem" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#editModal" data-id="'+data[0].items[i].id+'" data-price="'+data[0].items[i].price+'"  data-model="'+escape(data[0].items[i].model)+'" data-brand="'+data[0].items[i].brand+'" data-available="'+data[0].items[i].available+'" data-preorder="'+data[0].items[i].preOrder+'" data-provider="'+data[0].items[i].provider+'" data-shipper="'+data[0].items[i].shipper+'" data-purchase="'+data[0].items[i].purchase_price+'" data-itemid="'+data[0].items[i].itemId+'" >Редактировать</button></td>'+
				'<td style="vertical-align: middle; text-align: center;"><button id="profileButton" type="button" data-email="'+data[0].items[i].user.email+'" data-phone="'+data[0].items[i].user.phone+'" data-name="'+data[0].items[i].user.name+'" data-image="'+data[0].items[i].user.image+'" class="btn d-flex align-items-center" data-bs-toggle="modal" data-bs-target="#profileModal">'+"<img style='width: 40px; height: 40px; border-radius: 50%; margin-right: 10px;' src="+ (data[0].items[i].user.image != null ? (data[0].items[i].user.image.length > 0 ? data[0].items[i].user.image : 'images/avatar.png') : 'images/avatar.png') +"><p style='margin: 0;'>"+data[0].items[i].user.name+'</p></button></td>';
				tr += "<tr>" + el + "</tr>";
				el = "";
				

				// '<div class="col-sm-12 col-md-6 col-lg-4">'+
				// '<div class="card text-center">'+
				// '<div class="card-header">'+
				// 'sku: '+data[0].items[i].id+
				// '</div>'+
				// '<div class="card-body">'+
				// '<h5 class="card-title">'+data[0].items[i].model+'</h5>'+
				// '<p class="card-text"></p>'+
				// '<p><strong>Цена: '+price+' KZT</strong></p>'+
				// '</div>'+
				// '<div class="card-footer text-muted">'+
				// '<button id="editSelectedItem" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#editModal" data-id="'+data[0].items[i].id+'" data-price="'+data[0].items[i].price+'"  data-model="'+data[0].items[i].model+'" data-brand="'+data[0].items[i].brand+'" data-available="'+data[0].items[i].available+'" >Редактировать</button>'+
				// '</div>'+
				// '</div>'+
				// '</div>'
				// ;
			}
			// <thead class="table-dark">
	  //   ...
	  // </thead>

	  var th = 
	  '<thead class="table-dark">'+
	  '<tr style="vertical-align: middle; text-align: center;">'+
	  '<th >SKU</th>'+
	  '<th>Наименование</th>'+
	  '<th>Производитель</th>'+
	  '<th>Вход</th>'+
	  '<th>Цена</th>'+
	  '<th>Маржа</th>'+
	  '<th title="Предзаказ">Прд. зкз</th>'+
	  '<th>Статус</th>'+
	  '<th>На Kaspi</th>'+
	  '<th>Добавлен</th>'+
	  '<th>Штрих</th>'+
	  '<th>Поставщик</th>'+
	  '<th>Опции</th>'+
	  '<th>Редактор</th>'+
	  '</tr>'+
	  '</thead>';

	  th += tr;

	  list.innerHTML = th;

	  var pagesButton = "";
	  for (var i = 0; i < (data[0].count / 20); i++) {
	  	
	  	if(i == data[0].page) {
	  		pagesButton += '<option selected value="'+(i+1)+'">'+(i+1)+'</option>';
	  		continue;
	  	}
	  	pagesButton += '<option value="'+(i+1)+'">'+(i+1)+'</option>';

	  	// if(i == data[0].page+1) {
	  	// 	pagesButton += '<option selected value="'+i+'">'+i+'</option>';
	  	// } else
	  	// 	pagesButton += '<option value="'+i+'">'+i+'</option>';

	  	// if (i == Math.floor(data[0].count / 20)) {
	  	// 	pagesButton += '<option value="'+(i+1)+'">'+(i+1)+'</option>';
	  	// }
	  	// console.log(i)
	  	// console.log(Math.floor(data[0].count / 20))
	  }

	  document.getElementById("pages").innerHTML =
	  '<select id="selectForm" class="form-select" aria-label="Default select example">'+
	  pagesButton+
	  '</select>';
	  document.getElementById("selectForm").addEventListener("change", function(){
	  	page=this.value;
	  	getData();
	  })

	  // Counter
	  var counterLabel = document.getElementById("counterLabel");
	  counterLabel.innerHTML = "Показано: "+(showingItemsCount<20 ? page*20 - (20 - showingItemsCount) : page*showingItemsCount)+" товаров";
	  counterLabel.innerHTML += "<br>";
	  counterLabel.innerHTML += "Страница: "+"<strong>"+page+"</strong>";
	  counterLabel.innerHTML += "<br>";
	  counterLabel.innerHTML += "Найдено и будет изменено: "+"<strong>"+data[0].count+"</strong>";


	  // Profile data
	  var profileButton = document.querySelectorAll("#profileButton");
	  for (var i = 0; i < profileButton.length; i++) {
	  	profileButton[i].addEventListener("click", function(){
	  		
	  		var profileName = document.getElementById("profileName");
	  		var profileEmail = document.getElementById("profileEmail");
	  		var profileImage = document.getElementById("profileImage");

	  		profileName.innerHTML = this.dataset.name;
	  		profileEmail.innerHTML = 'Почта: <a href="mailto: '+this.dataset.email+'" target="_blank">'+this.dataset.email+'</a>';
	  		profileEmail.innerHTML += '<br>'
	  		profileEmail.innerHTML += 'Телефон: <a href="tel: '+this.dataset.phone+'" target="_blank">'+this.dataset.phone+'</a>';
	  		profileImage.innerHTML = "<img style='width: 150px; height: 150px; border-radius: 50%;' src="+(this.dataset.image.length > 0 ? this.dataset.image : 'images/avatar.png') +">";

	  	})
	  }

	  var shipperSelectUpload = document.getElementById("shipperSelectUpload");

	  var currentShipper = "";
	  var shiperlist = "";
	  var reserved = '<option value="0" selected> Выберите поставщика</option>';


	  for (var i = 0; i < allShippers.length; i++) {
	  	shiperlist += 
	  	'<option value="'+allShippers[i].id+'">'+allShippers[i].name+'</option>';			
	  }

	  shipperSelectUpload.innerHTML = 
	  currentShipper+
	  shiperlist+
	  reserved;

	  $("#shipperSelectUploadExcel").append( 
	  currentShipper+
	  shiperlist+
	  reserved);



	  var editButtons = document.querySelectorAll("#editSelectedItem");
	  for (var i = 0; i < editButtons.length; i++) {
	  	editButtons[i].addEventListener("click", function(){
	  		var brand = document.getElementById("editInputBrand");
	  		var model = document.getElementById("editInputModel");
	  		var sku = document.getElementById("editInputSKU");
	  		var price = document.getElementById("editInputPrice");
	  		var availablility = document.getElementById("editSwitchAvailable");
	  		var preorder = document.getElementById("editPreorder");
	  		var editProvider = document.getElementById("editProvider");
	  		var shippperSelect = document.getElementById("shipperSelect");
	  		var purchasePrice = document.getElementById("editInputPurchasePrice");
	  		var marzhaInput = document.getElementById("editInputMarzha");

	  		
	  		price.addEventListener("keyup", function(){
	  			
	  			var thisPurchase = purchasePrice.value;
	  			var thisPrice = price.value;
	  			console.log(thisPrice)
	  			console.log(thisPurchase)
	  			if (thisPrice < thisPurchase) {
	  				document.getElementById("editErrorMesage").classList.remove("hidden");
	  				console.log('Опасно')
	  			} else {
	  				document.getElementById("editErrorMesage").classList.add("hidden");
	  			}
				
				var marzh = Math.round(((thisPrice - thisPrice * 0.13) - thisPurchase));
	  			marzhaInput.value = marzh;

				marzhaInput.style.color = (marzh > 0 ? "green" : "red");
				// marzhaInput.style.color = "green";

	  		})

	  		sku.value = this.dataset.id;
	  		if (this.dataset.brand != "undefined") {
	  			brand.value = this.dataset.brand;
	  		} else {
	  			brand.value = "";
	  		}
	  		model.value = unescape(this.dataset.model);

	  		price.value =  (this.dataset.price == "undefined") ? 0 : this.dataset.price;

	  		availablility.checked = (this.dataset.available == "yes" ? true : false);

	  		preorder.value = (this.dataset.preorder);

	  		editProvider.value = (this.dataset.provider);

	  		purchasePrice.value = this.dataset.purchase;

	  		
	  		var marzh = Math.round(((this.dataset.price - this.dataset.price * 0.13) - this.dataset.purchase));
	  		var colMarzh = (marzh > this.dataset.price * 0.13 ? "green" : "red");

	  		marzhaInput.value = marzh;

	  		var deleteItemId = this.dataset.itemid;

	  		var deleteButton = document.getElementById("deleteOfferButton");
	  		deleteButton.addEventListener("click", function(){
	  			deleteOffer(deleteItemId);
	  		});

	  		var currentShipper = "";


	  		var shiplist = "";
	  		var reserved = '<option value="0" selected> Выберите поставщика</option>';


	  		for (var i = 0; i < allShippers.length; i++) {
	  			if (this.dataset.shipper == allShippers[i].name) {
	  				currentShipper = 
	  				'<option value="'+allShippers[i].id+'" selected>'+allShippers[i].name+'</option>';
	  				reserved = "<option value='0'>Выберите поставщика</option>";
	  			} else {
	  				shiplist += 
	  				'<option value="'+allShippers[i].id+'">'+allShippers[i].name+'</option>';
	  			}
	  		}

	  		shippperSelect.innerHTML = 
	  		currentShipper+
	  		shiplist+
	  		reserved;






	  	})
	  }



	    // Filter List 

	    var shipperFilter = $( "#checkboxes" );
	    var shiplist = "";

	    var reserved = '<li><label><input type="checkbox" id="shipperCheck" data-id="0" />Все поставщики</label></li>';

	    for (var i = 0; i < data[0].shippers.length; i++) {
	    	var shipperColor = "#000";
	    	if (allShippers[i].color != null) {
	    		shipperColor = allShippers[i].color;
	    	}
	    	for (var j = 0; j < searchShipper.length; i++) {
	    		if (allShippers[i].id == searchShipper[j]) {
	    			shiplist += 
	    			'<li><label style="color: '+shipperColor+'"  for="allShippers[i].id"><input checked type="checkbox" id="shipperCheck" name="'+allShippers[i].id+'" data-id="'+data[0].shippers[i].id+'" />'+data[0].shippers[i].name+'</label></li>';
	    			continue;
	    		}
	    	}
	    	
	    	shiplist += 

	    	'<li><label style="color: '+shipperColor+'" for="'+allShippers[i].id+'"><input type="checkbox" id="shipperCheck" name="'+allShippers[i].id+'" data-id="'+allShippers[i].id+'" />'+data[0].shippers[i].name+'</label></li>';
	    }

		shipperFilter.empty();
	    shipperFilter.append( 
	    reserved+
	    shiplist);

	    // var shipperFilter = document.getElementById("shipperFilter");
	    // var shiplist = "";

	    // var reserved = '<option value="0" selected>Все поставщики</option>';

	    // for (var i = 0; i < data[0].shippers.length; i++) {
	    // 	if (allShippers[i].id == searchShipper) {
	    // 		shiplist += 
	    // 		'<option value="'+allShippers[i].id+'" selected>'+data[0].shippers[i].name+'</option>';
	    // 		continue;
	    // 	}
	    // 	shiplist += 
	    // 	'<option value="'+allShippers[i].id+'">'+data[0].shippers[i].name+'</option>';
	    // }

	    // shipperFilter.innerHTML = 
	    // reserved+
	    // shiplist;


		// AddList
		var shipperAddList = document.getElementById("shipperAddList");
		var shipAddlist = "";

		var reserved = '<option value="0" selected>Выберите поставщика</option>';

		for (var i = 0; i < data[0].shippers.length; i++) {
			if (allShippers[i].id == searchShipper) {
				shipAddlist += 
				'<option value="'+allShippers[i].id+'" selected>'+data[0].shippers[i].name+'</option>';
				continue;
			}
			shipAddlist += 
			'<option value="'+allShippers[i].id+'">'+data[0].shippers[i].name+'</option>';
		}

		shipperAddList.innerHTML = 
		reserved+
		shipAddlist;

	}).fail(function(response) {
		$.notify("Вы неавторизованы код: "+response.status, "error");
		if (response.status == 403) {
			location.reload();
		}
	});
}

function deleteOffer (item) {
	$.ajax({
		method: "POST",
		url: 'api/deleteOffer.php',
		data: {
			deleteId: item,
		}
	}).done(function(data) {
		document.getElementById("closeDeleteModalButton").click();
		getData();
	});
}


function uploadFile() {
	var spinner = document.getElementById("uploadLoadingSpinner");
	var uploadTypeSelect = document.getElementById("uploadTypeSelect");
	var shipperSelectUpload = document.getElementById("shipperSelectUpload");

	spinner.classList.remove("hidden");

	var fileInp = $("#fileInput");

	var fm = new FormData();
	fm.append("file", fileInp[0].files[0]);
	fm.append("uploadType", uploadTypeSelect.value);
	fm.append("shipper", shipperSelectUpload.value);
	$.ajax({
		method: "POST",
		url: 'api/uploadDataToServer.php',
		data: fm,
		processData: false,
		contentType: false
	}).done(function(data) {
		document.getElementById("closeUploadModalButton").click();
		getData();
		fileInp[0].value = null;
		closeModalButton.click();
		spinner.classList.add("hidden");
	});
}

function uploadExcelFile() {
	var spinner = document.getElementById("uploadExcelLoadingSpinner");
	var uploadTypeSelect = document.getElementById("uploadTypeSelect");
	var shipperSelectUploadExcel = document.getElementById("shipperSelectUploadExcel");

	spinner.classList.remove("hidden");

	var fileInp = $("#fileInputExcel");

	var fm = new FormData();
	fm.append("file", fileInp[0].files[0]);
	fm.append("uploadType", uploadTypeSelect.value);
	fm.append("shipper", shipperSelectUploadExcel.value);

	$.ajax({
		method: "POST",
		url: 'api/exportData/uploadExcel.php',
		data: fm,
		processData: false,
		contentType: false
	}).done(function(data) {
		document.getElementById("closeExcelUploadModalButton").click();
		getData();
		fileInp[0].value = null;
		$.notify("Товары загружены успешно", "success");
		spinner.classList.add("hidden");
	}).fail(function(response) {
		if (response.status == 403) {
			$.notify("Вы неавторизованы код: "+response.status, "error");
			location.reload();
		} else {
			$.notify("Произошла неизвестная ошибка. Код: "+response.status, "error");
		}
	});
}


function updateExcelPrice() {
	var spinner = document.getElementById("uploadExcelLoadingSpinner");
	var uploadTypeSelect = document.getElementById("uploadTypeSelect");
	var shipperSelectUploadExcel = document.getElementById("shipperSelectUploadExcel");

	var addup = document.getElementById("PriceAddup");
	spinner.classList.remove("hidden");

	var fileInp = $("#fileUpdateExcel");

	var fm = new FormData();
	fm.append("file", fileInp[0].files[0]);
	fm.append("uploadType", uploadTypeSelect.value);
	fm.append("shipper", shipperSelectUploadExcel.value);

	$.ajax({
		method: "POST",
		url: 'api/exportData/updateExcelPrices.php?comission='+addup.value,
		data: fm,
		processData: false,
		contentType: false
	}).done(function(data) {
		document.getElementById("CloseExcelUpdateModal").click();
		getData();
		fileInp[0].value = null;
		$.notify("Товары загружены успешно", "success");
		spinner.classList.add("hidden");
	}).fail(function(response) {
		if (response.status == 403) {
			$.notify("Вы неавторизованы код: "+response.status, "error");
			location.reload();
		} else {
			$.notify("Произошла неизвестная ошибка. Код: "+response.status, "error");
		}
	});
}



var saveButton = document.getElementById("saveOfferButton");
saveButton.addEventListener("click", function(){
	saveEditedOfferData();
})

var sendButton = document.getElementById("sendNewOfferButton");
var closeModalButton = document.getElementById("closeModalButton");
var closeEditModalButton = document.getElementById("closeEditModalButton");

sendButton.addEventListener("click", sendNewOfferData);



function sendNewOfferData() {
	var brand = document.getElementById("inputNewBrand");
	var model = document.getElementById("inputNewModel");
	var sku = document.getElementById("inputNewSKU");
	var price = document.getElementById("inputNewPrice");
	var shipperAddList = document.getElementById("shipperAddList");
	var storesToAdd = document.querySelectorAll("#storeAddCheck");
	var inputNewPurchasePrice = document.getElementById("inputNewPurchasePrice");
	
	// if (model.length > 2 && price > 0) {
		var selectedStores = "";

		for (var i = 0; i < storesToAdd.length; i++) {
			if (storesToAdd[i].checked) {
				if (selectedStores.length == 0) {
					selectedStores += storesToAdd[i].dataset.id;	
				} else {
					selectedStores += ",";
					selectedStores += storesToAdd[i].dataset.id;
				}
			}
		}
		console.log(inputNewPurchasePrice.value);

		$.ajax({
			method: "POST",
			url: 'api/addOffer.php',
			data: {
				brand: brand.value,
				model: model.value,
				sku: sku.value,
				price: price.value,
				shipper: shipperAddList.value,
				store: selectedStores,
				purchasePrice: inputNewPurchasePrice.value
			}
		}).done(function(data) {
			getData();
			clearAddModal();
			closeModalButton.click();
			$.notify("Товар добавлен", "success");
		}).fail(function(response) {
			if (response.status == 403) {
				$.notify("Вы неавторизованы код: "+response.status, "error");
				location.reload();
			} else {
				$.notify("Произошла неизвестная ошибка", "error");
			}
		});
	// }

}

function saveEditedOfferData() {
	var brand = document.getElementById("editInputBrand");
	var model = document.getElementById("editInputModel");
	var sku = document.getElementById("editInputSKU");
	var price = document.getElementById("editInputPrice");
	var availablility = document.getElementById("editSwitchAvailable");
	var preorder = document.getElementById("editPreorder");
	var editProvider = document.getElementById("editProvider");
	var shippperSelect = document.getElementById("shipperSelect");
	var purchasePrice = document.getElementById("editInputPurchasePrice");

	$.ajax({
		method: "POST",
		url: 'api/editOffer.php',
		data: {
			brand: brand.value,
			model: model.value,
			sku: sku.value,
			newSku: sku.value,
			price: price.value,
			available: (editSwitchAvailable.checked ? "yes" : "no"),
			preOrder: preorder.value,
			provider: editProvider.value,
			shipper: shippperSelect.value,
			purchasePrice: purchasePrice.value,
		}
	}).done(function(data) {

		closeEditModalButton.click();
		clearEditModal();
		getData();
	});
}



function clearEditModal() {
	var brand = document.getElementById("editInputBrand");
	var model = document.getElementById("editInputModel");
	var sku = document.getElementById("editInputSKU");
	var price = document.getElementById("editInputPrice");
	var editProvider = document.getElementById("editProvider");
	brand.value="";
	model.value="";
	sku.value="";
	price.value="";
	editProvider.value="";
}

function clearAddModal() {
	var brand = document.getElementById("inputNewBrand");
	var model = document.getElementById("inputNewModel");
	var sku = document.getElementById("inputNewSKU");
	var price = document.getElementById("inputNewPrice");
	var shipperAddList = document.getElementById("shipperAddList");
	brand.value="";
	model.value="";
	sku.value="";
	price.value="";
}

function resetFilter() {

	var checks = document.querySelectorAll("#shipperCheck");
	for (var i = 0; i < checks.length; i++) {
		checks[i].checked = false;
	}

	var brandChecks = document.querySelectorAll("#brandCheckbox");
	for (var i = 0; i < brandChecks.length; i++) {
		brandChecks[i].checked = false;
	}

	searchSku = document.getElementById("inputSku").value = "";
	searchModel = document.getElementById("inputModel").value = "";
	searchBrand = document.getElementById("brand").value = "";
	searchShipper = "";
	searchAvailable = document.getElementById("availableFilter").value = "";
	page=1;
	getData();
}

function selectDippingFilter() {
	console.log(allShippers)
	var checks = document.querySelectorAll("#shipperCheck");
	for (var i = 0; i < checks.length; i++) {
		for (var j = 0; j < allShippers.length; j++) {
			if(checks[i].dataset.id == allShippers[j].id) {
				if(allShippers[j].dipping) {
					checks[i].checked = true;
				}
			}
		}
	}

		document.getElementById("searchButton").click();
}


function getCookie(cname) {
	let name = cname + "=";
	let decodedCookie = decodeURIComponent(document.cookie);
	let ca = decodedCookie.split(';');
	for(let i = 0; i <ca.length; i++) {
		let c = ca[i];
		while (c.charAt(0) == ' ') {
			c = c.substring(1);
		}
		if (c.indexOf(name) == 0) {
			return c.substring(name.length, c.length);
		}
	}
	return "";
}





function checkStore() {
	$.ajax({
		method: "GET",
		url: 'api/getStores.php'
	}).done(function(data) {

		data = JSON.parse(data);

		el="";
		elAdd="";

		var storeSelect = document.getElementById("storeSelect");
		var storAddCheckboxes = document.getElementById("StorCheckboxes");
			// var storeSelectUpload = document.getElementById("storeSelectUpload");

			for (var i = 0; i < data.length; i++) {
				if (getCookie("store_selection") == data[i].id) {
					// console.log(data[i].name)
					el +=
					'<option selected value="'+data[i].id+'">'+data[i].name+'</option>';
					
					elAdd += '<li><label for="allShippers[i].id"><input checked type="checkbox" id="storeAddCheck" name="'+data[i].id+'" data-id="'+data[i].id+'" />'+data[i].name+'</label></li>';
					continue;
				}
				el +=
				'<option value="'+data[i].id+'">'+data[i].name+'</option>';
				elAdd += '<li><label for="allShippers[i].id"><input type="checkbox" id="storeAddCheck" name="'+data[i].id+'" data-id="'+data[i].id+'" />'+data[i].name+'</label></li>';
				
			}

			storeSelect.innerHTML = el;
			storAddCheckboxes.innerHTML = elAdd;
			// storeSelectUpload.innerHTML = el;

			if (getCookie('store_selection').length > 0) {
				// console.log(getCookie('store_selection'))
			} else {
				document.cookie = "store_selection="+data[0].id;
			}
		});


}


});