<%- include('../../layouts/head.ejs') %>

<script src="/js/pagination.js"></script>

<%- include('../../layouts/header.ejs') %>
<main class="dashboard-main">
  <%- include('../../layouts/navbar.ejs') %>

  <div class="container flex-1 pt-20 w-full my-4">
    <%- include('../../partials/utils/title.ejs', {title: "Page Manager"}) %>

    <% 
      const breadcrumbs = [
        { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
          { label: " Page 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 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" 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 onclick="window.location.href='/admin/add-page'" 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 class="px-4 py-2 text-left text-sm font-medium text-gray-600">Page Name</th>
                <th class="px-4 py-2 text-left text-sm font-medium text-gray-600">Page Slug</th>
                <th class="px-4 py-2 text-left text-sm font-medium text-gray-600">Status </th>
                <th class="px-4 py-2 text-left text-sm font-medium text-gray-600">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/getPageData',
    defaultSort: {
      column: '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?.id}"></td>
        <td class="px-4 py-3 text-sm text-gray-700">${location.id}</td>
        <td class="px-4 py-3">${location.page_name}</td>
        <td class="px-4 py-3">${location.slug}</td>
        <td class=" ">
          <button 
            class="text-white rounded-md px-3 py-2 toggle-status"
            data-id="${location.id}" 
            data-active="${location.active}"
          >
            <iconify-icon icon="${location.active == 1 ? 'mdi:account-check' : 'mdi:account-remove'}" 
              style="font-size: 1.5rem;"
              class="${location.active == 1 ? 'text-success' : 'text-danger'}">
            </iconify-icon>
          </button>
        </td>
        <td class=" ">
          <div class=" ">
            <a href="/admin/edit-page/${location.id}" class="text-blue-600 hover:text-blue-900 focus:outline-none">
              <button class="text-white rounded-md px-3 py-2">
                <a href="/admin/edit-page/${location.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:edit"></iconify-icon>
                </a>
              </button>
            </a>
          </div>
        </td>
      </tr>
    `
  });

  $(document).ready(function() {
    // 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-page-status/${id}`,
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
          active: newStatus
        }),
        success: function(response) {
          if (response.success) {
            // 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 {
            alert('Failed to update status');
          }
        },
        error: function() {
          alert('Something went wrong');
        },
        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/deletePages",
            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>

<%- include('../../layouts/footer.ejs') %>