@include('admin::layouts.header')
<link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css"
    />
    <?php
use App\Models\CustomerDetails;
use App\Models\Products;
use App\Models\GRNS;
?>
<style>
    .big-text{
        font-size: 32px;
    }
    .block-content .block, .block-content .items-push>div, .block-content .push, .block-content p {
    margin-bottom: 0px;
}
.nav-tabs-block {
    background-color: #fff;
    border-bottom: none;
}
.nav-tabs-block .nav-item.show .nav-link, .nav-tabs-block .nav-link.active {
    color: #fff;
    background-color: #2E5FCF;
    border-color: #2E5FCF;
    border-radius: 6px;
}
.nav-tabs-block .nav-item.show .nav-link, .nav-tabs-block .nav-link {
    color: #2E5FCF;
    background-color: #A2BCFA;
    border-color: #A2BCFA;
    border-radius: 6px;
    margin-left:10px;
    margin-right:10px;
}
.keypad {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 5px;
        width: 100%;
        margin-top: 10px;
    }
    .key {
        padding: 10px;
        font-size: 18px;
        cursor: pointer;
        border: 1px solid #ccc;
        background: #f8f9fa;
    }
    .key:hover {
        background: #dcdcdc;
    }
    .key:active {
        background: #a9a9a9;
    }
</style>
<style>
      body {
        background-color: #f8f9fa;
        font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      }
      .category-tab {
        border-radius: 25px;
        padding: 10px 20px;
        font-weight: 600;
        transition: all 0.3s;
        cursor: pointer;
      }
      .category-tab.active {
        background-color: #3366cc !important;
        color: white !important;
      }
      .food-card {
        border-radius: 10px;
        overflow: hidden;
        transition: transform 0.3s;
        cursor: pointer;
        margin-bottom: 20px;
      }
      .food-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
      }
      .food-card img {
        height: 150px;
        object-fit: cover;
        width: 100%;
      }
      .food-price {
        color: #ff6600;
        font-weight: bold;
        font-size: 1.2rem;
      }
      .cart-item {
        border-bottom: 1px solid #eee;
        padding: 10px 0;
      }
      .cart-item-img {
        width: 60px;
        height: 60px;
        object-fit: cover;
        border-radius: 5px;
      }
      .quantity-btn {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        background-color: #f0f0f0;
        border: none;
        cursor: pointer;
      }
      .cart-total {
        font-size: 1.2rem;
        font-weight: bold;
      }
      .discount-badge {
        background-color: #f8f9fa;
        color: #666;
        font-size: 0.8rem;
        padding: 2px 5px;
        border-radius: 3px;
      }
      .clear-cart-btn {
        background-color: #dc3545;
        color: white;
        border: none;
        border-radius: 5px;
        padding: 10px 15px;
        cursor: pointer;
        margin-top: 10px;
      }
      #cart-container {
        max-height: 500px;
        overflow-y: auto;
      }

      /* Ticket Management Styles */
      .ticket-section {
        background-color: white;
        border-radius: 10px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        padding: 15px;
        margin-bottom: 20px;
      }
      .ticket-number {
        font-size: 2.5rem;
        font-weight: bold;
        line-height: 1;
        margin-bottom: 0;
      }
      .ticket-label {
        font-size: 0.8rem;
        color: #666;
      }
      .takeaway-btn {
        background-color: #ffc107;
        color: #212529;
        border: none;
        border-radius: 5px;
        padding: 8px 15px;
        margin-right: 5px;
        font-weight: 500;
      }
      .delivery-btn {
        background-color: #fd7e14;
        color: white;
        border: none;
        border-radius: 5px;
        padding: 8px 15px;
        margin-right: 5px;
        font-weight: 500;
      }
      .table-btn {
        background-color: #00c853;
        color: white;
        border: none;
        border-radius: 5px;
        padding: 8px 15px;
        margin-right: 5px;
        font-weight: 500;
      }
      .add-order-btn {
        background-color: #0d6efd;
        color: white;
        border: none;
        /* border-radius: 50%; */
        width: 140px;
        height: 40px;
        font-size: 1.5rem;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
        border-radius: 8px;
      }
      .customer-dropdown {
        border-radius: 5px;
        border: 1px solid #ced4da;
        padding: 8px 12px;
        width: 100%;
        cursor: pointer;
      }
      .add-customer-btn {
        background-color: #0d6efd;
        color: white;
        border: none;
        border-radius: 5px;
        padding: 8px 15px;
        font-weight: 500;
      }
      .order-type-modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1000;
        align-items: center;
        justify-content: center;
      }
      .order-type-content {
        background-color: white;
        border-radius: 10px;
        padding: 20px;
        width: 400px;
        max-width: 90%;
      }
      .customer-modal {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 1000;
        align-items: center;
        justify-content: center;
      }
      .customer-modal-content {
        background-color: white;
        border-radius: 10px;
        padding: 20px;
        width: 400px;
        max-width: 90%;
      }
      .active-order {
        box-shadow: 0 0 0 3px #0d6efd;
      }
      .search-container {
        position: relative;
        margin-left: auto;
      }
      .search-input {
        border-radius: 25px;
        padding: 10px 15px 10px 40px;
        border: 1px solid #ced4da;
        width: 200px;
      }
      .search-icon {
        position: absolute;
        left: 15px;
        top: 50%;
        transform: translateY(-50%);
        color: #6c757d;
      }
      .toast-container {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 1100;
      }
      .toast {
        background-color: #dc3545;
        color: white;
        padding: 15px 20px;
        border-radius: 5px;
        margin-bottom: 10px;
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        display: flex;
        align-items: center;
        animation: fadeIn 0.3s, fadeOut 0.3s 2.7s;
        opacity: 0;
        max-width: 350px;
      }
      .toast.show {
        opacity: 1;
      }
      @keyframes fadeIn {
        from {
          opacity: 0;
        }
        to {
          opacity: 1;
        }
      }
      @keyframes fadeOut {
        from {
          opacity: 1;
        }
        to {
          opacity: 0;
        }
      }
      #close-tab-btn {
        width: 40px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .order-type-btn.active {
        background-color: #0d6efd;
        color: white;
      }
    </style>
