<?php echo $__env->make('admin::layouts.header', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<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.success {
        background-color:rgb(24, 204, 93);
      }
      .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>
    <style>
   #orderDrawer {
      --primary-color: #0d6efd;
      --success-color: #198754;
      --light-gray: #f8f9fa;
      --border-color: #dee2e6;
    }
    
   .offcanvas-end.extra-wide {
      width: 800px;
      max-width: 95vw;
    }
    
    #orderDrawer .form-section {
      margin-bottom: 0.75rem;
      background-color: white;
      border-radius: 6px;
      padding: 0.75rem;
      box-shadow: 0 1px 3px rgba(0,0,0,0.05);
    }

    #orderDrawer .form-section:hover {
      box-shadow: 0 4px 8px rgba(0,0,0,0.1);
    }
    
    #orderDrawer .section-header {
      display: flex;
      align-items: center;
      margin-bottom: 0.5rem;
      padding-bottom: 0.25rem;
      border-bottom: 1px solid var(--border-color);
    }
    
    #orderDrawer .section-header i {
      margin-right: 0.5rem;
      color: var(--primary-color);
      font-size: 0.9rem;
    }
    
    #orderDrawer .section-header h6 {
      font-weight: 600;
      margin-bottom: 0;
      color: #333;
      font-size: 0.9rem;
    }
    
    #orderDrawer .form-control {
      border-radius: 4px;
      padding: 0.4rem 0.5rem;
      border: 1px solid var(--border-color);
      font-size: 0.9rem;
      height: auto;
    }
    
    #orderDrawer .form-control:focus {
      box-shadow: 0 0 0 0.15rem rgba(13, 110, 253, 0.15);
    }
    
    #orderDrawer .form-control:disabled {
      background-color: var(--light-gray);
    }
    
    #orderDrawer .form-label {
      margin-bottom: 0.25rem;
      font-size: 0.85rem;
      color: #555;
    }
    
    #orderDrawer .btn {
      border-radius: 4px;
      padding: 0.4rem 0.75rem;
      font-weight: 500;
      font-size: 0.9rem;
    }
    
    #orderDrawer .btn-success {
      background-color: var(--success-color);
    }
    
    #orderDrawer .btn-success:hover {
      background-color: #146c43;
    }
    
    #orderDrawer .btn-premium {
      background-color: #dc3545;
      color: white;
      opacity: 0.7;
      position: relative;
      padding-right: 1.5rem;
    }
    
    #orderDrawer .btn-premium::after {
      content: "Premium";
      position: absolute;
      top: -6px;
      right: -6px;
      background-color: #ffc107;
      color: #212529;
      font-size: 0.6rem;
      padding: 1px 4px;
      border-radius: 8px;
      font-weight: bold;
    }
    
    #orderDrawer .send-btns .btn {
      margin-right: 0.5rem;
      display: inline-flex;
      align-items: center;
    }
    
    #orderDrawer .send-btns .btn i {
      margin-right: 0.25rem;
    }
    
    #orderDrawer .total-display {
      background: linear-gradient(135deg, #0d6efd, #0a58ca);
      color: white;
      border-radius: 6px;
      padding: 0.75rem 1rem;
      margin-bottom: 0.75rem;
      box-shadow: 0 2px 4px rgba(0,0,0,0.1);
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    #orderDrawer .total-display h4 {
      margin: 0;
      font-weight: 400;
      font-size: 1rem;
    }
    
    #orderDrawer .total-display .amount {
      font-size: 1.5rem;
      font-weight: 700;
    }
    
    #orderDrawer .print-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 0.5rem;
      font-weight: 600;
      padding: 0.5rem;
      /* margin: 0.75rem 0; */
      margin: 1rem 0 1rem;
    }
    
    #orderDrawer .input-group-text {
      background-color: var(--light-gray);
      border-color: var(--border-color);
      padding: 0.4rem 0.5rem;
      font-size: 0.85rem;
    }
    
    #orderDrawer .offcanvas-header {
      border-bottom: 1px solid var(--border-color);
      padding: 0.75rem 1rem;
    }
    
    #orderDrawer .offcanvas-title {
      font-weight: 600;
      color: var(--primary-color);
      font-size: 1.1rem;
    }
    
    #orderDrawer .offcanvas-body {
      padding: 0.75rem;
    }
    
    #orderDrawer .mb-2 {
      margin-bottom: 0.5rem !important;
    }
    
    #orderDrawer .row {
      --bs-gutter-x: 0.75rem;
    }
    .food-card .card-title{
      font-size: 20px;
    }
    .cart-item h6{
      font-size: 20px;
    }
    .cart-item .cart-quantity{
      font-size: 22px;
    }
    .cart-item .cart-price{
      font-size: 22px;
    }
    /* Animation for the drawer */
    /* .offcanvas.show {
      animation: slideIn 0.3s ease-out;
    }
    
    @keyframes slideIn {
      from {
        transform: translateX(100%);
      }
      to {
        transform: translateX(0);
      }
    } */
