  <!DOCTYPE html>
  <html>

  <head>

  <!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> -->
  <script src="<?php echo base_url(); ?>assets/js/jquery.min.js"></script>
<!--
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/jquery.form/4.2.1/jquery.form.min.js" type="text/javascript"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" /> -->


<!--
  <script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" /> -->

<!-- <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> -->


  <?php include 'include/common.php';?>

 <!--  <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.min.css">
  <script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script> -->

<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/chosen.min.css">
  <script src="<?php echo base_url(); ?>assets/js/chosen.jquery.min.js"></script>

  <link href="<?php echo base_url(); ?>assets/css/bootstrap-toggle.min.css" rel="stylesheet">
  <script src="<?php echo base_url(); ?>assets/js/bootstrap-toggle.min.js"></script>


  <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/bootstrap-datepicker.min.css" />
  <!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/css/bootstrap-datepicker.min.css" /> -->
  <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.8.0/js/bootstrap-datepicker.min.js"></script> -->
  <script src="<?php echo base_url(); ?>assets/js/bootstrap-datepicker.min.js"></script>


<!-- Latest compiled and minified CSS -->
<!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/css/bootstrap-select.min.css"> -->
<link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/bootstrap-select.min.css">

<!-- Latest compiled and minified JavaScript -->
<!-- <script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.14/dist/js/bootstrap-select.min.js"></script> -->
<script src="<?php echo base_url(); ?>assets/js/bootstrap-select.min.js"></script>


  </head>

  <body>

      <!-- admin javascript -->
       <script type="text/javascript">

          // disable press enter

            // $(document).ready(function () {
            //     $(window).keydown(function(event){
            //         if(event.keyCode == 13) {
            //             e.preventDefault(); // Disable the " Entry " key
            //             return false;
            //         }
            //     });
            // });


          //end disable press enter

        $( document ).ready(function() {

               // alert("1");
            //reset button at the begining

               $('#btnInvoiceSubmit').attr('disabled', false);
               $('#btnUpdateInvoicePaymentSubmit').attr('disabled', false);
            //end reset button


            //added 2020-10-08
                //add original payment table
                 var selectedservicessub = document.getElementById('selected-services-sub');
                    // alert(city);
                  $(selectedservicessub).empty();

                   <?php
if ($pagemethod == "add") {
	?>
                  //add data to table
                      var total =0;
                      var html='';
                      html +='<h5 class="modal-title sales">銷售</h5>';
                      html +='<table id="packages" class="display table dataTable no-footer payment-record"> <thead><tr><th style="width:5%">套票</th><th style="width:35%">項目</th><th style="width:15%">實價($)</th><th style="width:15%">數量</th><th style="width:15%">折扣(%)</th><th style="width:15%">收費</th></tr></thead><tbody>';
                      //html+='</tbody></table>';

                      html+='<tr class="last-item-row sub_c"><td colspan="7"></td></tr>';
                    html+='</tbody></table>';

                      //total table
                      html+='<table id="packages-pay" class="" style="margin-top: 25px; width: 100%;"><tbody><!-- <tr><td style="width: 20%; text-align: right; padding-right: 10px; line-height: 35px;">優惠碼:</td><td style="width: 18%; text-align: center;" id="discountCode"><input class="form-control" type="text" style="display: inline-block; width: auto; min-height: auto; height: 35px; padding: 6px; text-align: center; background: #ddf0f4;" data-value="" /></td></tr><tr><td style="width: 82%; text-align: right; padding-right: 10px; line-height: 35px;">請輸入加入優惠碼的原因:</td><td style="width: 18%; text-align: center;" id="discountReason"><input class="form-control" type="text" style="display: inline-block; width: auto; min-height: auto; height: 35px; padding: 6px; text-align: center; background: #ddf0f4;" data-value="" /></td></tr> --><tr><td style="width: 82%; text-align: right; padding-right: 10px; line-height: 35px;">應繳款項總額:</td><td style="width: 18%; text-align: center; border-bottom: double #333;" id="totalAmountDue">'+total+'</td></tr></tbody></table>';
                      $(selectedservicessub).append(html);
                //end add original payment table


               //append payment amount
                       var paymentservicessub = document.getElementById('payment-services-sub');
                      // alert(city);
                      $(paymentservicessub).empty();

                      html='';
                      html +='<h5 class="modal-title sales">確認付款</h5>';
                      html +='<div class="form-group row"><div class="col-sm-3 text-center mas-title"><label for="s2id_autogen4">付款方式</label></div><div class="col-sm-9 mas-box initialized">   <select id="payment_type_1" class="select mas-select select2-offscreen form-control" name="payment_type_1" tabindex="-1" style="width:auto;"><option value="">--</option><option value="1" selected>現金</option><option value="2">Jarvix</option><option value="3">EPS</option><option value="4">CUP</option><option value="5">VISA</option><option value="6">MASTER</option><option value="7">use packages</option><option value="8">HSBC</option><option value="9">FPS</option><option value="10">Payme</option><option value="11">積分</option></select></div></div>';
                      html +='<div class="form-group row"><div class="col-sm-3 text-center mas-title"><label for="payment_amount_1">款項</label></div><div class="col-sm-9 mas-box"><input id="payment_amount_1" type="text" class="form-control mas-input" name="payment_amount_1" value=""></div></div>';
                       html +='<div class="form-group row"><div class="col-sm-3 text-center mas-title"><label for="s2id_autogen4">付款方式</label></div><div class="col-sm-9 mas-box initialized">   <select id="payment_type_2" class="select mas-select select2-offscreen form-control" name="payment_type_2" tabindex="-1" style="width:auto;"><option value="">--</option><option value="1">現金</option><option value="2">Jarvix</option><option value="3">EPS</option><option value="4">CUP</option><option value="5">VISA</option><option value="6">MASTER</option><option value="7">use packages</option>><option value="8">HSBC</option><option value="9">FPS</option><option value="10">Payme</option><option value="11">積分</option></select></div></div>';
                      html +='<div class="form-group row"><div class="col-sm-3 text-center mas-title"><label for="payment_amount_2">款項</label></div><div class="col-sm-9 mas-box"><input id="payment_amount_2" type="text" class="form-control mas-input" name="payment_amount_2"></div></div>';

                      html +='<div class="form-group row"><div class="col-sm-3 text-center mas-title"><label for="s2id_autogen4">付款方式</label></div><div class="col-sm-9 mas-box initialized">   <select id="payment_type_3" class="select mas-select select2-offscreen form-control" name="payment_type_3" tabindex="-1" style="width:auto;"><option value="">--</option><option value="1">現金</option><option value="2">Jarvix</option><option value="3">EPS</option><option value="4">CUP</option><option value="5">VISA</option><option value="6">MASTER</option><option value="7">use packages</option>><option value="8">HSBC</option><option value="9">FPS</option><option value="10">Payme</option><option value="11">積分</option></select></div></div>';
                      html +='<div class="form-group row"><div class="col-sm-3 text-center mas-title"><label for="payment_amount_3">款項</label></div><div class="col-sm-9 mas-box"><input id="payment_amount_3" type="text" class="form-control mas-input" name="payment_amount_3"></div></div>';

                      $(paymentservicessub).append(html);

                      //end　append payment amount
                        <?php
} //if($pagemethod=="add"){
?>
            //end added 2020-10-08


            //add control

          $("#btnPickUpSubmit").click(function(event) {

            let passedChecking=true;
            let emptyNewUser=false;
            //alert("pressed");
            //alert(document.querySelector("#display_name").value);
            // if( (document.querySelector("#display_name").value).trim() ==='' && (document.querySelector("#mobile").value).trim() ===''){
            //    emptyNewUser=true;
            // }
            //jQuery.trim(inp).length > 0
            //alert($( "#display_name" ).val());
            if( jQuery.trim($( "#display_name" ).val()).length  ==0 && jQuery.trim($( "#mobile" ).val()).length==0){
               emptyNewUser=true;
            }


            if(emptyNewUser===true && document.querySelector("#user_id").value === ''){
              alert("請選擇現有客戶 或填新客戶名稱及客戶電話.");
              passedChecking=false;
             // alert( document.querySelector("#user_id").value);
            }

            if(passedChecking==true){

              //load service content
               user_idajax(document.querySelector("#user_id").value);
               service_ajax();
              //end load service content


             $('#pickupModalCenter').modal({
                                      show: true,
                                  });

            }//if(passedChecking==true){



            // var forcusitem="";
            // var passCheck=true;


            // if($('#shortcode').val().length !== 0){
            //   $("#shortcode").addClass(" is-valid ");
            //   $("#shortcode").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#shortcode";
            //   }
            //   passCheck=false;
            //   $("#shortcode").addClass(" is-invalid ");
            //  $("#shortcode").removeClass(" is-valid ");
            // }


          //   if($('#inputadminname').val().length !== 0){
          //     $("#inputadminname").addClass(" is-valid ");
          //     $("#inputadminname").removeClass(" is-invalid ");
          //   }
          //   else{
          //     if(forcusitem.length===0){
          //        forcusitem="#inputadminname";
          //     }
          //     passCheck=false;
          //     $("#inputadminname").addClass(" is-invalid ");
          //    $("#inputadminname").removeClass(" is-valid ");
          //   }

            // if($('#password').val().length !== 0){
            //   $("#password").addClass(" is-valid ");
            //   $("#password").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#password";
            //   }
            //   passCheck=false;
            //   $("#password").addClass(" is-invalid ");
            //  $("#password").removeClass(" is-valid ");
            // }

            // if($('#confirm_password').val().length !== 0){
            //   $("#confirm_password").addClass(" is-valid ");
            //   $("#confirm_password").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#confirm_password";
            //   }
            //   passCheck=false;
            //   $("#confirm_password").addClass(" is-invalid ");
            //  $("#confirm_password").removeClass(" is-valid ");
            // }

            // if($('#confirm_password').val().length !== 0 || ($('#confirm_password').val()!==$('#password').val())){
            //   $("#confirm_password").addClass(" is-valid ");
            //   $("#confirm_password").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#confirm_password";
            //   }
            //   passCheck=false;
            //   $("#confirm_password").addClass(" is-invalid ");
            //  $("#confirm_password").removeClass(" is-valid ");
            // }



            //  if($('#chi_name').val().length !== 0){
            //   $("#chi_name").addClass(" is-valid ");
            //   $("#chi_name").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#chi_name";
            //   }
            //   passCheck=false;
            //   $("#chi_name").addClass(" is-invalid ");
            //  $("#chi_name").removeClass(" is-valid ");
            // }

            // if($('#eng_firstname').val().length !== 0){
            //   $("#eng_firstname").addClass(" is-valid ");
            //   $("#eng_firstname").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#eng_firstname";
            //   }
            //   passCheck=false;
            //   $("#eng_firstname").addClass(" is-invalid ");
            //  $("#eng_firstname").removeClass(" is-valid ");
            // }

            //  if($('#eng_lastname').val().length !== 0){
            //   $("#eng_lastname").addClass(" is-valid ");
            //   $("#eng_lastname").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#eng_lastname";
            //   }
            //   passCheck=false;
            //   $("#eng_lastname").addClass(" is-invalid ");
            //  $("#eng_lastname").removeClass(" is-valid ");
            // }


            //  if($('#role_name').val().length !== 0){
            //   $("#role_name").addClass(" is-valid ");
            //   $("#role_name").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#role_name";
            //   }
            //   passCheck=false;
            //   $("#role_name").addClass(" is-invalid ");
            //  $("#role_name").removeClass(" is-valid ");
            // }

            //  if($('#tenant_no').val().length !== 0){
            //   $("#tenant_no").addClass(" is-valid ");
            //   $("#tenant_no").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#tenant_no";
            //   }
            //   passCheck=false;
            //   $("#tenant_no").addClass(" is-invalid ");
            //  $("#tenant_no").removeClass(" is-valid ");
            // }

            //  if($('#income_type').val().length !== 0){
            //   $("#income_type").addClass(" is-valid ");
            //   $("#income_type").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#income_type";
            //   }
            //   passCheck=false;
            //   $("#income_type").addClass(" is-invalid ");
            //  $("#income_type").removeClass(" is-valid ");
            // }


            //  if($('#commission').val().length !== 0){
            //   $("#commission").addClass(" is-valid ");
            //   $("#commission").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#commission";
            //   }
            //   passCheck=false;
            //   $("#commission").addClass(" is-invalid ");
            //  $("#commission").removeClass(" is-valid ");
            // }

            // if($('#gender').val().length !== 0){
            //   $("#gender").addClass(" is-valid ");
            //   $("#gender").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#gender";
            //   }
            //   passCheck=false;
            //   $("#gender").addClass(" is-invalid ");
            //  $("#gender").removeClass(" is-valid ");
            // }




          //   alert("1");
            // if(passCheck==true){


            // var GlobalVariables ={
            //         'csrfToken': '123',
            //         'baseUrl':'<?php echo base_url(); ?>',
            //         // 'destUrl':'<?php echo base_url(); ?>/api/v1/frontend/add',
            //         'AJAX_SUCCESS' :'SUCCESS',
            //         'AJAX_FAILURE' :'FAILURE'
            //   };

            //   event.preventDefault();
            //   var postUrl= GlobalVariables.baseUrl +'/api/v1/brshopend/add';
            //   // var postData ={
            //   //       'csrfToken' :'',
            //   //       'custname' : $('#name').val(),
            //   //       'tel' : $('#tel').val(),
            //   //       'email' : $('#email').val(),
            //   //       'wechat' : $('#wechat').val(),
            //   //       'birthday' : $('#birthday').val(),
            //   //       // 'selectedBox' :$('.css-checkbox:checked').val()
            //   //       'selectedBox' :selectBox1

            //   // }
            //   var postData ={
            //       'shortcode':$('#shortcode').val(),
            //       'code':$('#code').val(),
            //       'name':$('#name').val()
            //       // 'inputadminname':$('#inputadminname').val(),

            //   }
            //   $.ajax({
            //         method: "POST",
            //         url: postUrl,
            //         dataType: "json",
            //        data: postData,
            //        success : function(data){

            //       // alert("posted");
            //       // // alert('formsubmit');
            //       // alert(data);

            //       // alert(data['recordstatus']);
            //       // alert(data['msg']);
            //       if(data['recordstatus']=="SUCCESS"){
            //           $('#feedback').remove();
            //           $( '#newmsg' ).append('<p class="text-primary" id="feedback">'+data['msg']+'</p>');
            //           setTimeout(function() {
            //               location.reload();
            //           }, 3000);
            //           // location.reload();

            //       }
            //         if(data['recordstatus']=="FAILURE"){
            //           $('#feedback').remove();
            //           $( '#newmsg' ).append('<p class="text-danger"  id="feedback">'+data['msg']+'</p>');
            //       //   $( '#modal-bodymsg' ).empty();
            //       //   $( '#modal-bodymsg' ).append( '<h5 class="text-center" style="color: #a03d49;">客戶不能增加。</h5> <h5 class="text-center" style="color: #a03d49;">請稍後再嘗試。</h5>' );
            //       //   $('#finishModal').modal('show');
            //       // }
            //         // if (data.AJAX_SUCCESS==GlobalVariables.AJAX_SUCCESS){
            //         //     window.location.href=GlobalVariables.destUrl;
            //         // } else {
            //         //     $('.alert').text("登入錯誤");
            //         //    $('.alert').removeClass('hidden');
            //         }
            //     }
            //   });

            //   }//if(passCheck==true){
          });//$("#btnPickUpSubmit").click(function(event) {

          //close modal
          $('#btnCloseSubmit').click(function(event) {
               $('#pickupModalCenter').modal('hide');
          });//$('#btnCloseSubmit').click(function(event) {
          //end close modal


          $("#btnSubmit").click(function(event) {
            var forcusitem="";
            var passCheck=true;


            if($('#shortcode').val().length !== 0){
              $("#shortcode").addClass(" is-valid ");
              $("#shortcode").removeClass(" is-invalid ");
            }
            else{
              if(forcusitem.length===0){
                 forcusitem="#shortcode";
              }
              passCheck=false;
              $("#shortcode").addClass(" is-invalid ");
             $("#shortcode").removeClass(" is-valid ");
            }


          //   if($('#inputadminname').val().length !== 0){
          //     $("#inputadminname").addClass(" is-valid ");
          //     $("#inputadminname").removeClass(" is-invalid ");
          //   }
          //   else{
          //     if(forcusitem.length===0){
          //        forcusitem="#inputadminname";
          //     }
          //     passCheck=false;
          //     $("#inputadminname").addClass(" is-invalid ");
          //    $("#inputadminname").removeClass(" is-valid ");
          //   }

            // if($('#password').val().length !== 0){
            //   $("#password").addClass(" is-valid ");
            //   $("#password").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#password";
            //   }
            //   passCheck=false;
            //   $("#password").addClass(" is-invalid ");
            //  $("#password").removeClass(" is-valid ");
            // }

            // if($('#confirm_password').val().length !== 0){
            //   $("#confirm_password").addClass(" is-valid ");
            //   $("#confirm_password").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#confirm_password";
            //   }
            //   passCheck=false;
            //   $("#confirm_password").addClass(" is-invalid ");
            //  $("#confirm_password").removeClass(" is-valid ");
            // }

            // if($('#confirm_password').val().length !== 0 || ($('#confirm_password').val()!==$('#password').val())){
            //   $("#confirm_password").addClass(" is-valid ");
            //   $("#confirm_password").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#confirm_password";
            //   }
            //   passCheck=false;
            //   $("#confirm_password").addClass(" is-invalid ");
            //  $("#confirm_password").removeClass(" is-valid ");
            // }



            //  if($('#chi_name').val().length !== 0){
            //   $("#chi_name").addClass(" is-valid ");
            //   $("#chi_name").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#chi_name";
            //   }
            //   passCheck=false;
            //   $("#chi_name").addClass(" is-invalid ");
            //  $("#chi_name").removeClass(" is-valid ");
            // }

            // if($('#eng_firstname').val().length !== 0){
            //   $("#eng_firstname").addClass(" is-valid ");
            //   $("#eng_firstname").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#eng_firstname";
            //   }
            //   passCheck=false;
            //   $("#eng_firstname").addClass(" is-invalid ");
            //  $("#eng_firstname").removeClass(" is-valid ");
            // }

            //  if($('#eng_lastname').val().length !== 0){
            //   $("#eng_lastname").addClass(" is-valid ");
            //   $("#eng_lastname").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#eng_lastname";
            //   }
            //   passCheck=false;
            //   $("#eng_lastname").addClass(" is-invalid ");
            //  $("#eng_lastname").removeClass(" is-valid ");
            // }


            //  if($('#role_name').val().length !== 0){
            //   $("#role_name").addClass(" is-valid ");
            //   $("#role_name").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#role_name";
            //   }
            //   passCheck=false;
            //   $("#role_name").addClass(" is-invalid ");
            //  $("#role_name").removeClass(" is-valid ");
            // }

            //  if($('#tenant_no').val().length !== 0){
            //   $("#tenant_no").addClass(" is-valid ");
            //   $("#tenant_no").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#tenant_no";
            //   }
            //   passCheck=false;
            //   $("#tenant_no").addClass(" is-invalid ");
            //  $("#tenant_no").removeClass(" is-valid ");
            // }

            //  if($('#income_type').val().length !== 0){
            //   $("#income_type").addClass(" is-valid ");
            //   $("#income_type").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#income_type";
            //   }
            //   passCheck=false;
            //   $("#income_type").addClass(" is-invalid ");
            //  $("#income_type").removeClass(" is-valid ");
            // }


            //  if($('#commission').val().length !== 0){
            //   $("#commission").addClass(" is-valid ");
            //   $("#commission").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#commission";
            //   }
            //   passCheck=false;
            //   $("#commission").addClass(" is-invalid ");
            //  $("#commission").removeClass(" is-valid ");
            // }

            // if($('#gender').val().length !== 0){
            //   $("#gender").addClass(" is-valid ");
            //   $("#gender").removeClass(" is-invalid ");
            // }
            // else{
            //   if(forcusitem.length===0){
            //      forcusitem="#gender";
            //   }
            //   passCheck=false;
            //   $("#gender").addClass(" is-invalid ");
            //  $("#gender").removeClass(" is-valid ");
            // }




          //   alert("1");
            if(passCheck==true){


            var GlobalVariables ={
                    'csrfToken': '123',
                    'baseUrl':'<?php echo base_url(); ?>',
                    // 'destUrl':'<?php echo base_url(); ?>/api/v1/frontend/add',
                    'AJAX_SUCCESS' :'SUCCESS',
                    'AJAX_FAILURE' :'FAILURE'
              };

              event.preventDefault();
              var postUrl= GlobalVariables.baseUrl +'/api/v1/brshopend/add';
              // var postData ={
              //       'csrfToken' :'',
              //       'custname' : $('#name').val(),
              //       'tel' : $('#tel').val(),
              //       'email' : $('#email').val(),
              //       'wechat' : $('#wechat').val(),
              //       'birthday' : $('#birthday').val(),
              //       // 'selectedBox' :$('.css-checkbox:checked').val()
              //       'selectedBox' :selectBox1

              // }
              var postData ={
                  'shortcode':$('#shortcode').val(),
                  'code':$('#code').val(),
                  'name':$('#name').val()
                  // 'inputadminname':$('#inputadminname').val(),

              }
              $.ajax({
                    method: "POST",
                    url: postUrl,
                    dataType: "json",
                    data: postData,
                   success : function(data){

                  // alert("posted");
                  // // alert('formsubmit');
                  // alert(data);

                  // alert(data['recordstatus']);
                  // alert(data['msg']);
                  if(data['recordstatus'] =="SUCCESS"){
                      $('#feedback').remove();
                      $( '#newmsg' ).append('<p class ="text-primary" id="feedback">'+data['msg']+'</p>');
                      setTimeout(function() {
                          location.reload();
                      }, 3000);
                      // location.reload();

                  }
                    if(data['recordstatus']=="FAILURE"){
                      $('#feedback').remove();
                      $( '#newmsg' ).append('<p class="text-danger"  id="feedback">'+data['msg']+'</p>');
                  //   $( '#modal-bodymsg' ).empty();
                  //   $( '#modal-bodymsg' ).append( '<h5 class="text-center" style="color: #a03d49;">客戶不能增加。</h5> <h5 class="text-center" style="color: #a03d49;">請稍後再嘗試。</h5>' );
                  //   $('#finishModal').modal('show');
                  // }
                    // if (data.AJAX_SUCCESS==GlobalVariables.AJAX_SUCCESS){
                    //     window.location.href=GlobalVariables.destUrl;
                    // } else {
                    //     $('.alert').text("登入錯誤");
                    //    $('.alert').removeClass('hidden');
                    }
                }
              });

              }//if(passCheck==true){
          });//$("#btnSubmit").click(function(event) {


          //Pick Up Submit Button
          $("#btnPickUpSubmitButton").click(function(event){
              var useproductboxvalue =  [];
              $("input:checkbox[id=useproduct]:checked").each(function(){
                // alert($(this).val());
                 useproductboxvalue.push( $(this).val() );
                 // alert($(this).val());
              });




              //ajax get item info and put in the html data
              var GlobalVariables ={
                    'csrfToken': '123',
                    'baseUrl':'<?php echo base_url(); ?>',
                    // 'destUrl':'<?php echo base_url(); ?>/api/v1/frontend/add',
                    'AJAX_SUCCESS' :'SUCCESS',
                    'AJAX_FAILURE' :'FAILURE'
              };

              event.preventDefault();
              var postUrl= '<?php echo base_url(); ?>' +'api/v1/brservicesend/getServiceGroup';
              // var postData ={
              //       'csrfToken' :'',
              //       'custname' : $('#name').val(),
              //       'tel' : $('#tel').val(),
              //       'email' : $('#email').val(),
              //       'wechat' : $('#wechat').val(),
              //       'birthday' : $('#birthday').val(),
              //       // 'selectedBox' :$('.css-checkbox:checked').val()
              //       'selectedBox' :selectBox1

              // }
              // $checkedpurchase=0;
              // if($('#need_purchase_service').is(':checked')){
              //     $checkedpurchase=1;
              // }
              // else
              // {
              //   $checkedpurchase=0;
              // }



              var postData ={
                  'groupIdArray':useproductboxvalue
              }





              // alert($('#level2').val());
              $.ajax({
                    method: "POST",
                    url: postUrl,
                   dataType: "json",
                   data: postData,

                   success : function(data){

                  // alert("posted");
                  // // alert('formsubmit');
                  // alert(data);

                  // alert(data['recordstatus']);
                  // alert(data['msg']);


                  //close modal

                   $('#pickupModalCenter').modal("hide");

                  //end close modal
                  var selectedservicessub = document.getElementById('selected-services-sub');
                    // alert(city);
                  $(selectedservicessub).empty();


                  //add data to table
                  var obj =data;
                  //end
                  if(obj.length==0){
                      var html="沒有任何記錄";
                      $(selectedservicessub).append(html);
                    }
                    if(obj.length!=0){
                      var total =0;
                      var html='';
                      html +='<h5 class="modal-title sales">銷售</h5>';
                      html +='<table id="packages" class="display table dataTable no-footer payment-record"> <thead><tr><th style="width:5%">套票</th><th style="width:35%">項目</th><th style="width:15%">實價($)</th><th style="width:15%">數量</th><th style="width:15%">折扣(%)</th><th style="width:15%">收費</th></tr></thead><tbody>';
                      for (var i = 0; i < obj.length; i++) {
                        // alert(i);
                        // $(prepaidservicessub).append('<p style="color:blue;">'+ obj[i].service_id+'</p>');
                        html+='<tr data-id="'+ obj[i].id+'" ';
                        html+='data-available_qty="'+ obj[i].available_qty+'">';

                        // new add ticket checkbox
                        html+='<td>';
                      // html+='<input class="selectproduct3" type="checkbox" name="useservice" id="useservice" value="'+obj[i].id+'" data-price="'+parseInt(obj[i].time)+'" onclick="add()" >';
                      html+='<input class="selectproduct3" type="checkbox" name="addticketid" id="addticketid" value="'+obj[i].id+'" data-price="'+obj[i].available_qty+'"  >';
                       html+='</td>';
                        // end new add ticket checkbox


                        // $(prepaidservicessub).append('<td>');
                        // html+='<td>';
                        // html+='<input class="selectproduct3" type="checkbox" name="useservice" id="useservice" value="'+obj[i].id+'" data-price="'+parseInt(obj[i].time)+'" >';
                        // html+='<input class="selectproduct3" type="checkbox" name="useservice" id="useservice" value="'+obj[i].id+'" data-price="'+parseInt(obj[i].time)+'" onclick="add()" >';
                        // html+='</td>';
                        // html+='<td>';
                        // html+=obj[i].code;
                        // html+='</td>';

                        // if(obj[i].category_id==1){
                        //   html+='<td>';
                        //   html+='FT-試做療程';
                        //   html+='</td>';
                        // }
                        //  if(obj[i].category_id==2){
                        //   html+='<td>';
                        //   html+='T-療程';
                        //   html+='</td>';
                        // }
                        html+='<td>';
                        // html+='<input id="btnSearch" type="text" value="Search" class="search_btn" onchange="Call()" />';
                        html+='<input type="hidden" class="form-control text-center ui-autocomplete-input ui-autocomplete-loading" name="product_id[]" id="product_id-'+i+'" autocomplete="off" value="'+obj[i].id+'" >';
                        html+='<input type="text" class="form-control text-center ui-autocomplete-input ui-autocomplete-loading" name="product_name[]" placeholder="Enter Product name or Code" id="productname-'+i+'" autocomplete="off" value="'+obj[i].name+'" readonly>';
                        // html+=obj[i].name;
                        html+='</td>';
                        // html+='<td>';
                        // html+=obj[i].work;
                        // html+='</td>';
                        html+='<td>';
                         html+='<input type="text" class="form-control req prc" name="product_price[]" id="price-'+i+'"  onkeyup="rowTotal('+i+'), billUpyog()" autocomplete="off" value="'+obj[i].price+'" >';
                         // html+='<input type="text" class="form-control req prc" name="product_price[]" id="price-'+i+'" onkeypress="return isNumber(event)" onkeyup="rowTotal("'+i+'"), billUpyog()" autocomplete="off" value="'+obj[i].price+'" >';
                        // html+=parseInt(obj[i].price);
                        html+='</td>';
                        html+='<td>';
                        html+='<input type="text" class="form-control req amnt" name="product_qty[]" id="amount-'+i+'" onkeypress="return isNumber(event)" onkeyup="rowTotal('+i+'), billUpyog()" autocomplete="off" value="1">';
                        // html+=1;
                        html+='</td>';
                        html+='<td>';
                        html+='<input type="text" class="form-control discount" name="product_discount[]" onkeypress="return isNumber(event)" id="discount-'+i+'" onkeyup="rowTotal('+i+'), billUpyog()" autocomplete="off" value="0.00">';
                        // html+=0.00;
                        html+='</td>';

                        html+='<td>';
                        html+='<input type="text" class="form-control  ttInput" name="product_subtotal[]" id="total-'+i+'" value="'+parseInt(obj[i].price)+'" onkeyup="rowPressTotal('+i+'), billUpyog()" autocomplete="off" >';
                        // html+='<td><span id="display-amount-'+i+'" >';
                        // html+=parseInt(obj[i].price);
                        // html+='</span>';
                        html+='<input type="hidden" name="disca[]" id="disca-'+i+'" value="0.00">';
                        // html+='<input type="hidden" class="ttInput" name="product_subtotal[]" id="total-'+i+'" value="'+parseInt(obj[i].price)+'">';
                        html+='</td>';
                        // html+='<td>';
                        // if(obj[i].no_credit_rebate==1){

                        //   html+='<i class="fas fa-check-circle"></i>';

                        // }
                        // html+='</td>';
                        html+='</tr>';
                        total+=obj[i].price*1;
                      // $(level2box).append('<option  value=' + obj[i].id + '>' + obj[i].chi_name + '</option>');
                      }

                      html+='</tbody></table>';

                      //total table
                      html+='<table id="packages-pay" class="" style="margin-top: 25px; width: 100%;"><tbody><!-- <tr><td style="width: 20%; text-align: right; padding-right: 10px; line-height: 35px;">優惠碼:</td><td style="width: 18%; text-align: center;" id="discountCode"><input class="form-control" type="text" style="display: inline-block; width: auto; min-height: auto; height: 35px; padding: 6px; text-align: center; background: #ddf0f4;" data-value="" /></td></tr><tr><td style="width: 82%; text-align: right; padding-right: 10px; line-height: 35px;">請輸入加入優惠碼的原因:</td><td style="width: 18%; text-align: center;" id="discountReason"><input class="form-control" type="text" style="display: inline-block; width: auto; min-height: auto; height: 35px; padding: 6px; text-align: center; background: #ddf0f4;" data-value="" /></td></tr> --><tr><td style="width: 82%; text-align: right; padding-right: 10px; line-height: 35px;">應繳款項總額:</td><td style="width: 18%; text-align: center; border-bottom: double #333;" id="totalAmountDue">'+total+'</td></tr></tbody></table>';
                      //end total table


                      $(selectedservicessub).append(html);


                      //append payment amount
                       var paymentservicessub = document.getElementById('payment-services-sub');
                      // alert(city);
                      $(paymentservicessub).empty();

                      html='';
                      html +='<h5 class="modal-title sales">確認付款</h5>';
                      html +='<div class="form-group row"><div class="col-sm-3 text-center mas-title"><label for="s2id_autogen4">付款方式</label></div><div class="col-sm-9 mas-box initialized">   <select id="payment_type_1" class="select mas-select select2-offscreen form-control" name="payment_type_1" tabindex="-1" style="width:auto;"><option value="">--</option><option value="1" selected>現金</option><option value="2">Jarvix</option><option value="3">EPS</option><option value="4">CUP</option><option value="5">VISA</option><option value="6">MASTER</option><option value="7">use packages</option><option value="8">HSBC</option><option value="9">FPS</option></select></div></div>';
                      html +='<div class="form-group row"><div class="col-sm-3 text-center mas-title"><label for="payment_amount_1">款項</label></div><div class="col-sm-9 mas-box"><input id="payment_amount_1" type="text" class="form-control mas-input" name="payment_amount_1" value="'+total+'"></div></div>';
                       html +='<div class="form-group row"><div class="col-sm-3 text-center mas-title"><label for="s2id_autogen4">付款方式</label></div><div class="col-sm-9 mas-box initialized">   <select id="payment_type_2" class="select mas-select select2-offscreen form-control" name="payment_type_2" tabindex="-1" style="width:auto;"><option value="">--</option><option value="1">現金</option><option value="2">Jarvix</option><option value="3">EPS</option><option value="4">CUP</option><option value="5">VISA</option><option value="6">MASTER</option><option value="7">use packages</option>><option value="8">HSBC</option><option value="9">FPS</option></select></div></div>';
                      html +='<div class="form-group row"><div class="col-sm-3 text-center mas-title"><label for="payment_amount_2">款項</label></div><div class="col-sm-9 mas-box"><input id="payment_amount_2" type="text" class="form-control mas-input" name="payment_amount_2"></div></div>';

                      $(paymentservicessub).append(html);
                      //end　append payment amount


                      // alert(data);
                      // level3boxajax(fileid+'-'+items+'-Level3', obj[0].id);
                      // alert('level3'+data);

                    }//if(obj.length!=0){

                  // if(data['recordstatus']=="SUCCESS"){
                  //     $('#feedback').remove();
                  //     $( '#newmsg' ).append('<p class="text-primary" id="feedback">'+data['msg']+'</p>');
                  //     setTimeout(function() {
                  //         location.reload();
                  //     }, 3000);
                  //     // location.reload();

                  // }
                  //   if(data['recordstatus']=="FAILURE"){
                  //     $('#feedback').remove();
                  //     $( '#newmsg' ).append('<p class="text-danger"  id="feedback">'+data['msg']+'</p>');
                  // //   $( '#modal-bodymsg' ).empty();
                  // //   $( '#modal-bodymsg' ).append( '<h5 class="text-center" style="color: #a03d49;">客戶不能增加。</h5> <h5 class="text-center" style="color: #a03d49;">請稍後再嘗試。</h5>' );
                  // //   $('#finishModal').modal('show');
                  // // }
                  //   // if (data.AJAX_SUCCESS==GlobalVariables.AJAX_SUCCESS){
                  //   //     window.location.href=GlobalVariables.destUrl;
                  //   // } else {
                  //   //     $('.alert').text("登入錯誤");
                  //   //    $('.alert').removeClass('hidden');
                  //   }
                }
              });

              //end ajax get item info and put in the html data

          });


          //end Pick Up Submit


          //Pick Up Submit 2  added function to only add rows
          var currentIndex=0;
          $("#btnPickUpSubmitButton2").click(function(event){
              var useproductboxvalue =  [];
              $("input:checkbox[id=useproduct]:checked").each(function(){
                // alert($(this).val());
                 useproductboxvalue.push( $(this).val() );
                 // alert($(this).val());
              });




              //ajax get item info and put in the html data
              var GlobalVariables ={
                    'csrfToken': '123',
                    'baseUrl':'<?php echo base_url(); ?>',
                    // 'destUrl':'<?php echo base_url(); ?>/api/v1/frontend/add',
                    'AJAX_SUCCESS' :'SUCCESS',
                    'AJAX_FAILURE' :'FAILURE'
              };

              event.preventDefault();
              var postUrl= '<?php echo base_url(); ?>' +'api/v1/brservicesend/getServiceGroup';
              // var postData ={
              //       'csrfToken' :'',
              //       'custname' : $('#name').val(),
              //       'tel' : $('#tel').val(),
              //       'email' : $('#email').val(),
              //       'wechat' : $('#wechat').val(),
              //       'birthday' : $('#birthday').val(),
              //       // 'selectedBox' :$('.css-checkbox:checked').val()
              //       'selectedBox' :selectBox1

              // }
              // $checkedpurchase=0;
              // if($('#need_purchase_service').is(':checked')){
              //     $checkedpurchase=1;
              // }
              // else
              // {
              //   $checkedpurchase=0;
              // }



              var postData ={
                  'groupIdArray':useproductboxvalue
              }





              // alert($('#level2').val());
              $.ajax({
                    method: "POST",
                    url: postUrl,
                   dataType: "json",
                   data: postData,

                   success : function(data){

                    //added core
                    $('#pickupModalCenter').modal("hide");
                    var obj =data;
                       if(obj.length==0){
                      //var html="沒有任何記錄";
                      //$(selectedservicessub).append(html);
                    }
                    if(obj.length!=0){
                      var total =0;
                      var html='';
                      var inputi=0;
                      for (var i = 0; i < obj.length; i++) {
                        inputi=currentIndex+i;
                        // alert(i);
                        // $(prepaidservicessub).append('<p style="color:blue;">'+ obj[i].service_id+'</p>');
                        html+='<tr data-id="'+ obj[i].id+'" ';
                        html+='data-available_qty="'+ obj[i].available_qty+'">';

                        // new add ticket checkbox
                        html+='<td>';
                      // html+='<input class="selectproduct3" type="checkbox" name="useservice" id="useservice" value="'+obj[i].id+'" data-price="'+parseInt(obj[i].time)+'" onclick="add()" >';
                      html+='<input class="selectproduct3" type="checkbox" name="addticketid" id="addticketid" value="'+obj[i].id+'" data-price="'+obj[i].available_qty+'"  >';
                       html+='</td>';
                        // end new add ticket checkbox


                        // $(prepaidservicessub).append('<td>');
                        // html+='<td>';
                        // html+='<input class="selectproduct3" type="checkbox" name="useservice" id="useservice" value="'+obj[i].id+'" data-price="'+parseInt(obj[i].time)+'" >';
                        // html+='<input class="selectproduct3" type="checkbox" name="useservice" id="useservice" value="'+obj[i].id+'" data-price="'+parseInt(obj[i].time)+'" onclick="add()" >';
                        // html+='</td>';
                        // html+='<td>';
                        // html+=obj[i].code;
                        // html+='</td>';

                        // if(obj[i].category_id==1){
                        //   html+='<td>';
                        //   html+='FT-試做療程';
                        //   html+='</td>';
                        // }
                        //  if(obj[i].category_id==2){
                        //   html+='<td>';
                        //   html+='T-療程';
                        //   html+='</td>';
                        // }
                        html+='<td>';
                        // html+='<input id="btnSearch" type="text" value="Search" class="search_btn" onchange="Call()" />';
                        html+='<input type="hidden" class="form-control text-center ui-autocomplete-input ui-autocomplete-loading" name="product_id[]" id="product_id-'+inputi+'" autocomplete="off" value="'+obj[i].id+'" >';
                        html+='<input type="text" class="form-control text-center ui-autocomplete-input ui-autocomplete-loading" name="product_name[]" placeholder="Enter Product name or Code" id="productname-'+inputi+'" autocomplete="off" value="'+obj[i].name+'" readonly>';
                        // html+=obj[i].name;
                        html+='</td>';
                        // html+='<td>';
                        // html+=obj[i].work;
                        // html+='</td>';
                        html+='<td>';
                         html+='<input type="text" class="form-control req prc" name="product_price[]" id="price-'+inputi+'"  onkeyup="rowTotal('+inputi+'), billUpyog()" autocomplete="off" value="'+obj[i].price+'" >';
                         // html+='<input type="text" class="form-control req prc" name="product_price[]" id="price-'+i+'" onkeypress="return isNumber(event)" onkeyup="rowTotal("'+i+'"), billUpyog()" autocomplete="off" value="'+obj[i].price+'" >';
                        // html+=parseInt(obj[i].price);
                        html+='</td>';
                        html+='<td>';
                        html+='<input type="text" class="form-control req amnt" name="product_qty[]" id="amount-'+inputi+'" onkeypress="return isNumber(event)" onkeyup="rowTotal('+inputi+'), billUpyog()" autocomplete="off" value="1">';
                        // html+=1;
                        html+='</td>';
                        html+='<td>';
                        html+='<input type="text" class="form-control discount" name="product_discount[]" onkeypress="return isNumber(event)" id="discount-'+inputi+'" onkeyup="rowTotal('+inputi+'), billUpyog()" autocomplete="off" value="0.00">';
                        // html+=0.00;
                        html+='</td>';

                        html+='<td>';
                        // html+='<input type="text" class="form-control  ttInput" name="product_subtotal[]" id="total-'+inputi+'" value="'+parseInt(obj[i].price)+'" onkeyup="rowPressTotal('+inputi+'), billUpyog()" autocomplete="off" size=30 >';
                        // // html+='<td><span id="display-amount-'+i+'" >';
                        // // html+=parseInt(obj[i].price);
                        // // html+='</span>';
                        // html+='<input type="hidden" name="disca[]" id="disca-'+i+'" value="0.00">';
                        // // html+='<input type="hidden" class="ttInput" name="product_subtotal[]" id="total-'+i+'" value="'+parseInt(obj[i].price)+'">';

                        //  //add remove button
                        // html+='<input type="button" value="X" onclick="DeleteRowFunction(this);">';
                        // //end add remove button


                          html+='<span class="input-group mb-3">';
                          html+='<input type="text" class="form-control  ttInput" name="product_subtotal[]" id="total-'+inputi+'" value="'+parseInt(obj[i].price)+'" onkeyup="rowPressTotal('+inputi+'), billUpyog()" autocomplete="off" size=30 >';
                           html+='<input type="hidden" name="disca[]" id="disca-'+i+'" value="0.00">';
                          html+='<span class="input-group-append">';
                           html+='<input type="button" class="btn  btn-danger" value="X" onclick="DeleteRowFunction(this);" data-toggle="tooltip" data-placement="right" title="取消">';
                           html+='</span>';
                           html+='</span>';



                        html+='</td>';
                        // html+='<td>';
                        // if(obj[i].no_credit_rebate==1){

                        //   html+='<i class="fas fa-check-circle"></i>';

                        // }
                        // html+='</td>';



                        html+='</tr>';
                        //remark field
                        html+='<tr>';
                        html+='<td colspan="6">';
                        html+='<input type="text" class="form-control  ttInput" name="product_remark[]" id="productremark-'+inputi+'" value="'+'"  autocomplete="off" size="50" style="width:80%;" placeholder="備註" >';
                        html+='</td>';
                        html+='</tr>';

                        //end remark field

                        total+=obj[i].price*1;
                      // $(level2box).append('<option  value=' + obj[i].id + '>' + obj[i].chi_name + '</option>');
                      }
                      currentIndex=currentIndex+i;
                    //end added core

                    //alert(html);
                    $('tr.last-item-row').before(html);

                    }
                    //after add all item

                    //recalculate total price
                    billUpyog();

                    //end recalculate total price

                  }
                });

            });

          //end Pick Up Submit 2 added function to only add rows


          //$( '#saman-row' ).on( 'click', '.removeProd', function () {
          $("#removeProd").click(function(event) {
            //alert("clicked");
            $(this).closest('tr').remove();
          });//$(".removeProd").click(function(event) {


          //added function
          function isValidDate(dateString) {
            var regEx = /^\d{4}-\d{2}-\d{2}$/;
            if(!dateString.match(regEx)) return false;  // Invalid format
            var d = new Date(dateString);
            var dNum = d.getTime();
            if(!dNum && dNum !== 0) return false; // NaN value, Invalid date
            return d.toISOString().slice(0,10) === dateString;
          }


          //end added function



           $("#btnInvoiceSubmit").click(function(event) {

              //


              //added 2020-11-13
              if((document.querySelector("#invoicedate").value).trim() === ''){
                alert("請選擇發票日期.");
               passedChecking=false;
             // alert( document.querySelector("#user_id").value);
              }
              if(isValidDate((document.querySelector("#invoicedate").value).trim())===false){
                alert("請輸入正確發票日期.");
                passedChecking=false;
              }
              //end added 2020-11-13

              // alert("Invocie Print");
              //get input field
              let passedChecking=true;
              let emptyNewUser=false;
              // if( (document.querySelector("#display_name").value).trim() ==='' && (document.querySelector("#mobile").value).trim() ===''){
              //   emptyNewUser=true;
              // }

              if( (document.querySelector("#display_name").value).trim() ==='' && (document.querySelector("#mobile").value).trim() ===''){
                emptyNewUser=true;
              }


              if(emptyNewUser===true && document.querySelector("#user_id").value === ''){
                alert("請選擇現有客戶 或填新客戶名稱及客戶電話.");
               passedChecking=false;
             // alert( document.querySelector("#user_id").value);
              }
              if( (document.querySelector("#pic_1").value).trim() !=='' && (document.querySelector("#pic_1").value).trim() ===(document.querySelector("#pic_2").value).trim()){
                 alert("請選擇不同的美容師及美容師2.");
               passedChecking=false;
              }


              let userId= (document.querySelector("#user_id").value).trim();
              let display_name= (document.querySelector("#display_name").value).trim();
              let mobile= (document.querySelector("#mobile").value).trim();
              let pic_1= (document.querySelector("#pic_1").value).trim();
              let pic_2= (document.querySelector("#pic_2").value).trim(); //added
              let consultant_1= (document.querySelector("#consultant_1").value).trim();


              // alert(userId);

              var product_add_ticker = [];
              var product_id_array =  [];
              var product_price_array =  [];
              var product_qty_array = [];
              var product_discount_array = [];
              var product_remark_array = [];


            $('input:checkbox[name^="addticketid"]').each(function(){
              // alert($(this).val());

              if ($(this).is(":checked")===true) {
               product_add_ticker.push(1);
              }
              if ($(this).is(":checked") ===false) {
               product_add_ticker.push(0);
              }
            });


              $('input[name^="product_id"]').each(function() {
                  // alert($(this).val());
                  product_id_array.push( $(this).val() );
              });

              $('input[name^="product_price"]').each(function() {
                  // alert($(this).val());
                  product_price_array.push( $(this).val() );
              });

              $('input[name^="product_qty"]').each(function() {
                  // alert($(this).val());
                  product_qty_array.push( $(this).val() );
              });

              $('input[name^="product_remark"]').each(function() {
                  // alert($(this).val());
                  product_remark_array.push( $(this).val() );
              });

              var passDiscountCheck=true;
              var askFor20Precent=false;
              var askFor30Precent=false;
              var askFor10Precent=false;

               $('input[name^="product_discount"]').each(function() {
                  // alert($(this).val());
                  product_discount_array.push( $(this).val() );
                  //for checking dicount value
                  // if($(this).val()<=30 && $(this).val()>=25){ //25~30% OFF

                  //   askFor20Precent=true;
                  // }
                  // //end for checking dicount value

                   //for checking dicount value
                  if($(this).val()>=25 && $(this).val()<=30){ //25~20% OFF

                    askFor30Precent=true;
                  }
                  //end for checking dicount value

                  //for checking dicount value
                  if($(this).val()>30 && $(this).val()>0){ //LOWER 20% OFF

                    askFor10Precent=true;
                  }
                  //end for checking dicount value
              });

              // alert(askFor20Precent);

              // if(askFor20Precent===true){
              //       if (confirm("折扣大過30%")) {
              //         // txt = "You pressed OK!";

              //       } else {

              //         passDiscountCheck=false;
              //         // return ;
              //       }
              // }

              if(askFor30Precent===true){

                passDiscountCheck=false;
                $('#loginModal').modal('show');
                //clear login value
                  document.getElementById('twentyfiveusername').value="";
                  document.getElementById('twentyfiveuserpass').value="";
                //end clear login value

//                 var callback = function(result)( {
//   alert(result);
// }); // define your callback somewhere
                // CheckPwd();
                // alert(document.getElementById('username25'));


              }//if($askFor30Precent==true){

               if(askFor10Precent===true){
                     alert("折扣大過30%");
                     passDiscountCheck=false;
              }



              if(passDiscountCheck===false){
                $('#btnInvoiceSubmit').attr('disabled', false);
                return ;
              }


              if(passedChecking===true && passDiscountCheck===true){
                printInvoice();
              }

              // alert($('#level2').val());



              //end submit form data



            });//$("#btnInvoiceSubmit").click(function(event) {
          //

            $("#btnUpdateInvoicePaymentSubmit").click(function(event) {
              $('#btnUpdateInvoicePaymentSubmit').attr('disabled', true);
               let invoiceid=$(event.target).attr('data-invoiceid');

               let paymentdate=(document.querySelector("#paymentdate").value).trim();


               let payment_id_1= (document.querySelector("#payment_id_1").value).trim();

               let payment_type_1= (document.querySelector("#payment_type_1").value).trim();
               let payment_amount_1= (document.querySelector("#payment_amount_1").value).trim();

                let payment_id_2= (document.querySelector("#payment_id_2").value).trim();

               let payment_type_2= (document.querySelector("#payment_type_2").value).trim();
               let payment_amount_2= (document.querySelector("#payment_amount_2").value).trim();


               let payment_id_3= (document.querySelector("#payment_id_3").value).trim();

               let payment_type_3= (document.querySelector("#payment_type_3").value).trim();
               let payment_amount_3= (document.querySelector("#payment_amount_3").value).trim();


               var GlobalVariables ={
                    'csrfToken': '123',
                    'baseUrl':'<?php echo base_url(); ?>',
                    // 'destUrl':'<?php echo base_url(); ?>/api/v1/frontend/add',
                    'AJAX_SUCCESS' :'SUCCESS',
                    'AJAX_FAILURE' :'FAILURE'
              };

              event.preventDefault();
              var postUrl= '<?php echo base_url(); ?>' +'api/v1/brinvoiceend/updateinvoicepayment';

               var postData ={
                  'paymentdate':paymentdate,
                  'invoiceid':invoiceid,
                  // 'display_name':display_name,
                  // 'mobile':mobile,
                  // 'pic_1':pic_1,
                  // 'consultant_1':consultant_1,
                  // 'product_add_ticker_array':product_add_ticker,
                  // 'product_id_array':product_id_array,
                  // 'product_price_array':product_price_array,
                  // 'product_qty_array':product_qty_array,
                  // 'product_discount_array':product_discount_array,
                  'payment_id_1':payment_id_1,
                  'payment_type_1':payment_type_1,
                  'payment_amount_1':payment_amount_1,
                  'payment_id_2':payment_id_2,
                  'payment_type_2':payment_type_2,
                  'payment_amount_2':payment_amount_2,
                  'payment_id_3':payment_id_3,
                  'payment_type_3':payment_type_3,
                  'payment_amount_3':payment_amount_3,
                  'shopId':<?php echo $this->session->userdata('currentshop'); ?>,
              }
              //send out invoice data
                 $('#loading').show();
              // alert($('#level2').val());
              $.ajax({
                    method: "POST",
                    url: postUrl,
                   dataType: "json",
                   data: postData,
                    // $("#search").prop('disabled', true);
                   success : function(data){

                   $('#btnUpdateInvoicePaymentSubmit').attr('disabled', false);
                  // alert("posted");
                  // // alert('formsubmit');
                  // alert(data);

                  // alert(data['recordstatus']);
                  // alert(data['msg']);

                  var invoicearray=data['invoicelist'];
                  // alert(invoicearray);
                  if(data['recordstatus']=="SUCCESS"){
                      $('#feedback').remove();
                      $( '#newmsg' ).append('<p class="text-primary" id="feedback">'+data['msg']+'</p>');
                      // setTimeout(function() {
                      //     location.reload();
                      // }, 3000);
                      // location.reload();
                      var link="";
                      if(invoicearray[0] !== undefined){
                          link=link+invoicearray[0];
                      }
                      if(invoicearray[1] !== undefined){
                          link=link+'/'+invoicearray[1];
                      }
                      // window.location.href = '../brinvoicepdfadmin/createInvoice/'+invoicearray[0]+'/'+invoicearray[1];
                        // alert(link);
                    window.location.href = '../../brinvoicepdfadmin/createInvoice/'+link;
                      // $("#search").prop('disabled', false);
                  }
                    if(data['recordstatus']=="FAILURE"){
                       $('#loading').hide();
                      $('#feedback').remove();
                      $( '#newmsg' ).append('<p class="text-danger"  id="feedback">'+data['msg']+'</p>');
                  //   $( '#modal-bodymsg' ).empty();
                  //   $( '#modal-bodymsg' ).append( '<h5 class="text-center" style="color: #a03d49;">客戶不能增加。</h5> <h5 class="text-center" style="color: #a03d49;">請稍後再嘗試。</h5>' );
                  //   $('#finishModal').modal('show');
                  // }
                    // if (data.AJAX_SUCCESS==GlobalVariables.AJAX_SUCCESS){
                    //     window.location.href=GlobalVariables.destUrl;
                    // } else {
                    //     $('.alert').text("登入錯誤");
                    //    $('.alert').removeClass('hidden');
                    }
                }
              });

              //end send out invoice data
            });//$("#btnUpdateInvoicePaymentSubmit").click(function(event) {

            //edit control
            $("#btnUpdate").click(function(event) {
            var forcusitem="";
            var passCheck=true;


           if($('#shortcode').val().length !== 0){
              $("#shortcode").addClass(" is-valid ");
              $("#shortcode").removeClass(" is-invalid ");
            }
            else{
              if(forcusitem.length===0){
                 forcusitem="#shortcode";
              }
              passCheck=false;
              $("#shortcode").addClass(" is-invalid ");
             $("#shortcode").removeClass(" is-valid ");
            }


             //   alert("1");
            if(passCheck==true){


            var GlobalVariables ={
                    'csrfToken': '123',
                    'baseUrl':'<?php echo base_url(); ?>',
                    // 'destUrl':'<?php echo base_url(); ?>/api/v1/frontend/add',
                    'AJAX_SUCCESS' :'SUCCESS',
                    'AJAX_FAILURE' :'FAILURE'
              };

              event.preventDefault();
              var postUrl= '<?php echo base_url(); ?>' +'api/v1/brshopend/edit';
              // var postData ={
              //       'csrfToken' :'',
              //       'custname' : $('#name').val(),
              //       'tel' : $('#tel').val(),
              //       'email' : $('#email').val(),
              //       'wechat' : $('#wechat').val(),
              //       'birthday' : $('#birthday').val(),
              //       // 'selectedBox' :$('.css-checkbox:checked').val()
              //       'selectedBox' :selectBox1

              // }
              // $checkedpurchase=0;
              // if($('#need_purchase_service').is(':checked')){
              //     $checkedpurchase=1;
              // }
              // else
              // {
              //   $checkedpurchase=0;
              // }



              var postData ={
                  'shortcode':$('#shortcode').val(),
                  'code':$('#code').val(),
                  'name':$('#name').val(),
                  'id':$('#id').val()

              }





              // alert($('#level2').val());
              $.ajax({
                    method: "POST",
                    url: postUrl,
                   dataType: "json",
                   data: postData,

                   success : function(data){

                  // alert("posted");
                  // // alert('formsubmit');
                  // alert(data);

                  // alert(data['recordstatus']);
                  // alert(data['msg']);
                  if(data['recordstatus']=="SUCCESS"){
                      $('#feedback').remove();
                      $( '#newmsg' ).append('<p class="text-primary" id="feedback">'+data['msg']+'</p>');
                      setTimeout(function() {
                          location.reload();
                      }, 3000);
                      // location.reload();

                  }
                    if(data['recordstatus']=="FAILURE"){
                      $('#feedback').remove();
                      $( '#newmsg' ).append('<p class="text-danger"  id="feedback">'+data['msg']+'</p>');
                  //   $( '#modal-bodymsg' ).empty();
                  //   $( '#modal-bodymsg' ).append( '<h5 class="text-center" style="color: #a03d49;">客戶不能增加。</h5> <h5 class="text-cefnter" style="color: #a03d49;">請稍後再嘗試。</h5>' );
                  //   $('#finishModal').modal('show');
                  // }
                    // if (data.AJAX_SUCCESS==GlobalVariables.AJAX_SUCCESS){
                    //     window.location.href=GlobalVariables.destUrl;
                    // } else {
                    //     $('.alert').text("登入錯誤");
                    //    $('.alert').removeClass('hidden');
                    }
                }
              });

              }//if(passCheck==true){
          });//$("#btnUpdate").click(function(event) {
            //end edit control

              //Print Update Invoice
              $("#btnUpdateInvoiceSubmit").click(function(event) {
                var id=$(event.target).attr('data-invoiceid');
                var url = '/at-cms/brinvoicepdfadmin/createInvoice/'+id;
                 // alert(url);
                  // window.location.href = url;

                   window.open(url,'_blank');
                  // alert('1');
                // alert($(event.target).attr('data-invoiceid'));
              });//$("#btnUpdateInvoiceSubmit").click(function(event) {
              //End Print Update Invoice

              //Print Update Receipt
              $("#btnUpdateReceiptSubmit").click(function(event) {
                var id=$(event.target).attr('data-invoiceid');
                var url = '/at-cms/brinvoicepdfadmin/createReceipt/'+id;
                 // alert(url);
                  // window.location.href = url;

                  window.open(url,'_blank');
                  // alert('1');
                // alert($(event.target).attr('data-invoiceid'));
              });//$("#btnUpdateInvoiceSubmit").click(function(event) {

              $("#btnUpdateRefundSubmit").click(function(event) {
                var invoiceid=$(event.target).attr('data-invoiceid');
                //get payment total
                var postData ={
                              'id':invoiceid,

                }
                //set refund_invoice_id
                 $('#refund_invoice_id').val(invoiceid);
                //end set refund_invoice_id
                var GlobalVariables ={
                        'csrfToken': '123',
                        'baseUrl':'<?php echo base_url(); ?>',
                        'destUrl':'<?php echo base_url(); ?>/api/v1/brinvoiceend/getTotalPayment',
                        'AJAX_SUCCESS' :'SUCCESS',
                        'AJAX_FAILURE' :'FAILURE'
                       };
                       var postUrl= GlobalVariables.baseUrl +'/api/v1/brinvoiceend/getTotalPayment';

                          //booking detail ajax
                          $.ajax({
                        method: "POST",
                        url: postUrl,
                        dataType: "json",
                       data: postData,
                       success : function(data){

                      // alert("posted");
                      // alert('formsubmit');
                      // alert(data);

                      // alert(data['recordstatus']);
                      // alert(data['msg']);


                      $("#amount_paid").text(data);
                      // alert(data);
                      // $('#startdate').val(data);
                      // $('#starttime').val(data['starttime']);
                      if(data['recordstatus']=="SUCCESS"){
                          // $('#feedback').remove();
                          // $( '#editmsg' ).append('<p class="text-primary" id="feedback">'+data['msg']+'</p>');
                          // setTimeout(function() {
                          //     location.reload();
                          // }, 3000);
                          // location.reload();

                      }
                        if(data['recordstatus']=="FAILURE"){
                      }

                      }
                  });
                 //end get payment total

                 // get refund date and amount
                 var postData ={
                              'id':invoiceid,

                }
                var GlobalVariables ={
                        'csrfToken': '123',
                        'baseUrl':'<?php echo base_url(); ?>',
                        'destUrl':'<?php echo base_url(); ?>/api/v1/brinvoiceend/getRefundData',
                        'AJAX_SUCCESS' :'SUCCESS',
                        'AJAX_FAILURE' :'FAILURE'
                       };
                       var postUrl= GlobalVariables.baseUrl +'/api/v1/brinvoiceend/getRefundData';

                          //booking detail ajax
                          $.ajax({
                        method: "POST",
                        url: postUrl,
                        dataType: "json",
                       data: postData,
                       success : function(data){

                      // alert("posted");
                      // alert('formsubmit');
                      // alert(data);

                      // alert(data['recordstatus']);
                      // alert(data['msg']);


                      // $("#amount_paid").text(data);
                      // alert(data);
                      // $('#startdate').val(data);

                      if(data['refundDate']!==''){
                        // $('#datepicker').val(data['refundDate']);
                        // alert(data['refundDate']);
                        $('#datepicker').val(data['refundDate']).datepicker("update");
                        // $('#datepicker').data({date: data['refundDate']});
                        // $('#datepicker').datepicker('update');
                        $('#datepicker').children('input').val( data['refundDate']);
                      }
                      if(data['refundAmount']!==''){

                         $('#refund_amount').val(data['refundAmount']);
                      }

                     // $('#refundAmount').val(data['refundAmount']);
                      // if(data['recordstatus']=="SUCCESS"){
                      //     // $('#feedback').remove();
                      //     // $( '#editmsg' ).append('<p class="text-primary" id="feedback">'+data['msg']+'</p>');
                      //     // setTimeout(function() {
                      //     //     location.reload();
                      //     // }, 3000);
                      //     // location.reload();

                      // }
                      //   if(data['recordstatus']=="FAILURE"){
                      // }

                      }
                  });

                 // end get get refund date and amount


                          $('#RefundModalCenter').modal({
                                              show: true,
                                          });
                });//function btnUpdateRefundSubmit() {


            $("#btnRefundSubmit").click(function(event) {
                var postData ={
                              'refund_invoice_id': $('#refund_invoice_id').val(),
                              'refund_date':$('#datepicker').val(),
                              'refund_amount': $('#refund_amount').val(),

                }
                //set refund_invoice_id
                //end set refund_invoice_id
                var GlobalVariables ={
                        'csrfToken': '123',
                        'baseUrl':'<?php echo base_url(); ?>',
                        'destUrl':'<?php echo base_url(); ?>/api/v1/brinvoiceend/setRefundDate',
                        'AJAX_SUCCESS' :'SUCCESS',
                        'AJAX_FAILURE' :'FAILURE'
                       };
                       var postUrl= GlobalVariables.baseUrl +'/api/v1/brinvoiceend/setRefundDate';

                          //booking detail ajax
                          $.ajax({
                        method: "POST",
                        url: postUrl,
                        dataType: "json",
                       data: postData,
                       success : function(data){

                      // alert("posted");
                      // alert('formsubmit');
                      // alert(data);

                      // alert(data['recordstatus']);
                      // alert(data['msg']);


                      // $("#amount_paid").text(data);
                      // alert(data);
                      // $('#startdate').val(data);
                      // $('#starttime').val(data['starttime']);
                      if(data['recordstatus']=="SUCCESS"){
                          // $('#feedback').remove();
                          // $( '#editmsg' ).append('<p class="text-primary" id="feedback">'+data['msg']+'</p>');
                          // setTimeout(function() {
                          //     location.reload();
                          // }, 3000);
                          // location.reload();

                          $('#RefundModalCenter').modal('hide');

                          var url = '/at-cms/brinvoicepdfadmin/createRefund/'+$('#refund_invoice_id').val();
                          // alert(url);
                          // window.location.href = url;

                          window.open(url,'_blank');

                      }
                      if(data['recordstatus']=="FAILURE"){
                        alert("Cannot Set Refund.");
                      }

                      }
                  });
                 //end get payment total

            });//$("#btnRefundSubmit").click(function(event) {

              //End Print Update Receipt
            $("#btnRefundCloseSubmit").click(function(event) {
                 $('#RefundModalCenter').modal('hide');
            });//$("#btnRefundCloseSubmit").click(function(event) {

            //for voide button

             $("#btnUpdateVoidSubmit").click(function(event) {
                //open modal
                 $('#deleteModalCenter').modal({
                                              show: true,
                                          });
            });//$("#btnUpdateVoidSubmit").click(function(event) {



            $("#btnVoidConfirmSubmit").click(function(event) {
              //confirm void this invoice
                let id=$(event.target).attr('data-invoiceid');


                //ajax delete invoice
                var postData ={
                                'invoice_id': id,
                  }
                  //set refund_invoice_id
                  //end set refund_invoice_id
                  var GlobalVariables ={
                          'csrfToken': '123',
                          'baseUrl':'<?php echo base_url(); ?>',
                          'destUrl':'<?php echo base_url(); ?>/api/v1/brinvoiceend/deleteInvoice',
                          'AJAX_SUCCESS' :'SUCCESS',
                          'AJAX_FAILURE' :'FAILURE'
                         };
                         var postUrl= GlobalVariables.baseUrl +'/api/v1/brinvoiceend/deleteInvoice';

                            //booking detail ajax
                            $.ajax({
                          method: "POST",
                          url: postUrl,
                          dataType: "json",
                         data: postData,
                         success : function(data){

                        // alert("posted");
                        // alert('formsubmit');
                        // alert(data);

                        // alert(data['recordstatus']);
                        // alert(data['msg']);


                        // $("#amount_paid").text(data);
                        // alert(data);
                        // $('#startdate').val(data);
                        // $('#starttime').val(data['starttime']);
                        if(data['recordstatus']=="SUCCESS"){
                            // $('#feedback').remove();
                            // $( '#editmsg' ).append('<p class="text-primary" id="feedback">'+data['msg']+'</p>');
                            // setTimeout(function() {
                            //     location.reload();
                            // }, 3000);
                            // location.reload();
                            // alert("success");
                            // alert(data['msg']);
                            // $('#feedback').remove();
                            $('#deleteinvoicemsg').append('<p class="text-primary" id="feedback">'+data['msg']+'</p>');
                            setTimeout(function() {
                            var url = '/at-cms/brinvoiceadmin/';
                              // alert(url);
                                window.location.href = url;
                            }, 3000);

                        }
                        if(data['recordstatus']=="FAILURE"){
                          // $('#feedback').remove();
                          $( '#deleteinvoicemsg' ).append('<p class="text-danger"  id="feedback">'+data['msg']+'</p>');
                        }

                        }
                    });
                //end ajax delete invoice
                // alert(id);
            });//$("#btnRefundCloseSubmit").click(function(event) {

            $("#btnVoidConfirmCloseSubmit").click(function(event) {
                //close modal
                 $('#deleteModalCenter').modal('hide');
            });//$("#btnUpdateVoidCloseSubmit").click(function(event) {


            //end for void button
          });// $( document ).ready(function() {

          //calculate row total

          function rowTotal($rownum){
            //alert($rownum);


            //alert($('#price-'+$rownum).val());

            //alert($('#amount-'+$rownum).val());

            let tempprice = $('#price-'+$rownum).val();
            let tempamount = $('#amount-'+$rownum).val();
            let tempdiscount=$('#discount-'+$rownum).val();
            //alert(tempdiscount);
            let calDiscount=1;
            if(parseFloat(tempdiscount)!==0){
              // calDiscount=tempdiscount/100;
              calDiscount=1-tempdiscount/100;
            }
            let temptotal=tempprice * tempamount*calDiscount;
            // $('#display-amount-'+$rownum).text( Math.round(temptotal));
            $('#total-'+$rownum).val( Math.round(temptotal));
            //#discount-

          }//function rowTotal($rownum){
          function rowPressTotal($rownum){
            // let tempprice = $('#price-'+$rownum).val();
            let tempamount = $('#amount-'+$rownum).val();
            let tempdiscount=$('#discount-'+$rownum).val();
            let product_subtotal=$('#total-'+$rownum).val();

            // let calDiscount=1;
            // if(parseFloat(tempdiscount)!==0){
            //   // calDiscount=tempdiscount/100;
            //   calDiscount=1-tempdiscount/100;
            // }

            // let tempprice=product_subtotal /calDiscount ;
            // // alert(tempprice);
            // tempprice= tempprice/tempamount;
            // tempprice=Math.round(tempprice * 1000)/1000;
            // $('#price-'+$rownum).val(tempprice);

            //Added discont rate
            let tempprice=$('#price-'+$rownum).val();

            let calDiscount=  product_subtotal /(tempprice*tempamount);
            // if(parseFloat(1-calDiscount)!==0){
              calDiscount=1-calDiscount;
            // }
            calDiscount = calDiscount *100; //calculate up to 100 precent
            calDiscount = Math.round(calDiscount *1000)/1000; //round to two digits
            $('#discount-'+$rownum).val(calDiscount);


            //end   Added discont rate

          }
          function billUpyog(){
            let total=0;

             let product_price_array=[];
             let product_qty_array=[];
             let product_discount=[];

             $('input[name^="product_price"]').each(function() {
                  // alert($(this).val());
                  product_price_array.push( $(this).val() );
              });

              $('input[name^="product_qty"]').each(function() {
                  // alert($(this).val());
                  product_qty_array.push( $(this).val() );
              });

               $('input[name^="product_discount"]').each(function() {
                product_discount.push( $(this).val() );
              });
              let calDiscount=1;
              for (var i = 0; i < product_price_array.length ; i++) {
                calDiscount=1;
                if(parseFloat(product_discount[i])!==0){
                  // calDiscount=product_discount[i]/100;
                  calDiscount=1-(product_discount[i]/100);
                }
                total=total+(Math.round(product_price_array[i] * product_qty_array[i]*calDiscount));
              }//for (var i = 0; i < product_price_array.length ; i++) {

              // alert(total);
              // $('#totalAmountDue').innerText=total;
               $('#totalAmountDue').html(total);

               //added update payment amount 2020-10-08

                $('#payment_amount_1').val(total);
               //end added update payment amount

          }//function billupyog(){

          //end calculate row total

          function Call(){
            //alert("Me");
          }
          //
          function twentyFivePrecentCheck(){

              var username=document.getElementById('twentyfiveusername').value;
              var password=document.getElementById('twentyfiveuserpass').value;

               var data = { username: username, password: password };
                  var ajaxcheckRole="";
                  $.ajax({
                      url: '<?php echo base_url(); ?>' +'api/v1/bremployeeend/checkRole',   //後端的URL
                      type: "POST",   //用POST的方式
                      dataType: "json",   //response的資料格式
                      async: false,
                      cache: false,   //是否暫存
                      data: data, //傳送給後端的資料
                      success: function(response) {
                          console.log(response);  //成功後回傳的資料

                          // alert(response['roleId']);
                          ajaxcheckRole=response['roleId'];
                          // if (response.auth === 1) {
                          //     window.location.href = "camera.html";   //帳密確認成功後，轉址
                          // } else {
                          //     $("#invalid").show();   //帳密輸入錯誤，訊息框
                          //     centered($("#invalid"));

                          //     $(window).resize(function() {
                          //         centered($("#invalid"));
                          //     });

                          //     setTimeout(function() {
                          //         $("#invalid").hide();
                          //     }, 3000);
                          // }
                      }
                  });

                //end ajax confirm role

                // alert(ajaxcheckRole);
                    // rold id 7=boss
                    // rold id 6=admin
                    // rold id 5=consultant/manager  ->can change shop but only view booking
                    // rold id 4=consultant          ->cannot change shop
                    // rold id 3=therapist/manager  ->can change shop
                    // role id 2=therapist          ->cannot change shop
                    //role id 1=manager             ->can change shop
                let roleNum=parseInt(ajaxcheckRole);
                if(roleNum!==7 && roleNum!==6 && roleNum!==5 && roleNum!==3 && roleNum!==1 ){
                  alert("沒有足夠權限");
                  passDiscountCheck=false;
                }
                else{
                    printInvoice();
                }
          }//function twentyFivePrecentCheck(){

          //for print invoice
          function printInvoice(){

              let passedChecking=true;
              let emptyNewUser=false;
              if( (document.querySelector("#display_name").value).trim() ==='' && (document.querySelector("#mobile").value).trim() ===''){
                emptyNewUser=true;
              }

              if(emptyNewUser===true && document.querySelector("#user_id").value === ''){
                alert("請選擇現有客戶 或填新客戶名稱及客戶電話.");
               passedChecking=false;
             // alert( document.querySelector("#user_id").value);
              }

              //added invoice date 2020-11-13
              let invoice_date=(document.querySelector("#invoicedate").value).trim() ;
              //end added invoice date 2020-11-13

              let userId= (document.querySelector("#user_id").value).trim();
              let display_name= (document.querySelector("#display_name").value).trim();
              let mobile= (document.querySelector("#mobile").value).trim();
              let pic_1= (document.querySelector("#pic_1").value).trim();
              let pic_2= (document.querySelector("#pic_2").value).trim(); //added
              let consultant_1= (document.querySelector("#consultant_1").value).trim();


              // alert(userId);

              var product_add_ticker = [];
              var product_id_array =  [];
              var product_price_array =  [];
              var product_qty_array = [];
              var product_discount_array = [];
              var product_remark_array = [];


            $('input:checkbox[name^="addticketid"]').each(function(){
              // alert($(this).val());

              if ($(this).is(":checked")===true) {
               product_add_ticker.push(1);
              }
              if ($(this).is(":checked") ===false) {
               product_add_ticker.push(0);
              }
            });


              $('input[name^="product_id"]').each(function() {
                  // alert($(this).val());
                  product_id_array.push( $(this).val() );
              });

              $('input[name^="product_price"]').each(function() {
                  // alert($(this).val());
                  product_price_array.push( $(this).val() );
              });

              $('input[name^="product_qty"]').each(function() {
                  // alert($(this).val());
                  product_qty_array.push( $(this).val() );
              });

              var passDiscountCheck=true;
              var askFor20Precent=false;
              var askFor30Precent=false;
              var askFor10Precent=false;

               $('input[name^="product_discount"]').each(function() {
                  // alert($(this).val());
                  product_discount_array.push( $(this).val() );
                  //for checking dicount value
                  // if($(this).val()<=30 && $(this).val()>=25){ //25~30% OFF

                  //   askFor20Precent=true;
                  // }
                  // //end for checking dicount value

              });

              $('input[name^="product_remark"]').each(function() {
                  // alert($(this).val());
                  product_remark_array.push( $(this).val() );
              });
              // alert(askFor20Precent);

              // if(askFor20Precent===true){
              //       if (confirm("折扣大過30%")) {
              //         // txt = "You pressed OK!";

              //       } else {

              //         passDiscountCheck=false;
              //         // return ;
              //       }
              // }








               let payment_type_1= (document.querySelector("#payment_type_1").value).trim();
               let payment_amount_1= (document.querySelector("#payment_amount_1").value).trim();

               let payment_type_2= (document.querySelector("#payment_type_2").value).trim();
               let payment_amount_2= (document.querySelector("#payment_amount_2").value).trim();

               let payment_type_3= (document.querySelector("#payment_type_3").value).trim();
               let payment_amount_3= (document.querySelector("#payment_amount_3").value).trim();

              //end get input field



              //submit form data
              var GlobalVariables ={
                    'csrfToken': '123',
                    'baseUrl':'<?php echo base_url(); ?>',
                    // 'destUrl':'<?php echo base_url(); ?>/api/v1/frontend/add',
                    'AJAX_SUCCESS' :'SUCCESS',
                    'AJAX_FAILURE' :'FAILURE'
              };

              event.preventDefault();
              var postUrl= '<?php echo base_url(); ?>' +'api/v1/brinvoiceend/addinvoice';
              // var postData ={
              //       'csrfToken' :'',
              //       'custname' : $('#name').val(),
              //       'tel' : $('#tel').val(),
              //       'email' : $('#email').val(),
              //       'wechat' : $('#wechat').val(),
              //       'birthday' : $('#birthday').val(),
              //       // 'selectedBox' :$('.css-checkbox:checked').val()
              //       'selectedBox' :selectBox1

              // }
              // $checkedpurchase=0;
              // if($('#need_purchase_service').is(':checked')){
              //     $checkedpurchase=1;
              // }
              // else
              // {
              //   $checkedpurchase=0;
              // }



              var postData ={
                  //added invoice date
                  'invoice_date':invoice_date,
                  //added invoice date
                  'userId':userId,
                  'display_name':display_name,
                  'mobile':mobile,
                  'pic_1':pic_1,
                  'pic_2':pic_2,
                  'consultant_1':consultant_1,
                  'product_add_ticker_array':product_add_ticker,
                  'product_id_array':product_id_array,
                  'product_price_array':product_price_array,
                  'product_qty_array':product_qty_array,
                  'product_discount_array':product_discount_array,
                  'product_remark_array':product_remark_array,
                  'payment_type_1':payment_type_1,
                  'payment_amount_1':payment_amount_1,
                  'payment_type_2':payment_type_2,
                  'payment_amount_2':payment_amount_2,
                  'payment_type_3':payment_type_3,
                  'payment_amount_3':payment_amount_3,
                  'shopId':<?php echo $this->session->userdata('currentshop'); ?>,
              }

              if(passedChecking===false){
                $('#btnInvoiceSubmit').attr('disabled', false);
                return ;
              }


              $('#loading').show();
              // alert($('#level2').val());
              $.ajax({
                    method: "POST",
                    url: postUrl,
                   dataType: "json",
                   data: postData,
                    // $("#search").prop('disabled', true);
                   success : function(data){

                   $('#btnInvoiceSubmit').attr('disabled', false);
                  // alert("posted");
                  // // alert('formsubmit');
                  // alert(data);

                  // alert(data['recordstatus']);
                  // alert(data['msg']);

                  var invoicearray=data['invoicelist'];
                  // alert(invoicearray);
                  if(data['recordstatus']=="SUCCESS"){
                     $('#loading').hide();
                      $('#feedback').remove();
                      $( '#newmsg' ).append('<p class="text-primary" id="feedback">'+data['msg']+'</p>');
                      // setTimeout(function() {
                      //     location.reload();
                      // }, 3000);
                      // location.reload();
                      var link="";
                      if(invoicearray[0] !== undefined){
                          link=link+invoicearray[0];
                      }
                      if(invoicearray[1] !== undefined){
                          link=link+'/'+invoicearray[1];
                      }
                      // window.location.href = '../brinvoicepdfadmin/createInvoice/'+invoicearray[0]+'/'+invoicearray[1];
                        // alert(link);
                    // window.location.href = '../brinvoicepdfadmin/createInvoice/'+link;
                    // window.location.href = '<?php echo base_url(); ?>at-cms/brinvoicepdfadmin/createInvoice/'+link;

                    //cancel at 2020-10-19
                      setTimeout(function() {
                           window.location.href = '<?php echo base_url(); ?>at-cms/brinvoiceadmin';
                      }, 3000);
                    //end cancel at 2020-10-19


                    window.open('<?php echo base_url(); ?>at-cms/brinvoicepdfadmin/createInvoice/'+link,'_blank');
                      // $("#search").prop('disabled', false);
                  }
                    if(data['recordstatus']=="FAILURE"){
                       $('#loading').hide();
                      $('#feedback').remove();
                      $( '#newmsg' ).append('<p class="text-danger"  id="feedback">'+data['msg']+'</p>');
                  //   $( '#modal-bodymsg' ).empty();
                  //   $( '#modal-bodymsg' ).append( '<h5 class="text-center" style="color: #a03d49;">客戶不能增加。</h5> <h5 class="text-center" style="color: #a03d49;">請稍後再嘗試。</h5>' );
                  //   $('#finishModal').modal('show');
                  // }
                    // if (data.AJAX_SUCCESS==GlobalVariables.AJAX_SUCCESS){
                    //     window.location.href=GlobalVariables.destUrl;
                    // } else {
                    //     $('.alert').text("登入錯誤");
                    //    $('.alert').removeClass('hidden');
                    }
                }
              });
          }//end function printInvoice()

          //end for print invoice
          function user_idajax($id){
                var id = $id;
                // alert(id);
                // var res = id.split("-");
                // var fileid=res[0];
                // var items=res[1];
                // alert("fileid"+fileid);
                // alert("items"+items);
                // var selectedid= $({"#".id}).val();
                // var selectedid=$value;
                // alert(selectedid);
                var GlobalVariables ={
                    'csrfToken': '123',
                    'baseUrl':'<?php echo base_url(); ?>',
                    'destUrl':'<?php echo base_url(); ?>/api/v1/brcustomerserviceend/getService',
                    'AJAX_SUCCESS' :'SUCCESS',
                    'AJAX_FAILURE' :'FAILURE'
              };

                //empty lower select box

                 var prepaidservicessub = document.getElementById('prepaid-services-sub');
                    // alert(city);
                     $(prepaidservicessub).empty();


                //end empty lower select box

                var postUrl= GlobalVariables.baseUrl +'/api/v1/brcustomerserviceend/getService';
                //change select box option
                   $.ajax({
                          type:'POST',
                          url:postUrl,
                          data:{'cust_id':id},
                      success:function(data){

                        // alert('empty');
                        // var obj = $.parseJSON(data);
                        var obj =data;
                        // alert('empty2');
                      // var v = data.k;

                     // the next thing you want to do
                     // alert(fileid+'-'+items+'Level2');
                     // id='row' + id.toString();
                    // var findname=fileid.toString()+'-'+items.toString()+'-Level2';
                    // var city = document.getElementById(fileid+'-'.items+'Level2');
                    // var city = document.getElementById('5-1-Level2');
                    // var level2box = document.getElementById('level2');
                    // alert(city);
                     // $(level2box).empty();
                    //  $jsondata=json_decode($data);
                    // alert( obj.length);
                    // alert( obj[0]['name']);

                     //added empty select record
                    // $prepaidservicessub.append('<p>'+ obj[i].service_id+'</p>');

                    // $(level2box).append('<option  value=' + '>--- 請選擇居住範圍---'  + '</option>');

                    //end added empty select record
                    // '<table id="prepaid-services-table" class="display table table1 dataTable no-footer"><thead><tr><th></th><th>服務編號</th><th>服務種類</th><th>服務項目</th><th>工數</th><th>售價</th><th>購買次數</th><th>剩除次數</th><th>沒有積分回贈</th></tr></thead><tbody><tr data-id="7" data-available_qty="10"><td><input class="checkbox-check" type="checkbox" style="position: relative;left: 20px;top: 8px;opacity: 1;"></td><td>T-001</td><td>T - 療程</td><td>皮秒二代(全臉)</td><td>1</td><td>$1,980.00</td><td>10</td><td>10</td><td></td></tr></tbody></table>'
                    if(obj.length==0){
                      var html="沒有任何記錄";
                      $(prepaidservicessub).append(html);
                    }
                    if(obj.length!=0){
                      var html='';
                      // html +='<table id="prepaid-services-table" class="display table table1 dataTable no-footer"><thead><tr><th></th><th>服務編號</th><th>服務種類</th><th>服務項目</th><th>工數</th><th>售價</th><th>時間</th><th>購買次數</th><th>剩除次數</th><th>沒有積分回贈</th></tr></thead><tbody>';
                      html +='<table id="prepaid-services-table" class="display table table1 dataTable no-footer"><thead><tr><th></th><th>服務編號</th><th>服務種類</th><th>服務項目</th><th>工數</th><th>售價</th><th>時間</th><th>購買次數</th><th>剩除次數</th></tr></thead><tbody>';
                      for (var i = 0; i < obj.length; i++) {
                        // alert(i);
                        // $(prepaidservicessub).append('<p style="color:blue;">'+ obj[i].service_id+'</p>');
                        html+='<tr data-id="'+ obj[i].id+'" ';
                        html+='data-available_qty="'+ obj[i].available_qty+'">';
                        // $(prepaidservicessub).append('<td>');
                        html+='<td>';
                        // html+='<input class="selectproduct3" type="checkbox" name="useservice" id="useservice" value="'+obj[i].id+'" data-price="'+parseInt(obj[i].time)+'" >';
                        // html+='<input class="selectproduct3" type="checkbox" name="useservice" id="useservice" value="'+obj[i].id+'" data-price="'+parseInt(obj[i].time)+'" onclick="add()" >';
                        html+='</td>';
                        html+='<td>';
                        html+=obj[i].code;
                        html+='</td>';

                        if(obj[i].category_id==1){
                          html+='<td>';
                          html+='FT-試做療程';
                          html+='</td>';
                        }
                         if(obj[i].category_id==2){
                          html+='<td>';
                          html+='T-療程';
                          html+='</td>';
                        }
                        html+='<td>';
                        html+=obj[i].name;
                        html+='</td>';
                        html+='<td>';
                        html+=obj[i].work;
                        html+='</td>';
                        html+='<td>';
                        html+=obj[i].price;
                        html+='</td>';
                        html+='<td>';
                        html+=parseInt(obj[i].time);
                        html+=' 分鐘';
                        html+='</td>';
                        html+='<td>';
                        html+=obj[i].purchased_qty;
                        html+='</td>';
                        html+='<td>';
                        html+=obj[i].available_qty;
                        html+='</td>';
                        // html+='<td>';
                        // if(obj[i].no_credit_rebate==1){

                        //   html+='<i class="fas fa-check-circle"></i>';

                        // }
                        // html+='</td>';
                        html+='</tr>';
                      // $(level2box).append('<option  value=' + obj[i].id + '>' + obj[i].chi_name + '</option>');
                      }

                      html+='</tbody></table>';

                      $(prepaidservicessub).append(html);
                      // alert(data);
                      // level3boxajax(fileid+'-'+items+'-Level3', obj[0].id);
                      // alert('level3'+data);

                    }//if(obj.length!=0){


                }
              });

            }
          //end user_idajax

          //service_ajax
           function service_ajax(){
                // var id = $id;
                // alert('service');
                // var res = id.split("-");
                // var fileid=res[0];
                // var items=res[1];
                // alert("fileid"+fileid);
                // alert("items"+items);
                // var selectedid= $({"#".id}).val();
                // var selectedid=$value;
                // alert(selectedid);
                var GlobalVariables ={
                    'csrfToken': '123',
                    'baseUrl':'<?php echo base_url(); ?>',
                    'destUrl':'<?php echo base_url(); ?>/api/v1/brservicesend/getAllServices',
                    'AJAX_SUCCESS' :'SUCCESS',
                    'AJAX_FAILURE' :'FAILURE'
              };

                //empty lower select box

                 var newservicessub = document.getElementById('new-services-sub');
                    // alert(city);
                     $(newservicessub).empty();


                //end empty lower select box

                // var postUrl= GlobalVariables.baseUrl +'/api/v1/servicesend/getAllServices';
                var postUrl= GlobalVariables.baseUrl +'/api/v1/brservicesend/getAllServicesWithConvert';
                //change select box option
                   $.ajax({
                          type:'POST',
                          url:postUrl,
                          data:'',
                      success:function(data){
                        // alert('empty');
                        // var obj = $.parseJSON(data);
                        var obj =data;
                        // alert('empty2');
                      // var v = data.k;

                     // the next thing you want to do
                     // alert(fileid+'-'+items+'Level2');
                     // id='row' + id.toString();
                    // var findname=fileid.toString()+'-'+items.toString()+'-Level2';
                    // var city = document.getElementById(fileid+'-'.items+'Level2');
                    // var city = document.getElementById('5-1-Level2');
                    // var level2box = document.getElementById('level2');
                    // alert(city);
                     // $(level2box).empty();
                    //  $jsondata=json_decode($data);
                    // alert( obj.length);
                    // alert( obj[0]['name']);

                     //added empty select record
                    // $prepaidservicessub.append('<p>'+ obj[i].service_id+'</p>');

                    // $(level2box).append('<option  value=' + '>--- 請選擇居住範圍---'  + '</option>');

                    //end added empty select record
                    // '<table id="prepaid-services-table" class="display table table1 dataTable no-footer"><thead><tr><th></th><th>服務編號</th><th>服務種類</th><th>服務項目</th><th>工數</th><th>售價</th><th>購買次數</th><th>剩除次數</th><th>沒有積分回贈</th></tr></thead><tbody><tr data-id="7" data-available_qty="10"><td><input class="checkbox-check" type="checkbox" style="position: relative;left: 20px;top: 8px;opacity: 1;"></td><td>T-001</td><td>T - 療程</td><td>皮秒二代(全臉)</td><td>1</td><td>$1,980.00</td><td>10</td><td>10</td><td></td></tr></tbody></table>'
                    if(obj.length==0){
                      var html="沒有任何記錄";
                      $(newservicessub).append(html);
                    }
                    if(obj.length!=0){
                      var html='';
                      // html +='<table id="new-services-table" class="display table table1 dataTable no-footer"><thead><tr><th></th><th>服務編號</th><th>服務種類</th><th>服務項目</th><th>工數</th><th>售價</th><th>時間</th><th>沒有積分回贈</th></tr></thead><tbody>';
                      html +='<table id="new-services-table" class="display table table1 dataTable no-footer"><thead><tr><th></th><th>服務編號</th><th>服務種類</th><th>服務項目</th><th>工數</th><th>售價</th><th>時間</th></tr></thead><tbody>';
                      for (var i = 0; i < obj.length; i++) {
                        // alert(i);
                        // $(newservicessub).append('<p style="color:blue;">'+ obj[i].service_id+'</p>');
                        html+='<tr data-id="'+ obj[i].id+'" ';
                        html+='data-available_qty="'+ obj[i].available_qty+'">';
                        // $(newservicessub).append('<td>');
                        html+='<td>';
                        // html+='<input class="selectproduct3"  type="checkbox" name="useproduct" id="useproduct" value="'+obj[i].id+'" data-price="'+parseInt(obj[i].time)+'"  onclick="add()" >';
                        html+='<input class="selectproduct3"  type="checkbox" name="useproduct" id="useproduct" value="'+obj[i].id+'" data-price="'+parseInt(obj[i].time)+'" >';
                        html+='</td>';
                        html+='<td>';
                        html+=obj[i].code;
                        html+='</td>';

                        if(obj[i].category_id==1){
                          html+='<td>';
                          html+='FT-試做療程';
                          html+='</td>';
                        }
                         if(obj[i].category_id==2){
                          html+='<td>';
                          html+='T-療程';
                          html+='</td>';
                        }
                        html+='<td>';
                        html+=obj[i].name;
                        html+='</td>';
                        html+='<td>';
                        html+=obj[i].work;
                        html+='</td>';
                        html+='<td>';
                        html+=obj[i].price;
                        html+='</td>';
                        // html+='<td>';
                        // html+=obj[i].purchased_qty;
                        // html+='</td>';
                        // html+='<td>';
                        // html+=obj[i].available_qty;
                        // html+='</td>';
                        html+='<td>';
                        html+=parseInt(obj[i].time);
                        html+=' 分鐘';
                        html+='</td>';
                        // html+='<td>';
                        // if(obj[i].no_credit_rebate==1){

                        //   html+='<i class="fas fa-check-circle"></i>';

                        // }
                        // html+='</td>';
                        html+='</tr>';
                      // $(level2box).append('<option  value=' + obj[i].id + '>' + obj[i].chi_name + '</option>');
                      }

                      html+='</tbody></table>';

                      $(newservicessub).append(html);
                      // alert(data);
                      // level3boxajax(fileid+'-'+items+'-Level3', obj[0].id);
                      // alert('level3'+data);

                    }//if(obj.length!=0){


                }
              });

            }
          //end service_ajax
            // function CheckPwd() {
            // // msgWindow=window.open("","displayWindow","height=150,width=400");
            // //    msgWindow.document.write("<HEAD><TITLE>Password required</TITLE></HEAD>")
            // //    msgWindow.document.write("<BODY bgcolor='gray'><FORM formpwd><table><tr><td>Your name:</td><td><input type=text size=20 id='username25'></td></tr>");
            // //    msgWindow.document.write("<tr><td>Your password:</td><td><input type=password size=20 id='password25'></td></tr>");
            // //    msgWindow.document.write("<tr><td COLSPAN=2 ALIGN=CENTER><input type=button value=' OK '>&nbsp;&nbsp;<input type=button value=' Cancel '></td></tr></table></form>");
            // //    return msgWindow;

            // $('<form> <input type="text" style="z-index:10000" class="namedialog"> <br> </form>').dialog({
            //     modal: true,
            //     onClose: function() {
            //       var name = $(this).find(".namedialog").val();
            //       var Label = Parse.Object.extend("Label");
            //       var result = new Label();
            //       result.set("labels", localStorage.getItem("labels"));
            //       result.set("name", name);

            //       result.save(null, {
            //         sucess: function(result) {
            //           alert("Stored data sucessfully!");
            //         },
            //         error: function(result, error) {
            //           alert("Error submitting data, error code:" + error.message);
            //         }
            //       });
            //     }
            //   });


            // }

