//= require jquery
//= require tether
//= require jquery_ujs
//= require bootstrap/js/popper.min
//= require bootstrap/js/bootstrap-material-design.min
//= require momentjs/moment
//= require bootstrap-material-datetimepicker/js/bootstrap-material-datetimepicker
//= require jquery-slimscroll/jquery.slimscroll.js
//= require bootstrap-notify/bootstrap-notify.js
//= require node-waves/waves.js
//= require sweetalert/sweetalert.min.js
//= require fileinput.min
//= require cable
//= require turbolinks
//= require BSBMaterial/turbolink_admin.js
//= require BSBMaterial/demo.js
//= require custom.js
//= require order_reservation.js

/* Constant Varaibles */
_CREDIT_PAYMENTS_	= "/&nbsp;&nbsp;&nbsp;CREDIT PAYMENTS";
_CUSTOMERS_			= "/&nbsp;&nbsp;&nbsp;CUSTOMERS";
_DISCOUNTS_			= "/&nbsp;&nbsp;&nbsp;DISCOUNTS";
_IN_DUTIES_			= "/&nbsp;&nbsp;&nbsp;IN DUTIES";
_JCB_				= "/&nbsp;&nbsp;&nbsp;JCB PAYMENT";
_MASTER_			= "/&nbsp;&nbsp;&nbsp;MASTER PAYMENT";
_MPU_				= "/&nbsp;&nbsp;&nbsp;MPU PAYMENT";
_ALIPAY_			= "/&nbsp;&nbsp;&nbsp;Alipay";
_JUNCTIONPAY_		= "/&nbsp;&nbsp;&nbsp;JunctionPay";
_PAYMAL_			= "/&nbsp;&nbsp;&nbsp;PAYMAL";
_DINGA_				= "/&nbsp;&nbsp;&nbsp;DINGA PAYMENT";
_GIFT_VOUCHER_		= "/&nbsp;&nbsp;&nbsp;GIFT VOUCHER";
_OTHER_CHARGES_		= "/&nbsp;&nbsp;&nbsp;CHARGES";
_OTHER_PAYMENTS_	= "/&nbsp;&nbsp;&nbsp;OTHER PAYMENT";
_PAYMENTS_ 			= "/&nbsp;&nbsp;&nbsp;PAYMENT";
_PAYPAR_PAYMENT_	= "/&nbsp;&nbsp;&nbsp;PAYPAR PAYMENT";
_COMMISSIONS_		= "/&nbsp;&nbsp;&nbsp;COMMISSIONS";
_REDEEM_PAYMENT_	= "/&nbsp;&nbsp;&nbsp;REDEEM PAYMENT";
_SALE_EDIT_			= "/&nbsp;&nbsp;&nbsp;SALE EDIT";
_SPLIT_BILL_		= "/&nbsp;&nbsp;&nbsp;SPLIT BILL";
_UNION_				= "/&nbsp;&nbsp;&nbsp;UNION PAYMENT";
_VISA_				= "/&nbsp;&nbsp;&nbsp;VISA PAYMENT";
_VOUCHER_			= "/&nbsp;&nbsp;&nbsp;VOUCHER";
_SURVEY_ 			= "/&nbsp;&nbsp;&nbsp;SURVEY";
/* Constant Varaibles */

$(document).on('turbolinks:load', function() {

    $("#customer_image_path").fileinput({
	      previewFileType: "image",
	      allowedFileExtensions: ["jpg", "gif", "png"],
	      browseClass: "btn btn-success",
	      browseLabel: "Pick Image",
	      browseIcon: "<i class=\"fa fa-image\"></i> ",
	      removeClass: "btn btn-danger",
	      removeLabel: "Delete",
	      removeIcon: "<i class=\"fa fa-trash\"></i> ",
	      showUpload: false,
	      // uploadClass: "btn btn-info",
	      // uploadLabel: "Upload",
	      // uploadIcon: "<i class=\"fa fa-upload\"></i> ",
	      previewTemplates: {
	        image: '<div class="file-preview-frame" id="{previewId}" data-fileindex="{fileindex}">\n' +
	                '   <img src="{data}" class="file-preview-image" title="{caption}" alt="{caption}" style="width: 200px;height: 200px;">\n' +
	                '</div>\n',
	    }
	  });  
});

