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

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

       <%- 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="deleteSelected" class="btn shadow btn-danger" style="padding-block: 6px;">
             <i class="fas fa-trash"></i>
           </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 Pages: <span id="totalRows"></span> </h5>

           <!-- Include Heroicons or your icon set -->
           <!-- Example: Add Icon (Plus Icon from Heroicons) -->
           <button data-bs-toggle="modal" data-bs-target="#addRoleModal" 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">
             <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="trip_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>Status</th>
                   <th>Actions</th>
                 </tr>
               </thead>
               <tbody></tbody>
             </table>
           </div>
         </div>

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

   <script>
     // Initialize Pagination
     const pagination = new Pagination({
       fetchUrl: '/admin/rolesData',
       defaultSort: {
         column: 'id',
         order: 'DESC'
       },
       dataMapper: (role) => `
      <tr class="bg-white border-b hover:bg-gray-100">
        <td><input type="checkbox" class="select-role form-check-input" value="${role.id}"></td>
        <td>${role.id}</td>
        <td>${role.name}</td>
        <td>
          <button 
            class="toggle-status btn btn-sm ${role.active == 1 ? 'btn-success' : 'btn-danger'}"
            data-id="${role.id}" 
            data-active="${role.active}">
            ${role.active == 1 ? 'Active' : 'Inactive'}
          </button>
        </td>
        <td>
          <a href="/admin/roles/edit/${role.id}" class="btn btn-sm btn-primary">
            <i class="fas fa-edit"></i>
          </a>
          <button class="btn btn-sm btn-danger delete-single" data-id="${role.id}">
            <i class="fas fa-trash-alt"></i>
          </button>
        </td>
      </tr>
    `
     });

     $(document).ready(() => {
       pagination.loadData(1);

       // Select All Checkbox
       $(document).on('change', '#selectAll', function() {
         $('.select-role').prop('checked', this.checked);
       });

       // Toggle Status
       $(document).on('click', '.toggle-status', async function() {
         const id = $(this).data('id');
         const currentStatus = $(this).data('active');
         const newStatus = currentStatus == 1 ? 0 : 1;
         const action = currentStatus == 1 ? "deactivate" : "activate";

         Swal.fire({
           title: `Are you sure you want to ${action} this role?`,
           icon: "warning",
           showCancelButton: true,
           confirmButtonText: `Yes, ${action}`,
         }).then(async (result) => {
           if (result.isConfirmed) {
             try {
               const res = await fetch(`/admin/role-status/${id}`, {
                 method: "PUT",
                 headers: {
                   "Content-Type": "application/json"
                 },
                 body: JSON.stringify({
                   status: newStatus
                 })
               });
               const result = await res.json();
               if (res.ok) {
                 Swal.fire("Updated!", result.message, "success");
                 pagination.loadData(1);
               } else throw new Error(result.message);
             } catch (err) {
               Swal.fire("Error", err.message, "error");
             }
           }
         });
       });

       // Single Delete
       $(document).on('click', '.delete-single', function() {
         const id = $(this).data('id');
         deleteRoles([id]);
       });

       // Bulk Delete
       $('#deleteSelected').on('click', function() {
         const selectedIds = $('.select-role:checked').map((_, el) => el.value).get();
         if (selectedIds.length === 0) {
           return Swal.fire("No Selection", "Please select at least one role to delete.", "info");
         }
         deleteRoles(selectedIds);
       });

       async function deleteRoles(ids) {
         Swal.fire({
           title: `Are you sure?`,
           text: `This will delete ${ids.length} role(s) permanently.`,
           icon: "warning",
           showCancelButton: true,
           confirmButtonText: "Yes, delete",
           cancelButtonText: "Cancel",
           confirmButtonColor: "#d33",
           cancelButtonColor: "#3085d6",
         }).then(async (result) => {
           if (result.isConfirmed) {
             try {
               const res = await fetch(`/admin/delete-role`, {
                 method: "DELETE",
                 headers: {
                   "Content-Type": "application/json"
                 },
                 body: JSON.stringify({
                   ids
                 })
               });
               const result = await res.json();
               if (res.ok) {
                 Swal.fire("Deleted!", result.message, "success");
                 pagination.loadData(1);
               } else throw new Error(result.message);
             } catch (err) {
               Swal.fire("Error", err.message, "error");
             }
           }
         });
       }
     });
   </script>


   <script>
     // Create Role
     document.getElementById("createRoleForm").addEventListener("submit", async function(e) {
       e.preventDefault();

       const form = e.target;
       const name = form.name.value.trim();
       const status = form.status.value;

       try {
         const response = await fetch("/admin/create-role", {
           method: "POST",
           headers: {
             "Content-Type": "application/json",
           },
           body: JSON.stringify({
             name,
             status
           }),
         });

         const result = await response.json();

         if (response.ok) {
           Swal.fire("Success", result.message, "success").then(() => window.location.reload());
         } else {
           throw new Error(result.message);
         }
       } catch (error) {
         Swal.fire("Error", error.message, "error");
       }
     });
   </script>
   <%- footer %>