
<style>
  /* Base Styling */
  .payment-modal {
    border-radius: 18px;
    overflow: hidden;
    box-shadow: 0 10px 30px rgba(0,0,0,0.15);
  }

  .payment-header {
    background: #f8fbfc;
    padding: 1.5rem;
    border-bottom: 2px solid #e0f0f3;
    text-align: center;
  }

  .merchant-logo {
    height: 65px;
    margin-bottom: 1rem;
    filter: drop-shadow(0 2px 4px rgba(84,165,175,0.1));
  }

  .modal-title {
    color: #2a626b;
    font-size: 1.5rem;
    font-weight: 700;
    letter-spacing: -0.5px;
  }

  /* Amount Display */
  .amount-section {
    background: #54A5AF15;
    padding: 1.2rem;
    margin: 0 1.5rem;
    border-radius: 12px;
    border: 2px dashed #54A5AF40;
  }

  .total-amount {
    color: #2a626b;
    font-size: 1.8rem;
    font-weight: 800;
    margin: 0;
  }

  .amount-label {
    color: #678c93;
    font-size: 0.95rem;
    margin-bottom: 0.5rem;
  }

  /* Payment Options Grid */
  .payment-grid {
    display: flex;
    flex-direction: column;
    /* grid-template-columns: repeat(1, 1fr); */
    gap: 1rem;
    padding: 1.5rem;
  }

  .payment-card {
    background: white;
    border: 2px solid #e0f0f3;
    border-radius: 14px;
    padding: 1.5rem;
    cursor: pointer;
    transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
    position: relative;
  }

  .payment-card:hover {
    transform: translateY(-3px);
    border-color: #54A5AF;
    box-shadow: 0 6px 20px rgba(84,165,175,0.1);
  }

  .payment-card.active {
    border-color: #54A5AF;
    background: #f8fbfc;
  }

  .payment-icon {
    font-size: 2.2rem;
    color: #54A5AF;
    margin-bottom: 1rem;
  }

  .payment-label {
    color: #2a626b;
    font-weight: 700;
    margin-bottom: 0.5rem;
  }

  .payment-description {
    color: #678c93;
    font-size: 0.9rem;
    line-height: 1.4;
  }

  /* Footer Actions */
  .modal-footer {
    background: #f8fbfc;
    padding: 1.2rem;
    display: flex;
    justify-content: space-between;
    border-top: 2px solid #e0f0f3;
  }

  .btn-cancel {
    background: transparent;
    border: 2px solid #e0f0f3;
    color: #678c93;
    padding: 0.8rem 1.5rem;
    border-radius: 10px;
    font-weight: 600;
    transition: all 0.2s ease;
  }

  .btn-cancel:hover {
    border-color: #ff4757;
    color: #ff4757;
  }

  .btn-proceed {
    background: transparent;
    border: 2px solid #e0f0f3;
    color: #678c93;
    padding: 0.8rem 1.5rem;
    border-radius: 10px;
    font-weight: 600;
    transition: all 0.2s ease;
    cursor: pointer;
  }

  .btn-proceed:hover {
    border-color: #ff4757;
    color: #ff4757;
  }
  .payment-card#read_nfc {
      opacity: 0.6;
      cursor: not-allowed;
  }

  /* Loading Dot */
  .processing-indicator {
    display: flex;
    gap: 6px;
    justify-content: center;
  }

  .processing-dot {
    width: 10px;
    height: 10px;
    background: #2196F3;
    border-radius: 50%;
    animation: bounce 1.4s infinite ease-in-out;
  }

  .processing-dot:nth-child(2) {
    animation-delay: 0.2s;
  }

  .processing-dot:nth-child(3) {
    animation-delay: 0.4s;
  }

  @keyframes bounce {
    0%, 80%, 100% {
        transform: translateY(0);
    }
    40% {
        transform: translateY(-12px);
    }
  }

  #fullpage-loading {
    display: none;
    position: fixed;
    z-index: 9999;
    top: 0; left: 0;
    width: 100vw; height: 100vh;
    background: rgba(0, 0, 0, 0.712);
    align-items: center;
    justify-content: center;
  }
