/*
Created by Hendi
Created date 2021-03-15
Created update 2021-04-14
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:"time", sortable: false},	
                    {data:"menu_name", sortable: false},
                    {data:"qty", sortable: false},
					{data:"queue_number", sortable: false},
                    {data:"actions", sortable: false, width: "25%"}	
                ];
				break;
			case 'dt-menu':
				_url = _HOST + "/get-datatables/" + _mod;
                _includedColumns = [
                    {data:"menu_id", sortable: true, width: "10%"},
                    {data:"menu_name", sortable: true},	
                    //{data:"slug", visible: false},
                    {data:"unit", sortable: true},
                    {data:"price", sortable: true, className: "align-right", render: $.fn.dataTable.render.number( '.', ',', 0, '' )},
                    //{data:"description", sortable: true},
					{data:"actions", sortable: false, width: "15%"}	
                ];
				break;
            case 'dt-transaksi-detail': 
                //
                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:"time", sortable: true},	
                    {data:"menu_name", sortable: true},
                    {data:"qty", sortable: true},
					{data:"queue_number", 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:"date", sortable: true},	
                    {data:"time", sortable: true},	
                    {data:"menu_name", sortable: true},
                    {data:"qty", sortable: true},
					{data:"queue_number", sortable: false},
                    {data:"start", sortable: false},
                    {data:"finish", sortable: false},
                    {data:"duration", sortable: false}	
                ];
				break;
            case 'dt-laporan':
				_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:"date", sortable: true},	
                    {data:"transaction_id", sortable: true},	
                    {data:"total", sortable: true, className: "align-right", render: $.fn.dataTable.render.number( '.', ',', 0, '' )},
                    {data:"tax", sortable: true, className: "align-right", render: $.fn.dataTable.render.number( '.', ',', 0, '' )},
					{data:"total_paid", sortable: true, className: "align-right", render: $.fn.dataTable.render.number( '.', ',', 0, '' )},
                    {data:"note", sortable: false}
                ];
				break;
            case 'dt-user':
				_url = _HOST + "/get-datatables/" + _mod;
				_includedColumns = [
                    {data:"user_id", sortable: true, width: "10%"},
					{data:"full_name", sortable: true, width: "40%"},	
                    {data:"level", sortable: true, searchable: false},
					{data:"description", sortable: true},
                    {data:"actions", sortable: false, width: "10%"}	
                ];
				break;
		}
		// untuk detail transaksi, tidak pake datatables library, tp menggunakan json/array
        if (_id == 'dt-transaksi-detail') {
            _datatable = _table.DataTable({
                "destroy": true,
                "processing": true,
                "jQueryUI": false,
                "autoWidth": false,
                "lengthChange" : false,
                "searching": false,
                "paging": false,
                "sort": false,
                "info": false,
                "scrollX": true, 
                "scrollY": "300px", 
                "scrollCollapse": true,                                   
                "data": _arr_detail_trx,
                "columnDefs": [
                    {
                        "targets": [ -1 ], 
                        "orderable": false,
                        "searchable": false
                    },
                ],
                "columns": [
                    {data: "no","width": "3%"},
                    {data: "menu_id"},
                    {data: "menu_name"},
                    {data: "price", className: "align-right", render: $.fn.dataTable.render.number( '.', ',', 0, '' )},
                    {data: "qty", className: "align-right"},
                    {data: "subtotal", className: "align-right", render: $.fn.dataTable.render.number( '.', ',', 0, '' )},
                    {data: "action"}
                ]
            });
          
        } else {
            let _start = 0;
    		let _limit = 10;
    		_datatable = _table.DataTable({
                "destroy": true,
                "processing": true, 
                "jQueryUI": false,
                "autoWidth": false,
                "searching": (_id == 'dt-dashboard' || _id == 'dt-laporan' ? false : true),
                "paging": (_id == 'dt-laporan' ? 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-dashboard' || _id == 'dt-antrian' || _id == 'dt-history' || _id == 'dt-laporan' ? [ 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 #unit').val(_data.unit);
                        $('#form-menu #price').val(numberFormat(_data.price, 0, ',', '.'));
    					$('#form-menu #description').val(_data.description);
                        $('#form-menu #menu-id').attr('readonly', true);
    					$('#form-menu #menu-name').focus();
    				});
    			},
    			"rowCallback": function(row, data, displayIndex) {
    				//untuk status antrian di dashboard
    				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;
    			},
                "footerCallback": function ( row, data, start, end, display ) {
                    // S: untuk laporan
                    if (_id == 'dt-laporan') {
                        var api = this.api(), data;
             
                        // Remove the formatting to get integer data for summation
                        var intVal = function ( i ) {
                            return typeof i === 'string' ?
                                i.replace(/[\$,]/g, '')*1 :
                                typeof i === 'number' ?
                                    i : 0;
                        };
             
                        // Total over all pages
                        total = api
                            .column( 5 )
                            .data()
                            .reduce( function (a, b) {
                                return intVal(a) + intVal(b);
                            }, 0 );
             
                        // Total over this page
                        pageTotal = api
                            .column( 5, { page: 'current'} )
                            .data()
                            .reduce( function (a, b) {
                                return intVal(a) + intVal(b);
                            }, 0 );
             
                        // Update footer
                        $( api.column( 5 ).footer() ).html(
                            //'$'+pageTotal +' ( $'+ total +' total)'
                            numberFormat(total, 0, ',', '.')
                        ).addClass('align-right');
                    }
                    // E: untuk laporan
                }
            });
    		// 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 #unit').val('');
        $('#form-menu #price').val('');
		$('#form-menu #description').val('');
        $('#form-menu #menu-id').attr('readonly', false);
		$('#form-menu #menu-id').focus();
	});
    $('#form-menu #price').on('keydown', function() {
		$('#form-menu #price').val(stringToNumber(this.value, 0));
	});
    $('#form-menu #price').on('keyup', function() {
		$('#form-menu #price').val(numberFormat(this.value, 0, ',', '.'));
	});
    $('#form-menu').on('submit', function(e) {
		e.preventDefault;
        // konversi ke angka
		$('#form-menu #price').val(stringToNumber($('#form-menu #price').val(), 0));
		return true;
	});
    // form transaksi
    // shortcut untuk memudahkan
    $('body').on('keydown', function(e) {
        if (e.keyCode >= 117 && e.keyCode <= 121) {
            // Cancel the default action, if needed
            e.preventDefault();
        }
        // key on the keyboard
        // 116 = F5
        if (e.keyCode === 116) {
            //  trigger input transaksi baru
            $('#form-transaksi #new-trx').trigger('click');
        }
        // 117 = F6
        if (e.keyCode === 117) {
            // focus ke menu  
            $('#form-transaksi #menu-id').focus();
        }
        // 118 = F7
        if (e.keyCode === 118) {
            // trigger tambah rincian trx
            $('#form-transaksi #add-detail-trx').trigger('click');
        }
        // 119 = F8
        if (e.keyCode === 119) {
            // focus ke uang bayar
            $('#form-transaksi #cash').focus();
        }
        // 120 = F9 
        if (e.keyCode === 120) {
            // trigger cetak struk
            $('#form-transaksi #print-trx').trigger('click');
        }
        // 121 = F10
        if (e.keyCode === 121) {
            // trigger cetak struk
            $('#form-transaksi #save-trx').trigger('click');
        }
	});
    $('#form-transaksi #qty').on('keydown', function(e) {
        // 13 = Enter key on the keyboard
        if (e.keyCode === 13) {
            // Cancel the default action, if needed
            e.preventDefault();
            // Trigger the button element with a click
            $('#form-transaksi #add-detail-trx').trigger('click');
        }
	});
    $('#form-transaksi #add-detail-trx').on('click', function(e) {
        e.preventDefault();
        var _menu_id = $('#form-transaksi #menu-id').val();
		var _qty = $('#form-transaksi #qty').val();
        
        // validasi inputan
        if (_menu_id == '') {
			swalMsg("Peringatan", "Menu belum diisi", "warning", $('#form-transaksi #menu-id').focus());
            return;
		} 
        if (_qty == '' || parseInt(_qty) < 1) {
			swalMsg("Peringatan", "QTY belum diisi", "warning", $('#form-transaksi #qty').focus());
            return;
		} 
        // validasi kode
        var _menu_json_filter = $.grep(_menu_json, function(n, i) {
            return n.menu_id == _menu_id;
        });
        if (_menu_json_filter.length < 1) {
            swalMsg("Peringatan", "Kode Menu tidak valid", "warning", $('#form-transaksi #menu-id').focus());
			return;
        }  
        // jika sudah ada jangan dimasukkan lg
		var _cek = $.grep(_arr_detail_trx, function (element, index)  {
			return element.menu_id == _menu_id;
		});  
		if(_cek.length > 0) {
            swalMsg("Peringatan", "Menu tersebut sudah diinput", "warning", $('#form-transaksi #menu-id').focus());
			return;
		}    
        // end    
		var _menu_name = (_menu_json_filter[0].menu_name).toUpperCase();
		var _price = _menu_json_filter[0].price;
		var _subtotal = parseInt(_price) * parseInt(_qty);
		// ambil no urut terakhir dari tabel detail transaksi
		var _maxno = Math.max.apply(Math, _arr_detail_trx.map(function(o) { return o.no; }));
		_maxno = (_maxno < 0 ? 0 : _maxno);
		
		var _arr_tambah = new Array();
		_arr_tambah['no'] = _maxno + 1;
		_arr_tambah['menu_id'] = _menu_id;
		_arr_tambah['menu_name'] = _menu_name;
		_arr_tambah['price'] = _price;
		_arr_tambah['qty'] = _qty;
		_arr_tambah['subtotal'] = _subtotal;
		_arr_tambah['action'] = '<button type="button" class="btn btn-link btn-danger btn-just-icon" onclick="javascript:removeDetailTrx(&quot;'+_menu_id+'&quot;);" title="hapus"><i class="fa fa-close"></i></button>';		
		_arr_detail_trx.push(_arr_tambah);
		//alert(_arr_detail_trx.length);
		$('#dt-transaksi-detail').DataTable().clear();
		$('#dt-transaksi-detail').DataTable().rows.add(_arr_detail_trx);
		$('#dt-transaksi-detail').DataTable().draw();
        // kosongkan inputan
        $('#form-transaksi #menu-id').val('');
        $('#form-transaksi #menu-name').val('');
        $('#form-transaksi #qty').val('');
        // sum total
        let _total = getSumDetailTrx();
        // pajak 10%
        let _tax = 0.1 * _total; 
        // total bayar 
        let _total_paid = _total + _tax;
        //kembalian
        let _change = stringToNumber($('#form-transaksi #cash').val(), 0) - _total_paid;
        $('#form-transaksi #total').val(numberFormat(_total, 0, ',', '.'));
        $('#form-transaksi #tax').val(numberFormat(_tax, 0, ',', '.'));
        $('#form-transaksi #total-paid').val(numberFormat(_total_paid, 0, ',', '.'));
        $('#form-transaksi #change').val(numberFormat(_change, 0, ',', '.'));
        $('#form-transaksi #menu-id').focus();
    });
    $('#form-transaksi #cash').on('keydown', function() {
		$('#form-transaksi #cash').val(stringToNumber(this.value, 0));
	});
    $('#form-transaksi #cash').on('keyup', function(e) {
		$('#form-transaksi #cash').val(numberFormat(this.value, 0, ',', '.'));
        //kembalian
        let _change = stringToNumber(this.value, 0) - stringToNumber($('#form-transaksi #total-paid').val(), 0);
        $('#form-transaksi #change').val(numberFormat(_change, 0, ',', '.'));
        
        // 13 = Enter key on the keyboard
        if (e.keyCode === 13) {
            // Cancel the default action, if needed
            e.preventDefault();
            // Trigger the button element with a click
            $('#form-transaksi #save-trx').trigger('click');
        }
	});
    $('#form-transaksi #print-trx').on('click', function(e) {
        e.preventDefault();
        let _id = $('#form-transaksi #transaction-id').val();
        
        if (_id == '') {
            swalMsg('Peringatan', "No. Transaksi tidak ditemukan", 'warning');
			return;
        }
        
        //var myWindow = window.open(_HOST+"/transaksi/print/1", "MsgWindow", "width=200,height=300");
        //myWindow.document.write("<p>This is 'MsgWindow'. I am 200px wide and 100px tall!</p>");
        popupWindow(_HOST+"/transaksi/print/"+_id, "Print Struk", 300, 400);
    });
    $('#form-transaksi #save-trx').on('click', function(e) {
        e.preventDefault();
        //alert('simpan transaksi');
        let _sts = $('#form-transaksi #sts').val();
        let _transaction_id = $('#form-transaksi #transaction-id').val();
		let _date = $('#form-transaksi #date').val();
		let _queue_number = $('#form-transaksi #queue-number').val();
		let _note = $('#form-transaksi #note').val();
		let _total = stringToNumber($('#form-transaksi #total').val(), 0);
        let _tax = stringToNumber($('#form-transaksi #tax').val(), 0);
        let _total_paid = stringToNumber($('#form-transaksi #total-paid').val(), 0);
        let _cash = stringToNumber($('#form-transaksi #cash').val(), 0);
        let _change = stringToNumber($('#form-transaksi #change').val(), 0);
        
        if (date == '' || stringToNumber(_total, 0) == 0 || stringToNumber(_change, 0) < 0) {
			swalMsg('Peringatan', "Mohon periksa kembali inputan", 'warning');
			return;
		}
		
		if (_arr_detail_trx.length < 1) {
			swalMsg('Peringatan', "Mohon lengkapi rincian transaksi", 'warning');
			return;			
		}
		
		//detail transaksi
		let _jsonstr = '[';
		
		$.each(_arr_detail_trx, function(i, value) {
			_jsonstr = _jsonstr + '{';
			_jsonstr = _jsonstr + '"no":"'+_arr_detail_trx[i]['no']+'",';
			_jsonstr = _jsonstr + '"menu_id":"'+_arr_detail_trx[i]['menu_id']+'",';
			_jsonstr = _jsonstr + '"menu_name":"'+_arr_detail_trx[i]['menu_name']+'",';
			_jsonstr = _jsonstr + '"price":"'+_arr_detail_trx[i]['price']+'",'; 
			_jsonstr = _jsonstr + '"qty":"'+_arr_detail_trx[i]['qty']+'",';
			_jsonstr = _jsonstr + '"subtotal":"'+_arr_detail_trx[i]['subtotal']+'"';
			_jsonstr = _jsonstr + '}';
			
			if (i < (_arr_detail_trx.length - 1)) {
				_jsonstr = _jsonstr + ',';
			}
		});
		
		_jsonstr = _jsonstr + ']';
		
		let _data = {
            sts:_sts,
			transaction_id:_transaction_id,
			date:_date,
			queue_number:_queue_number,
			note:_note,
            total:_total,
            tax:_tax,
            total_paid:_total_paid,
            cash:_cash,
            change:_change,
			detail_trx:_jsonstr
        };
		
		let _url = _HOST + '/transaksi/save' ;
		
		$.ajax({
			type: "POST",
			url: _url,
			data: _data,
            headers: {
			    'X-CSRF-TOKEN': _csrf_content
		    },
            //cache:false,
			//contentType: 'application/json',
			//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();
                    //});
                    
                    // update status jadi edit
                    $('#form-transaksi #sts').val('edit');
                    $('#form-transaksi #transaction-id').val(_res.transaction_id);
                    $('#form-transaksi #queue-number').val(_res.queue_number);
                    confirmAfterSaveTrx();
				} 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
                _csrf_content = _res.csrf_content;
				updateCSRF(_res.csrf_content);
			},
	        error: function(jqXHR, textStatus, errorThrown) {
				swalMsg('Error', 'status code: ' + jqXHR.status + ' errorThrown: ' + errorThrown + ' responseText: ' + jqXHR.responseText, 'error');
			}
		});
    });
    // form antrian
	$('#list-antrian #btn-add').on('click', function() {
		location.reload();
	});
	$('#form-antrian #save-antrian').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');
			}
		});
	});
    // form laporan
  	$('#list-laporan #btn-print').on('click', function(e) {
        e.preventDefault();    
        $('#list-laporan').removeClass('col-md-10').addClass('col-md-12');
        window.print();
        $('#list-laporan').removeClass('col-md-12').addClass('col-md-10');
    });
    // form user
	$("#form-user").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: [' + _id + '] ' + _ket +'.';
			_route = 'menu/delete';
            break;
        case 'user':
			// khusus admin tidak boleh dihapus
            if (_id == 'admin') {swalMsg('Peringatan', 'User ID admin tidak boleh dihapus.', 'warning');exit;}
            _msg = 'Anda akan menghapus data User ID: ' + _id + '.';
			_route = 'user/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);
                }		   
            });
        }
    });
}
// fungsi untuk konfersi 999.999,00 ke 999999.00
function stringToNumber(_val, _dec) {
    if (_val == null || _val == '') {
        _val = '0';    
    }
    
    var _number_string = _val;
    _number_string = _number_string
        .replace(/\./g, '')  // replace all separators
        .replace(/,/, '.');  // replace comma with dot 

    var _parsed = parseFloat(_number_string).toFixed(_dec);
    
    return _parsed;
}
// fungsi untuk format angka jadi 999,999.00 atau 999.999,00
var numberFormat = function (number, decimals, dec_point, thousands_sep) {
    //  discuss at: http://phpjs.org/functions/number_format/
    // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // improved by: davook
    // improved by: Brett Zamir (http://brett-zamir.me)
    // improved by: Brett Zamir (http://brett-zamir.me)
    // improved by: Theriault
    // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // bugfixed by: Michael White (http://getsprink.com)
    // bugfixed by: Benjamin Lupton
    // bugfixed by: Allan Jensen (http://www.winternet.no)
    // bugfixed by: Howard Yeend
    // bugfixed by: Diogo Resende
    // bugfixed by: Rival
    // bugfixed by: Brett Zamir (http://brett-zamir.me)
    //  revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    //  revised by: Luke Smith (http://lucassmith.name)
    //    input by: Kheang Hok Chin (http://www.distantia.ca/)
    //    input by: Jay Klehr
    //    input by: Amir Habibi (http://www.residence-mixte.com/)
    //    input by: Amirouche
    //   example 1: number_format(1234.56);
    //   returns 1: '1,235'
    //   example 2: number_format(1234.56, 2, ',', ' ');
    //   returns 2: '1 234,56'
    //   example 3: number_format(1234.5678, 2, '.', '');
    //   returns 3: '1234.57'
    //   example 4: number_format(67, 2, ',', '.');
    //   returns 4: '67,00'
    //   example 5: number_format(1000);
    //   returns 5: '1,000'
    //   example 6: number_format(67.311, 2);
    //   returns 6: '67.31'
    //   example 7: number_format(1000.55, 1);
    //   returns 7: '1,000.6'
    //   example 8: number_format(67000, 5, ',', '.');
    //   returns 8: '67.000,00000'
    //   example 9: number_format(0.9, 0);
    //   returns 9: '1'
    //  example 10: number_format('1.20', 2);
    //  returns 10: '1.20'
    //  example 11: number_format('1.20', 4);
    //  returns 11: '1.2000'
    //  example 12: number_format('1.2000', 3);
    //  returns 12: '1.200'
    //  example 13: number_format('1 000,50', 2, '.', ' ');
    //  returns 13: '100 050.00'
    //  example 14: number_format(1e-8, 8, '.', '');
    //  returns 14: '0.00000001'

    number = (number + '')
    .replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
    prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
    sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
    dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
    s = '',
    toFixedFix = function(n, prec) {
        var k = Math.pow(10, prec);
        return '' + (Math.round(n * k) / k)
        .toFixed(prec);
    };
    
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n))
    .split('.');
    
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    
    if ((s[1] || '')
        .length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1)
        .join('0');
    }
    
    return s.join(dec);
}
// cari nama menu 
function getMenuName(_id) {
    // _menu_json ada di view transaksi
    var _menu_json_filter = $.grep(_menu_json, function(n, i) {
        return n.menu_id == _id;
    });  
    if (_menu_json_filter.length < 1) 
        return '';
    else
        return _menu_json_filter[0].menu_name;
}
// hapus detail transaksi
function removeDetailTrx(_id) {
    // _arr_detail_trx ada di view transaksi
	//if (confirm("Yakin mau dihapus menu " + _id + "?")) {
		// hapus detail
		_arr_detail_trx = $.grep(_arr_detail_trx, function(_detail) {
            return (_detail.menu_id).indexOf(_id) == -1;
        }); 
		
		var _len = _arr_detail_trx.length;
          
        if (_len > 0) {
            //update no urut
            for (i = 0; i < _len; i++) {
                _arr_detail_trx[i]['no'] = i + 1;
            }
        }
		
		$('#dt-transaksi-detail').DataTable().clear();
		$('#dt-transaksi-detail').DataTable().rows.add(_arr_detail_trx);
		$('#dt-transaksi-detail').DataTable().draw();
        // sum total
        let _total = getSumDetailTrx();
        // pajak 10%
        let _tax = 0.1 * _total; 
        // total bayar 
        let _total_paid = _total + _tax;
        //kembalian
        let _change = stringToNumber($('#form-transaksi #cash').val(), 0) - _total_paid;
        $('#form-transaksi #total').val(numberFormat(_total, 0, ',', '.'));
        $('#form-transaksi #tax').val(numberFormat(_tax, 0, ',', '.'));
        $('#form-transaksi #total-paid').val(numberFormat(_total_paid, 0, ',', '.'));
        $('#form-transaksi #change').val(numberFormat(_change, 0, ',', '.'));
	//}
}
// total detail transaksi
function getSumDetailTrx() {
    // _arr_detail_trx ada di view transaksi
    let _sum = 0;
    let _len = _arr_detail_trx.length;
          
    if (_len > 0) {
        for (i = 0; i < _len; i++) {
            _sum += parseInt(_arr_detail_trx[i]['subtotal']);
        }
    }
    return _sum;
}
// fungsi konfirmasi setelah simpan transaks
function confirmAfterSaveTrx() {
    swal({
        title: 'Konfirmasi',
        text: 'Transaksi berhasil disimpan. Input transaksi lagi?',
        type: 'question',
        showCancelButton: true,
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        confirmButtonText: 'Ya',
        cancelButtonText: 'Tidak',
        buttonsStyling: false
    }).then(function(result) {
        if (result.value) {
	       location.reload();
        }
    });
}
// agar popup di tengah
function popupWindow(_url, _title, _width, _height) {
    var _left = (screen.width / 2)-(_width / 2);
    var _top = (screen.height / 2)-(_height / 2);
    return window.open(_url, _title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+_width+', height='+_height+', top='+_top+', left='+_left);
} 
// refresh halaman tiap 5 detik
if (_mod == 'dashboard') {
    setTimeout(function() { 
        location.reload(true); 
        //_datatable.ajax.reload();
    }, 5000);
}