<main id="main-container">



    <div class="content">

        <div class="block block-rounded">
        <div class="ticket-section mb-4">
        <div class="row align-items-center">
          <!-- Ticket Number -->
          <div class="col-md-2 col-sm-3 text-center text-sm-start">
            <h1 class="ticket-number" id="ticket-number"></h1>
            <div class="ticket-label">TKT Number</div>
          </div>

          <!-- Customer Section -->
          <div class="col-md-4 col-sm-9">
            <div class="mb-2">Customer</div>
            <div class="d-flex gap-2">
              <button style="height:40px;" class="add-customer-btn" id="add-customer-btn" data-bs-toggle="offcanvas" data-bs-target="#offcanvasAddCustomer" aria-controls="offcanvasAddCustomer">
                Add Customer
              </button>
              <div class="flex-grow-1">
              <select class="js-select2 form-select" id="customer" name="customer" style="width: 100%;" data-placeholder="Select a customer.." required>
                <?php if(old('customer')) { ?> 
                    <option data-mobile="{{ CustomerDetails::where('user_id', old('customer'))->value('phone') }}" 
                            value="{{ old('customer') }}" selected>
                        {{ CustomerDetails::where('user_id', old('customer'))->value('customer_name').' ('.CustomerDetails::where('user_id', old('customer'))->value('phone').')' }}
                    </option>
                    <?php } ?>
                    <option data-mobile="-" data-discount="0" value="Cash">Cash</option>
                    <?php foreach($customers as $customer) { ?> 
                        <option data-mobile="{{ $customer->customerDetails->phone }}" data-discount="{{ $customer->customerDetails->discount ?? 0 }}" value="{{ $customer->id }}">
                            {{ $customer->customerDetails->customer_name.' ('.$customer->customerDetails->phone.')' }}
                        </option>
                    <?php } ?>
            </select>
            <div id="select-waiter" style="display:none;">
            <div class="mt-2 mb-2">Select Waiter</div>
            <select class="js-select2 form-select" id="waiter" name="waiter" style="width: 100%;" data-placeholder="Select a waiter..">
                <?php if(old('waiter')) { ?> 
                    <option
                            value="{{ old('waiter') }}" selected>
                            {{ old('waiter') }}
                    </option>
                    <?php } ?>
                    <option value="Waiter 1">Waiter 1</option>
                    <option value="Waiter 2">Waiter 2</option>
                    <option value="Waiter 3">Waiter 3</option>
            </select>
            </div>
            <div id="select-rider" style="display:none;">
            <div class="mt-2 mb-2">Select Rider</div>
            <select class="js-select2 form-select" id="rider" name="rider" style="width: 100%;" data-placeholder="Select a rider..">
                <?php if(old('rider')) { ?> 
                    <option
                            value="{{ old('rider') }}" selected>
                            {{ old('rider') }}
                    </option>
                    <?php } ?>
                    <option value="Rider 1">Rider 1</option>
                    <option value="Rider 2">Rider 2</option>
                    <option value="Rider 3">Rider 3</option>
            </select>
            </div>
              </div>
            </div>
          </div>

          <!-- Order Management Buttons -->
          <div class="col-md-6 mt-3 mt-md-0">
            <div
              class="d-flex flex-wrap justify-content-end gap-2"
              id="order-buttons"
            >
              <button class="add-order-btn pb-1" id="add-order-btn">
                Create Invoice +
              </button>
            </div>
          </div>
        </div>
      </div>

      <div class="row">
        <!-- Menu Section -->
        <div class="col-lg-8" id="menu-section">
          <!-- Category Tabs with Search -->
          <div
            class="d-flex justify-content-between align-items-center mb-4"
            id="category-container"
          >
            <div class="d-flex flex-wrap gap-2" id="category-tabs">
              <!-- Categories will be loaded here -->
            </div>
            <div class="search-container">
              <i class="bi bi-search search-icon"></i>
              <input
                type="text"
                class="search-input"
                id="search-input"
                placeholder="Search items..."
              />
            </div>
          </div>
          <!-- Food Items Grid -->
          <div class="row" id="food-items-container">
            <!-- Food items will be loaded here -->
          </div>
        </div>

        <!-- Cart Section -->
        <div class="col-lg-4" id="cart-section" style="display: none">
          <div class="card shadow-sm">
            <div class="card-header bg-white">
              <div class="d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Item List</h5>
                <div class="d-flex gap-3 align-items-center">
                  <span>Qty</span>
                  <span>Price</span>
                </div>
              </div>
            </div>
            <div class="card-body" id="cart-container">
              <!-- Cart items will be loaded here -->
            </div>
            <div class="card-footer bg-white">
              <div
                class="d-flex justify-content-between align-items-center mb-3"
              >
                <span class="fw-bold">Total:</span>
                <span class="cart-total" id="cart-total">0.00</span>
              </div>
              <div class="d-flex gap-2">
                <button class="btn btn-secondary flex-grow-1" id="save-order-btn" >Save</button>
                <button class="btn btn-primary flex-grow-1"  id="bill-order-btn">Payment</button>
                <button class="btn btn-warning" id="close-tab-btn">
                  <i class="bi bi-x-circle"></i>
                </button>
              </div>
              <button
                id="clear-cart-btn"
                class="clear-cart-btn w-100 d-flex justify-content-center align-items-center mt-2"
              >
                <i class="bi bi-trash me-2"></i> Clear Cart
              </button>
            </div>
          </div>
        </div>
      </div>
        </div>
        <!-- END Your Block -->
    </div>
    <!-- END Page Content -->