$(document).on('turbolinks:load', function() {
	$('.datetimepicker').bootstrapMaterialDatePicker({
	  format: 'DD-MM-YYYY - HH:mm',
	  clearButton: true,
	  weekStart: 1
	});

	$('.datepicker').bootstrapMaterialDatePicker({
	  format: 'DD-MM-YYYY',
	  clearButton: true,
	  weekStart: 1,
	  time: false
	});

	$('.timepicker').bootstrapMaterialDatePicker({
	  format: 'HH:mm',
	  clearButton: true,
	  date: false
	});

	// For selected order return
	var order_status = "";
	order_status = $(".selected-item").children().find(".orders-order-status").text().substr(0,6).trim();

	// Enable/Disable Button
	//control_button(order_status);

	$(".orders").on('click', function(){
		$("#order-sub-total").text('');
        // $("#order-food").text('');
        // $("#order-beverage").text('');
        $("#order-discount").text('');
        $("#order-Tax").text('');
        $("#order-grand-total").text('');

		var zone_name=$(this).find(".orders-table").text();
		var receipt_no=$(this).find(".orders-receipt-no").text();
		var unique_id = $(this).find(".orders-id").text();
		var order_status=$(this).find(".orders-order-status").text().trim();

		// Enable/Disable Button
		//control_button(order_status);

		var customer_id=$(this).find(".customer-id").text();
		show_customer_details(customer_id);

		$("#re-print").val(unique_id);

		var cashier="";
		var receipt_date="";
		var sub_total=0.0;
		var discount_amount=0;
		var tax_amount=0;
		var grand_total_amount=0;

		$("#order-title").text("ORDER DETAILS - " + zone_name);
		// clear order items
		$("#order-items-table").children("tbody").empty();

		// AJAX call for order
		$.ajax({
			type: "POST",
		    url: "/origami/" + unique_id,
		    data: { 'booking_id' : unique_id },
		    success:function(result){		    	
		    	for (i = 0; i < result.length; i++) {
		    		var data = JSON.stringify(result[i]);
        			var parse_data = JSON.parse(data);
        			var show_date = "";        			

        			// Receipt Header
        			receipt_no = result[i].receipt_no;
			        cashier = result[i].cashier_name;
			        if(result[i].receipt_date != null){
				        receipt_date = new Date(result[i].receipt_date);
				        show_date = receipt_date.getDate() + "-" + receipt_date.getMonth() + "-" + receipt_date.getFullYear() + ' ' +  receipt_date.getHours()+ ':' +  receipt_date.getMinutes()
				    }			        

			        //Receipt Charges
        			sub_total += parseFloat(parse_data.price);

        			discount_amount = parse_data.discount_amount == null? '0.0' : parse_data.discount_amount;
        			tax_amount = parse_data.tax_amount;
			        grand_total_amount = parse_data.grand_total_amount;			        

			        // Ordered Items
			        var order_items_rows = "<tr>" +
				        						"<td class='item-name'>" + parse_data.item_name + "</td>" +
				        						"<td class='item-attr'>" + parse_data.qty + "</td>" +
				        						"<td class='item-attr'>" + parse_data.price + "</td>" +
			        					   "</tr>";

			        $("#order-items-table").children("tbody").append(order_items_rows);
		    	}

		    	// Cashier Info
		    	$("#receipt_no").text(receipt_no);
		        $("#cashier").text(cashier == null ? "" : cashier);
		        $("#receipt_date").text(show_date);

		        // Payment Info
		    	$("#order-sub-total").text(sub_total);
		        // $("#order-food").text('');
		        // $("#order-beverage").text('');
		        $("#order-discount").text(discount_amount);
		        $("#order-Tax").text(tax_amount);
		        $("#order-grand-total").text(grand_total_amount);
		    }
		});
		// End AJAX Call

		$('.orders').removeClass('selected-item');
	    $(this).addClass('selected-item');
	});

	// Payment for Bill
	$('#pay-bill').click(function() {
		var sale_id=$(".selected-item").find(".orders-id").text().substr(0,16);
		if(sale_id!=""){
			window.location.href = '/origami/sale/'+ sale_id  + "/payment"
		}
		else {
			alert("Please select an order!");
		}

		return false;
	});

	$(document).on('click', '.access_modal', function(event){
      type = $(this).data("type");
      $(".ok").attr("data-action",type)
      $('#AccessCodeModal').modal('show');
    });

	$(document).on('click', '.access_number', function(event){
      if(event.handled !== true) {
        var original_value = $('#access_code').val();
        var input_type = $(this).attr("data-type");

        switch (input_type) {
            case 'num':
              var input_value = $(this).attr("data-value");
              if (original_value){
                $('#access_code').val(original_value + input_value);
              }else{
                $('#access_code').val(original_value + input_value);
              }
              break;
            case 'ok':
              var type = $(this).attr("data-action");
              code = $('#access_code').val();
              check_emp_access_code(code,type)
              break;
            case 'clr':
              $('#access_code').val("");
              break;
        }
        event.handled = true;
      } else {
          return false;
      }
    });
});

