   <%- 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 role: <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">
             <!-- 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="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>
     <!-- Add Role Modal -->
     <div class="modal fade" id="addRoleModal" tabindex="-1">
       <div class="modal-dialog">
         <div class="modal-content">
           <form id="createRoleForm">
             <div class="modal-header">
               <h5 class="modal-title">Add New Role</h5>
               <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
             </div>
             <div class="modal-body">
               <div class="mb-3">
                 <label class="form-label">Role Name</label>
                 <input type="text" class="form-control" name="name" required>
               </div>
               <div class="mb-3">
                 <label>Status</label>
                 <select name="status" class="form-control" required>
                   <option value="1">Active</option>
                   <option value="0">Inactive</option>
                 </select>
               </div>
             </div>
             <div class="modal-footer">
               <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
               <button type="submit" class="btn btn-primary">Save</button>
             </div>
           </form>
         </div>
       </div>
     </div>

     <!-- Edit Role Modal -->
     <div class="modal fade" id="editRoleModal" tabindex="-1">
       <div class="modal-dialog">
         <div class="modal-content">
           <form id="editRoleForm">
             <div class="modal-header">
               <h5 class="modal-title">Edit Role</h5>
               <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
             </div>
             <div class="modal-body">
               <input type="hidden" name="id" id="editRoleId">
               <div class="mb-3">
                 <label class="form-label">Role Name</label>
                 <input type="text" class="form-control" name="name" id="editRoleName" required>
               </div>
               <div class="mb-3">
                 <label>Status</label>
                 <select name="active" class="form-control" id="editRoleStatus" required>
                   <option value="1">Active</option>
                   <option value="0">Inactive</option>
                 </select>
               </div>
             </div>
             <div class="modal-footer">
               <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
               <button type="submit" class="btn btn-primary">Update</button>
             </div>
           </form>
         </div>
       </div>
     </div>
   </main>

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


     // 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="text-white rounded-md px-3 py-2 toggle-status"
            data-id="${role.id}" 
            data-active="${role.active}"
          >
            <iconify-icon icon="${role.active == 1 ? 'mdi:account-check' : 'mdi:account-remove'}" 
              style="font-size: 1.5rem;"
              class="${role.active == 1 ? 'text-success' : 'text-danger'}">
            </iconify-icon>
          </button>
        </td>
        <td>
          <button class="btn btn-sm btn-primary edit-role" 
                  data-id="${role.id}" 
                  data-name="${role.name}" 
                  data-active="${role.active}"
                  title="Edit Role">
            <i class="fas fa-edit"></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");
             }
           }
         });
       });

       // Edit Role
       $(document).on('click', '.edit-role', function() {
         const id = $(this).data('id');
         const name = $(this).data('name');
         const active = $(this).data('active');

         $('#editRoleId').val(id);
         $('#editRoleName').val(name);
         $('#editRoleStatus').val(active);
         $('#editRoleModal').modal('show');
       });

       // 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(() => {
             $('#addRoleModal').modal('hide');
             pagination.loadData(1);
             form.reset();
           });
         } else {
           throw new Error(result.message);
         }
       } catch (error) {
         Swal.fire("Error", error.message, "error");
       }
     });

     // Edit Role
     document.getElementById("editRoleForm").addEventListener("submit", async function(e) {
       e.preventDefault();

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

       try {
         const response = await fetch(`/admin/update-role/${id}`, {
           method: "PUT",
           headers: {
             "Content-Type": "application/json",
           },
           body: JSON.stringify({
             name,
             active
           }),
         });

         const result = await response.json();

         if (response.ok) {
           Swal.fire("Success", result.message, "success").then(() => {
             $('#editRoleModal').modal('hide');
             pagination.loadData(1);
           });
         } else {
           throw new Error(result.message);
         }
       } catch (error) {
         Swal.fire("Error", error.message, "error");
       }
     });
   </script>
   <%- footer %>