</style>

<!-- loading -->
<div id="fullpage-loading" style="display:none; position:fixed; z-index:9999; top:0; left:0; width:100vw; height:100vh; background:rgba(0,0,0,0.35); align-items:center; justify-content:center;">
  <div>
    <div style="display:flex; gap:10px; justify-content:center;">
      <div class="processing-dot"></div>
      <div class="processing-dot"></div>
      <div class="processing-dot"></div>
    </div>
    <div style="color:white; text-align:center; margin-top:1rem; font-size:1.2rem;">Please Wait...</div>
  </div>
</div>

<!-- nfc modal -->
<div class="modal fade" id="read_modal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true" >
    <div class="modal-dialog read-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header" style="background-color: #54A5AF;padding-top:10px !important;">
                <h4 class="modal-title" id="defaultModalLabel" style="color:#fff;">Customer Detail</h4>
            </div>
            <div class="modal-body">
                <p style="text-align: center; font-weight: bolder; color: black; font-size: larger">Please tap NFC Card or Scan Code</p>
                <div style="text-align: center;">
                    <img src="/image/barcode.png" style="height: 200px">
                    <img src="/image/nfc.png" style="height: 200px"><br>
                </div>
            </div>
            <div class="modal-footer" style="justify-content: center;">
                <button type="button" class="btn btn-danger" id="close" >Cancel</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade payment-modal" id="payment_modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="payment-header">
                <h2 class="modal-title">Payment Options</h2>
        </div>
      <div class="payment-grid">
        <% mmqr = PaymentMethodSetting.find_by(payment_method: 'MMQR') %>
        <% if mmqr.present? && mmqr.is_active %>
            <div class="payment-card" id="dynamic_qr">
            <div class="payment-icon text-center">
                <img src="/image/mmqr.webp" width="100" height="100" />
            </div>
            <div class="payment-label text-center">Click here to pay with MMQR</div>
                <div class="processing-indicator" style="display:none; margin: 1rem 0;">
                <div class="processing-dot"></div>
                <div class="processing-dot"></div>
                <div class="processing-dot"></div>
                </div>
            </div>

            <div class="text-center text-bold text-muted">
                (Or)
            </div>
        <% end %>

        <!-- Read NFC Card -->
        <button type="button" id="read_nfc" data-toggle="modal" data-target="#read_modal">
            <div class="payment-card disabled" id="read_nfc" style="grid-column: span 2;">
              <div class="payment-icon text-center">
                  <img src="/image/nfc.png" width="100" height="100" />
              </div>
              <div class="payment-label text-center">Tap your NFC-enabled card or device</div>
            </div>
        </button>

      </div>

      <div class="modal-footer">
        <button type="button" class="btn-cancel" id="close">
          Cancel
        </button>
      </div>
    </div>
  </div>
</div>