</main>
<!-- END Main Container -->
@include('admin::layouts.footer')
<div class="order-type-modal" id="order-type-modal">
      <div class="order-type-content">
        <h5 class="mb-3">Create New Order</h5>
        <div class="mb-3">
          <label class="form-label">Select Order Type</label>
          <div class="d-flex gap-2 mt-2" id="order-type-buttons">
            <button
              class="btn btn-outline-primary flex-grow-1 order-type-btn"
              data-type="takeaway"
            >
              Take Away
            </button>
            <button
              class="btn btn-outline-primary flex-grow-1 order-type-btn"
              data-type="dine-in"
            >
              Dine-In
            </button>
            <button
              class="btn btn-outline-primary flex-grow-1 order-type-btn"
              data-type="delivery"
            >
              Delivery
            </button>
          </div>
        </div>
        <div class="mb-3" id="table-selection" style="display: none">
          <label for="table-number" class="form-label">Table Number</label>
          <select class="form-select" id="table-number">
            <option value="1">Table 1</option>
            <option value="5">Table 5</option>
            <option value="6">Table 6</option>
            <option value="7">Table 7</option>
          </select>
          <div class="d-flex justify-content-end mt-3">
            <button class="btn btn-primary" id="select-table-btn">
              Select Table
            </button>
          </div>
        </div>
      </div>
    </div>


    <!-- Toast Notification Container -->
    <div class="toast-container" id="toast-container"></div>

    <script>
      // JSON data for categories and food items
      const restaurantData = {
    categories: [
        { id: "all", name: "All Items" },
        @foreach($categories as $category)
            {
                id: "{{ $category->id }}",
                name: "{{ $category->category_name }}",
            },
        @endforeach
    ],
    foodItems: [
        @foreach($services as $service)
            {
                id: {{ $service->id }},
                name: "{{ $service->name }}",
                price: {{ $service->price }},
                image: "{{ $service->featured_image_url && $service->featured_image_url !== '-' ? $service->featured_image_url : 'https://www.allrecipes.com/thmb/5JVfA7MxfTUPfRerQMdF-nGKsLY=/1500x0/filters:no_upscale():max_bytes(150000):strip_icc()/25473-the-perfect-basic-burger-DDMFS-4x3-56eaba3833fd4a26a82755bcd0be0c54.jpg' }}",
                categories: ["all", "{{ $service->parent_category }}"],
            },
        @endforeach
    ],
    customers: [
        {
            id: 1,
            name: "John Doe",
            phone: "555-1234",
            email: "john@example.com",
        },
        {
            id: 2,
            name: "Jane Smith",
            phone: "555-5678",
            email: "jane@example.com",
        },
        {
            id: 3,
            name: "Robert Johnson",
            phone: "555-9012",
            email: "robert@example.com",
        }
    ],
    orders: []
    }

      // Cart data
      let cart = []
      const discount = 5 // 5% discount
      let currentTicketNumber = 12
      let activeOrderId = null // No active order initially
      let nextTokenNumber = 100

      // DOM elements
      const categoryTabsContainer = document.getElementById("category-tabs")
      const saveOrderBtn = document.getElementById("save-order-btn")
      const billOrderBtn = document.getElementById("bill-order-btn")
      const foodItemsContainer = document.getElementById("food-items-container")
      const cartContainer = document.getElementById("cart-container")
      const cartTotalElement = document.getElementById("cart-total")
      const cartSection = document.getElementById("cart-section")
      // const clearCartBtn = document.querySelector(".clear-cart-btn")
      const clearCartBtn = document.getElementById("clear-cart-btn")
      // const orderTypeModal = document.getElementById("order-type-modal")
      const orderTypeSelect = document.getElementById("order-type")
      // const tableSelection = document.getElementById("table-selection")
      // const addOrderBtn = document.getElementById("add-order-btn")
      const cancelOrderBtn = document.getElementById("cancel-order-btn")
      const createOrderBtn = document.getElementById("create-order-btn")
      const customerModal = document.getElementById("customer-modal")
      const addCustomerBtn = document.getElementById("add-customer-btn")
      const cancelCustomerBtn = document.getElementById("cancel-customer-btn")
      const saveCustomerBtn = document.getElementById("save-customer-btn")
      const orderButtonsContainer = document.getElementById("order-buttons")
      const searchInput = document.getElementById("search-input")
      const toastContainer = document.getElementById("toast-container")

      //new
      const orderTypeModal = document.getElementById("order-type-modal")
      const tableSelection = document.getElementById("table-selection")
      const addOrderBtn = document.getElementById("add-order-btn")
      const selectTableBtn = document.getElementById("select-table-btn")
      const orderTypeButtons = document.querySelectorAll(".order-type-btn")

      const selectWaiter = document.getElementById("select-waiter");
      const selectRider = document.getElementById("select-rider");
      // Initialize the page
      // function init() {
      //   loadCategories()
      //   loadFoodItems("all")
      //   setupEventListeners()
      // }

      // Initialize column widths
      // function resetLayout() {
      //     if (!activeOrderId) {
      //         document.getElementById('menu-section').classList.remove('col-lg-8');
      //         document.getElementById('menu-section').classList.add('col-12');
      //         cartSection.style.display = 'none';
      //     }
      // }

      // Initialize column widths
      function resetLayout() {
        if (!activeOrderId) {
          document.getElementById("menu-section").classList.remove("col-lg-8")
          document.getElementById("menu-section").classList.add("col-12")
          cartSection.style.display = "none"
        }
      }

      //new
      // Set up event listeners for the order type modal
      function setupOrderTypeModal() {
        // Open modal when clicking "Create Invoice +" button
        addOrderBtn.addEventListener("click", () => {
          orderTypeModal.style.display = "flex"
          tableSelection.style.display = "none" // Hide table selection initially
        })

        // Handle order type button clicks
        orderTypeButtons.forEach((button) => {
          button.addEventListener("click", () => {
            const orderType = button.dataset.type

            if (orderType === "dine-in") {
              // For dine-in, show table selection
              tableSelection.style.display = "block"
            } else {
              // For takeaway and delivery, create order immediately
              createNewOrder(orderType)
            }
          })
        })

        // Handle table selection button click
        selectTableBtn.addEventListener("click", () => {
          createNewOrder("dine-in")
        })
      }

      // Call this in your init function
      function init() {
        resetLayout()
        loadCategories()
        loadFoodItems("all")
        setupEventListeners()
      }

      // Set up event listeners
      function setupEventListeners() {
        // Clear cart button
        clearCartBtn.addEventListener("click", clearCart)

        // Add this to your setupEventListeners function
        const closeTabBtn = document.getElementById("close-tab-btn")
        closeTabBtn.addEventListener("click", closeTab)

        setupOrderTypeModal()

        // Order type modal
        addOrderBtn.addEventListener("click", () => {
          orderTypeModal.style.display = "flex"
        })

        cancelOrderBtn.addEventListener("click", () => {
          orderTypeModal.style.display = "none"
        })

        orderTypeSelect.addEventListener("change", () => {
          if (orderTypeSelect.value === "dine-in") {
            tableSelection.style.display = "block"
          } else {
            tableSelection.style.display = "none"
          }
        })

        createOrderBtn.addEventListener("click", createNewOrder)

        // Customer modal
        addCustomerBtn.addEventListener("click", () => {
          customerModal.style.display = "flex"
        })

        cancelCustomerBtn.addEventListener("click", () => {
          customerModal.style.display = "none"
        })

        saveCustomerBtn.addEventListener("click", saveNewCustomer)

        // Search functionality
        searchInput.addEventListener("input", searchItems)
      }

      // Show toast notification
      function showToast(message, type = "error") {
        const toast = document.createElement("div")
        toast.className = "toast"
        toast.innerHTML = `
                <i class="bi bi-exclamation-circle me-2"></i>
                <span>${message}</span>
            `

        toastContainer.appendChild(toast)

        // Force reflow to enable animation
        void toast.offsetWidth

        toast.classList.add("show")

        setTimeout(() => {
          toast.classList.remove("show")
          setTimeout(() => {
            toastContainer.removeChild(toast)
          }, 300)
        }, 3000)
      }

      // Create new order
      // function createNewOrder() {
      //   const orderType = orderTypeSelect.value
      //   let newOrder

      //   if (orderType === "dine-in") {
      //     const tableNumber = document.getElementById("table-number").value
      //     newOrder = {
      //       id: Date.now(),
      //       type: "table",
      //       number: tableNumber,
      //       items: [],
      //       active: false,
      //     }

      //     const tableBtn = document.createElement("button")
      //     tableBtn.className = "table-btn"
      //     tableBtn.textContent = `Table ${tableNumber}`
      //     tableBtn.dataset.id = newOrder.id
      //     tableBtn.addEventListener("click", function () {
      //       setActiveOrder(this)
      //     })

      //     // Insert before the add button
      //     orderButtonsContainer.insertBefore(tableBtn, addOrderBtn)
      //   } else if (orderType === "takeaway") {
      //     // Generate a token number for takeaway
      //     const tokenNumber = nextTokenNumber++
      //     newOrder = {
      //       id: Date.now(),
      //       type: "takeaway",
      //       number: tokenNumber.toString(),
      //       items: [],
      //       active: false,
      //     }

      //     const tokenBtn = document.createElement("button")
      //     tokenBtn.className = "takeaway-btn"
      //     tokenBtn.textContent = `Token ${tokenNumber}`
      //     tokenBtn.dataset.id = newOrder.id
      //     tokenBtn.addEventListener("click", function () {
      //       setActiveOrder(this)
      //     })

      //     // Insert before the add button
      //     orderButtonsContainer.insertBefore(tokenBtn, addOrderBtn)
      //   } else if (orderType === "delivery") {
      //     // Generate a token number for delivery
      //     const tokenNumber = nextTokenNumber++
      //     newOrder = {
      //       id: Date.now(),
      //       type: "delivery",
      //       number: tokenNumber.toString(),
      //       items: [],
      //       active: false,
      //     }

      //     const tokenBtn = document.createElement("button")
      //     tokenBtn.className = "delivery-btn"
      //     tokenBtn.textContent = `Token ${tokenNumber}`
      //     tokenBtn.dataset.id = newOrder.id
      //     tokenBtn.addEventListener("click", function () {
      //       setActiveOrder(this)
      //     })

      //     // Insert before the add button
      //     orderButtonsContainer.insertBefore(tokenBtn, addOrderBtn)
      //   }

      //   restaurantData.orders.push(newOrder)
      //   orderTypeModal.style.display = "none"

      //   // Set this as the active order
      //   const newBtn = document.querySelector(`[data-id="${newOrder.id}"]`)
      //   if (newBtn) {
      //     setActiveOrder(newBtn)
      //   }
      // }

      //new
      function createNewOrder(orderType) {
        let newOrder

        if (orderType === "dine-in") {
          const tableNumber = document.getElementById("table-number").value;
         
          selectWaiter.style.display="block";
          selectRider.style.display="none";

          newOrder = {
            id: Date.now(),
            type: "table",
            number: tableNumber,
            items: [],
            active: false,
            token: '',
            order_total: 0,
          }

          const tableBtn = document.createElement("button")
          tableBtn.className = "table-btn"
          tableBtn.textContent = `Table ${tableNumber}`
          tableBtn.dataset.id = newOrder.id
          tableBtn.addEventListener("click", function () {
            setActiveOrder(this)
          })

          // Insert before the add button
          orderButtonsContainer.insertBefore(tableBtn, addOrderBtn)
        } else if (orderType === "takeaway") {
          selectWaiter.style.display="none";
          selectRider.style.display="none";
          // Generate a token number for takeaway
          const tokenNumber = nextTokenNumber++
          newOrder = {
            id: Date.now(),
            type: "takeaway",
            number: tokenNumber.toString(),
            items: [],
            active: false,
            token: '',
            order_total: 0,
          }

          const tokenBtn = document.createElement("button")
          tokenBtn.className = "takeaway-btn"
          // tokenBtn.textContent = `Token ${tokenNumber}`
          tokenBtn.textContent = `Token `
          tokenBtn.dataset.id = newOrder.id
          tokenBtn.addEventListener("click", function () {
            setActiveOrder(this)
          })

          // Insert before the add button
          orderButtonsContainer.insertBefore(tokenBtn, addOrderBtn)
        } else if (orderType === "delivery") {
          selectWaiter.style.display="none";
          selectRider.style.display="block";
          // Generate a token number for delivery
          const tokenNumber = nextTokenNumber++
          newOrder = {
            id: Date.now(),
            type: "delivery",
            number: tokenNumber.toString(),
            items: [],
            active: false,
            token: '',
            order_total: 0,
          }

          const tokenBtn = document.createElement("button")
          tokenBtn.className = "delivery-btn"
          tokenBtn.textContent = `Token `
          tokenBtn.dataset.id = newOrder.id
          tokenBtn.addEventListener("click", function () {
            setActiveOrder(this)
          })

          // Insert before the add button
          orderButtonsContainer.insertBefore(tokenBtn, addOrderBtn)
        }

        // Add the new order to the data
        restaurantData.orders.push(newOrder)

        // Close and reset the modal
        orderTypeModal.style.display = "none"
        tableSelection.style.display = "none"

        // Set this as the active order
        const newBtn = document.querySelector(`[data-id="${newOrder.id}"]`)
        if (newBtn) {
          setActiveOrder(newBtn)
        }
      }

      // Save new customer
      function saveNewCustomer() {
        const name = document.getElementById("customer-name").value
        const phone = document.getElementById("customer-phone").value
        const email = document.getElementById("customer-email").value

        if (name) {
          const newCustomer = {
            id: restaurantData.customers.length + 1,
            name,
            phone,
            email,
          }

          restaurantData.customers.push(newCustomer)

          // Add to dropdown
          const option = document.createElement("option")
          option.value = newCustomer.id
          option.textContent = newCustomer.name
          document.getElementById("customer-dropdown").appendChild(option)

          // Select the new customer
          document.getElementById("customer-dropdown").value = newCustomer.id

          // Clear and close modal
          document.getElementById("customer-name").value = ""
          document.getElementById("customer-phone").value = ""
          document.getElementById("customer-email").value = ""
          customerModal.style.display = "none"
        }
      }

      // Set active order
      // function setActiveOrder(buttonElement) {
      //   // Remove active class from all buttons
      //   document
      //     .querySelectorAll(".takeaway-btn, .delivery-btn, .table-btn")
      //     .forEach((btn) => {
      //       btn.classList.remove("active-order")
      //     })

      //   // Add active class to clicked button
      //   buttonElement.classList.add("active-order")

      //   // Find the order based on button data-id
      //   const orderId = parseInt(buttonElement.dataset.id)
      //   const order = restaurantData.orders.find((o) => o.id === orderId)

      //   if (order) {
      //     // Set active order
      //     restaurantData.orders.forEach((o) => (o.active = false))
      //     order.active = true
      //     activeOrderId = order.id

      //     // Load cart items from this order
      //     cart = [...order.items]
      //     updateCart()

      //     // Show cart section
      //     cartSection.style.display = "block"
      //   }
      // }
      // Set active order
      function setActiveOrder(buttonElement) {

        const tokenNumber = document.getElementById("ticket-number");

        // Remove active class from all buttons
        document
          .querySelectorAll(".takeaway-btn, .delivery-btn, .table-btn")
          .forEach((btn) => {
            btn.classList.remove("active-order")
          })

        // Add active class to clicked button
        buttonElement.classList.add("active-order")

        // Find the order based on button data-id
        const orderId = parseInt(buttonElement.dataset.id)
        const order = restaurantData.orders.find((o) => o.id === orderId)

        if (order) {
          // Set active order
          restaurantData.orders.forEach((o) => (o.active = false))
          order.active = true
          activeOrderId = order.id

          saveOrderBtn.setAttribute("data-active-order-id", order.id);
          billOrderBtn.setAttribute("data-active-order-id", order.id);
          const targetButton = document.querySelector(`.takeaway-btn[data-id="${activeOrderId}"]`);
          if (targetButton) {
              targetButton.textContent = `Token ${order.token}`;
          }
          tokenNumber.textContent = `${order.token}`
          // Load cart items from this order
          cart = [...order.items]
          updateCart()

          console.log(order);
          console.log(order.items);
          // Show cart section and adjust column widths
          cartSection.style.display = "block"
          document.getElementById("menu-section").classList.remove("col-12")
          document.getElementById("menu-section").classList.add("col-lg-8")

          if(order.type === "takeaway"){
            selectWaiter.style.display="none";
            selectRider.style.display="none";
          }
          if(order.type === "table"){
            selectWaiter.style.display="block";
            selectRider.style.display="none";
          }
          if(order.type === "delivery"){
            selectWaiter.style.display="none";
            selectRider.style.display="block";
          }
        }
      }
