<div class="row">
	<div class="col-lg-12">
		<form method="get" class="form-horizontal">
			<div class="form-group"><label class="col-sm-2 control-label">Item Group</label>
				<div class="col-sm-10">
					<select id="id_item_group" name="t_id_item_group" data-placeholder="Pilih..." class="chosen-select" tabindex="0">
					</select>
				</div>
			</div>
			<div class="hr-line-dashed"></div>
			<div class="form-group">
				<div class="col-sm-4 col-sm-offset-2">
					<button class="btn btn-primary categoryBtn" type="button" onclick="updateCategory()"><i class="fa fa-plus"></i> Add new Category</button>
				</div>
			</div>
		</form>
	</div>
	<div class="col-sm-12">
		<div class="table-responsive " style="width:100%">
			<table id="listDataTableCrudCategory" class="table table-striped table-bordered table-hover" style="width:100%;">
				<thead>
					<tr>
						<th>No</th>
						<th>ID Category</th>
						<th>Description</th>
						<th>*</th>
					</tr>
				</thead>
			</table>
		</div>
	</div>
</div>
<script>
	var listDataTableCrudCategory = null;
	$(document).ready(function() {
		$('.chosen-select').chosen({width: "100%",search_contains: true});
		combo_item_group('<?=$id_item_group ?>');
		$('#id_item_group').change(function(){
			refreshDataCrudCategory(true);
		})
	})
	async function updateCategory(id_category = 0, text = '') {
		let id_item_group = $('#id_item_group').val();
		title = 'Add Category';
		if (id_category)
			title = 'Update Category ' + id_category
		var {
			value: formValues
		} = await Swal.fire({
			title: title,
			html: '<form id="form-input-category" autocomplete="off">' +
				'<input hidden id="swal-input1" value="' + id_category + '" name="id_category" class="swal2-input">' +
				'<input id="swal-input2" value="' + text + '" name="category_description" class="swal2-input" placeholder="Description">' +
				'<input hidden id="swal-input3" value="' + id_item_group + '" name="id_item_group" class="swal2-input">' +
				'</form>',
			focusConfirm: false,
			preConfirm: () => {
				if (!$('#swal-input2').val()) {
					Swal.showValidationMessage('Data belum di isi!');
					$('#swal-input2').focus();
				}
				return $('#form-input-category').serialize()
			}
		})

		if (formValues) {
			$.ajax({
				type: 'POST',
				url: site_url + "main/modal/saveCrudCategory/",
				dataType: 'json',
				data: formValues,
				success: function(response) {
					swal.fire(response['header'] || 'success', response['message'] || '', "success").then(() => {
						refreshDataCrudCategory();
					});
				},
				error: function(jqXhr, textStatus, errorThrown) {
					var error_message = 'internal error';
					if (jqXhr.responseJSON !== undefined) {
						error_message = jqXhr['responseJSON']['message'];
					}
					swal.fire('error', error_message, "error");
				}
			});
		}
	}

function combo_item_group(id_default)
{
	$.ajax({
		type: 'POST',
		url: site_url + "mms/product/getItemGroup/",
		dataType: 'html',
		success: function(result) {
			$('#id_item_group').empty();
			$('#id_item_group').append(result);
			$('#id_item_group').val(id_default).trigger("chosen:updated");
			list_data_table();
		}
	});
}

function list_data_table()
{
	listDataTableCrudCategory = $('#listDataTableCrudCategory')
			.on('preXhr.dt', function(e, settings, data) {
				$('.browseBtn').ladda('start');
			}).DataTable({
				"lengthMenu": [
					[10, 25, 50, -1],
					[10, 25, 50, "All"]
				],
				'processing': true,
				'serverSide': true,
				'responsive': true,
				'serverMethod': 'post',
				'ajax': {
					'async': true,
					'url': site_url + "main/modal/crudCategoryListPage",
					'beforeSend': function(xhr) {},
					'data': function(d) {
						d.id_item_group = $('#id_item_group').val()?$('#id_item_group').val():<?=$id_item_group?:0 ?>
					},
					'error': function(jqXhr, textStatus, errorThrown) {
						var error_message = 'internal error';
						if (jqXhr.responseJSON !== undefined) {
							error_message = jqXhr['responseJSON']['message'];
						}
						swal.fire('error', error_message, "error");
						$('.browseBtn').ladda('stop');
					}
				},
				'dom': '<"html5buttons"B>lTfg<"PrintArea"tr><"row"<"col-sm-5"i><"col-sm-7"p>>',
				"columnDefs": [{
						render: function(data, type, row, meta) {
							return meta.row + meta.settings._iDisplayStart + 1;
						},
						"targets": 0,
						"orderable": false
					},
					{
						render: function(data, type, row) {
							return `<button class="btn btn-primary btn-xs" onClick="updateCategory('${row['IdCategory']}','${row['Description']}')"><i class="fa fa-pencil"></i></button>`;
						},
						"targets": 3,
						"orderable": false
					},
				],
				'columns': [{
						defaultContent: ''
					},
					{
						data: 'IdCategory'
					},
					{
						data: 'Description'
					},
					{
						defaultContent: ''
					}
				],
				order: [
					[1, 'asc']
				],
				initComplete: function() {},
				drawCallback: function(settings) {
					$('.browseBtn').ladda('stop');
					$('.row-elipsis').ellipsis().tooltip();
				},
				buttons: [{
					extend: 'copy',
					exportOptions: {
						orthogonal: 'export'
					}
				}, ],
			});
}
	function refreshDataCrudCategory(reload_paging = false) {
		$('#listDataTableCrudCategory').DataTable().ajax.reload(null, reload_paging);
	}
</script>