// $(function () {
// $('#tdog').dialog({
//      autoOpen: false,
//      width: 200,
//      modal: true,
//   });
// });


  //Set up the dialog box
// $("#myDialog").dialog({
//     autoOpen  : false,
//     modal     : true,
//     title     : "A Dialog Box",
//     buttons   : {
//               'OK' : function() {
//                   var textValue = $('#myTextBox').val();
//                   alert('The value of the text box is ' + textValue);
//                   //Now you have the value of the textbox, you can do something with it, maybe an AJAX call to your server!
//               },
//               'Close' : function() {
//                   alert('The Close button was clicked');
//                   $(this).dialog('close');
//               }
//                 }
// });

//Open the dialog box when the button is clicked.
// $('#clickMe').click(function() {
//     $("#myDialog").dialog("open");
// });

function DeleteRowFunction(btndel) {
              //alert("clicked2");
    if (typeof(btndel) == "object") {
        $(btndel).closest('tr').next('tr').remove(); //remove remark
        $(btndel).closest("tr").remove();
        billUpyog();
    } else {
        return false;
    }
}


//ajax load point
$(document).ready(function(){
    $('#user_id').change(function(){
      var customerpointsub= document.getElementById('customer_point');
      $(customerpointsub).empty();

      // alert(this.value);
      // $.ajax({
      //     url: "artist_field.php",
      //     data: { "value": $("#artist").val() },
      //     dataType:"html",
      //     type: "post",
      //     success: function(data){
      //        $('#artist').append(data);
      //     }
      // });

            var GlobalVariables ={
                    'csrfToken': '123',
                    'baseUrl':'<?php echo base_url(); ?>',
                    // 'destUrl':'<?php echo base_url(); ?>/api/v1/frontend/add',
                    'AJAX_SUCCESS' :'SUCCESS',
                    'AJAX_FAILURE' :'FAILURE'
              };
              var cust_id=this.value;
              event.preventDefault();
              var postUrl= '<?php echo base_url(); ?>' +'api/v1/brcustomerpointend/getCustPoint';
              // var postData ={
              //       'csrfToken' :'',
              //       'custname' : $('#name').val(),
              //       'tel' : $('#tel').val(),
              //       'email' : $('#email').val(),
              //       'wechat' : $('#wechat').val(),
              //       'birthday' : $('#birthday').val(),
              //       // 'selectedBox' :$('.css-checkbox:checked').val()
              //       'selectedBox' :selectBox1

              // }
              // $checkedpurchase=0;
              // if($('#need_purchase_service').is(':checked')){
              //     $checkedpurchase=1;
              // }
              // else
              // {
              //   $checkedpurchase=0;
              // }



              var postData ={
                  'cust_id':cust_id
              }





              // alert($('#level2').val());
            if(cust_id.length>0){


              $.ajax({
                    method: "POST",
                    url: postUrl,
                   dataType: "json",
                   data: postData,

                   success : function(data){
                      // alert(data);

                      var customerpointsub= document.getElementById('customer_point');
                    // alert(city);
                      $(customerpointsub).empty();
                      if(data==null){
                        $(customerpointsub).append('<h5 class="modal-title ">客戶積分: 0</h5><br>');
                      }
                      else{
                        $(customerpointsub).append('<h5 class="modal-title ">客戶積分: '+parseInt(data)+'</h5><br>');
                      }


                   }
              });
             }//if(cust_id.length>0){

    });
});