</style>
<main id="main-container">



    <div class="content">

        <div class="block block-rounded p-3">
        <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="<?php echo e(CustomerDetails::where('user_id', old('customer'))->value('phone')); ?>" 
                            value="<?php echo e(old('customer')); ?>" selected>
                        <?php echo e(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="<?php echo e($customer->customerDetails->phone); ?>" data-discount="<?php echo e($customer->customerDetails->discount ?? 0); ?>" value="<?php echo e($customer->id); ?>">
                            <?php echo e($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 foreach($waiters as $waiter){ ?> 
                      <option value="<?php echo e($waiter->id); ?>"><?php echo e($waiter->name); ?></option>
                    <?php } ?>
                    
            </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 foreach($riders as $rider){ ?> 
                      <option value="<?php echo e($rider->id); ?>"><?php echo e($rider->name); ?></option>
                    <?php } ?>
            </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..."
                oninput="searchItems()"
              />
            </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" >Send to Kitchen</button>
                <button class="btn btn-primary flex-grow-1"  id="bill-order-btn"><i class="bi bi-cart-check"></i> 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 -->
<?php echo $__env->make('admin::layouts.footer', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?>
<div class="order-type-modal" id="order-type-modal">
      <div class="order-type-content position-relative">
      <button
      type="button"
      class="btn-close position-absolute top-0 end-0 m-2"
      aria-label="Close"
      id="close-order-type-modal"
    ></button>
        <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">
          <?php foreach($tables_rooms as $tables_room) { ?> 
              <option data-table-name="<?php echo e($tables_room->name); ?>" value="<?php echo e($tables_room->id); ?>">
                  <?php echo e($tables_room->name); ?>

              </option>
          <?php } ?>
          </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" },
        <?php $__currentLoopData = $categories; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $category): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            {
                id: "<?php echo e($category->id); ?>",
                name: "<?php echo e($category->category_name); ?>",
            },
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
    ],
    foodItems: [
        <?php $__currentLoopData = $services; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $service): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            {
                id: <?php echo e($service->id); ?>,
                code: "<?php echo e($service->code); ?>",
                name: "<?php echo e($service->name); ?>",
                price: <?php echo e($service->price); ?>,
                image: "<?php echo e($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", "<?php echo e($service->parent_category); ?>"],
            },
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
    ],
    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: [
      <?php $first = true; ?>
        <?php $__currentLoopData = $pending_orders; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $pending_order): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
            {
                id: <?php echo e($pending_order->front_id); ?>,
                type: "<?php echo e($pending_order->order_type); ?>",
                number: "<?php echo e($pending_order->table); ?>",
                table_name: "<?php echo e($pending_order->table_name); ?>",
                token: "<?php echo e($pending_order->token); ?>",
                order_total: <?php echo e($pending_order->total); ?>,
                active: <?php echo e($first ? 'true' : 'false'); ?>,
                customer_id: "<?php echo e($pending_order->customer); ?>",
                customer_name: "<?php echo e($pending_order->customer_name); ?>",
                waiter_id: "<?php echo e($pending_order->waiter); ?>",
                waiter_name: "<?php echo e($pending_order->waiter_name); ?>",
                rider_id: "<?php echo e($pending_order->rider); ?>",
                rider_name: "<?php echo e($pending_order->rider_name); ?>",
                is_cart_updated: 0,
                items: [
                    <?php $__currentLoopData = $pending_order->products; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $item): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                        {
                            id: <?php echo e($item->product); ?>,
                            name: "<?php echo e($item->item_name); ?>",
                            price: <?php echo e($item->price); ?>,
                            image: "<?php echo e($item->image && $item->image !== '-' ? $item->image : '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'); ?>",
                            quantity: <?php echo e($item->quantity); ?>,
                            note: "<?php echo e($item->note ?? ''); ?>",
                            note_color : "red"
                        }<?php if(!$loop->last): ?>,<?php endif; ?>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                ]
            }<?php if(!$loop->last): ?>,<?php endif; ?>
            <?php $first = false; ?>
        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
    ]
    }

      // 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() {

        clearCartBtn.addEventListener("click", function (e) {
          const confirmClear = confirm("Are you sure you want to clear the cart?");
          if (confirmClear) {
            clearCart();
          }
        });

        const closeTabBtn = document.getElementById("close-tab-btn")

        closeTabBtn.addEventListener("click", function (e) {
          const confirmCancel = confirm("Are you sure you want to cancel the order?");
          if (confirmCancel) {
            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"; // default "toast" class

      // Add success class if type is success
      if (type === "success") {
          toast.classList.add("success");
      }

      // Set icon based on type
      let iconHtml = `<i class="bi bi-exclamation-circle me-2"></i>`; // error icon
      if (type === "success") {
          iconHtml = `<i class="bi bi-check-circle me-2"></i>`; // success icon
      }

      toast.innerHTML = `
          ${iconHtml}
          <span>${message}</span>
      `;
function showToast(message, type = "error") {
    const toast = document.createElement("div");
    toast.className = "toast"; // default "toast" class

    // Add success class if type is success
    if (type === "success") {
        toast.classList.add("success");
    }

    // Set icon based on type
    let iconHtml = `<i class="bi bi-exclamation-circle me-2"></i>`; // error icon
    if (type === "success") {
        iconHtml = `<i class="bi bi-check-circle me-2"></i>`; // success icon
    }

    toast.innerHTML = `
        ${iconHtml}
        <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);
}

      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;
          const tableSelect = document.getElementById("table-number");
          const selectedOption = tableSelect.options[tableSelect.selectedIndex];
        const tableName = selectedOption.getAttribute("data-table-name");
            
          $.ajax({
            url: "<?php echo e(url('admin/check-table-avilability')); ?>", 
            type: "POST",
            data: {
                _token: "<?php echo e(csrf_token()); ?>",
                tableNumber: tableNumber
            },
            success: function (response) {
                if(response.status === "table booked"){
                  showToast(
                    "Table is already booked. Please close the pending order."
                  )
                  
                }
                else{
                  selectWaiter.style.display="block";
                  selectRider.style.display="none";

                  newOrder = {
                    id: Date.now(),
                    type: "table",
                    number: tableNumber,
                    table_name: tableName,
                    items: [],
                    active: false,
                    token: '',
                    order_total: 0,
                    customer_id: '',
                    customer_name: '',
                    waiter_id: '',
                    waiter_name: '',
                    rider_id: '',
                    rider_name: '',
                    is_cart_updated: 1,
                  }

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

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

                  restaurantData.orders.push(newOrder);

                  orderTypeModal.style.display = "none";
                  tableSelection.style.display = "none";

                  const newBtn = document.querySelector(`[data-id="${newOrder.id}"]`);
                  if (newBtn) {
                    setActiveOrder(newBtn);
                  }
                }
            },
            error: function (xhr) {
                let errors = xhr.responseJSON.errors;
                if (errors) {
                    let errorMessages = "";
                    $.each(errors, function (key, value) {
                        errorMessages += value[0] + "\n";
                    });
                    showToast(errorMessages)
                   
                    // alert(errorMessages);
                }
            }
        });
         return;
        } 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(),
            table_name: '',
            items: [],
            active: false,
            token: '',
            order_total: 0,
            customer_id: '',
            customer_name: '',
            waiter_id: '',
            waiter_name: '',
            rider_id: '',
            rider_name: '',
            is_cart_updated: 1,
          }

          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(),
            table_name: '',
            items: [],
            active: false,
            token: '',
            order_total: 0,
            customer_id: '',
            customer_name: '',
            waiter_id: '',
            waiter_name: '',
            rider_id: '',
            rider_name: '',
            is_cart_updated: 1,
          }

          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,is_old = false) {

        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(is_old)

          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")

          $("#customer").val(order.customer_id).trigger("change");
          $("#waiter").val(order.waiter_id).trigger("change");
          $("#rider").val(order.rider_id).trigger("change");

          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 loader = document.getElementById("loader-container");
  const activeOrderId = parseInt(this.getAttribute("data-active-order-id"));
  let customer =  $("#customer").val() ? $("#customer").val().trim() : "";
  let waiter = $("#waiter").val() ? $("#waiter").val().trim() : "";
  let rider = $("#rider").val() ? $("#rider").val().trim() : "";
  const order = restaurantData.orders.find((o) => o.id === activeOrderId);
  loader.style.display = "flex";
  $.ajax({
    url: "<?php echo e(url('admin/save-bill')); ?>", 
    type: "POST",
    data: {
        _token: "<?php echo e(csrf_token()); ?>",
        customer: customer,
        waiter: waiter,
        rider: rider,
        order: order,
    },
    success: function (response) {
        loader.style.display = "none";
        // 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.is_cart_updated = 0;
        order.order_total = response.order_total;
        order.customer_id = customer;
        order.customer_name = $("#customer option:selected").text();
        order.waiter_id = waiter;
        order.waiter_name = $("#waiter option:selected").text();
        order.rider_id = rider;
        order.rider_name = $("#rider option:selected").text();
        showToast(
            "Order successfully saved", 'success'
          )
        // const billOrderBtn = document.getElementById('bill-order-btn');
        // billOrderBtn.click();
        // window.open(response.bill_url, '_blank');
        printToPrinterA(response.bill_url)
    },
    error: function (xhr) {
        loader.style.display = "none";
        let errors = xhr.responseJSON.errors;
        if (errors) {
            let errorMessages = "";
            $.each(errors, function (key, value) {
                errorMessages += value[0] + "\n";
            });
            // alert(errorMessages);
            showToast(errorMessages)    
        }
    }
});
});
document.getElementById("bill-order-btn").addEventListener("click", function () {
  const activeOrderId = parseInt(this.getAttribute("data-active-order-id"));
  let customer = $("#customer").val().trim();
  var discount = $("#customer").find(':selected').data('discount');

  const order = restaurantData.orders.find((o) => o.id === activeOrderId);
  if (!order || order.is_cart_updated === 1) {
    // alert('You have to save the bill first');
    showToast("You have to save the bill first")

  }
  
  else{ 
    let orderTotal = order.order_total;
    // let originalTotal = order.order_total;
    if(order.type === "table"){
      $('#service_charges').val(5);
      // orderTotal = orderTotal + parseFloat((orderTotal * 0.05).toFixed(2));
      document.getElementById('service_charges_div').style.display = "block";
      document.getElementById('customer-receipt').style.display = "block";
    }
    else{
      $('#service_charges').val(0);
      document.getElementById('service_charges_div').style.display = "none";
      document.getElementById('customer-receipt').style.display = "none";
    }

    if(order.type === "delivery"){
      document.getElementById('delivery_charges_div').style.display = "block";
    }
    else{
      document.getElementById('delivery_charges_div').style.display = "none";
    }
   
    $('#total-span').text('Rs.'+orderTotal.toFixed(2));
    $('#order_total_input').val(orderTotal).attr('data-original', orderTotal);

    $('#cash_amount').val(orderTotal);
    $('#paid_amount').val(orderTotal);
    $("#discount").val(discount);
    document.getElementById("print-button").setAttribute("data-active-order-id", order.id);
    document.getElementById("customer-receipt").setAttribute("data-active-order-id", order.id);
    const offcanvasElement = document.getElementById('orderDrawer');
    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
        console.log( restaurantData.foodItems);
        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.code && item.code.toString().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}" data-code="${item.code}">
                            <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: '',
              note_color : "red"
            })
          }

          // 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(is_old = false) {
        console.log(activeOrderId);
        const order = restaurantData.orders.find((o) => o.id === activeOrderId);
        if(is_old === true){
          order.is_cart_updated = 0;
        }
       else{
        order.is_cart_updated = 1;
       }
        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" style="color:${item.note_color || 'red'};" class="form-control note-input" placeholder="Note" value="${item.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 cart-quantity">${item.quantity}</span>
                                    <button class="quantity-btn plus-btn" data-id="${
                                      item.id
                                    }">+</button>
                                </div>
                                <div class="text-end cart-price" style="width: 100px;">
                                    ${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
        }

        $.ajax({
                url: "<?php echo e(url('admin/cancel-order')); ?>", 
                type: "POST",
                data: {
                    _token: "<?php echo e(csrf_token()); ?>",
                    front_id: activeOrderId,
                },
                success: function (response) {
                    console.log('order canceled');
                },
                error: function (xhr) {
                    let errors = xhr.responseJSON.errors;
                    if (errors) {
                        let errorMessages = "";
                        $.each(errors, function (key, value) {
                            errorMessages += value[0] + "\n";
                        });
                        showToast(errorMessages)
                                       
                        // alert(errorMessages);
                    }
                }
            });
        // 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()
      }
      function hideOrder() {
        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;
        cartItem.note_color = "green"; 

        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 enter-nav" 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 enter-nav" 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 enter-nav" 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 () {

      $(".enter-nav").on("keypress", function (e) {
            if (e.which === 13) {
                e.preventDefault(); 

                const inputs = $(".enter-nav");
                const index = inputs.index(this);

                if (index < inputs.length - 1) {
                    inputs.eq(index + 1).focus();
                } else {
                    $(".add-customer-submit").click(); 
                }
            }
        });

        $(".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: "<?php echo e(url('admin/add-customer-ajax')); ?>", 
                type: "POST",
                data: {
                    _token: "<?php echo e(csrf_token()); ?>",
                    customer_name: customer_name,
                    phone: customer_phone,
                    email: '',
                    discount: customer_discount
                },
                success: function (response) {
                    // alert(response.message);
                     showToast(
                      response.message, 'success'
                    )
                    $("#customer_name, #customer_phone, #customer_email, #customer_discount").val("");
                     refreshCustomers(response.customer_id); 
                     bootstrap.Offcanvas.getInstance(document.getElementById('offcanvasAddCustomer')).hide();
                },
                error: function (xhr) {
                    let errors = xhr.responseJSON.errors;
                    if (errors) {
                        let errorMessages = "";
                        $.each(errors, function (key, value) {
                            errorMessages += value[0] + "\n";
                        });
                        showToast(errorMessages)
                    
                        // alert(errorMessages);
                    }
                }
            });
        });

       function refreshCustomers(selectedId = null) {
          $.ajax({
              url: "<?php echo e(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();

                  if (selectedId) {
                      customerSelect.val(selectedId).trigger("change");
                  }
              }
          });
      }

    });
</script>
<div class="offcanvas offcanvas-end extra-wide" tabindex="-1" id="orderDrawer">
                            <div class="offcanvas-header">
                            <h5 class="offcanvas-title"><i class="bi bi-check-circle"></i> Confirm Order</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
                            </div>
                            <div class="offcanvas-body">
                            <div class="total-display">
                                <h4>Total Amount</h4>
                                <div class="amount" id="total-span">Rs.0.00</div>
                            </div>

                            <div class="row">
                                <!-- <div class="col-md-4">
                                <div class="form-section">
                                    <div class="section-header">
                                    <i class="bi bi-receipt"></i>
                                    <h6>Bill Details</h6>
                                    </div>
                                    <div class="mb-2">
                                    <label class="form-label">Bill Amount</label>
                                    <div class="input-group">
                                        <span class="input-group-text">Rs.</span>
                                        <input type="number" id="billAmount" class="form-control" placeholder="0.00" />
                                    </div>
                                    </div>
                                </div>
                                </div> -->
                                <input type="hidden" class="form-control" name="order_total_input" id="order_total_input" value="0">
                                
                                <div class="col-md-12">
                                <div class="form-section">
                                    <div class="section-header">
                                    <i class="bi bi-calculator"></i>
                                    <h6>Payment Summary</h6>
                                    </div>
                                    <div class="row">
                                    <div class="col-6">
                                       
                                        <div class="mb-2" id="service_charges_div" style="display:none;">
                                        <label class="form-label">+ Service Charges (%)</label>
                                        <div class="input-group">
                                            <span class="input-group-text">%</span>
                                            <input type="number" class="form-control" name="service_charges" id="service_charges" readonly />
                                        </div>
                                        </div>
                                        <div class="mb-2" id="delivery_charges_div" style="display:none;">
                                        <label class="form-label">+ Delivery Charges</label>
                                        <div class="input-group">
                                            <span class="input-group-text">Rs.</span>
                                            <input type="number" class="form-control" name="delivery_charges" id="delivery_charges"  />
                                        </div>
                                        </div>
                                        <div class="mb-2">
                                        <label class="form-label">Discount</label>
                                        <div class="input-group">
                                            <span class="input-group-text">Rs.</span>
                                            <input type="number" class="form-control" name="discount" id="discount" />
                                        </div>
                                        </div>
                                         <div class="mb-2">
                                        <label class="form-label">Payable Amount</label>
                                        <div class="input-group">
                                            <span class="input-group-text">Rs.</span>
                                            <input type="number" class="form-control" name="paid_amount" id="paid_amount" readonly />
                                        </div>
                                        </div>
                                    </div>
                                    <div class="col-6 d-none">
                                        <div class="mb-2">
                                        <label class="form-label">Remaining Amount</label>
                                        <div class="input-group">
                                            <span class="input-group-text">Rs.</span>
                                            <input type="number" class="form-control" name="remaining_amount" id="remaining_amount" readonly />
                                        </div>
                                        </div>
                                    </div>
                                    <div class="col-6 d-none">
                                        
                                    </div>
                                    </div>
                                </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-4">
                                <div class="form-section">
                                    <div class="section-header">
                                    <i class="bi bi-cash"></i>
                                    <h6>Cash Payment</h6>
                                    </div>
                                    <div class="mb-2">
                                    <label class="form-label">Cash Amount</label>
                                    <div class="input-group">
                                        <span class="input-group-text">Rs.</span>
                                        <input type="number" class="form-control" name="cash_amount" id="cash_amount" />
                                    </div>
                                    </div>
                                    <div class="mb-2">
                                    <label class="form-label">Received Amount</label>
                                    <div class="input-group">
                                        <span class="input-group-text">Rs.</span>
                                        <input type="number" class="form-control" name="received_amount" id="received_amount" />
                                    </div>
                                    </div>
                                    <div class="mb-2">
                                    <label class="form-label">Balance</label>
                                    <div class="input-group">
                                        <span class="input-group-text">Rs.</span>
                                        <input type="number" class="form-control" name="balance" id="balance" readonly />
                                    </div>
                                    </div>
                                </div>
                                </div>
                                
                                <div class="col-md-4">
                                <div class="form-section">
                                    <div class="section-header">
                                    <i class="bi bi-credit-card"></i>
                                    <h6>Card Payment</h6>
                                    </div>
                                    <div class="mb-2">
                                    <label class="form-label">Card Amount</label>
                                    <div class="input-group">
                                        <span class="input-group-text">Rs.</span>
                                        <input type="number" class="form-control" name="card_paying_amount" id="card_paying_amount"/>
                                    </div>
                                    </div>
                                    <div class="mb-2">
                                    <label class="form-label">Card Reference No.</label>
                                    <input type="text" class="form-control" name="card_ref_no" id="card_ref_no"/>
                                    </div>
                                </div>
                                </div>
                                
                                <div class="col-md-4">
                                <div class="form-section">
                                    <div class="section-header">
                                    <i class="bi bi-laptop"></i>
                                    <h6>Online Payment</h6>
                                    </div>
                                    <div class="mb-2">
                                    <label class="form-label">Online Amount</label>
                                    <div class="input-group">
                                        <span class="input-group-text">Rs.</span>
                                        <input type="number" class="form-control" name="online_amount" id="online_amount"/>
                                    </div>
                                    </div>
                                  <div class="form-section">
                                    <div class="section-header">
                                    <i class="bi bi-laptop"></i>
                                    <h6>Credit Amount</h6>
                                    </div>
                                    <div class="mb-2">
                                    <label class="form-label">Credit Amount</label>
                                    <div class="input-group">
                                        <span class="input-group-text">Rs.</span>
                                        <input type="number" class="form-control" name="credit_amount" id="credit_amount"/>
                                    </div>
                                    </div>
                                     <div class="mb-2">
                                    <label class="form-label">Due Date</label>
                                    <div class="input-group">
                                        <input type="date" class="form-control" name="credit_due_date" id="credit_due_date"/>
                                    </div>
                                    </div>
                                </div>
                                </div>
                                
                                <!-- <div class="form-section mt-2">
                                    <div class="section-header">
                                    <i class="bi bi-share"></i>
                                    <h6>Send Receipt</h6>
                                    </div>
                                    <div class="send-btns d-flex flex-wrap">
                                    <button class="btn btn-success btn-sm">
                                        <i class="bi bi-whatsapp"></i> WhatsApp
                                    </button>
                                    <button class="btn btn-premium btn-sm">
                                        <i class="bi bi-envelope"></i> Email
                                    </button>
                                    <button class="btn btn-premium btn-sm">
                                        <i class="bi bi-chat-dots"></i> SMS
                                    </button>
                                    </div>
                                </div> -->
                                </div>
                                
                            </div>
                            <p class="mb-0 mt-2"  id="bill-error" style="color:red;font-weight:600"></p>
                            <button class="btn btn-info w-100 " type="button" name="submit_button" id="customer-receipt" value="customer_invoice">
                                <i class="bi bi-printer"></i> Customer Receipt
                            </button>
                            <button class="btn btn-success w-100 print-btn " type="button" name="submit_button" disabled id="print-button" value="print_submit">
                                <i class="bi bi-printer"></i> Print Bill
                            </button>
                            <div class="form-section mt-2">
                                <div class="section-header">
                                <i class="bi bi-share"></i>
                                <h6>Send Receipt</h6>
                                </div>
                                <div class="send-btns d-flex flex-wrap">
                                <button class="btn btn-success btn-sm" type="button" name="submit_button" disabled id="whatsapp-button" value="whatsapp_submit">
                                    <i class="bi bi-whatsapp"></i> WhatsApp
                                </button>
                                <button class="btn btn-premium btn-sm" type="button" name="submit_button" disabled id="email-button" value="whatsapp_email">
                                    <i class="bi bi-envelope"></i> Email
                                </button>
                                <button class="btn btn-premium btn-sm"  type="button" name="submit_button" disabled id="sms-button" value="whatsapp_sms">
                                    <i class="bi bi-chat-dots"></i> SMS
                                </button>
                                </div>
                            </div>
                            </div>
                        </div>
                        <script>
                        document.getElementById('orderDrawer').addEventListener('shown.bs.offcanvas', function () {
                          const discount = document.getElementById('discount');
                          discount.dispatchEvent(new Event('input', { bubbles: true }));
                          const input = document.getElementById('cash_amount');
                          input.focus();
                          input.dispatchEvent(new Event('input', { bubbles: true }));
                          // console.log($('#service_charges').val());
                        });

                        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 creditAmount = document.getElementById("credit_amount");
                            
                            const printButton = document.getElementById("print-button");
                            const recieptButton = document.getElementById("customer-receipt");
                            const whatsappButton = document.getElementById("whatsapp-button");
                            const billError = document.getElementById("bill-error");

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

                                cash = billAmount - (card + online + credit);
                                if (cash < 0) cash = 0;

                                cashAmount.value = cash.toFixed(2);

                                const totalPaid = cash + card + online + credit;
                                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;
                                    recieptButton.disabled = false;
                                    whatsappButton.disabled = false;
                                    billError.innerHTML = "";
                                } else {
                                    printButton.disabled = true;
                                    recieptButton.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();
                                    creditAmount.focus(); 
                                }
                            });
                            creditAmount.addEventListener("keydown", function (e) {
                                if (e.key === "Enter") {
                                    e.preventDefault();
                                    creditAmount.blur(); 
                                }
                            });
                            // Attach event listeners
                            document.querySelectorAll("#cash_amount, #received_amount, #card_paying_amount, #online_amount, #delivery_charges,#credit_amount").forEach(input => {
                                input.addEventListener("input", updatePaymentDetails);
                            });

                            document.querySelectorAll("#delivery_charges, #discount").forEach(input => {
                                input.addEventListener("input", updateOrderInputTotal);
                            });
                            function updateOrderInputTotal() {
                                const orderTotalInput = document.getElementById("order_total_input");
                                const cashAmount = document.getElementById("cash_amount");
                                const deliveryChargesInput = document.getElementById("delivery_charges");
                                const discount = document.getElementById("discount");
                                const serviceCharge = document.getElementById("service_charges");

                                const deliveryCharges = parseFloat(deliveryChargesInput.value) || 0;
                                const originalOrderValue = parseFloat(orderTotalInput.dataset.original) || 0;
                                const OrderValue = parseFloat(orderTotalInput.value) || 0;
                                const discountPercent = parseFloat(discount.value) || 0;
                                const serviceChargePercent = parseFloat(serviceCharge.value) || 0;
                                const discountAmount = (originalOrderValue * discountPercent) / 100;
                                const serviceChargeAmount = (originalOrderValue * serviceChargePercent) / 100;
                                const total = originalOrderValue + deliveryCharges - discountAmount + serviceChargeAmount;

                                orderTotalInput.value = total.toFixed(2);
                                cashAmount.value = total.toFixed(2);

                                updatePaymentDetails();

                                console.log("Parsed Delivery Charges:", deliveryCharges);
                                console.log("Original Order Value:", originalOrderValue);
                                console.log("New Total:", total);
                              }


                        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>
                  <script>
document.addEventListener("DOMContentLoaded", function () {
  const printBtn = document.getElementById("print-button");
  const receiptBtn = document.getElementById("customer-receipt");
  if (printBtn) {
    printBtn.addEventListener("click", function () {
      const loader = document.getElementById("loader-container");
      const activeOrderId = parseInt(this.getAttribute("data-active-order-id"));
      let paid_amount = $("#paid_amount").val().trim();
      let service_charges = $("#service_charges").val().trim();
      let delivery_charges = $("#delivery_charges").val().trim();
      let cash_amount = $("#cash_amount").val().trim();
      let received_amount = $("#received_amount").val().trim();
      let balance = $("#balance").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();
      let credit_amount = $("#credit_amount").val().trim();
      let credit_due_date = $("#credit_due_date").val().trim();
      let discount = $("#discount").val().trim();
      const order = restaurantData.orders.find((o) => o.id === activeOrderId);
      console.log(order);
      // return;
      loader.style.display = "flex";
      $.ajax({
        url: "<?php echo e(url('admin/print-bill')); ?>",
        type: "POST",
        data: {
          _token: "<?php echo e(csrf_token()); ?>",
          paid_amount: paid_amount,
          service_charges: service_charges,
          delivery_charges: delivery_charges,
          cash_amount: cash_amount,
          received_amount: received_amount,
          balance: balance,
          card_paying_amount: card_paying_amount,
          card_ref_no: card_ref_no,
          online_amount: online_amount,
          credit_amount: credit_amount,
          credit_due_date: credit_due_date,
          discount: discount,
          order: order,
        },
        success: function (response) {
          loader.style.display = "none";
          // alert(response.message);

          $("#cash_amount").val("");
          $("#received_amount").val("");
          $("#balance").val("");
          $("#card_paying_amount").val("");
          $("#card_ref_no").val("");
          $("#online_amount").val("");
          $("#paid_amount").val("");
          $("#remaining_amount").val("");
          $("#order_total_input").val("0");
          $("#credit_amount").val("0");
          $("#delivery_charges").val("");
          $("#credit_due_date").val("");

          $("#print-button").prop("disabled", true);
          $("#whatsapp-button").prop("disabled", true);
          $("#email-button").prop("disabled", true);
          $("#sms-button").prop("disabled", true);

          const offcanvasElement = document.getElementById("orderDrawer");
          const offcanvasInstance = bootstrap.Offcanvas.getInstance(offcanvasElement);
          if (offcanvasInstance) {
            offcanvasInstance.hide();
          }
          //  window.open(response.bill_url, '_blank');
          printToPrinterB(response.bill_url)
          hideOrder();
        },
        error: function (xhr) {
          loader.style.display = "none";
          let errors = xhr.responseJSON.errors;
          if (errors) {
            let errorMessages = "";
            $.each(errors, function (key, value) {
              errorMessages += value[0] + "\n";
            });
            showToast(errorMessages)
                   
            // alert(errorMessages);
          }
        },
      });
    });
  }

  if (receiptBtn) {
    receiptBtn.addEventListener("click", function () {
      const loader = document.getElementById("loader-container");
      const activeOrderId = parseInt(this.getAttribute("data-active-order-id"));
      let paid_amount = $("#paid_amount").val().trim();
      let service_charges = $("#service_charges").val().trim();
      let delivery_charges = $("#delivery_charges").val().trim();
      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();
      let credit_amount = $("#credit_amount").val().trim();
      const order = restaurantData.orders.find((o) => o.id === activeOrderId);
      // console.log(order);
      // return;
      loader.style.display = "flex";
      $.ajax({
        url: "<?php echo e(url('admin/customer-bill')); ?>",
        type: "POST",
        data: {
          _token: "<?php echo e(csrf_token()); ?>",
          paid_amount: paid_amount,
          service_charges: service_charges,
          delivery_charges: delivery_charges,
          cash_amount: cash_amount,
          card_paying_amount: card_paying_amount,
          card_ref_no: card_ref_no,
          online_amount: online_amount,
          credit_amount: credit_amount,
          order: order,
        },
        success: function (response) {
          loader.style.display = "none";
          // alert(response.message);

          $("#cash_amount").val("");
          $("#received_amount").val("");
          $("#balance").val("");
          $("#card_paying_amount").val("");
          $("#card_ref_no").val("");
          $("#online_amount").val("");
          $("#paid_amount").val("");
          $("#remaining_amount").val("");
          $("#order_total_input").val("0");
          $("#credit_amount").val("0");
          $("#delivery_charges").val("");

          $("#print-button").prop("disabled", true);
          $("#whatsapp-button").prop("disabled", true);
          $("#email-button").prop("disabled", true);
          $("#sms-button").prop("disabled", true);

          // const offcanvasElement = document.getElementById("orderDrawer");
          // const offcanvasInstance = bootstrap.Offcanvas.getInstance(offcanvasElement);
          // if (offcanvasInstance) {
          //   offcanvasInstance.hide();
          // }
          // window.open(response.bill_url, '_blank');
          printToPrinterB(response.bill_url)
          // closeTab();
        },
        error: function (xhr) {
          loader.style.display = "none";
          let errors = xhr.responseJSON.errors;
          if (errors) {
            let errorMessages = "";
            $.each(errors, function (key, value) {
              errorMessages += value[0] + "\n";
            });
             showToast(errorMessages)
            // alert(errorMessages);
          }
        },
      });
    });
  }
});
</script>

<script>
  window.addEventListener("DOMContentLoaded", function () {
    restaurantData.orders.forEach((order, index) => {
        let orderBtn = document.createElement("button");

        // Assign class based on order type
        if (order.type === "table") {
            orderBtn.className = "table-btn";
            orderBtn.textContent = `${order.table_name} ${order.token}`;
        } else if (order.type === "takeaway") {
            orderBtn.className = "takeaway-btn";
            orderBtn.textContent = `Token ${order.token}`;
        } else if (order.type === "delivery") {
            orderBtn.className = "delivery-btn";
            orderBtn.textContent = `Token ${order.token}`;
        }

        // Set dataset and event listener
        orderBtn.dataset.id = order.id;
        orderBtn.addEventListener("click", function () {
            setActiveOrder(this,true);
        });

        orderButtonsContainer.insertBefore(orderBtn, addOrderBtn);

        // Set the first order as active
        if (index === 0) {
          setActiveOrder(orderBtn,true);
        }
    });
});
</script>
<style>

#loader-container {
  position: fixed;
    height: 100vh;
    display: none;
    justify-content: center;
    align-items: center;
    background-color: rgb(255 255 255 / 70%);
    overflow: hidden;
    top: 0px;
    right: 0px;
    z-index: 99999;
    width: 100%;

}
  /* Loader container */
.loader {
  position: relative;
  width: 150px;
  height: 150px;
}

/* Central glowing orb */
.orb {
  position: absolute;
top: 50%;
left: 50%;
width: 30px;
height: 30px;
background: #0665d0;
border-radius: 50%;
box-shadow: 
  0 0 15px #0665d0,
  0 0 30px #0665d0,
  0 0 60px rgba(6, 101, 208, 0.5);
transform: translate(-50%, -50%);
animation: pulse 2s infinite ease-in-out;

}

/* Pulsating waves */
.wave {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100%;
  height: 100%;
  background: none;
  border: 2px solid rgba(6, 101, 208, 0.5);
  border-radius: 50%;
  transform: translate(-50%, -50%) scale(0);
  animation: expand 3s infinite ease-in-out;
}

.wave:nth-child(2) {
  animation-delay: 1s;
}
.wave:nth-child(3) {
  animation-delay: 2s;
}

/* Animations */
@keyframes pulse {
  0%, 100% {
    transform: translate(-50%, -50%) scale(1);
  }
  50% {
    transform: translate(-50%, -50%) scale(1.2);
  }
}

@keyframes expand {
  0% {
    transform: translate(-50%, -50%) scale(0);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(1.5);
    opacity: 0;
  }
}
</style>
<div id="loader-container">
<div class="loader">
  <div class="orb"></div>
  <div class="wave"></div>
  <div class="wave"></div>
  <div class="wave"></div>
</div>
</div>


<script src="<?php echo e(asset('qz-tray.js')); ?>"></script>
<script>
    qz.websocket.connect()
        .then(() => console.log("Connected to QZ Tray"))
        .catch(err => console.error("Connection failed:", err));

      async function printFromUrl(printerName, url) { 
          try { 
                const response = await fetch(url); 
                const content = await response.text(); 

                const config = qz.configs.create(printerName, {
                    scaleContent: false,
                    margins: { top: 0, right: 0, bottom: 0, left: 0 }
                });

                const data = [{ 
                    type: 'html', 
                    format: 'plain', 
                    data: content 
                }]; 

                await qz.print(config, data); 
                console.log(`Printed to ${printerName}`);

          } catch (err) { 
              console.error("Print error:", err); 
          } 
} 


    function printToPrinterA(url) {
        printFromUrl('KOT', url);
    }

    function printToPrinterB(url) {
        printFromUrl('INVOICE', url);
    }

    document.getElementById('close-order-type-modal').addEventListener('click', () => {
  document.getElementById('order-type-modal').style.display = 'none';
});
</script>

<?php /**PATH /home/u446954234/domains/orionerp.xyz/public_html/demo/Modules/Admin/resources/views/cashier/cashier_v2.blade.php ENDPATH**/ ?>