/* start check first bill or not funs: */
function checkReceiptNoInFirstBillData(receipt_no,payment) {
	// localStorage.removeItem('receipt_lists');
	var status = false;
	var json_data = [];
	if((receipt_no!=undefined) && (receipt_no!="")){
		if(localStorage.hasOwnProperty("receipt_lists")===true){
			var arr_data = JSON.parse(localStorage.getItem("receipt_lists"));
			if (payment) {
				json_data = arr_data.filter(function(e) { return e.receipt_no == receipt_no });
			}else{
				json_data = arr_data.filter(function(e) { return e.receipt_no !== receipt_no });
			}

			if((arr_data.length) > (json_data.length)){
				status = true;
			}
		}
	}

	if (payment) {
		if (json_data.length>0) {
		  return json_data[0]["payment"];
	    }else{
	    	return false;
	    }
	}else{
		return status;
	}
}

function createReceiptNoInFirstBillData(receipt_no,payment) {
	var arr_data = [];
	var json_data = [];
	if(localStorage.hasOwnProperty("receipt_lists") === true){
		arr_data = JSON.parse(localStorage.getItem("receipt_lists"));
		json_data = arr_data.filter(function(e) { return e.receipt_no == receipt_no });
		if (payment) {
			jdata = arr_data.filter(function(e) { return e.receipt_no !== receipt_no });
			jdata.push({'receipt_no':receipt_no,'payment':payment});
		   localStorage.setItem("receipt_lists",JSON.stringify(jdata));
		}
	}
	if(((arr_data.length == 0) && (json_data.length == 0)) || ((arr_data.length > 0) && (json_data.length == 0))){
		arr_data.push({'receipt_no':receipt_no,'payment':payment});
		localStorage.setItem("receipt_lists",JSON.stringify(arr_data));
	}
}

function deleteReceiptNoInFirstBillData(receipt_no) {
	if(localStorage.hasOwnProperty("receipt_lists") ===true ){
		var arr_data = JSON.parse(localStorage.getItem("receipt_lists"));
		var json_data = arr_data.filter(function(e) { return e.receipt_no !== receipt_no });
		localStorage.setItem("receipt_lists",JSON.stringify(json_data));
	}
}
/* end check first bill or not funs: */

//start CB ECR integration
//set CB com port data
function setCommPorts(comPortLists) {
	var sale_id = "<%= @sale_id %>";
    $('#com_port_name').html("");
    var jsonPortLists = $.parseJSON(comPortLists);
    // alert(jsonPortLists);
    if((jsonPortLists!=undefined && jsonPortLists!='') && (jsonPortLists.length > 0)){
        $.each(jsonPortLists,function(key,value){
            $('#com_port_name').append("<option value='"+value+"'>"+value+"</option>");
        });
    }
    else{
    	swal({
		  title: 'Oops',
		  text: 'Payment device has been disconnected! Please plug it in.',
		  type: 'error',
		  html: true,
		  closeOnConfirm: false,
		  closeOnCancel: false,
		  allowOutsideClick: false
		}, function () {
			window.location.href = '/origami/sale/'+ sale_id  +"/"+cashier_type+"/payment/others_payment";
		});
    }
}

/** pay with CB bank **/
function pay_withBank(cmd_type, payment_type, bnk_bill_amount,sale_id,receipt_no,cashier_type) {
	$("#loading_wrapper").show();
    var com_port = $("#com_port_name").val();
    reqCardSaleTrans(cmd_type, payment_type, bnk_bill_amount, sale_id, receipt_no, com_port,cashier_type);
}

//add req data to card_sale_trans table
function reqCardSaleTrans(cmd_type, payment_type, bnk_bill_amount, sale_id, receipt_no, com_port,cashier_type) {
  var jobj = {"cmd_type" : cmd_type, "payment_type" : "CARD", "amt" : bnk_bill_amount, "sale_id" : sale_id, "inv_no" : receipt_no, "com_port" : com_port};
  $.ajax({
      type: "POST",
      url: "/origami/bank_integration/sale_trans",
      data: {type:"request", data: jobj},
      dataType: "json",
      success: function(data) {
          if (data.status == "success"){
            card_sale_trans_id = data.card_sale_trans_id;
            resCardSaleTrans(card_sale_trans_id,cmd_type,payment_type, bnk_bill_amount, sale_id, receipt_no,com_port,cashier_type);
          }
       }
    });
}