//end ajax load point



        </script>



      <?php include 'include/header.php';?>
      <div class="wrapper" >

          <?php include 'include/sidebar.php';?>
          <!-- pickup modal -->

            <!-- loading modal -->
         <style type="text/css">
               /* Start by setting display:none to make this hidden.
                 Then we position it in relation to the viewport window
                 with position:fixed. Width, height, top and left speak
                 for themselves. Background we set to 80% white with
                 our animation centered, and no-repeating */
              .modal3 {
                  display:    none;
                  position:   fixed;
                  z-index:    100000;
                  top:        0;
                  left:       0;
                  height:     100%;
                  width:      100%;
                  background: rgba( 255, 255, 255, .8 )
                              url('http://i.stack.imgur.com/FhHRx.gif')
                              /*url('images/FhHRx.gif') */
                              50% 50%
                              no-repeat;
              }

              /* When the body has the loading class, we turn
                 the scrollbar off with overflow:hidden */
              body.loading2 .modal3 {
                  overflow: hidden;
              }

              /* Anytime the body has the loading class, our
                 modal element will be visible */
              body.loading2 .modal3 {
                  display: block;
              }


            </style>
            <!-- loading modal -->
            <div class="modal3" id="loading"><!-- Place at bottom of page --></div>

        <!-- end of loading modal -->

            <!-- login modal -->
            <div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel" aria-hidden="true">
              <div class="modal-dialog modal-dialog-centered" role="document">
                <div class="modal-content">
                  <div class="modal-header">
                    <h5 class="modal-title" id="loginModalLabel">折扣大過25%</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                          </button>
                  </div>
                  <form id="loginForm">
                     <div class="px-3">
                      <div class="">
                        <label for="" class="col-form-label">請輸入經理或以上權限的登入名稱及密碼</label>

                      </div>
                  </div>
                    <div class="px-3">
                      <div class="">
                        <label for="twentyfiveusername" class="col-form-label">登入名稱:</label>
                        <input type="text" name="twentyfiveusername" class="form-control" id="twentyfiveusername">
                      </div>
                  </div>
                  <div class="px-3">
                      <div class="">
                        <label for="twentyfiveuserpass" class="col-form-label">密碼:</label>
                        <input type="password" name="twentyfiveuserpass" class="form-control" id="twentyfiveuserpass">
                      </div>
                  </div>
                  <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary"  onclick="twentyFivePrecentCheck()">Login</button>
                  </div>
                  </form>
                </div>
              </div>
            </div>

            <!-- end login modal -->



              <!-- refund modal -->
              <script>

              </script>

              <div class="modal fade" id="RefundModalCenter" tabindex="-1" role="dialog" aria-labelledby="refundModalCenterTitle" aria-hidden="true">
              <div class="modal-dialog modal-dialog-centered  " role="document" style="max-width: 600px;">
                  <div class="modal-content px-3">
                  <!-- <div class="modal-header">
                      <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
                      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                      <span aria-hidden="true">&times;</span>
                      </button>
                  </div> -->
                  <div class="modal-body "  style="z-index:2000">
                       <h5 style="color:#957c78" class="text-center py-2"><i class="fas fa-plus mr-2" style="color:#957c78"></i>退換發票</h5>
                       <form id="refund" class="form-horizontal" role="form">





                            <div class="form-group row">
                              <div class="col-sm-3 text-center mas-title2">
                                <label for="amount_paid">已付款項</label>
                              </div>
                              <div class="col-sm-9 mas-box">
                                <label class="mas-text"><span class="text block" name="amount_paid" id="amount_paid">1276</span></label>
                              </div>
                            </div>
                            <div class="form-group row">
                              <div class="col-sm-3 text-center mas-title">
                                <label for="refund_date">退還日期</label>
                              </div>
                              <div class="col-sm-9 mas-box">
                                <div class="input-group clickable">
                                  <!-- <input class="form-control date-picker" type="text" name="refund_date" value="2020-07-29" readonly="true"> -->
                                  <!-- date picker -->
                                  <!-- dob readonly="true" -->


                                  <input id="datepicker" width="276" value="<?php
