   <%- 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: "Audience Manager"}) %>

     <% 
    const breadcrumbs = [
      { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
       { label: " Audience 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 audience"  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-withApi.ejs') %>
         </div>
       </div>
     </div>

     <div class="card basic-data-table" style="margin-top: 20px;">
       <div class="card-header">
         <h5 class="card-title mb-0">Total Audiences: <span id="totalRows"></span> </h5>
       </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="audience_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>Audience Name</th>
                 <th>SMS</th>
                                                   <th>Email</th>

                 <th>Notification</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", "Audience Name"],
       dataMapper: (u) => [
         u.audience_id,
         u.title || "N/A",
       ],
       filename: 'audience.csv'
     },
     pdf: {
       headers: ["ID", "Audience Name"],
       dataMapper: (u) => [
         u.audience_id,
         u.title || "N/A",
       ],
       title: 'Audience Report',
       filename: 'audience.pdf'
     },
     fetchAllUrl: '/admin/getaudiencedata?limit=99999',
     currentData: []
   };

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

   // Initialize pagination
   const pagination = new Pagination({
     fetchUrl: '/admin/getaudiencedata',
     defaultSort: {
       column: 'audience_id',
       order: 'DESC'
     },
     dataMapper: (user) => `
  <tr>
  <td>
    <div class="form-check style-check d-flex align-items-center">
      <input class="select-driver form-check-input" type="checkbox" value="${user.audience_id}">
    </div>
  </td> 
  <td>${user.audience_id}</td>
  <td>${user?.title || 'N/A'}</td>

  <!-- SMS Icon -->
  <td>
    <a data-tooltip="Send SMS to this audience"  href="/admin/sendSMS/${user.audience_id}" 
       class="text-blue-600" 
       style="font-size: 25px;"
       >
      <iconify-icon icon="ic:baseline-sms"></iconify-icon>
    </a>
  </td>

  <!-- Email Icon -->
  <td>
    <a href="/admin/sendEmail/${user.audience_id}" 
       class="text-green-600" 
       style="font-size: 25px;"
       data-tooltip="Send Email to this audience" >
      <iconify-icon icon="ic:baseline-email"></iconify-icon>
    </a>
  </td>

  <!-- Notification Icon -->
  <td>
    <a href="/admin/sendNotification/${user.audience_id}" 
       class="text-purple-600" 
       style="font-size: 25px;"
       data-tooltip="Send notification to this audience" >
      <iconify-icon icon="mdi:bell-outline"></iconify-icon>
    </a>
  </td>

  <!-- Edit Button -->
  <td>
    <button data-tooltip="Edit user"  style="background: transparent; border: none; padding: 0.25rem; margin-left: 0.5rem;">
      <a href="/admin/detail-audience/${user.audience_id}" 
         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:view"></iconify-icon>
      </a>
    </button>
  </td>
</tr>
 
    `
   });

   $(document).ready(function() {
     const filterOffcanvasEl = document.getElementById('filterOffcanvas');
     const filterOffcanvas = bootstrap.Offcanvas.getOrCreateInstance(filterOffcanvasEl);

     $(document).on('shown.bs.offcanvas hidden.bs.offcanvas', function() {
       const backdrops = $('.offcanvas-backdrop');
       if (backdrops.length > 1) {
         backdrops.slice(1).remove(); // Keep only one
       }
     });

     // When applying filters
     $("#applyFilters").click(function() {
       let filters = {};
       $("#searchForm").find("input, select").each(function() {
         const key = $(this).attr("name");
         const value = $(this).val().trim();
         if (value) filters[key] = value;
       });

       // Clear global search input
       $(window.globalSearchInput).val('');
       pagination.searchTerm = ''; // Clear global search term

       pagination.loadData(1, filters); // Apply filters
       filterOffcanvas.hide();
     });

     // Reset button
     $("#resetForm").click(function() {
       $("#searchForm")[0].reset();

       // Clear global search input
       $(window.globalSearchInput).val('');
       pagination.searchTerm = ''; // Clear global search term

       pagination.loadData(1, {}); // Reload with no filters
       filterOffcanvas.hide();
     });

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

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

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

       Swal.fire({
         title: 'Are you sure?',
         text: "Selected audience will be permanently deleted.",
         icon: 'warning',
         showCancelButton: true,
         confirmButtonColor: '#d33',
         cancelButtonColor: '#3085d6',
         confirmButtonText: 'Yes, delete'
       }).then((result) => {
         if (result.isConfirmed) {
           $.ajax({
             url: "/admin/audience/toggle-delete",
             type: "POST",
             contentType: "application/json",
             data: JSON.stringify({
               ids: selectedAudience
             }),
             success: function(response) {
               Swal.fire({
                 icon: 'success',
                 title: response.message || 'Deleted successfully!',
                 toast: true,
                 position: 'top-end',
                 showConfirmButton: false,
                 timer: 3000
               });
               pagination.loadData(1, {}); // Reload with no filters
             },
             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');
             }
           });
         }
       });
     });

     pagination.loadData(1);

   });
 </script>

 <%- footer %>