//add res data to card_sale_trans table
function resCardSaleTrans(card_sale_trans_id,cmd_type,payment_type, bnk_bill_amount, sale_id, receipt_no,com_port,cashier_type) {

  var resMsg = "";
  var card_payment_type="";
  if($("#loading_wrapper").is(":visible")){
    if(payment_type=="mpu" || payment_type=="visa" || payment_type=="master" || payment_type=="jcb" || payment_type=="unionpay"){
        card_payment_type = "CARD";
    }
    else if(payment_type == "alipay"){
        card_payment_type = "EWALLET";
    }

    bnk_bill_amount = parseFloat(bnk_bill_amount);

    resMsg = code2lab.reqBankPayment(cmd_type,card_payment_type,bnk_bill_amount,receipt_no,com_port);
  }

  if(resMsg.includes("STATUS")){
    var jobj = $.parseJSON(resMsg);

      $.ajax({
          type: "POST",
          url: "/origami/bank_integration/sale_trans",
          data: {type:"response", card_sale_trans_id: card_sale_trans_id, data: jobj},
          dataType: "json",
          success: function(data) {
            if(data.status == "success"){
                resCBPay(resMsg,card_sale_trans_id,cmd_type,payment_type,bnk_bill_amount,sale_id,receipt_no,com_port,cashier_type);
            }
          }
        });
  }else{
  	if(payment_type!="master"){
		payment_type = payment_type.toUpperCase();
	}else{
		payment_type = "Master";
	}
	
  	$("#loading_wrapper").hide();
    swal({
		  title: 'Oops',
		  text: resMsg.toString(),
		  type: 'error',
		  html: true,
		  closeOnConfirm: false,
		  closeOnCancel: false,
		  allowOutsideClick: false
		}, function () {
		window.location.href = '/origami/sale/'+ sale_id +"/"+cashier_type + "/payment/others_payment/"+payment_type;
	});
  }
}


function resCBPay(resMsg,card_sale_trans_id,cmd_type,payment_type,bnk_bill_amount,sale_id,receipt_no,com_port,cashier_type) {
	$("#loading_wrapper").hide();
    var jobj = $.parseJSON(resMsg);
    $("#reference_no").val(jobj.REFNUM);
    if(jobj.STATUS == "Approved"){
        $.ajax({type: "POST",
         	url: "/origami/payment/"+payment_type,
         	data: "amount="+ bnk_bill_amount + "&sale_id="+ sale_id + "&ref_no=" + jobj.REFNUM,
         	success:function(result){
         		if(result){
         			swal({
         				title: "Information!",
         				text: "Payment Successfully",
         				html: true,
						closeOnConfirm: false,
						closeOnCancel: false,
						allowOutsideClick: false
         			}, function () {
         				window.location.href = '/origami/sale/'+ sale_id  +"/"+cashier_type+"/payment";
         			});
         		}
         	}
         });
    }else{
    	if(payment_type!="master"){
    		payment_type = payment_type.toUpperCase();
    	}else{
    		payment_type = "Master";
    	}
        swal({
		  title: 'Oops',
		  text: "Transaction is " + (jobj.STATUS).toLowerCase(),
		  type: 'error',
		  html: true,
		  closeOnConfirm: false,
		  closeOnCancel: false,
		  allowOutsideClick: false
		}, function () {
				window.location.href = '/origami/sale/'+ sale_id +"/"+cashier_type + "/payment/others_payment/"+payment_type;
			});
    }
}
//end CB ECR integration

function setHeaderBreadCrumb(params){
	$("#others_payment").html(params);
}

//show hide nav bar for webview
function showHideNavbar(webview,page){
	if(webview){
		$("nav.navbar").addClass("hidden");
		$("section").addClass("section-margin");
		$(".page-loader-wrapper").addClass("hidden");
		if(page!=undefined){
			$("#back").hide();
		}
	}else{
		$("nav.navbar").removeClass("hidden");
		$("section").removeClass("section-margin");
		$(".page-loader-wrapper").removeClass("hidden");
		if(page!=undefined){
			$("#back").show();
		}
	}
}

function createAccessCode(code) {
	localStorage.setItem("access_code",code);
}