/*
Created by Hendi
Created date 2021-03-15
Created update 2021-03-23
Titasictech.com
JS for Admin Panel
*/
var _table;
var _datatable;
var _mod;
// _csrf_content dibuat global agar bisa direplace dengan csrf token yang baru
// saat mendapat respon json
var _csrf_content;

$(function() {
	// saat pertama kali page diload
	_csrf_content = $('meta[name="X-CSRF-TOKEN"]').attr('content');
	// hide sidebar
	$('.navbar-toggler.desktop').on('click', function() {
		if ($('body').hasClass('sidebar-mini')) {
			$('body').removeClass('sidebar-mini');
		} else {
			$('body').addClass('sidebar-mini');
		}
	});
	// menu level 1 click
	$('.sidebar .sidebar-wrapper .nav .nav-item a.nav-link.level-1').on('click', function() {
		//hide menu lain yang terbuka
		let _menulain = $('.sidebar .sidebar-wrapper .nav .nav-item a.nav-link.level-1').not(this);
		_menulain.addClass('collapsed');
		_menulain.attr('aria-expanded', false);
		_menulain.find('p i.arrow').html('keyboard_arrow_down');
		_menulain.parent().find('.sub-menu').collapse('hide');
		_menulain.parent().find('span i.arrow').html('keyboard_arrow_down'); //level 2+
		
		if ($(this).hasClass('collapsed')) {
			$(this).find('p i.arrow').html('keyboard_arrow_up');
		} else {
			$(this).parent().find('.sub-menu').collapse('hide');
			$(this).parent().find('span i.arrow').html('keyboard_arrow_down'); //level 2+
			$(this).find('p i.arrow').html('keyboard_arrow_down');
		}
	});
	// menu level 2 click
	$('.sidebar .sidebar-wrapper .nav .nav-item a.nav-link.level-2').on('click', function() {
		//hide menu lain yang terbuka
		let _menulain = $('.sidebar .sidebar-wrapper .nav .nav-item a.nav-link.level-2').not(this);
		_menulain.addClass('collapsed');
		_menulain.attr('aria-expanded', false);
		_menulain.find('span i.arrow').html('keyboard_arrow_down');
		_menulain.parent().find('.sub-menu').collapse('hide');
		
		if ($(this).hasClass('collapsed')) {
			$(this).find('span i.arrow').html('keyboard_arrow_up');
		} else {
			$(this).parent().find('.sub-menu').collapse('hide');
			$(this).find('span i.arrow').html('keyboard_arrow_down');
		}
	});
	// Jika security CSRF diaktifkan
	// pake cara ini hanya bisa jalan jika ajaxnya sekali saja
	// misal pada post input data
	// tidak jalan pada datatables
	/*$.ajaxSetup({
		headers: {
			'X-CSRF-TOKEN': _csrf_content
		}
	});*/
	// datatables
	$('.table').each(function(i) {
		// DataTable config
        _table = $(this);
        let _id = _table.attr('id');
		let _url = '';
		let _includedColumns = [];
		
		switch (_id) {
		    case 'dt-dashboard':
				_url = _HOST + "/get-datatables/" + _mod;
                _includedColumns = [
					{
						data:null, 
						sortable: false, 
						searchable: false,
						render: function(data, type, full, meta) {
							return meta.row + 1;
						} 
					},	
                    {data:"jam", sortable: false},	
                    {data:"menu_name", sortable: false},
                    {data:"qty", sortable: false},
					{data:"no_antrian", sortable: false},
                    {data:"actions", sortable: false, width: "25%"}	
                ];
				break;
			case 'dt-menu':
				_url = _HOST + "/get-datatables/" + _mod;
                _includedColumns = [
                    {data:"menu_name", sortable: true},	
                    //{data:"slug", visible: false},
                    {data:"description", sortable: true},
					{data:"actions", sortable: false, width: "15%"}	
                ];
				break;
			case 'dt-antrian':
				_url = _HOST + "/get-datatables/" + _mod;
                _includedColumns = [
					{
						data:null, 
						sortable: false, 
						searchable: false,
						render: function(data, type, full, meta) {
							return meta.row + 1;
						} 
					},	
                    {data:"jam", sortable: true},	
                    {data:"menu_name", sortable: true},
                    {data:"qty", sortable: true},
					{data:"no_antrian", sortable: true},
                    {data:"actions", sortable: false, width: "25%"}	
                ];
				break;
			case 'dt-history':
				_url = _HOST + "/get-datatables/" + _mod + "/" + _tglawal + "/" + _tglakhir;
                _includedColumns = [
					{
						data:null, 
						sortable: false, 
						searchable: false,
						render: function(data, type, full, meta) {
							return meta.row + 1;
						} 
					},	
					{data:"tanggal", sortable: true},	
                    {data:"jam", sortable: true},	
                    {data:"menu_name", sortable: true},
                    {data:"qty", sortable: true},
					{data:"no_antrian", sortable: false},
                    {data:"start", sortable: false},
                    {data:"finish", sortable: false},
                    {data:"durasi", sortable: false}	
                ];
				break;
		}
		
		let _start = 0;
		let _limit = 10;
		_datatable = _table.DataTable({
            "destroy": true,
            "processing": true, 
            "jQueryUI": false,
            "autoWidth": false,
            "searching": (_id == 'dt-dashboard' ? false : true),
            "pagingType": "full_numbers",
            "serverSide": true, 
            "displayStart": _start,
            "pageLength": _limit,
            "lengthMenu": [5,10,25,50,100],
            "language": {
                "processing": "<img src='" + _HOST + "/public/assets/img/ajax-loader.gif'>"
            },  
            //"scrollX" : true,
            //"scrollY" : "300",
            "scrollCollapse" : true,
            "initComplete": function() {
                //code
			},
            "ajax": {
                "url": _url, 
				"type": "POST",
				"data": function (d) {
					d.csrf_token_name = _csrf_content //csrf_token_name ada di Config/App.php
				}
			},
            "columnDefs": [
                {
					"targets": [ -1 ], 
					"orderable": false,
					"searchable": false
                },
            ], 
            "columns": _includedColumns,
			"order": (_id == 'dt-antrian' ? [ 1, 'asc' ] : [ 0, 'asc' ]), //
            "drawCallback": function(settings) { 
                // untuk menu (edit menu)
				 $('.menu.btn-edit').on('click', function() {
                    let _menuid = $(this).attr('id'); 
                    let _tr = $(this).closest('tr');  
                    let _row = _datatable.row(_tr);
					let _data = _row.data();
					$('#from-menu-category').html('Edit menu');
					$('#form-menu #sts').val('edit');
					$('#form-menu #menu-id').val(_menuid);
					$('#form-menu #menu-name').val(_data.menu_name);
					$('#form-menu #slug').val(_data.slug);
					$('#form-menu #description').val(_data.description);
					$('#form-menu #menu-name').focus();
				});
			},
			"rowCallback": function(row, data, displayIndex) {
				//untuk status antrian
				if (data.status == '0') {
					$('td', row).each(function() {
						$(this).find('.dashboard.btn-process, .dashboard.btn-out').remove();
						$(this).find('.antrian.btn-wait').addClass('dipilihna');
					});
				} else if (data.status == '1') {
				    $('td', row).each(function() {
				        $(this).find('.dashboard.btn-wait, .dashboard.btn-out').remove();
						$(this).find('.antrian.btn-process').addClass('dipilihna');
					});
				} else if (data.status == '2') {
				    $('td', row).each(function() {
				        $(this).find('.dashboard.btn-wait, .dashboard.btn-process').remove();
						$(this).find('.antrian.btn-out').addClass('dipilihna');
					});
				}
				return row;
			}
        });
		// refresh data
		//_datatable.ajax.reload();
		// UNTUK KEPERLUAN CEK DATA
		// untuk menghilangkan pesan error datatable, biar dilihat di consol sj
		$.fn.dataTable.ext.errMode = 'throw';
		// untuk cek menampilkan data di datatable
		_datatable.on('xhr', function() {
			var _json = _datatable.ajax.json();
			//alert(_json.data.length +' row(s) were loaded' );
			//alert(JSON.stringify(_json));
			//alert(_json.csrf_content);
			_csrf_content = _json.csrf_content;
			updateCSRF(_csrf_content);
		});
	});
	// form menu
	$('#form-menu #menu-name').on('keyup', function() {
		$('#form-menu #slug').val(getSlug(this.value));
	});
	$('#list-menu #btn-add').on('click', function() {
		$('#from-menu-category').html('Tambah menu');
		$('#form-menu #sts').val('add');
		$('#form-menu #menu-id').val('');
		$('#form-menu #menu-name').val('');
		$('#form-menu #slug').val('');
		$('#form-menu #description').val('');
		$('#form-menu #menu-name').focus();
	});
	// form antrian
	$('#list-antrian #btn-add').on('click', function() {
		$('#from-antrian-category').html('Tambah antrian');
		$('#form-antrian #sts').val('add');
		$('#form-antrian #antrian-id').val('');
		$('#form-antrian #no-antrian').val('');
		$('#form-antrian #menu-id').val('');
		$('#form-antrian #menu-id.selectpicker').selectpicker('val', [-1]);  // agar title selectpicker kembali ke "Tidak Ada"
		$('#form-antrian #menu-id.selectpicker').selectpicker('refresh');
		$('#form-antrian #qty').val('');
		$('#form-antrian #no-antrian').focus();
	});
	$('#form-antrian #simpan').on('click', function(e) {
    	swal({
            title: 'Anda yakin?',
            text: 'Periksa kembali inputan Anda sebelum simpan.',
            type: 'question',
            showCancelButton: true,
            confirmButtonClass: 'btn btn-success',
            cancelButtonClass: 'btn btn-danger',
            confirmButtonText: 'Ya',
            cancelButtonText: 'Tidak',
            buttonsStyling: false
        }).then(function(result) {
            if (result.value) {
                $("#form-antrian").submit();
            }
        });
	});
	$("#form-antrian").on('submit', function(e) {
	    e.preventDefault();    
        let _url = $(this).attr("action");
		let _data = new FormData(this); // form.serialize() tidak bisa upload file/gambar
		$.ajax({
			type: 'post',
			url: _url,
			data: _data,
			cache:false,
			contentType: false,
			processData: false,
			beforeSend: function() {
				loadingna('show');
			},
			complete: function() {
				loadingna('hide');
			},
			success: function(result) {
				let _res = JSON.parse(result);
				
				if (_res.rc == '1') {
					swalMsg('Sukses', _res.rd, 'success', function() {
						location.reload();
					});
				} else {
					let _error = '';
					for (err in _res.errors) {_error += _res.errors[err] + ", ";}
					swalMsg('Gagal', _res.rd + _error , 'warning');
				}
				// jika csrf diaktifkan di Config/Filters.php
				updateCSRF(_res.csrf_content);
			},
			error: function(jqXHR, textStatus, errorThrown) {
				swalMsg('Error', 'status code: ' + jqXHR.status + ' errorThrown: ' + errorThrown + ' responseText: ' + jqXHR.responseText, 'error');
			}
		});
	});
});
// fungsi untuk create URL Friendly
// contoh: Test aja menjadi test-aja
function getSlug(_str) {
	return _str
        .toLowerCase()
        .replace(/ /g,'-')
        .replace(/[^\w-]+/g,''); 
}
// fungsi Sweet Alert Msg
function swalMsg(_title, _text, _type, callback) {
    swal({
        title: _title,
        text: _text,
        type: _type,
        confirmButtonClass: "btn btn-info",
        buttonsStyling: false
    }).then(function() {
		callback();
	}).catch(swal.noop);
}
// fungsi konfirmasi saat hapus data
function deleteData(_mod, _id, _ket, e) {
    e.preventDefault();
    let _msg = '';
	let _route = ''; //karena sekarang tiap modul satu controller
	
    switch(_mod) {
		case "menu":
            _msg = 'Anda akan menghapus menu: ' + _ket +'.';
			_route = 'menu/delete';
            break;
	}
	
    swal({
        title: 'Anda yakin?',
        text: _msg,
        type: 'question',
        showCancelButton: true,
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        confirmButtonText: 'Ya',
        cancelButtonText: 'Tidak',
        buttonsStyling: false
    }).then(function(result) {
        if (result.value) {
			// csrf_token_name harus disertakan jika csrf diaktifkan di Config/Filters.php
            $.post(_HOST + '/' + _route, {id:_id, csrf_token_name: _csrf_content}, function(result) {
                let _res = JSON.parse(result);
				if (_res.rc == '1') {
                    swal({
                        title: 'Sukses',
                        text: _res.rd,
                        type: 'success',
                        confirmButtonClass: "btn btn-success",
                        buttonsStyling: false
					}).then(function() {
						// jika ingin pake datatable reload, 
						// csrf token harus disertakan pada respon ajax
						//_datatable.ajax.reload();
						location.reload();	
					}).catch(swal.noop);
	            } else {
                    //swalMsg('Gagal', result, 'error');
					swal({
						title: 'Gagal',
						text: _res.rd,
						type: 'error',
						confirmButtonClass: "btn btn-success",
						buttonsStyling: false
					}).then(function() {
						// jika ingin pake datatable reload, 
						// csrf token harus disertakan pada respon ajax
						//_datatable.ajax.reload();
						location.reload();	
					}).catch(swal.noop);
                }		   
            });
        }
    });
}
// untuk update csrf token
function updateCSRF(_token) {
	// untuk meta di head (ajax)
	$('meta[name="X-CSRF-TOKEN"]').attr('content', _token);
	// untuk form inputan jika ada
	if (typeof $('input[name="csrf_token_name"]') !== "undefined") {
		$('input[name="csrf_token_name"]').attr('value', _token);
	}
}
// fungsi untuk mengurutkan json, _field = [nama field], _sort = ['asc' | 'desc']
// belum dipakai
function sortJSON(_json, _field, _sort) {
    _json.sort(function(a, b) {
        if (_short == 'asc') {
            return (a[_field] > b[_field]) ? 1 : ((a[_field] < b[_field]) ? -1 : 0);
        } else {
            return (b[_field] > a[_field]) ? 1 : ((b[_field] < a[_field]) ? -1 : 0);
        }
    });
}
// fungsi untuk loading
function loadingna(_sts) {
	if (_sts == 'show') 
		$('#loadingna').show();
	else
		$('#loadingna').hide();
}
// fungsi update status antrian
function updateStatusAntrian(_status, _id, _no, _mn, e) {
    e.preventDefault();
    
	let	_msg = _mn + ' No Antrian: ' + _no +' '+(_status == '0' ? 'Wait' : (_status == '1' ? 'Process' : 'Out')) + '?';
	let	_route = 'antrian/update-status';
    
    swal({
        title: 'Anda yakin?',
        text: _msg,
        type: 'question',
        showCancelButton: true,
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        confirmButtonText: 'Ya',
        cancelButtonText: 'Tidak',
        buttonsStyling: false
    }).then(function(result) {
        if (result.value) {
			// csrf_token_name harus disertakan jika csrf diaktifkan di Config/Filters.php
            $.post(_HOST + '/' + _route, {id:_id, status:_status, csrf_token_name: _csrf_content}, function(result) {
                let _res = JSON.parse(result);
				if (_res.rc == '1') {
                    swal({
                        title: 'Sukses',
                        text: _res.rd,
                        type: 'success',
                        confirmButtonClass: "btn btn-success",
                        buttonsStyling: false
					}).then(function() {
						// jika ingin pake datatable reload, 
						// csrf token harus disertakan pada respon ajax
						//_datatable.ajax.reload();
						location.reload();	
					}).catch(swal.noop);
	            } else {
                    //swalMsg('Gagal', result, 'error');
					swal({
						title: 'Gagal',
						text: _res.rd,
						type: 'error',
						confirmButtonClass: "btn btn-success",
						buttonsStyling: false
					}).then(function() {
						// jika ingin pake datatable reload, 
						// csrf token harus disertakan pada respon ajax
						//_datatable.ajax.reload();
						location.reload();	
					}).catch(swal.noop);
                }		   
            });
        }
    });
}

if (_mod == 'dashboard') {
    setTimeout(function() { 
        location.reload(true); 
        //_datatable.ajax.reload();
    }, 5000);
}

