    <%- header %>
<style>
  #tripsTable td {
    padding: 8px;
    vertical-align: middle;
  }

  /* Editable fields — always show black border */
  #tripsTable td.editable {
    background-color: #f9fafb; /* light gray background */
    border: 1px solid #000000; /* black border */
    border-radius: 4px;
    cursor: text;
    padding: 6px 8px;
    transition: all 0.2s ease-in-out;
    box-sizing: border-box;
  }

  /* When hovered — show white background */
  #tripsTable td.editable:hover {
    background-color: #ffffff;
    border-color: #000000;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  }

  /* When focused (clicked for editing) */
  #tripsTable td.editable:focus,
  #tripsTable td.editable[contenteditable="true"]:focus {
    outline: none;
    background-color: #ffffff;
    border: 2px solid #2563eb; /* blue border when editing */
    box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.25);
  }

  /* Static (non-editable) cells */
  #tripsTable td.static-text {
    background-color: #f3f4f6;
    font-weight: 600;
    border: 1px solid #e5e7eb;
    border-radius: 4px;
  }

  /* Description column (larger cell for multiline text) */
  .editable.desc-html {
    min-width: 250px;
    white-space: pre-wrap;
    word-break: break-word;
  }

  /* Optional: small edit icon in corner */
  #tripsTable td.editable::after {
    content: "✎";
    font-size: 11px;
    color: #6b7280;
    float: right;
    margin-left: 6px;
    opacity: 0.5;
  }

  #tripsTable td.editable:hover::after {
    opacity: 0.9;
    color: #000000;
  }

  #tripsTable td.editable:focus::after {
    color: #2563eb;
    opacity: 1;
  }

  .table-striped>tbody>tr:nth-of-type(odd)>*{
    background-color: #ffffff !important;
    --bs-table-bg-type: #ffffff !important;
  }
  .table-striped>tbody>tr:nth-of-type(odd)>*{
    background-color: #ffffff !important;
  }
  .table-striped>tbody>tr:nth-of-type(odd)>*{
    background-color: #ffffff !important; 
  }