document.getElementById("save-order-btn").addEventListener("click", function () {
  const tokenNumber = document.getElementById("ticket-number");
  const activeOrderId = parseInt(this.getAttribute("data-active-order-id"));
  let customer = $("#customer").val().trim();
  let waiter = $("#waiter").val().trim();
  let rider = $("#rider").val().trim();
  const order = restaurantData.orders.find((o) => o.id === activeOrderId);

  $.ajax({
    url: "{{ url('admin/save-bill') }}", 
    type: "POST",
    data: {
        _token: "{{ csrf_token() }}",
        customer: customer,
        waiter: waiter,
        rider: rider,
        order: order,
    },
    success: function (response) {
        alert(response.message);
        const targetButton = document.querySelector(`.takeaway-btn[data-id="${activeOrderId}"]`);
        if (targetButton && response.token) {
            targetButton.textContent = `Token ${response.token}`;
        }
        tokenNumber.textContent = `${response.token}`
        order.token = response.token;
        order.order_total = response.order_total;
    },
    error: function (xhr) {
        let errors = xhr.responseJSON.errors;
        if (errors) {
            let errorMessages = "";
            $.each(errors, function (key, value) {
                errorMessages += value[0] + "\n";
            });
            alert(errorMessages);
        }
    }
});
});
document.getElementById("bill-order-btn").addEventListener("click", function () {
  const activeOrderId = parseInt(this.getAttribute("data-active-order-id"));
  let customer = $("#customer").val().trim();

  const order = restaurantData.orders.find((o) => o.id === activeOrderId);
  if (!order || order.token === '') {
    alert('You have to save the bill first');
  }
  else{
    
    const orderTotal = order.order_total;
    $('#total-span').text('Rs.'+orderTotal.toFixed(2));
    $('#order_total_input').val(orderTotal);
    document.getElementById("print-button").setAttribute("data-active-order-id", order.id);
    const offcanvasElement = document.getElementById('offcanvasRight');
    const offcanvas = new bootstrap.Offcanvas(offcanvasElement);
    offcanvas.show();
  }
});

      // Clear cart
      function clearCart() {
        // console.log("hehe")
        cart = []

        // Update the active order's items
        const activeOrder = restaurantData.orders.find(
          (order) => order.id === activeOrderId
        )
        if (activeOrder) {
          activeOrder.items = []
        }

        updateCart()
      }

      // Search items
      // function searchItems() {
      //     const searchTerm = searchInput.value.toLowerCase();

      //     if (searchTerm === '') {
      //         // If search is empty, show the current category
      //         const activeCategory = document.querySelector('.category-tab.active');
      //         if (activeCategory) {
      //             loadFoodItems(activeCategory.dataset.category);
      //         } else {
      //             loadFoodItems('all');
      //         }
      //         return;
      //     }

      //     // Filter items based on search term
      //     const filteredItems = restaurantData.foodItems.filter(item =>
      //         item.name.toLowerCase().includes(searchTerm)
      //     );

      //     // Display filtered items
      //     displayFoodItems(filteredItems);
      // }

      // Search items
      function searchItems() {
        const searchTerm = searchInput.value.toLowerCase()
        const activeCategory = document.querySelector(".category-tab.active")
          .dataset.category

        if (searchTerm === "") {
          // If search is empty, show the current category
          loadFoodItems(activeCategory)
          return
        }

        // Filter items based on search term AND current category
        const filteredItems = restaurantData.foodItems.filter(
          (item) =>
            item.name.toLowerCase().includes(searchTerm) &&
            item.categories.includes(activeCategory)
        )

        // Display filtered items
        displayFoodItems(filteredItems)
      }

      // Load categories
      function loadCategories() {
        let categoriesHTML = ""

        restaurantData.categories.forEach((category, index) => {
          categoriesHTML += `
                    <div class="category-tab ${
                      index === 0 ? "active" : ""
                    } bg-light text-dark" 
                         data-category="${category.id}">
                        ${category.name}
                    </div>
                `
        })

        categoryTabsContainer.innerHTML = categoriesHTML

        // Add event listeners to category tabs
        document.querySelectorAll(".category-tab").forEach((tab) => {
          tab.addEventListener("click", () => {
            document
              .querySelectorAll(".category-tab")
              .forEach((t) => t.classList.remove("active"))
            tab.classList.add("active")
            loadFoodItems(tab.dataset.category)
            // Clear search when category is changed
            searchInput.value = ""
          })
        })
      }

      // Load food items based on selected category
      function loadFoodItems(categoryId) {
        const filteredItems = restaurantData.foodItems.filter((item) =>
          item.categories.includes(categoryId)
        )

        displayFoodItems(filteredItems)
      }

      // Display food items
      function displayFoodItems(items) {
        let foodItemsHTML = ""

        if (items.length === 0) {
          foodItemsContainer.innerHTML =
            '<div class="col-12 text-center py-5">No items found</div>'
          return
        }

        items.forEach((item) => {
          foodItemsHTML += `
                    <div class="col-md-3 col-sm-6">
                        <div class="food-card shadow-sm" data-id="${item.id}">
                            <img src="${item.image}" alt="${
            item.name
          }" class="card-img-top">
                            <div class="card-body">
                                <h6 class="card-title">${item.name}</h6>
                                <div class="food-price">${item.price.toFixed(
                                  2
                                )}</div>
                            </div>
                        </div>
                    </div>
                `
        })

        foodItemsContainer.innerHTML = foodItemsHTML

        // Add event listeners to food cards
        document.querySelectorAll(".food-card").forEach((card) => {
          card.addEventListener("click", () => {
            const itemId = parseInt(card.dataset.id)
            addToCart(itemId)
          })
        })
      }

      // Add item to cart
      function addToCart(itemId) {
        // Check if there's an active order
        if (!activeOrderId) {
          showToast(
            "Please create or select an Invoice first before adding items"
          )
          return
        }

        const item = restaurantData.foodItems.find((item) => item.id === itemId)

        if (item) {
          const existingItem = cart.find((cartItem) => cartItem.id === itemId)

          if (existingItem) {
            existingItem.quantity += 1
          } else {
            cart.push({
              id: item.id,
              name: item.name,
              price: item.price,
              image: item.image,
              quantity: 1,
              note: '',
            })
          }

          // Update the active order's items
          const activeOrder = restaurantData.orders.find(
            (order) => order.id === activeOrderId
          )
          if (activeOrder) {
            activeOrder.items = [...cart]
          }

          updateCart()
        }
      }

      // Update cart display
      function updateCart() {
        if (cart.length === 0) {
          cartContainer.innerHTML = `<div class="text-center py-4 text-muted">Your cart is empty</div>`
          cartTotalElement.textContent = "0.00"
          return
        }

        let cartHTML = ""
        let total = 0

        cart.forEach((item) => {
          const itemTotal = item.price * item.quantity
          // const discountedPrice = itemTotal * (1 - discount / 100)
          // total += discountedPrice
          const discountedPrice = itemTotal
          total += discountedPrice
          cartHTML += `
                    <div class="cart-item">
                        <div class="d-flex align-items-center">
                            <img src="${item.image}" alt="${
            item.name
          }" class="cart-item-img me-3">
                            <div class="flex-grow-1">
                                <h6 class="mb-0">${item.name}</h6>
                                <div class="discount-badge">Discount: ${discount}%</div>
                                 <input type="text" class="form-control note-input" placeholder="Note" data-id="${
                                      item.id
                                    }">
                            </div>
                            <div class="d-flex gap-2 align-items-center">
                                <div class="d-flex align-items-center">
                                    <button class="quantity-btn minus-btn" data-id="${
                                      item.id
                                    }">-</button>
                                    <span class="mx-2">${item.quantity}</span>
                                    <button class="quantity-btn plus-btn" data-id="${
                                      item.id
                                    }">+</button>
                                </div>
                                <div class="text-end" style="width: 70px;">
                                    ${discountedPrice.toFixed(2)}
                                   
                                </div>
                            </div>
                        </div>
                    </div>
                `
        })

        cartContainer.innerHTML = cartHTML
        cartTotalElement.textContent = total.toFixed(2)

        // Add event listeners to quantity buttons
        document.querySelectorAll(".minus-btn").forEach((btn) => {
          btn.addEventListener("click", (e) => {
            e.stopPropagation()
            updateQuantity(parseInt(btn.dataset.id), -1)
          })
        })

        document.querySelectorAll(".plus-btn").forEach((btn) => {
          btn.addEventListener("click", (e) => {
            e.stopPropagation()
            updateQuantity(parseInt(btn.dataset.id), 1)
          })
        })

        document.querySelectorAll(".note-input").forEach((input) => {
        input.addEventListener("keydown", (e) => {
            if (e.key === "Enter") {
            e.preventDefault();
            const itemId = parseInt(input.dataset.id);
            const note = input.value;
            updateNote(itemId, note);
            input.value = input.value;
            }
        });
        });
       
      }

      // Close/delete the active tab
      function closeTab() {
        if (!activeOrderId) {
          showToast("No active order to close")
          return
        }

        // Find the active order
        const activeOrder = restaurantData.orders.find(
          (order) => order.id === activeOrderId
        )
        if (!activeOrder) return

        // Find and remove the button
        const activeButton = document.querySelector(
          `.takeaway-btn.active-order, .delivery-btn.active-order, .table-btn.active-order`
        )
        if (activeButton) {
          activeButton.remove()
        }

        // Remove the order from the data
        restaurantData.orders = restaurantData.orders.filter(
          (order) => order.id !== activeOrderId
        )

        // Clear the cart
        cart = []

        // Reset active order
        activeOrderId = null

        // Reset the layout
        resetLayout()
      }

      // Update item quantity in cart
      function updateNote(itemId, note) {
        const cartItem = cart.find((item) => item.id === itemId);

        if (cartItem) {
            cartItem.note = note;

            const activeOrder = restaurantData.orders.find(
            (order) => order.id === activeOrderId
            );

            if (activeOrder) {
            activeOrder.items = [...cart];
            }

            updateCart();
        }
        }
      function updateQuantity(itemId, change) {
        const cartItem = cart.find((item) => item.id === itemId)

        if (cartItem) {
          cartItem.quantity += change

          if (cartItem.quantity <= 0) {
            cart = cart.filter((item) => item.id !== itemId)
          }

          // Update the active order's items
          const activeOrder = restaurantData.orders.find(
            (order) => order.id === activeOrderId
          )
          if (activeOrder) {
            activeOrder.items = [...cart]
          }

          updateCart()
        }
      }
      
      // Initialize the page when DOM is loaded
      document.addEventListener("DOMContentLoaded", init)
    </script>