if ($pagemethod == "add") {
	echo
	date("Y-m-d");
}
if ($pagemethod == "edit" || $pagemethod == "details") {

	// echo  $customerdetails->dob;
}?>" <?php

if ($pagemethod == "details") {
	echo
		"readonly";
}
?> autocomplete="off" />
                                  <script>
                                      $('#datepicker').datepicker({
                                          uiLibrary: 'bootstrap4',
                                          format: 'yyyy-mm-dd'
                                      });
                                  </script>
                                  <!-- end date picker -->

                                  <span class="input-group-addon"><span class="glyphicon-calendar glyphicon"></span></span>
                                  <!-- <a><i class="fa fa-calendar"></i></a> -->
                                </div>
                              </div>
                            </div>
                            <div class="form-group row">
                              <div class="col-sm-3 text-center mas-title">
                                <label for="refund_amount">退還款項</label>
                              </div>
                              <div class="col-sm-9 mas-box">
                                <input id="refund_amount" type="text" class="form-control mas-input" name="refund_amount" value="">
                              </div>
                            </div>
                          <input id="refund_invoice_id" type="hidden" class="form-control mas-input" name="refund_invoice_id" value="">

                         <!--  <label for="inputRePassword" class="col-sm-12 "><span style="color:#7d4495;" >確定删除?</span></label> -->

                          <span id="deletemsg" class="text-center"></span>

                      <!-- <div class="form-group row">
                          <div class="col-sm-12">
                          <p style="font-size: 12px;"><span style="color:#616161">*為必填項目<br>登入名稱為英文字或數字組成(不分大小寫)</span></p>
                          <span id="editmsg" class="text-center"></span>
                           </div>
                      </div> -->
                      <div class="form-group row">
                          <div class="col-sm-12 text-center">
                          <button type="button" class="btn  px-5  custombutton" id="btnRefundSubmit">確定</button>
                          <button type="button" class="btn  px-5  custombutton" id="btnRefundCloseSubmit">關閉</button>
                          </div>
                      </div>
  <!--                     <input type="hidden" class="form-control" id="inputadminid" placeholder=""> -->
                      </form>
                  </div>
                  <!-- <div class="modal-footer">
                      <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                      <button type="button" class="btn btn-primary">Save changes</button>
                  </div> -->
                  </div>
              </div>
              </div>
              <script type="text/javascript">



              </script>
              <!-- end refund modal -->

               <!-- delete modal -->
              <?php if ($pagemethod == "edit") {?>
              <script>

              </script>

              <div class="modal fade" id="deleteModalCenter" tabindex="-1" role="dialog" aria-labelledby="deleteModalCenterTitle" aria-hidden="true">
              <div class="modal-dialog modal-dialog-centered  " role="document" style="max-width: 600px;">
                  <div class="modal-content px-3">
                  <!-- <div class="modal-header">
                      <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
                      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                      <span aria-hidden="true">&times;</span>
                      </button>
                  </div> -->
                  <div class="modal-body ">
                       <h5 style="color:#957c78" class="text-center py-2"><i class="fas fa-plus mr-2" style="color:#957c78"></i>確定</h5>
                       <form>


                      <div class="form-group row">
                          <label for="inputRePassword" class="col-sm-12 "><span style="color:#957c78;" >是否繼續?</span></label>

                          <span id="deleteinvoicemsg" class="text-center"></span>
                      </div>
                      <!-- <div class="form-group row">
                          <div class="col-sm-12">
                          <p style="font-size: 12px;"><span style="color:#616161">*為必填項目<br>登入名稱為英文字或數字組成(不分大小寫)</span></p>
                          <span id="editmsg" class="text-center"></span>
                           </div>
                      </div> -->
                      <div class="form-group row">
                          <div class="col-sm-12 text-center">
                          <button type="button" class="btn  px-5  custombutton" id="btnVoidConfirmSubmit" data-invoiceid="<?php echo $invoiceDetail[0]['id']; ?>">確定</button>

                          <button type="button" class="btn  px-5  custombutton" id="btnVoidConfirmCloseSubmit">關閉
                          </button>
                          </div>
                      </div>
                      <input type="hidden" class="form-control" id="inputadminid" placeholder="">
                      </form>
                  </div>
                  <!-- <div class="modal-footer">
                      <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                      <button type="button" class="btn btn-primary">Save changes</button>
                  </div> -->
                  </div>
              </div>
              </div>
              <script type="text/javascript">



              </script>
              <!-- end delete modal -->
            <?php } //if($pagemethod=="edit"){?>

              <script>

              </script>

              <div class="modal fade" id="pickupModalCenter" tabindex="-1" role="dialog" aria-labelledby="pickupModalCenterTitle" aria-hidden="true">
              <div class="modal-dialog modal-dialog-centered  " role="document" style="max-width: 800px;">
                  <div class="modal-content px-3">
                  <!-- <div class="modal-header">
                      <h5 class="modal-title" id="exampleModalLongTitle">Modal title</h5>
                      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                      <span aria-hidden="true">&times;</span>
                      </button>
                  </div> -->
                  <div class="modal-body ">
                       <h5 >預約已購買的服務</h5>
                       <div id="prepaid-services-sub">
                <!-- <p style="color:blue;">1</p> -->
               <!--  <table id="prepaid-services-table" class="display table table1 dataTable no-footer"><thead><tr><th></th><th>服務編號</th><th>服務種類</th><th>服務項目</th><th>工數</th><th>售價</th><th>購買次數</th><th>剩除次數</th><th>沒有積分回贈</th></tr></thead><tbody><tr data-id="7" data-available_qty="10"><td><input class="checkbox-check" type="checkbox" style="position: relative;left: 20px;top: 8px;opacity: 1;"></td><td>T-001</td><td>T - 療程</td><td>皮秒二代(全臉)</td><td>1</td><td>$1,980.00</td><td>10</td><td>10</td><td></td></tr></tbody></table> -->

              </div>


                      <h5>預約新服務</h5>

                      <!-- search row -->
                      <!-- <input type="text" id="myInput" onkeyup="myFunction()" placeholder="  輸入關鍵字搜尋" title="  輸入關鍵字搜尋"> -->

                       <span class="d-block d-md-block">
                <div class="input-group   mt-1 mr-3 ml-auto  " style="float: right;">
                <input type="search" id="myInput" placeholder="  輸入關鍵字搜尋" aria-describedby="button-addon5" class="form-control " style="max-width:80vw;" onkeyup="myFunction()">
                <div class="input-group-append">
                  <button id="button-addon5" type="submit" class="btn btn-outline-secondary customsearch"><svg class="svg-inline--fa fa-search fa-w-16" style="color: #e67358;" aria-hidden="true" data-prefix="fa" data-icon="search" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" data-fa-i2svg=""><path fill="currentColor" d="M505 442.7L405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 9.4 33.9 0l28.3-28.3c9.4-9.4 9.4-24.6.1-34zM208 336c-70.7 0-128-57.2-128-128 0-70.7 57.2-128 128-128 70.7 0 128 57.2 128 128 0 70.7-57.2 128-128 128z"></path></svg><!-- <i class="fa fa-search" style="color:#7d4495"></i> --></button>
                </div>
                </div>
            </span>
                      <script>

                      function myFunction() {
                        var input, filter, table, tr, td, i, txtValue,find;
                        input = document.getElementById("myInput");
                        filter = input.value.toUpperCase();
                        table = document.getElementById("new-services-table");
                        tr = table.getElementsByTagName("tr");
                        for (i = 1; i < tr.length; i++) {
                          td1 = tr[i].getElementsByTagName("td")[1];
                          td2 = tr[i].getElementsByTagName("td")[2];
                          td3 = tr[i].getElementsByTagName("td")[3];
                          td4 = tr[i].getElementsByTagName("td")[4];
                          td5 = tr[i].getElementsByTagName("td")[5];
                          td6 = tr[i].getElementsByTagName("td")[6];
                          find=false;
                          if (td1) {
                            txtValue = td1.textContent || td1.innerText;
                            if (txtValue.toUpperCase().indexOf(filter) > -1) {
                              find=true;
                              // tr[i].style.display = "";
                            } else {
                              //tr[i].style.display = "none";
                            }
                          }
                          if (td2) {
                            txtValue = td2.textContent || td2.innerText;
                            if (txtValue.toUpperCase().indexOf(filter) > -1) {
                              find=true;
                              // tr[i].style.display = "";
                            } else {
                              //tr[i].style.display = "none";
                            }
                          }
                          if (td3) {
                            txtValue = td3.textContent || td3.innerText;
                            if (txtValue.toUpperCase().indexOf(filter) > -1) {
                              find=true;
                              // tr[i].style.display = "";
                            } else {
                              //tr[i].style.display = "none";
                            }
                          }
                          if (td4) {
                            txtValue = td4.textContent || td4.innerText;
                            if (txtValue.toUpperCase().indexOf(filter) > -1) {
                              find=true;
                              // tr[i].style.display = "";
                            } else {
                              //tr[i].style.display = "none";
                            }
                          }
                          if (td5) {
                            txtValue = td5.textContent || td5.innerText;
                            if (txtValue.toUpperCase().indexOf(filter) > -1) {
                              find=true;
                              // tr[i].style.display = "";
                            } else {
                              //tr[i].style.display = "none";
                            }
                          }
                          if (td6) {
                            txtValue = td6.textContent || td6.innerText;
                            if (txtValue.toUpperCase().indexOf(filter) > -1) {
                              find=true;
                              // tr[i].style.display = "";
                            } else {
                              //tr[i].style.display = "none";
                            }
                          }
                          if(find===true){
                            tr[i].style.display = "";
                          }else{
                             tr[i].style.display = "none";
                          }
                        }
                      }
                      </script>
                      <!-- end search row -->

                      <div id="new-services-sub">
                      請先選擇客戶
                      </div>


                       <form>


                     <!--  <div class="form-group row">
                          <label for="inputRePassword" class="col-sm-12 "><span style="color:#7d4495;" >確定删除</span><span id="deletenum" style="color:#7d4495;"></span><span style="color:#7d4495;" >個房間?</span></label>

                          <span id="deletemsg" class="text-center"></span>
                      </div> -->
                      <!-- <div class="form-group row">
                          <div class="col-sm-12">
                          <p style="font-size: 12px;"><span style="color:#616161">*為必填項目<br>登入名稱為英文字或數字組成(不分大小寫)</span></p>
                          <span id="editmsg" class="text-center"></span>
                           </div>
                      </div> -->
                      <div class="form-group row">
                          <div class="col-sm-12 text-center">
                          <button type="button" class="btn  px-5  custombutton" id="btnPickUpSubmitButton2">確定</button>
                          <button type="button" class="btn  px-5  custombutton" id="btnCloseSubmit">關閉</button>
                          </div>
                      </div>
                      <input type="hidden" class="form-control" id="inputadminid" placeholder="">
                      </form>
                  </div>
                  <!-- <div class="modal-footer">
                      <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                      <button type="button" class="btn btn-primary">Save changes</button>
                  </div> -->
                  </div>
              </div>
              </div>
              <script type="text/javascript">



              </script>
              <!-- end pickup modal -->



          <!-- Page Content  -->
          <div id="content" style="background-color: #ffffff;">

            <!-- <div id="myDialog">
    This is the content of my modal dialog box
    <input type="text" id="myTextBox" />
