   <%- header %>
   <!-- pre-rendered navbar inserted -->
   <main class="dashboard-main">
     <%- navbar %>
     <!-- pre-rendered navbar inserted -->

     <script src="/js/pagination.js"></script>



     <div class="container flex-1 pt-20 w-full my-4">

       <%- include('../../partials/utils/title.ejs', {title: "Redzone Manager"}) %>

       <% 
    const breadcrumbs = [
      { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
       { label: " Redzone Manager" }
    ];
  %>

       <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>
       <div style="display: flex; justify-content: space-between; align-items: center;">
         <%- include('../../partials/utils/export-buttons.ejs') %>
         <!-- Offcanvas for Search Filter Panel -->
         <div style="display: flex; justify-content: space-between; align-items: center; gap: 10px;">
           <button data-tooltip="Delete selected redzone" 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 Redzones: <span id="totalRows"></span> </h5>
           <div style="display: flex; justify-content: space-between; align-items: center; gap: 10px;">
             <button class="btn btn-primary" onclick="window.location.href='/admin/redzones-on-map'">
               view on map
             </button>
             <button data-tooltip="Add new redzone" onclick="window.location.href='/admin/add-redzones'" class="bg-green-600 hover:bg-green-700 text-white font-semibold py-[10px] px-[12px] rounded-lg flex items-center justify-center" title="Add Page">
               <!-- Reusable Icon Component -->
               <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-5 h-5">
                 <path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15" />
               </svg>
             </button>
           </div>
         </div>

         <%- include('../../partials/globalSearch.ejs') %>


         <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="id">
                     ID
                     <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>Name</th>
                   <th>Address</th>
                   <th>Status</th>
                   <th>Options</th>
                 </tr>
               </thead>
               <tbody></tbody>
             </table>
           </div>
         </div>


         <div class="pagination">
           <div id="pagination"></div>
         </div>

       </div>
     </div>
   </main>



   <script>
     // Configure the export component
     window.exportConfig = {
       csv: {
         headers: ["ID", "Name", "Address", "Radius", "Created"],
         dataMapper: (redzone) => [
           redzone.id,
           redzone.name,
           redzone.location,
           redzone.radius,
           new Date(redzone.created).toLocaleString()
         ],
         filename: 'redzones.csv'
       },
       pdf: {
         headers: ["ID", "Name", "Address", "Radius", "Created"],
         dataMapper: (redzone) => [
           redzone.id,
           redzone.name,
           redzone.location,
           redzone.radius,
           new Date(redzone.created).toLocaleString()
         ],
         title: 'Redzones Report',
         filename: 'redzones.pdf',
         pageSize: 'A4',
         margin: {
           top: 20,
           right: 10,
           bottom: 20,
           left: 10
         },
         fontSize: 10
       },
       fetchAllUrl: '/admin/getRedzone?limit=99999',
       currentData: []
     };

     // Set global search input for pagination
     window.globalSearchInput = '#globalSearch';

     // Initialize pagination
     const pagination = new Pagination({
       fetchUrl: '/admin/getRedzone',
       defaultSort: {
         column: 'id',
         order: 'DESC'
       },
       dataMapper: (redzone) => {
         return `
    <tr class="bg-white border-b hover:bg-gray-100">
      <td>
        <div class="form-check style-check d-flex align-items-center">
          <input class="select-driver form-check-input" type="checkbox" value="${redzone.id}">
        </div>
      </td>
      <td class="px-4 py-3 text-sm text-gray-700">${redzone.id}</td>
      <td class="px-4 py-3">${redzone.name}</td>
      <td class="px-4 py-3">${redzone.location}</td>
      <td class="px-4 py-3 text-center">
        <button type="button" 
          data-tooltip="${redzone.active ==1 ? 'Click to deactivate redzone' : 'Click to activate redzone'}"
          class="toggle-status btn btn-sm d-flex align-items-center gap-2"
          data-id="${redzone.id}" 
          data-active="${redzone.active}">
          <iconify-icon icon="${redzone.active == 1 ? 'mdi:account-check' : 'mdi:account-remove'}" 
            class="status-icon ${redzone.active == 1 ? 'text-success' : 'text-danger'}" 
            style="font-size: 1.5rem;"></iconify-icon>
        </button>
      </td>
      <td class="px-4 py-3 text-center">
        <div class="flex justify-center items-center space-x-2" data-tooltip="Edit redzone">
          <button class="edit-trip" onclick="window.location.href='/admin/edit-redzone/${redzone.id}'" data-id="${redzone.id}">
            <a href="javascript:void(0)" class="w-32-px h-32-px bg-success-focus text-success-main rounded-circle d-inline-flex align-items-center justify-content-center">
              <iconify-icon icon="lucide:edit"></iconify-icon>
            </a>
          </button>
        </div>
      </td>
    </tr>
  `;
       }
     });

     $(document).ready(function() {
       // Initialize with default limit
       const defaultLimit = $("#pageLength").val();
       pagination.loadData(1, defaultLimit);

       // Handle page length change
       $("#pageLength").change(function() {
         const newLimit = $(this).val();
         pagination.loadData(1, newLimit);
       });

       // Toggle status event
       // Toggle status event
       $(document).on('click', '.toggle-status', function() {
         const button = $(this);
         const id = button.data('id');
         const currentStatus = parseInt(button.data('active'), 10);
         const newStatus = currentStatus === 1 ? 0 : 1;

         Swal.fire({
           title: 'Are you sure?',
           text: `Do you want to ${newStatus === 1 ? 'activate' : 'deactivate'} this redzone?`,
           icon: 'question',
           showCancelButton: true,
           confirmButtonColor: '#3085d6',
           cancelButtonColor: '#d33',
           confirmButtonText: 'Yes, update it!'
         }).then((result) => {
           if (result.isConfirmed) {
             $.ajax({
               url: `/admin/update-redzone-status/${id}`,
               method: 'POST',
               contentType: 'application/json',
               data: JSON.stringify({
                 active: newStatus
               }),
               success: function(response) {
                 if (response.success) {
                   // Update button data
                   button.data('active', newStatus);

                   // Update icon
                   const icon = button.find('.status-icon');
                   icon.attr('icon', newStatus === 1 ? 'mdi:account-check' : 'mdi:account-remove');
                   icon.removeClass('text-success text-danger')
                     .addClass(newStatus === 1 ? 'text-success' : 'text-danger');

                   // Update label
                   const label = button.find('.status-label');
                   // label.text(newStatus === 1 ? 'Active' : 'Inactive');

                   Swal.fire({
                     toast: true, // makes it a floating toast
                     position: 'top-end', // position of the toast (top-right)
                     icon: 'success', // icon type
                     title: 'Redzone status updated successfully!',
                     showConfirmButton: false, // no "OK" button
                     timer: 3000, // auto close after 3 seconds
                     timerProgressBar: true, // shows progress bar
                     background: '#ffffff', // optional: custom background
                     color: '#0f5132' // optional: custom text color
                   });
                 } else {
                   Swal.fire('Error!', response.message || 'Failed to update status', 'error');
                 }
               },
               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');
               }

             });
           }
         });
       });

       // Select/Deselect all checkboxes
       $("#selectAll").on("click", function() {
         $(".select-driver").prop("checked", this.checked);
       });

       // Delete selected redzones
       $("#deleteSelected").on("click", function() {
         const selectedRedzones = $(".select-driver:checked").map(function() {
           return $(this).val();
         }).get();

         if (selectedRedzones.length === 0) {
           Swal.fire({
             icon: 'warning',
             title: 'No selection',
             text: 'Please select at least one redzone to delete.',
             toast: true,
             position: 'top-end',
             showConfirmButton: false,
             timer: 3000
           });
           return;
         }

         Swal.fire({
           title: 'Are you sure?',
           text: "You won't be able to revert this!",
           icon: 'warning',
           showCancelButton: true,
           confirmButtonColor: '#d33',
           cancelButtonColor: '#3085d6',
           confirmButtonText: 'Yes, delete it!'
         }).then((result) => {
           if (result.isConfirmed) {
             $.ajax({
               url: "/admin/deleteRedzone",
               method: "POST",
               contentType: "application/json",
               data: JSON.stringify({
                 ids: selectedRedzones
               }),
               success: function(response) {
                 if (response.success) {
                   Swal.fire(
                     'Deleted!',
                     'Selected redzones have been deleted.',
                     'success'
                   );
                   pagination.loadData(pagination.currentPage, $("#pageLength").val());
                 } else {
                   Swal.fire(
                     'Failed!',
                     response.message || 'Failed to delete redzones',
                     'error'
                   );
                 }
               },
               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');
               }
             });
           }
         });
       });
     });
   </script>

   <%- footer %>