<script>
    $(document).ready(function() {
    $('.toggle-nav-bar').click();
});
</script>



<div class="offcanvas offcanvas-end bg-body-extra-light" tabindex="-1" id="offcanvasAddCustomer" aria-labelledby="offcanvasAddCustomerLabel">
<div class="offcanvas-header bg-body-light">
    <h5 class="offcanvas-title" id="offcanvasAddCustomerLabel">Add Customer</h5>
    <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
</div>
<div class="offcanvas-body">
<div class="col-md-12 mb-3">
<label class="form-label">Customer Name</label>
<input type="text" class="form-control" name="customer_name" value="" id="customer_name">
</div>
<div class="col-md-12 mb-3">
    <label class="form-label">Phone No</label>
    <input type="text" class="form-control" name="phone"  value="" id="customer_phone">
</div>
<!-- <div class="col-md-12 mb-3">
    <label class="form-label">Email</label>
    <input type="email" class="form-control" name="email" value="" id="customer_email">
</div> -->
<div class="col-md-12 mb-3">
    <label class="form-label">Discount</label>
    <input type="number" class="form-control" name="discount" value="" id="customer_discount">
</div>

<button class="btn btn-success mt-2 add-customer-submit" type="button" >Add Customer</button>
</div>
</div>
<script>
    $(document).ready(function () {
        $(".add-customer-submit").click(function () {
            let customer_name = $("#customer_name").val().trim();
            let customer_phone = $("#customer_phone").val().trim();
            let customer_email = $("#customer_email").val().trim();
            let customer_discount = $("#customer_discount").val().trim();

            $.ajax({
                url: "{{ url('admin/add-customer-ajax') }}", 
                type: "POST",
                data: {
                    _token: "{{ csrf_token() }}",
                    customer_name: customer_name,
                    phone: customer_phone,
                    email: customer_email,
                    discount: customer_discount
                },
                success: function (response) {
                    alert(response.message);
                    $("#customer_name, #customer_phone, #customer_email, #customer_discount").val("");
                    refreshCustomers();
                },
                error: function (xhr) {
                    let errors = xhr.responseJSON.errors;
                    if (errors) {
                        let errorMessages = "";
                        $.each(errors, function (key, value) {
                            errorMessages += value[0] + "\n";
                        });
                        alert(errorMessages);
                    }
                }
            });
        });

        function refreshCustomers() {
            $.ajax({
                url: "{{ url('admin/refresh-customers-ajax') }}", 
                type: "GET",
                success: function (data) {
                    let customerSelect = $("#customer");
                    customerSelect.empty();

                    customerSelect.append('<option data-mobile="-" data-discount="0" value="Cash">Cash</option>');

                    $.each(data, function (key, customer) {
                        customerSelect.append(
                            `<option data-mobile="${customer.phone}" data-discount="${customer.discount}" value="${customer.id}">
                                ${customer.customer_name} (${customer.phone})
                            </option>`
                        );
                    });

                    customerSelect.select2();
                }
            });
        }
    });