</div>

<button id="clickMe">Click Me</button> -->


            <div style="" class="menubar2  p-2">
             <a href="/at-cms/brinvoiceadmin"> <i class="fas fa-chevron-left" style=" display: inline-block;
/*  border-radius: 10px;
  box-shadow: 0px 0px 2px #888;*/
  color: #957c78;
  padding: 2px 2px;"></i>返回</a>
  </div>
              <!-- add button -->
              <?php
if ($pagemethod == "add") {
	?>
              <h5>發票收據管理</h5>
               <?php
}
?>
              <?php
if ($pagemethod == "edit") {
	?>
              <h5>發票收據管理-更改</h5>
               <?php
}
?>
              <?php
if ($pagemethod == "detail") {
	?>
              <h5>發票收據管理-發票資料</h5>
               <?php
}
?>
              <!-- input form -->
              <form >

        <!--         <select class="selectpicker" data-live-search="true" data-width="auto">
  <option data-tokens="ketchup mustard">Hot Dog, Fries and a Soda</option>
  <option data-tokens="mustard">Burger, Shake and a Smile</option>
  <option data-tokens="frosting">Sugar, Spice and all things nice</option>
</select> -->


                <!-- added invoice date at 2020-11-13 -->
                <?php
if ($pagemethod == 'add') {
	?>
                <div class="form-group row">
                <label for="user_id" class="col-sm-2 col-form-label">發票日期</label>
                <div class="col-sm-10">
                <div class="input-group "  style="width: 276px;">

                            <input type="text" class="form-control" id="invoicedate" width="" name="invoicedate" value="<?php echo date("Y-m-d"); ?>" data-type="datepicker" data-guid="a301c1ee-3420-1d33-ff63-751e72feaad5" data-datpicker="truee" role="input" day="<?php echo date("Y-m-d"); ?>"  >
                            <div class="input-group-prepend">
                              <span class="input-group-text" id="basic-addon1"><i class="fas fa-calendar-alt"></i></span>
                            </div>
                          </div>

                             <script>
                                $('#invoicedate').datepicker({
                                    uiLibrary: 'bootstrap4',
                                    format: 'yyyy-mm-dd'
                                });
                            </script>
                            <div class="valid-feedback">正確</div>
                            <div class="invalid-feedback">没有资料</div>
                    </div>
                  </div>

                <?php
} //if($pagemethod=='add'){
?>
                 <!-- end invoice date at 2020-11-13 -->



                <!-- added customer list -->
                <div class="form-group row">
                <label for="user_id" class="col-sm-2 col-form-label">現有客戶</label>
                <div class="col-sm-10">
                  <select class="user_idselect selectpicker form-control"  data-live-search="true" data-width="auto" id="user_id" name="user_id" <?php
