   <%- 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 ">
       <%- include('../../partials/utils/title.ejs', {title: "Deleted Companies"}) %>

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

       <%- include('../../partials/utils/breadcrumb', { breadcrumbs }) %>
       <div style="display: flex; justify-content: space-between; align-items: center;">
         <!-- Offcanvas for Search Filter Panel -->
         <div style="display: flex; justify-content: space-between; align-items: center; gap: 10px;">
           <button id="restoreSelected" class="btn shadow btn-success" style="padding-block: 6px;">
             <i class="fas fa-undo"></i> Restore
           </button>

         </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">Total Deleted Companies: <span id="totalRows"></span> </h5>

           <!-- Include Heroicons or your icon set -->
           <!-- Example: Add Icon (Plus Icon from Heroicons) -->
           <button onclick="window.location.href='/admin/add-sub-admin'" 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>



         <%- 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="user_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 class="px-4 py-2 text-left text-sm font-medium text-gray-600">Contact Detail</th>
                   <th class="px-4 py-2 text-left text-sm font-medium text-gray-600">Agency Code</th>
                   <th class="px-4 py-2 text-left text-sm font-medium text-gray-600">Other Detail</th>
                   <th class="px-4 py-2 text-left text-sm font-medium text-gray-600">Status</th>
                   <th class="">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: (t) => [
           t.id,
           t.name,
           t.location,
           t.radius,
           new Date(t.created).toLocaleString(),
         ],
         filename: 'pages.csv'
       },
       pdf: {
         headers: ["ID", "Name", "Address", "Radius", "Created"],
         dataMapper: (t) => [
           t.id,
           t.name,
           t.location,
           t.radius,
           new Date(t.created).toLocaleString(),
         ],
         title: 'Audience Report',
         filename: 'pages.pdf'
       },
       fetchAllUrl: '/admin/getPageData?limit=99999',
       currentData: []
     };

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


     // Initialize pagination
     const pagination = new Pagination({
       fetchUrl: '/admin/deletedCompaniesData',
       defaultSort: {
         column: 'user_id',
         order: 'DESC'
       },
       dataMapper: (location) => `
      <tr class="bg-white border-b hover:bg-gray-100">
        <td><input type="checkbox" class="select-driver form-check-input" value="${location?.user_id}"></td>
        <td class="px-4 py-3 text-sm text-gray-700">${location.user_id}</td>
        <td class="px-4 py-3">
          <div class="d-flex align-items-center">
            <img 
              src="<%= CATEGORY_BASE_URL %>${location.profile_image || '/placeholder.jpg'}" 
              alt="Profile" 
              class="me-2 rounded" 
              width="50" 
              height="50"
              style="object-fit: cover;"
              onerror="this.onerror=null; this.src='/placeholder.jpg';"
            >
            <div>
              <strong>${location.u_name}</strong><br>
              <small><i class="fas fa-envelope"></i> ${location.u_email}</small><br>
              <small><i class="fas fa-phone"></i> ${location.c_code || ''} ${location.u_phone || ''}</small>
            </div>
          </div>
        </td>
        <td class="px-4 py-3"><span class="badge bg-info"><%= AGENCY_CODE_PREFIX %>${location.user_id}</span></td>
        <td class="px-4 py-3">
          <div>
            <small><i class="fas fa-user-check text-success"></i> Active Driver: <strong>${location.active_drivers || 0}</strong></small><br>
            <small><i class="fas fa-user-times text-danger"></i> Inactive Driver: <strong>${location.inactive_drivers || 0}</strong></small><br>
            <small><i class="fas fa-car text-info"></i> Total Rides: <strong>${location.total_trips || 0}</strong></small><br>
            <small><i class="fas fa-wallet text-primary"></i> Wallet: <strong><%= city_cur || 'INR' %> ${(location.u_wallet || 0).toFixed(2)}</strong></small>
          </div>
        </td>
        <td class="px-4 py-3">
          <span class="badge bg-secondary">inactive</span>
        </td>
        <td class="px-4 py-3">
          <button class="restore-company w-32-px h-32-px bg-success-focus text-success-main rounded-circle d-inline-flex align-items-center justify-content-center" data-id="${location.user_id}" data-tooltip="Restore" style="border: none; cursor: pointer;  min-height:20px !important; margin-top: -8px;">
            <iconify-icon icon="mdi:restore"></iconify-icon>
          </button>
        </td>
      </tr>
    `
     });

     $(document).ready(function() {
       // Event delegation for restore button
       $(document).on('click', '.restore-company', function() {
         const button = $(this);
         const id = button.data('id');

         Swal.fire({
           title: 'Are you sure?',
           text: "This company will be restored.",
           icon: 'question',
           showCancelButton: true,
           confirmButtonColor: '#28a745',
           cancelButtonColor: '#6c757d',
           confirmButtonText: 'Yes, restore it!'
         }).then((result) => {
           if (result.isConfirmed) {
             button.prop('disabled', true);

             $.ajax({
               url: `/admin/restore-sub-admin/${id}`,
               method: 'POST',
               contentType: 'application/json',
               success: function(response) {
                 if (response.success) {
                   Swal.fire({
                     icon: 'success',
                     title: 'Restored!',
                     text: 'Company has been restored successfully.',
                     toast: true,
                     position: 'top-end',
                     showConfirmButton: false,
                     timer: 3000
                   });
                   pagination.loadData(pagination.currentPage);
                 } else {
                   Swal.fire('Error!', response.message || 'Failed to restore company', 'error');
                 }
               },
               error: function(xhr) {
                 const errorMessage = xhr.responseJSON?.message || 'Something went wrong';
                 Swal.fire('Error!', errorMessage, 'error');
               },
               complete: function() {
                 button.prop('disabled', false);
               }
             });
           }
         });
       });

       // Bulk restore selected companies
       $("#restoreSelected").on("click", function() {
         const selectedCompanies = $(".select-driver:checked").map(function() {
           return $(this).val();
         }).get();

         if (selectedCompanies.length === 0) {
           Swal.fire({
             icon: 'warning',
             title: 'No company selected',
             text: 'Please select at least one company to restore.',
             toast: true,
             position: 'top-end',
             showConfirmButton: false,
             timer: 3000
           });
           return;
         }

         Swal.fire({
           title: 'Are you sure?',
           text: `${selectedCompanies.length} company(ies) will be restored.`,
           icon: 'question',
           showCancelButton: true,
           confirmButtonColor: '#28a745',
           cancelButtonColor: '#6c757d',
           confirmButtonText: 'Yes, restore them!'
         }).then((result) => {
           if (result.isConfirmed) {
             $.ajax({
               url: "/admin/restore-sub-admins",
               type: "POST",
               contentType: "application/json",
               data: JSON.stringify({
                 ids: selectedCompanies
               }),
               success: function(response) {
                 Swal.fire({
                   icon: 'success',
                   title: response.message || 'Restored successfully!',
                   toast: true,
                   position: 'top-end',
                   showConfirmButton: false,
                   timer: 3000
                 });
                 pagination.loadData(1);
               },
               error: function(xhr) {
                 Swal.fire({
                   icon: 'error',
                   title: 'Error restoring companies.',
                   text: xhr.responseJSON?.message || 'Something went wrong',
                   toast: true,
                   position: 'top-end',
                   showConfirmButton: false,
                   timer: 3000
                 });
               }
             });
           }
         });
       });

       // Event delegation for toggle status buttons
       $(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;

         // Show loading state
         button.prop('disabled', true);

         // Send AJAX request to update status
         $.ajax({
           url: `/admin/update-sub-admin-status/${id}`,
           method: 'POST',
           contentType: 'application/json',
           data: JSON.stringify({
             active: newStatus
           }),
           success: function(response) {
             if (response.success) {
               // Show success message
               Swal.fire({
                 icon: 'success',
                 title: 'Success!',
                 text: response.message || 'Status updated successfully',
                 toast: true,
                 position: 'top-end',
                 showConfirmButton: false,
                 timer: 3000
               });
               // Update the button's data attribute and icon
               button.data('active', newStatus);
               const icon = button.find('iconify-icon');
               icon.attr('icon', newStatus === 1 ? 'mdi:account-check' : 'mdi:account-remove');
               icon.removeClass(newStatus === 1 ? 'text-danger' : 'text-success').addClass(newStatus === 1 ? 'text-success' : 'text-danger');
             } else {
               Swal.fire('Error!', response.message || 'Failed to update status', 'error');
             }
           },
           error: function(xhr) {
             const errorMessage = xhr.responseJSON?.message || 'Something went wrong';
             Swal.fire('Error!', errorMessage, 'error');
           },
           complete: function() {
             button.prop('disabled', false);
           }
         });
       });

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

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

         if (selectedDrivers.length === 0) {
           Swal.fire({
             icon: 'warning',
             title: 'No id selected',
             text: 'Please select at least one id to delete.',
             toast: true,
             position: 'top-end',
             showConfirmButton: false,
             timer: 3000
           });
           return;
         }

         Swal.fire({
           title: 'Are you sure?',
           text: "Selected id will be permanently deleted.",
           icon: 'warning',
           showCancelButton: true,
           confirmButtonColor: '#d33',
           cancelButtonColor: '#3085d6',
           confirmButtonText: 'Yes, delete'
         }).then((result) => {
           if (result.isConfirmed) {
             $.ajax({
               url: "/admin/delete-sub-admins",
               type: "POST",
               contentType: "application/json",
               data: JSON.stringify({
                 ids: selectedDrivers
               }),
               success: function(response) {
                 Swal.fire({
                   icon: 'success',
                   title: response.message || 'Deleted successfully!',
                   toast: true,
                   position: 'top-end',
                   showConfirmButton: false,
                   timer: 3000
                 });
                 pagination.loadData(1);
               },
               error: function() {
                 Swal.fire({
                   icon: 'error',
                   title: 'Error deleting redzone.',
                   toast: true,
                   position: 'top-end',
                   showConfirmButton: false,
                   timer: 3000
                 });
               }
             });
           }
         });
       });

       pagination.loadData(1);
     });
   </script>

   <%- footer %>