</script>

<div class="offcanvas offcanvas-end bg-body-extra-light" tabindex="-1" id="offcanvasRight" aria-labelledby="offcanvasRightLabel">
                    <div class="offcanvas-header bg-body-light">
                      <h5 class="offcanvas-title" id="offcanvasRightLabel">Confirm Order</h5>
                      <button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
                    </div>
                    <div class="offcanvas-body">
                      <p>
                      <div class="block-content">
                        <div class="py-2">
                            <p>
                            <strong>Total : <span class="big-text" id="total-span" style="color:#0665d0;">0</span></strong> 
                            </p>
                            <p>
                           
                            </p>

                            <div class=" tab-content overflow-hidden mt-4">
                            <div class="tab-pane fade fade-right active show" id="btabs-animated-slideright-home" role="tabpanel" aria-labelledby="btabs-animated-slideright-home-tab" tabindex="0">
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Bill Amount</label>
                                    <input type="number" class="form-control" name="order_total_input" id="order_total_input" value="0" readonly>
                                </div>
                                <div class="col-md-12 mb-3">
                                <p class="mt-4 mb-1" style="color:#0665d0;"><strong>Cash Payments</strong> </p>
                                    <label class="form-label">Cash Amount</label>
                                    <input type="number" class="form-control" name="cash_amount" id="cash_amount">
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Received Amount</label>
                                    <input type="number" class="form-control" name="received_amount" id="received_amount">
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Balance</label>
                                    <input type="number" class="form-control" name="balance" id="balance" readonly>
                                </div>
                                <div class="col-md-12 mb-3">
                                <p class="mt-4 mb-1" style="color:#0665d0;"><strong>Card Payments</strong> </p>
                                    <label class="form-label">Card Amount</label>
                                    <input type="number" class="form-control" name="card_paying_amount" id="card_paying_amount">
                                </div>
                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Card Ref No</label>
                                    <input type="text" class="form-control" name="card_ref_no" id="card_ref_no">
                                </div>
                                <div class="col-md-12 mb-3">
                                <p class="mt-4 mb-1" style="color:#0665d0;"><strong>Online Payments</strong> </p>
                                    <label class="form-label">Online Amount</label>
                                    <input type="number" class="form-control" name="online_amount" id="online_amount">
                                </div>

                                <div class="col-md-12 mb-3">
                                <p class="mt-4 mb-1" style="color:#0665d0;"><strong>Summery</strong> </p>
                                    <label class="form-label">Paid Amount</label>
                                    <input type="number" class="form-control" name="paid_amount" id="paid_amount" readonly>
                                </div>

                                <div class="col-md-12 mb-3">
                                    <label class="form-label">Remaining Amount</label>
                                    <input type="number" class="form-control" name="remaining_amount" id="remaining_amount" readonly>
                                </div>
                            </div>
                            
                            </div>
                            <!-- <div id="keypad" class="keypad">
                                <button type="button" class="key" data-value="1">1</button>
                                <button type="button" class="key" data-value="2">2</button>
                                <button type="button" class="key" data-value="3">3</button>
                                <button type="button" class="key" data-value="4">4</button>
                                <button type="button" class="key" data-value="5">5</button>
                                <button type="button" class="key" data-value="6">6</button>
                                <button type="button" class="key" data-value="7">7</button>
                                <button type="button" class="key" data-value="8">8</button>
                                <button type="button" class="key" data-value="9">9</button>
                                <button type="button" class="key" data-value="0">0</button>
                                <button type="button" class="key" data-action="clear">C</button>
                                <button type="button" class="key" data-action="backspace">←</button>
                            </div> -->
                        <p class="mb-0 mt-2"  id="bill-error" style="color:red;font-weight:600"></p>
                        <button class="btn btn-success mt-4" type="button" name="submit_button" disabled id="print-button" value="print_submit">Print Bill
                        </button>
                        <p class="mb-0 mt-4" >
                            <strong>Send VIA</strong> 
                        </p>
                        <button class="btn btn-success mt-2" type="button" name="submit_button" disabled id="whatsapp-button" value="whatsapp_submit">Whatsapp
                        </button>
                        <a href="{{url('admin/premium')}}"><button class="btn btn-success mt-2" type="button" name="submit_button" disabled id="email-button" value="whatsapp_email">Email <span class="nav-main-link-badge badge rounded-pill bg-danger">Premium</span>
                        </button></a>
                        <a href="{{url('admin/premium')}}"><button class="btn btn-success mt-2" type="button" name="submit_button" disabled id="sms-button" value="whatsapp_sms">SMS <span class="nav-main-link-badge badge rounded-pill bg-danger">Premium</span>
                        </button></a>
                        
                    <script>
    document.getElementById('offcanvasRight').addEventListener('shown.bs.offcanvas', function () {
        document.getElementById('cash_amount').focus();
    });

    document.addEventListener("DOMContentLoaded", function () {
        const orderTotalInput = document.getElementById("order_total_input");
        const cashAmount = document.getElementById("cash_amount");
        const receivedAmount = document.getElementById("received_amount");
        const balance = document.getElementById("balance");
        const cardPayingAmount = document.getElementById("card_paying_amount");
        const cardRef = document.getElementById("card_ref_no");
        const onlineAmount = document.getElementById("online_amount");
        const paidAmount = document.getElementById("paid_amount");
        const remainingAmount = document.getElementById("remaining_amount");

        const printButton = document.getElementById("print-button");
        const whatsappButton = document.getElementById("whatsapp-button");
        const billError = document.getElementById("bill-error");

        function updatePaymentDetails() {
            const billAmount = parseFloat(orderTotalInput.value) || 0;
            const cash = parseFloat(cashAmount.value) || 0;
            const received = parseFloat(receivedAmount.value) || 0;
            const card = parseFloat(cardPayingAmount.value) || 0;
            const online = parseFloat(onlineAmount.value) || 0;

            const totalPaid = cash + card + online;
            const remaining = billAmount - totalPaid;
            const cashBalance = received - cash;

            // Set calculated values
            paidAmount.value = totalPaid.toFixed(2);
            remainingAmount.value = remaining > 0 ? remaining.toFixed(2) : "0.00";
            balance.value = cashBalance >= 0 ? cashBalance.toFixed(2) : "0.00";

            // Enable/disable submit buttons
            if (remaining <= 0 && totalPaid >= billAmount) {
                printButton.disabled = false;
                whatsappButton.disabled = false;
                billError.innerHTML = "";
            } else {
                printButton.disabled = true;
                whatsappButton.disabled = true;
                billError.innerHTML = "Please complete the full payment. Remaining amount must be 0.";
            }
        }
        cashAmount.addEventListener("keydown", function (e) {
            if (e.key === "Enter") {
                e.preventDefault();
                receivedAmount.focus();
            }
        });

        receivedAmount.addEventListener("keydown", function (e) {
            if (e.key === "Enter") {
                e.preventDefault();
                cardPayingAmount.focus();
            }
        });

        cardPayingAmount.addEventListener("keydown", function (e) {
            if (e.key === "Enter") {
                e.preventDefault();
                cardRef.focus();
            }
        });

        cardRef.addEventListener("keydown", function (e) {
            if (e.key === "Enter") {
                e.preventDefault();
                onlineAmount.focus();
            }
        });

        onlineAmount.addEventListener("keydown", function (e) {
            if (e.key === "Enter") {
                e.preventDefault();
                onlineAmount.blur(); 
            }
        });
        // Attach event listeners
        document.querySelectorAll("#cash_amount, #received_amount, #card_paying_amount, #online_amount").forEach(input => {
            input.addEventListener("input", updatePaymentDetails);
        });

    
    document.querySelectorAll(".key").forEach(key => {
        key.addEventListener("click", function () {
            if (!activeInput) return;
            const value = this.getAttribute("data-value");
            const action = this.getAttribute("data-action");
            
            if (value) {
                activeInput.value += value;
            } else if (action === "clear") {
                activeInput.value = "";
            } else if (action === "backspace") {
                activeInput.value = activeInput.value.slice(0, -1);
            }
            updateBalance();
        });
    });
});