if ($pagemethod == 'edit'
) {echo 'disabled="disabled"';}?>>
                     <!--  <select class="chosen user_idselect form-control" style="width:300px;" id="user_id" name="user_id" <?php
// if($pagemethod=='edit'
// ){ echo 'disabled="disabled"';}?>> -->
                  <option value>--</option>
                  <?php foreach ($customerlist as $customerrow) {
	?>
                    <option data-content="<?php
$name = "";
	$printname = false;

	if (!empty($customerrow->chi_name) && $printname == false) {
		$printname = true;
		$name = $customerrow->chi_name;
	}

	if (!empty($customerrow->display_name) && $printname == false) {
		$printname = true;
		$name = $customerrow->display_name;
	}
	echo $name;
	echo "<br>";
	if (!empty($customerrow->mobile)) {
		echo " ";
		echo "(";
		echo $customerrow->mobile;
		echo ")";
	}?>" value="<?php echo $customerrow->id; ?>"
                    <?php
//for add method & select user id
	if ($pagemethod == 'add') {
		if (!empty($user_id)) {
			if ($user_id == $customerrow->id) {
				echo 'selected="selected"';
			}
		}
	}
	if ($pagemethod == 'edit') {
		if ($invoiceDetail[0]['user_id'] == $customerrow->id) {
			echo 'selected="selected"';
		}
	}
	?> ><?php
$name = "";
	$printname = false;

	if (!empty($customerrow->chi_name) && $printname == false) {
		$printname = true;
		$name = $customerrow->chi_name;
	}

	if (!empty($customerrow->display_name) && $printname == false) {
		$printname = true;
		$name = $customerrow->display_name;
	}
	echo $name;
	echo "<br>";
	if (!empty($customerrow->mobile)) {
		echo " ";
		echo "(";
		echo $customerrow->mobile;
		echo ")";
	}?></option>
                  <?php
} //php foreach ($customers as $customerrow){ ?>


                  </select>

                  <script type="text/javascript">
                  // $("#user_id").chosen({search_contains: true});
                  </script>
                  <div class="valid-feedback">正確</div>
                  <div class="invalid-feedback">没有资料或密碼和登入密碼不同</div>
                </div>
              </div>
               <?php