<script defer type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
    const paymentCards = document.querySelectorAll('.payment-card:not(.disabled)');
    const cancelButton = document.querySelector('.btn-cancel');

    $("#read_nfc").on('click', function() {
      $('#payment_modal').css('display', 'none');
      $('.modal-backdrop.fade').css('display', 'none');
    });


    cancelButton.addEventListener('click', function () {
        console.log("Action: Cancel payment.");

        paymentCards.forEach(c => c.classList.remove('active'));

        styleProceedButton(false);
    });

    const disabledNfcCard = document.querySelector('.payment-card.disabled');

    document.querySelector('.payment-card#dynamic_qr').addEventListener('click', function() {
      document.getElementById('fullpage-loading').style.display = 'flex';

      setTimeout(function() {
        document.getElementById('fullpage-loading').style.display = 'none';
      }, 5000);
      precreateDynamicQrPay();
      // initDynamicQrPay();
    });

    function precreateDynamicQrPay() {
        const paymentMethod = 'MMQR';
        const $serverMode = $('#server_mode');
        const $createOrderBtn = $('#create_order');
        const $createPayOrderBtn = $('#create_pay_order');

        const params = {
            order_source: "food_court",
            order_type: "dine_in",
            customer_id: $("#customer_id").text(),
            guest_info: "",
            table_id: $("#table_id").text(),
            order_items: JSON.stringify(get_order_item_rows()),
            create_type: "create_pay",
        };

        modify_order = window.location.href.indexOf("modify_order");
        type = $("#link_type").val();
        if (modify_order !=-1) {
          var ajax_url   = '/foodcourt/food_court/update_modify_order';
          var table_type = $('#table_type').text();
          var table_id    = $('#table_id').text();
          var customer_id = $('#customer_id').text();
          var sale_id     = $('#sale_id').text();
        }else{
          var ajax_url = '/foodcourt/addorders/create';
        }

        var booking_id  = $('#booking_id').text();
        if (booking_id.length > 0) {
          params.booking_id = booking_id;
        }



        $.ajax({
            url: ajax_url,
            method: 'POST',
            contentType: 'application/json',
            headers: {
                'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
            },
            data: JSON.stringify(params),
            success: function(result) {

              if (!result.sale_id) {
                request_bill(0, function(saleId) {
                  window.location.href = `/foodcourt/${saleId}/qrpay/precreate`;
                });
              }else{
                window.location.href = `/foodcourt/${result.sale_id}/qrpay/precreate`;
              }

                if ($serverMode.val() !== "cloud" && $("#display_type").val() === "2") {
                    // customer_display_view(null, "reload");
                }
            },
            error: function(xhr) {
                $('#oqs_loading_wrapper').hide();
                $createOrderBtn.prop('disabled', false);
                $createPayOrderBtn.prop('disabled', false);

                const errorMsg = xhr.status ? `Status: ${xhr.status} - ${xhr.statusText}` : "Network error";
                swal("Error", errorMsg, "error");
            }
        });
    }


    function request_bill(customer_id, callback){
      if (window.location.pathname.includes('foodcourt')) {
        const order_id = $('#order_id').val() || $('#save_order_id').val();
        const data = { 'customer_id': customer_id };

        $.ajax({
          type: "GET",
          url: "/foodcourt/food_court/" + order_id + "/request_bill",
          data: data,
          dataType: "json",
          success: function(data) {
            if(data.status === true) {
              callback(data.sale_id); // ✅ return via callback
            } else {
              swal("Alert!", "Error!", "error");
              location.reload();
            }
          }
        });
      }
    }


    // function initDynamicQrPay() {
    //     const paymentMethod = 'MMQR';
    //     const $serverMode = $('#server_mode');
    //     const $createOrderBtn = $('#create_order');
    //     const $createPayOrderBtn = $('#create_pay_order');

    //     const params = {
    //         order_source: "food_court",
    //         order_type: "dine_in",
    //         customer_id: $("#customer_id").text(),
    //         guest_info: "",
    //         table_id: $("#table_id").text(),
    //         order_items: JSON.stringify(get_order_item_rows()),
    //         create_type: "create_pay",
    //     };

    //     $.ajax({
    //         url: '/foodcourt/addorders/create',
    //         method: 'POST',
    //         contentType: 'application/json',
    //         headers: {
    //             'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
    //         },
    //         data: JSON.stringify(params),
    //         success: function(result) {
    //             const booking_id = result.booking_id;
    //             window.location.href = `/foodcourt/${result.sale_id}/qrpay/init`;
    //             if ($serverMode.val() !== "cloud" && $("#display_type").val() === "2") {
    //                 // customer_display_view(null, "reload");
    //             }
    //         },
    //         error: function(xhr) {
    //             $('#oqs_loading_wrapper').hide();
    //             $createOrderBtn.prop('disabled', false);
    //             $createPayOrderBtn.prop('disabled', false);

    //             const errorMsg = xhr.status ? `Status: ${xhr.status} - ${xhr.statusText}` : "Network error";
    //             swal("Error", errorMsg, "error");
    //         }
    //     });
    // }
  });
</script>