</script>
                        </div>
                        </div>
                      </p>
                    </div>
                  </div>

                  <script>
document.addEventListener("DOMContentLoaded", function () {
  const printBtn = document.getElementById("print-button");
  if (printBtn) {
    printBtn.addEventListener("click", function () {
      const activeOrderId = parseInt(this.getAttribute("data-active-order-id"));
      let cash_amount = $("#cash_amount").val().trim();
      let card_paying_amount = $("#card_paying_amount").val().trim();
      let card_ref_no = $("#card_ref_no").val().trim();
      let online_amount = $("#online_amount").val().trim();
      const order = restaurantData.orders.find((o) => o.id === activeOrderId);

      $.ajax({
        url: "{{ url('admin/print-bill') }}",
        type: "POST",
        data: {
          _token: "{{ csrf_token() }}",
          cash_amount: cash_amount,
          card_paying_amount: card_paying_amount,
          card_ref_no: card_ref_no,
          online_amount: online_amount,
          order: order,
        },
        success: function (response) {
          alert(response.message);
        },
        error: function (xhr) {
          let errors = xhr.responseJSON.errors;
          if (errors) {
            let errorMessages = "";
            $.each(errors, function (key, value) {
              errorMessages += value[0] + "\n";
            });
            alert(errorMessages);
          }
        },
      });
    });
  }
});
</script>