if ($pagemethod == "add") {
	?>
              <div class="form-group row">
                <label for="display_name" class="col-sm-2 col-form-label">客戶名稱</label>
                <div class="col-sm-10">
                  <input type="text" class="form-control" id="display_name" name="display_name"  value="" placeholder="" >
                  <div class="valid-feedback">正確</div>
                  <div class="invalid-feedback">没有资料</div>
                </div>
              </div>

              <?php

}
?>

              <?php
if ($pagemethod == "add") {
	?>
              <div class="form-group row">
                <label for="mobile" class="col-sm-2 col-form-label">客戶電話</label>
                <div class="col-sm-10">
                  <input type="text" class="form-control" id="mobile" name="mobile"  value="" placeholder="">
                  <div class="valid-feedback">正確</div>
                  <div class="invalid-feedback">没有资料</div>
                </div>
              </div>

              <?php

}
?>

              <!-- theraphist -->
              <div class="form-group row">
                <label for="pic_1" class="col-sm-2 col-form-label">美容師</label>
                <div class="col-sm-10">

                   <select class="chosen form-control" style="width:300px;" id="pic_1" name="pic_1" <?php
if ($pagemethod == 'edit') {echo 'disabled="disabled"';}?>>
                  <option value>--</option>
                  <?php foreach ($therapistlist as $therapistrow) {
	?>
                    <option value="<?php echo $therapistrow->id; ?>" <?php
if ($pagemethod == 'edit') {
		if ($invoiceDetail[0]['therapist_id'] == $therapistrow->id) {
			echo 'selected="selected"';
		}
	}
	?>><?php

	echo $therapistrow->username;

	?></option>
                  <?php
} //php foreach ($customers as $customerrow){ ?>


                  </select>
                  <div class="valid-feedback">正確</div>
                  <div class="invalid-feedback">没有资料</div>
                </div>
              </div>

              <!-- end theraphist -->

              <!-- theraphist2 -->
              <div class="form-group row">
                <label for="pic_1" class="col-sm-2 col-form-label">美容師2</label>
                <div class="col-sm-10">

                   <select class="chosen form-control" style="width:300px;" id="pic_2" name="pic_2" <?php
if ($pagemethod == 'edit') {echo 'disabled="disabled"';}?>>
                  <option value>--</option>
                  <?php foreach ($therapistlist as $therapistrow) {
	?>
                    <option value="<?php echo $therapistrow->id; ?>" <?php
if ($pagemethod == 'edit') {
		if ($invoiceDetail[0]['therapist2_id'] == $therapistrow->id) {
			echo 'selected="selected"';
		}
	}
	?>><?php

	echo $therapistrow->username;

	?></option>
                  <?php
} //php foreach ($customers as $customerrow){ ?>


                  </select>
                  <div class="valid-feedback">正確</div>
                  <div class="invalid-feedback">没有资料</div>
                </div>
              </div>

              <!-- end theraphist2 -->

              <!-- consultant list -->
               <div class="form-group row">
                <label for="consultant_1" class="col-sm-2 col-form-label">顧問</label>
                <div class="col-sm-10">

                   <select class="chosen form-control" style="width:300px;" id="consultant_1" name="consultant_1" <?php
if ($pagemethod == 'edit') {echo 'disabled="disabled"';}?>>
                  <option value>--</option>
                  <?php foreach ($consultantlist as $consultantrow) {
	?>
                    <option value="<?php echo $consultantrow->id; ?>" <?php
if ($pagemethod == 'edit') {
		if ($invoiceDetail[0]['consultant_id'] == $consultantrow->id) {
			echo 'selected="selected"';
		}
	}
	?>><?php

	echo $consultantrow->username;

	?></option>
                  <?php
} //php foreach ($customers as $customerrow){ ?>


                  </select>
                  <div class="valid-feedback">正確</div>
                  <div class="invalid-feedback">没有资料</div>
                </div>
              </div>
              <!-- end consultant list -->


              <!-- end customer list -->

            <!--   <div class="form-group row">
                <label for="shortcode" class="col-sm-2 col-form-label">門店簡稱*</label>
                <div class="col-sm-10">
                  <input type="text"  class="form-control" id="shortcode" name="shortcode" value="<?php
if ($pagemethod == "edit" || $pagemethod == "detail") {
	echo $shopdetails->shortcode;
}
?>" placeholder="輸入門店簡稱" <?php if ($pagemethod == "detail") {echo "readonly";}?> >
                  <div class="valid-feedback">正確</div>
                  <div class="invalid-feedback">没有资料</div>
                </div>
              </div> -->
            <!--   <div class="form-group row">
                <label for="code" class="col-sm-2 col-form-label">門店長寫</label>
                <div class="col-sm-10">
                  <input type="text" class="form-control" id="code" name="code" value="<?php