</style>


    <!-- pre-rendered navbar inserted -->
    <main class="dashboard-main">
      <%- navbar %>
      <!-- pre-rendered navbar inserted -->

      <script src="/js/pagination.js"></script>

      <style>
        #tripsTable td {
          padding: 8px;
          vertical-align: middle;
        }

        #tripsTable td.editable {
          background-color: #f9f9f9;
          cursor: text;
        }

        #tripsTable td.static-text {
          background-color: #efefef;
          font-weight: bold;
        }

        .save-btn {
          padding: 4px 10px;
          font-size: 12px;
        }
      </style>


      <div class="container flex-1 pt-20 w-full my-4">

        <%- include('../../partials/utils/title.ejs', {title: "Rental Packages Manager"}) %>

        <% 
    const breadcrumbs = [
      { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
       { label: "Rental Packages Manager" }
    ];
  %>

        <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>
        <div style="display: flex; justify-content: end; align-items: center;">
          <!-- Offcanvas for Search Filter Panel -->
          <div style="display: flex; justify-content: space-between; align-items: center; gap: 10px;">
            <button  data-tooltip="Delete selected package" id="deleteSelected" class="btn shadow btn-danger" style="padding-block: 6px;">
              <i class="fas fa-trash"></i>
            </button>
            <div style="display: flex; justify-content: end;">
              <%- include('../../partials/utils/searchFilter.ejs') %>
            </div>
          </div>
        </div>

        <div class="card basic-data-table" style="margin-top: 20px;">
          <div class="card-header" style="display: flex; justify-content: space-between; align-items: center;">
            <h5 class="card-title mb-0">Total Rental Packages: <span id="totalRows"></span> </h5>

                 <div class="sticky-save-btn d-flex justify-content-center align-items-center">
    
                     <button type="submit"  id="saveAllBtn" class="btn btn-primary btn-lg px-5 py-2" style="font-size: 1.2rem !important;">
                       Save  
                     </button>
                   </div>

                   <style>
                     .sticky-save-btn {
                       position: fixed;
                       /* fixed to viewport bottom */
                       bottom: 20px;
                       /* distance from bottom */
                       right: 10px;
                       transform: translateX(-50%);
                       z-index: 1000;
                       background: white;
                       /* button itself has color */
                       padding: 0;
                       /* remove extra padding from container */
                     }

                     .sticky-save-btn .btn-primary {
                       /* background: linear-gradient(90deg, #4e73df, #224abe); */
                       border: none;
                       border-radius: 50px;
                       /* rounded for modern look */
                       box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
                       font-weight: 600;
                       transition: transform 0.2s, box-shadow 0.2s;
                     }

                     .sticky-save-btn .btn-primary:hover {
                       transform: translateY(-2px);
                       box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25);
                     }
                   </style>
        
          </div>

          <%- include('../../partials/globalSearch.ejs') %>

          <!-- Responsive Table -->
          <div style="padding-inline: 20px; overflow-x: auto;">
            <div class="table-responsive bordered-table">
              <table id="tripsTable" class="table table-striped table-bordered">
                <thead>
                  <tr>
                    <th scope="col">
                      <div class="form-check style-check d-flex align-items-center">
                        <input id="selectAll" class="form-check-input" type="checkbox">
                      </div>
                    </th>
                    <th data-sort="package_id">
                      Category Name
                      <span class="sort-icons">
                        <i class="fa fa-sort sort-neutral"></i>
                        <i class="fa fa-sort-up sort-asc"></i>
                        <i class="fa fa-sort-down sort-desc"></i>
                      </span>
                    </th>

                    <th>Description</th>
                    <th>Distance</th>
                    <th>Hours</th>
                    <th>Price</th>
                    <th>Extra KM Fare</th>
                    <th>Extra Hours Fare</th>
                    <th>Extra Minutes</th>
                    <th>Night Charges</th>
                    <!-- <th>Booking Max HRS Limit</th> -->
                  </tr>
                </thead>
                <tbody></tbody>
              </table>
            </div>
          </div>

          <div class="pagination">
            <div id="pagination"></div>
          </div>
        </div>
    </main>

    <script>
      // Helper function to handle null values
      function handleNull(value) {
        return value === null || value === undefined || value === '' ? '0' : value;
      }

      // Set global search input for pagination
      window.globalSearchInput = '#globalSearch';

      // Initialize pagination
      const pagination = new Pagination({
        fetchUrl: '/admin/getRentalPackages',
        defaultSort: {
          column: 'package_id',
          order: 'DESC'
        },
        dataMapper: (pkg) => {
          return `
        <tr data-id="${pkg.pkg_cat_id}">
          <td>
            <div class="form-check style-check d-flex align-items-center">
              <input class="select-pack form-check-input" type="checkbox" value="${pkg.pkg_cat_id}">
            </div>
          </td>
          <td contenteditable="false" class="static-text">
            ${pkg?.category?.cat_name || ''} (${pkg?.name || ''})
          </td>
          <td contenteditable="true" style="font-size:10px; width:300px" class="editable desc-html" style="white-space: pre-wrap; word-break: break-word; width: 300px;">
            ${handleNull(pkg?.pkg_desc)}
          </td>
          <td contenteditable="true" class="editable">${handleNull(pkg?.distance)}</td>
          <td contenteditable="true" class="editable">${handleNull(pkg?.hours)}</td>
          <td contenteditable="true" class="editable">${handleNull(pkg?.price)}</td>
          <td contenteditable="true" class="editable">${handleNull(pkg?.extra_km_fare)}</td>
          <td contenteditable="true" class="editable">${handleNull(pkg?.extra_hrs_fare)}</td>
          <td contenteditable="true" class="editable">${handleNull(pkg?.extra_min_fare)}</td>
          <td contenteditable="true" class="editable">${handleNull(pkg?.night_charges)}</td>
          <!-- <td contenteditable="true" class="editable">${handleNull(pkg?.booking_max_hrs_limit)}</td> -->
        </tr>
      `;
        }
      });

      // Select/Deselect all checkboxes
      $("#selectAll").on("click", function() {
        $(".select-pack").prop("checked", this.checked);
      });

      // Delete selected packages with SweetAlert2
      $("#deleteSelected").on("click", function() {
        const selectedPackages = $(".select-pack:checked").map(function() {
          return $(this).val();
        }).get();

        if (selectedPackages.length === 0) {
          Swal.fire({
            icon: 'warning',
            title: 'No package selected!',
            toast: true,
            position: 'top-end',
            showConfirmButton: false,
            timer: 3000
          });
          return;
        }

        Swal.fire({
          title: 'Are you sure?',
          text: "Selected packages will be permanently deleted.",
          icon: 'warning',
          showCancelButton: true,
          confirmButtonColor: '#d33',
          cancelButtonColor: '#3085d6',
          confirmButtonText: 'Yes, delete'
        }).then((result) => {
          if (result.isConfirmed) {
            $.ajax({
              url: "/admin/delete-rental-packages",
              type: "POST",
              contentType: "application/json",
              data: JSON.stringify({
                package_ids: selectedPackages
              }),
              success: function(response) {
                Swal.fire({
                  icon: 'success',
                  title: response.message || 'Deleted successfully!',
                  toast: true,
                  position: 'top-end',
                  showConfirmButton: false,
                  timer: 3000
                });
                pagination.loadData(pagination.currentPage, $("#pageLength").val());
              },
              error: function(xhr) {
                let errorMsg = 'Something went wrong!';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                  errorMsg = xhr.responseJSON.message;
                } else if (xhr.responseText) {
                  try {
                    const parsed = JSON.parse(xhr.responseText);
                    if (parsed.message) errorMsg = parsed.message;
                  } catch (e) {
                    errorMsg = xhr.responseText;
                  }
                }
                Swal.fire('Error!', errorMsg, 'error');
              }
            });
          }
        });
      });

      function attachSaveEvents() {
        $("#saveAllBtn").on("click", function() {
          let updatedPackages = [];

          $("#tripsTable tbody tr").each(function() {
            const $row = $(this);
            const packageId = $row.data("id");

            const updatedData = {
              package_id: packageId,
              pkg_desc: $row.find(".desc-html").text().trim() || '0',
              distance: $row.find("td").eq(3).text().trim() || '0',
              hours: $row.find("td").eq(4).text().trim() || '0',
              price: $row.find("td").eq(5).text().trim() || '0',
              extra_km_fare: $row.find("td").eq(6).text().trim() || '0',
              extra_hrs_fare: $row.find("td").eq(7).text().trim() || '0',
              extra_min_fare: $row.find("td").eq(8).text().trim() || '0',
              night_charges: $row.find("td").eq(9).text().trim() || '0',
              booking_max_hrs_limit: $row.find("td").eq(10).text().trim() || '0'
            };

            updatedPackages.push(updatedData);
          });

          // Confirm before saving
          Swal.fire({
            title: "Are you sure?",
            text: "You are about to save all changes!",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#3085d6",
            cancelButtonColor: "#d33",
            confirmButtonText: "Yes, save it!"
          }).then((result) => {
            if (result.isConfirmed) {
              // Send the updated data in bulk
              $.ajax({
                url: '/admin/update-rental-packages',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({
                  packages: updatedPackages
                }),
                success: function(response) {
                  Swal.fire({
                    icon: 'success',
                    title: response.message || 'Packages updated successfully!',
                    toast: true,
                    position: 'top-end',
                    showConfirmButton: false,
                    timer: 3000
                  });
                  pagination.loadData(pagination.currentPage, $("#pageLength").val());
                },
                error: function(xhr) {
                  let errorMsg = 'Something went wrong!';
                  if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMsg = xhr.responseJSON.message;
                  } else if (xhr.responseText) {
                    try {
                      const parsed = JSON.parse(xhr.responseText);
                      if (parsed.message) errorMsg = parsed.message;
                    } catch (e) {
                      errorMsg = xhr.responseText;
                    }
                  }
                  Swal.fire('Error!', errorMsg, 'error');
                }
              });
            }
          });
        });
      }

      $(document).ready(function() {
        const defaultLimit = $("#pageLength").val();
        pagination.loadData(1, defaultLimit);

        // Handle page length change
        $("#pageLength").change(function() {
          const newLimit = $(this).val();
          pagination.loadData(1, newLimit);
        });

        attachSaveEvents();

        // Show save button when editing
        $(document).on('focus', '.editable', function() {
          $('#saveAllBtn').show();
        });
      });
    </script>

    <%- footer %><script src="/js/demo-protection.js"></script>
