<script>
	$("#bulk-upload-asset-form").validate({
		ignore: ":hidden:not(#location_id)",
		rules: {
			location_id: {
				required: true,
			},
			po_id: {
				required: true,
			},
			upload_asset_type_id: "required",
			asset_tag: {
				required: true,
				minlength: 2,
				unique: true,
				clientunique: true,
				unique_fields: [5, 'asset_tag']
			},
			serial_no: {
				required: true,
				unique: true,
				minlength: 2,
				serialunique: 5,
				unique_fields: [6, 'serial_no']
			},
			carrier_id: {
				required: function () {
					if ($("#upload_asset_type_id option:selected").text() == "Mobile Phone" || $("#upload_asset_type_id option:selected").text() == "Mobile Phone Number") {
						return true;
					}
					return true;
				}
			},
			imei: {
				unique: function (element) {
					if ($("#imei").val().length == 0) {
						return false;
					}
					return true;
				},
				required: function () {
					if ($("#upload_asset_type_id option:selected").text() == "Mobile Device" || $("#upload_asset_type_id option:selected").text() == "Mobile Phone Number") {
						return true;
					}
					return true;
				}
			},
			make_and_model_id: {
				required: function () {
					return true;
				},
				custome_required: true
			},
			technical_spec_id: {
				required: true,
				custome_required: true
			},
			// ticket_no: {
			// 	required: true,
			// },
			bulk_upload_asset_file: {
				extension: "csv",
				required: true,
			}
		},
		messages: {
			bulk_upload_asset_file: {
				extension: "Please upload a csv file"
			}
		},
		errorPlacement: function (error, element) {
			if (element.attr("type") == "file") {
				error.insertAfter('.errorTextfile');
			}
			else {
				error.insertAfter($(element).next($('.errorText')));
			}

		},
	});

	$('#bulk-upload-asset-form').submit(function (e) {
		e.preventDefault();
		if ($('#bulk-upload-asset-form').valid()) {
			$('.alert-danger').hide();
			// get all the inputs into an array.
			var $inputs = $('#bulk-upload-asset-form :input');
			// get an associative array of just the values.
			
			var formData = new FormData();
			formData.append('file', $('#bulk_upload_asset_file')[0].files[0]);

			$inputs.each(function () {
				if (this.name) {
					let fieldName = this.name;

					// Remove ONLY the "upload_" prefix
					if (fieldName.startsWith('upload_')) {
						fieldName = fieldName.substring(7); // 7 is the length of "upload_"
					}

					formData.append(fieldName, $(this).val());
				}
			});

			$.ajax({
				type: "POST",
				url: $(this).attr('action'),
				data: formData,
				async: false,
				success: function (response) {
					updateTable(response);
					resetForm();
					updateCreateAssetButton(response.countVal);
				},
				cache: false,
				contentType: false,
				processData: false
			});
		}
	});


	// function to update the table
	function updateTable(response) {
		const tableBody = $('#tblview tbody');
		const currentRowCount = tableBody.find('tr').length;
		const newRowCount = currentRowCount + parseInt(response.countVal);

		tableBody.append(response.data);

		// Update row numbers
		tableBody.find('tr').each(function (index) {
			$(this).find('td:first').text(index + 1);
		});

		// Append errors and duplicate errors
		$('#bulk-upload-asset-form').append(response.errors);
		$('#bulk-upload-asset-form').append(response.duplicate_errors);

		// Update asset count
		$('#asset_count').text(newRowCount);
	}

	// function to reset the form
	function resetForm() {
		$('#bulk-upload-asset-form')[0].reset();
		$('select').val('').change();
		$('.select2').select2({ placeholder: 'Select' });
		$('.filter-field-storage-location').trigger('chosen:updated');
	}

	// function to update the "Create Asset" button state
	function updateCreateAssetButton(countVal) {
		const createAssetBtn = $('#createAssetBtn');
		createAssetBtn.prop('disabled', countVal <= 0);
	}

</script>