if ($pagemethod == "edit" || $pagemethod == "detail") {
	echo $shopdetails->code;
}
?>" <?php if ($pagemethod == "detail") {echo "readonly";}?>>
                  <div class="valid-feedback">正確</div>
                  <div class="invalid-feedback">没有资料</div>
                </div>
              </div> -->
            <!--   <div class="form-group row">
                <label for="name" class="col-sm-2 col-form-label">門店中文名</label>
                <div class="col-sm-10">
                  <input type="text" class="form-control" id="name" name="name" value="<?php
if ($pagemethod == "edit" || $pagemethod == "detail") {
	echo $shopdetails->name;
}
?>" <?php if ($pagemethod == "detail") {echo "readonly";}?>>
                  <div class="valid-feedback">正確</div>
                  <div class="invalid-feedback">没有资料或密碼和登入密碼不同</div>
                </div>
              </div>
   -->


  <!--             <div class="form-group row">
                <label for="inputPassword" class="col-sm-2 col-form-label">備註</label>
                <div class="col-sm-10">
                  <textarea  type="text" class="form-control" id="remark" name="remark" rows="4" cols="50" placeholder="輸入備註"></textarea>
                </div>
              </div>
   -->
            <!--   <div class="form-group row">
                          <div class="col-sm-12">
                          <p style="font-size: 12px;"><span style="color:#616161">*為必填項目<br>登入名稱為英文字或數字組成(不分大小寫)</span></p>
                          <span id="newmsg" class="text-center"></span>
                           </div>
              </div> -->




              <!-- for printing selected service -->
              <div id="selected-services-sub">
                <!-- <p style="color:blue;">1</p> -->
               <!--  <table id="prepaid-services-table" class="display table table1 dataTable no-footer"><thead><tr><th></th><th>服務編號</th><th>服務種類</th><th>服務項目</th><th>工數</th><th>售價</th><th>購買次數</th><th>剩除次數</th><th>沒有積分回贈</th></tr></thead><tbody><tr data-id="7" data-available_qty="10"><td><input class="checkbox-check" type="checkbox" style="position: relative;left: 20px;top: 8px;opacity: 1;"></td><td>T-001</td><td>T - 療程</td><td>皮秒二代(全臉)</td><td>1</td><td>$1,980.00</td><td>10</td><td>10</td><td></td></tr></tbody></table> -->

              </div>

              <!-- end for printing selected service -->



              <!-- for edit invoice detail -->
              <?php if ($pagemethod == "edit" || $pagemethod == "detail") {
	?>
                <div id="selected-services-sub">
                  <h5 class="modal-title sales">銷售</h5>

                  <table id="packages" class="display table dataTable no-footer payment-record">
                    <thead><tr><th style="width:5%">套票</th><th style="width:35%">項目</th><th style="width:15%">實價($)</th><th style="width:15%">數量</th><th style="width:15%">折扣(%)</th><th style="width:15%">收費</th></tr></thead>

                    <tbody>
                      <?php
$count = 0;
	foreach ($invoiceItemDetail as $invoiceItemDetailRow) {

		$inputRemark = "";
		if (!empty($invoiceItemDetailRow->remark)) {
			$inputRemark = " (" . $invoiceItemDetailRow->remark . ") ";
		}
		?>
                      <tr data-id="13" data-available_qty="undefined">
                        <td>
                          <input class="selectproduct3" type="checkbox" name="addticketid" id="addticketid" value="<?php echo $invoiceItemDetailRow->id; ?>" data-price="undefined"
                          <?php
if ($invoiceItemDetailInService[$count] == 1) {
			echo "checked";
		}
		?>

                          disabled="disabled"
                          >
                        </td>
                        <td>

                          <input type="hidden" class="form-control text-center ui-autocomplete-input ui-autocomplete-loading" name="product_id[]" id="product_id-<?php echo $count; ?>" autocomplete="off" value="13">
                          <input type="text" class="form-control text-center ui-autocomplete-input ui-autocomplete-loading" name="product_name[]" placeholder="Enter Product name or Code" id="productname-<?php echo $count; ?>" autocomplete="off" value="<?php echo $invoiceItemDetailRow->item_name . $inputRemark; ?>" readonly=""></td>
                        <td>
                            <input type="text" class="form-control req prc" name="product_price[]" id="price-<?php echo $count; ?>" onkeypress="return isNumber(event)" onkeyup="rowTotal('<?php echo $count; ?>'), billupyog()" autocomplete="off" value="<?php echo $invoiceItemDetailRow->price; ?>" <?php
if ($pagemethod == 'edit') {echo 'readonly';}?>>
                        </td>
                        <td>
                          <input type="text" class="form-control req amnt" name="product_qty[]" id="amount-<?php echo $count; ?>" onkeypress="return isNumber(event)" onkeyup="rowTotal('<?php echo $count; ?>'),billupyog()" autocomplete="off" value="<?php echo $invoiceItemDetailRow->qty; ?>"  <?php
if ($pagemethod == 'edit') {echo 'readonly';}?>>
                        </td>
                        <td><input type="text" class="form-control discount" name="product_discount[]" onkeypress="return isNumber(event)" id="discount-<?php echo $count; ?>" onkeyup="rowTotal('<?php echo $count; ?>'), billupyog()" autocomplete="off" value="<?php echo $invoiceItemDetailRow->discount; ?>"  <?php
if ($pagemethod == 'edit') {echo 'readonly';}?>>
                        </td>
                        <td><?php echo $invoiceItemDetailRow->amount; ?><input type="hidden" name="disca[]" id="disca-<?php echo $count; ?>" value="0.00">
                          <input type="hidden" class="ttInput" name="product_subtotal[]" id="total-<?php echo $count; ?>" value="<?php echo $invoiceItemDetailRow->amount; ?>" >

                        </td>
                      </tr>




                      <?php
$count++;
	} //foreach ($invoiceItemDetail as $invoiceItemDetail) {
	?>
                    </tbody>
                  </table>

                  <table id="packages-pay" class="" style="margin-top: 25px; width: 100%;"><tbody><!-- <tr><td style="width: 20%; text-align: right; padding-right: 10px; line-height: 35px;">優惠碼:</td><td style="width: 18%; text-align: center;" id="discountCode"><input class="form-control" type="text" style="display: inline-block; width: auto; min-height: auto; height: 35px; padding: 6px; text-align: center; background: #ddf0f4;" data-value="" /></td></tr><tr><td style="width: 82%; text-align: right; padding-right: 10px; line-height: 35px;">請輸入加入優惠碼的原因:</td><td style="width: 18%; text-align: center;" id="discountReason"><input class="form-control" type="text" style="display: inline-block; width: auto; min-height: auto; height: 35px; padding: 6px; text-align: center; background: #ddf0f4;" data-value="" /></td></tr> -->

                    <tr><td style="width: 82%; text-align: right; padding-right: 10px; line-height: 35px;">應繳款項總額:</td><td style="width: 18%; text-align: center; border-bottom: double #333;" id="totalAmountDue"> <?php
echo $invoiceDetail[0]['total_amount_due'];
	?></td></tr>

                  </tbody></table>

              </div>
              <?php }?>

              <!-- end for edit invoice detail -->


              <!-- for display customer point -->
              <div id="customer_point">
              </div>
              <?php if ($pagemethod == "edit" || $pagemethod == "detail") {?>
                <div id="customer_point">
                 <h5 class="modal-title ">客戶積分: <?php echo $customerpoint; ?></h5>
                </div>
              <?}?>
              <!-- end for display customer point -->

              <!-- payment -->

              <div  id="payment-services-sub">
                    <!-- for edit payment -->
                    <?php if ($pagemethod == "edit" || $pagemethod == "detail") {
	?>
                        <h5 class="modal-title sales">確認付款</h5>


                          <!-- added payment at 2020-11-13 -->
              <div class="form-group row">
                          <div class="col-sm-3 text-center mas-title">
                            <label for="s2id_autogen4">付款日期</label>
                          </div>
                          <div class="col-sm-9 max-box initialized">

                            <div class="input-group "  style="width: 276px;">

                            <input type="text" class="form-control" id="paymentdate" width="" name="paymentdate" value="<?php

	if ($invoiceDetail[0]['invoice_status'] == 'paid') {
		echo date('Y-m-d', $invoiceDetail[0]['issued_date']);
	}
	if ($invoiceDetail[0]['invoice_status'] == 'open') {
		echo date("Y-m-d");
	}

	?>" data-type="datepicker" data-guid="a301c1ee-3420-1d33-ff63-751e72feaad5" data-datpicker="true" role="input" day="<?php

	if ($invoiceDetail[0]['invoice_status'] == 'paid') {
		echo date('Y-m-d', $invoiceDetail[0]['issued_date']);
	}
	if ($invoiceDetail[0]['invoice_status'] == 'open') {
		echo date("Y-m-d");
	}

	?>" <?php
if ($pagemethod == 'edit' && $invoiceDetail[0]['invoice_status'] == 'paid') {echo 'readonly';}?>  >
                            <div class="input-group-prepend">
                              <span class="input-group-text" id="basic-addon1"><i class="fas fa-calendar-alt"></i></span>
                            </div>
                          </div>

                             <script>
                                $('#paymentdate').datepicker({
                                    uiLibrary: 'bootstrap4',
                                    format: 'yyyy-mm-dd'
                                });
                            </script>
                            <div class="valid-feedback">正確</div>
                            <div class="invalid-feedback">没有资料</div>
                          </div>
                </div>

              <!-- end added payment at 2020-11-13 -->


                        <?php

	$count = 1;
	foreach ($invoicePayment as $invoicePaymentRow) {

		?>


                        <div class="form-group row">
                          <div class="col-sm-3 text-center mas-title">
                            <label for="s2id_autogen4">付款方式 <?php echo $count; ?></label>
                          </div>
                          <div class="col-sm-9 mas-box initialized">
                            <select id="payment_type_<?php echo $count; ?>" class="select mas-select select2-offscreen form-control" name="payment_type_<?php echo $count; ?>" tabindex="-1" <?php
if ($pagemethod == 'edit' && $invoiceDetail[0]['invoice_status'] == 'paid') {echo 'disabled="disabled"';}?>>
                              <option value="" <?php if ($invoicePaymentRow->payment_type == "") {echo "selected";}?>>--</option>
                              <option value="1" <?php if ($invoicePaymentRow->payment_type == "1") {echo "selected";}?>>現金</option>
                              <option value="2" <?php if ($invoicePaymentRow->payment_type == "2") {echo "selected";}?>>Jarvix</option>
                              <option value="3" <?php if ($invoicePaymentRow->payment_type == "3") {echo "selected";}?>>EPS</option>
                              <option value="4" <?php if ($invoicePaymentRow->payment_type == "4") {echo "selected";}?>>CUP</option>
                              <option value="5" <?php if ($invoicePaymentRow->payment_type == "5") {echo "selected";}?>>VISA</option>
                              <option value="6" <?php if ($invoicePaymentRow->payment_type == "6") {echo "selected";}?>>MASTER</option>
                              <option value="7" <?php if ($invoicePaymentRow->payment_type == "7") {echo "selected";}?>>use packages</option>
                              <option value="8" <?php if ($invoicePaymentRow->payment_type == "8") {echo "selected";}?>>HSBC 分期</option>
                              <option value="9" <?php if ($invoicePaymentRow->payment_type == "9") {echo "selected";}?>>FPS</option>
                              <option value="10" <?php if ($invoicePaymentRow->payment_type == "10") {echo "selected";}?>>Payme</option>
                              <option value="11" <?php if ($invoicePaymentRow->payment_type == "11") {echo "selected";}?>>積分</option>
                            </select>
                          </div>
                        </div>
                        <div class="form-group row">
                          <div class="col-sm-3 text-center mas-title">
                            <label for="payment_amount_<?php echo $count; ?>">款項</label>
                          </div>
                          <div class="col-sm-9 mas-box">
                            <input id="payment_id_<?php echo $count; ?>" type="hidden" class="form-control mas-input" name="payment_id_<?php echo $count; ?>" value="<?php echo $invoicePaymentRow->id; ?>" >

                            <input id="payment_amount_<?php echo $count; ?>" type="text" class="form-control mas-input" name="payment_amount_<?php echo $count; ?>" value="<?php echo $invoicePaymentRow->payment_amount; ?>" <?php
if ($pagemethod == 'edit' && $invoiceDetail[0]['invoice_status'] == 'paid') {echo 'readonly';}?>>
                          </div>
                        </div>
                        <?php
$count = $count + 1;
	} //foreach ($invoicePayment as $invoicePaymentRow) {

	?>

                    <?php } //if($pagemethod=="edit" || $pagemethod=="detail"){  ?>
                    <!-- end for edit payment  -->
              </div>


              <!-- end payment -->



              <div class="form-group row">
                          <div class="col-sm-12 text-center">
                        <?php
if ($pagemethod == "add") {?>

                            <button type="button" class="btn  px-5  custombutton mt-2" id="btnPickUpSubmit">選擇療程服務</button>

                          <!-- <button type="button" class="btn  px-5  custombutton" id="btnSubmit">確定</button> -->
                           <?php
} //if($pagemethod=="add"){?>
                            <?php
if ($pagemethod == "add") {?>
                            <button type="button" class="btn  px-5  custombutton mt-2" id="btnInvoiceSubmit">列印發票</button>
                            <?php
} //if($pagemethod=="add"){?>





                          <?php
if ($pagemethod == 'edit' && $invoiceDetail[0]['invoice_status'] == 'open') {?>
                          <button type="button" class="btn  px-5  custombutton mt-2" id="btnUpdateInvoicePaymentSubmit" data-invoiceid="<?php echo $invoiceDetail[0]['id']; ?>">
                              確認付款
                            </button>
                          <?php
} //if($pagemethod=='edit' && $invoiceDetail[0]['invoice_status'] == 'open'){
?>

                           <?php
if ($pagemethod == "edit") {
	?>
                            <button type="button" class="btn  px-5  custombutton mt-2" id="btnUpdateInvoiceSubmit" data-invoiceid="<?php echo $invoiceDetail[0]['id']; ?>">
                              列印發票
                            </button>

                            <button type="button" class="btn  px-5  custombutton mt-2" id="btnUpdateReceiptSubmit" data-invoiceid="<?php echo $invoiceDetail[0]['id']; ?>">
                              列印收據
                            </button>


                            <!-- not do function -->
                            <button type="button" class="btn  px-5  custombutton mt-2" id="btnUpdateRefundSubmit" data-invoiceid="<?php echo $invoiceDetail[0]['id']; ?>">
                              退換發票
                            </button>
                            <?php
if ($this->session->userdata('brinvoice_delete') == true) {
		?>
                            <button type="button" class="btn  px-5  custombutton mt-2" id="btnUpdateVoidSubmit" data-invoiceid="<?php echo $invoiceDetail[0]['id']; ?>">
                              Void
                            </button>
                            <?php
} //if($this->session->userdata('brinvoice_delete')==true){
	?>
                            <!--end not do function -->
                            <?php
} //if($pagemethod=="edit"){?>
                          <?php
// if($pagemethod=="edit"){
if (false) {

	?>
                            <!--  <input type="hidden" class="form-control" id="id" name="id" placeholder="" value="<?php echo
	$shopdetails->id;
	?>"> -->
                            <button type="button" class="btn  px-5  custombutton mr-5" id="btnResetUpdate" onClick="window.location.reload();">重設</button>
                            <button type="button" class="btn  px-5  custombutton" id="btnUpdate">更改</button>
                          <?php
} //if($pagemethod=="edit"){?>
                          <?php
if ($pagemethod == "details") {?>

                          <?php
} //if($pagemethod=="edit"){?>


                          </div>
              </div>
              <div class="form-group row">
                          <div class="col-sm-12 text-center">
              <span id="newmsg" class="text-center"></span>
                          </div>
              </div>


            </form>
            <!-- end input form -->

              <!-- end add button -->


          </div>
      </div>


      <script type="text/javascript">
          $(document).ready(function () {
              $('#sidebarCollapse').on('click', function () {
                  $('#sidebar').toggleClass('active');
              });

              // password click
              bootstrapRevealPassword();

  // Plugin to integrate in your javascript file
              function bootstrapRevealPassword() {
              $('[data-password]').closest('.form-group').addClass('position-relative').append('<span class="form-password-icon"><i class="material-icons">visibility_off</i></span>');

              $('.form-password-icon').on('click', function() {
                  var clicks = $(this).data('clicks');
                  if (clicks) {
                  // odd clicks
                  $(this).html('<span class="input-group-text "><i class="fas fa-eye-slash"></i></span>').prevAll(':input').attr('type', 'password');
                  } else {
                  // even clicks
                  $(this).html('<span class="input-group-text "><i class="fas fa-eye"></i></span>').prevAll(':input').attr('type', 'text');
                  }
                  $(this).data("clicks", !clicks);
              });
              }

              // end password click

          });
      </script>
  </body>

  </html>