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

            <% const breadcrumbs=[ { label: "Dashboard" , href: "/admin/dashboard" , icon: "bi bi-house-door" }, {
              label: "Location 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 locations" 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.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 Locations: <span id="totalRows"></span> </h5>
                  </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="city_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">Basic Details</th>
                              <th class="px-4 py-2 text-left text-sm font-medium text-gray-600">Country Details</th>
                              <th class="px-4 py-2 text-left text-sm font-medium text-gray-600">Commission (%)</th>
                              <th class="px-4 py-2 text-left text-sm font-medium text-gray-600">TAX / VAT (%)</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: [
            "City ID", "City Code", "Currency", "PG Currency", "Distance Unit",
            "Country Code", "Timezone", "Commission (%)", "Tax (%)"
          ],
          dataMapper: (location) => [
            location.city_id,
            location.city_code || "N/A",
            location.city_cur || "N/A",
            location.pg_cur || "N/A",
            location.city_dist_unit || "N/A",
            location.country_code || "N/A",
            location.timezone || "N/A",
            location.city_comm || "0",
            location.city_tax || "0"
          ],
          filename: 'locations.csv'
        },
        pdf: {
          headers: [
            "City ID", "City Code", "Currency", "PG Currency", "Distance Unit",
            "Country Code", "Timezone", "Commission (%)", "Tax (%)"
          ],
          dataMapper: (location) => [
            location.city_id,
            location.city_code || "N/A",
            location.city_cur || "N/A",
            location.pg_cur || "N/A",
            location.city_dist_unit || "N/A",
            location.country_code || "N/A",
            location.timezone || "N/A",
            location.city_comm || "0",
            location.city_tax || "0"
          ],
          title: 'Locations Report',
          filename: 'locations.pdf',
          pageSize: 'A4',
          margin: {
            top: 20,
            right: 10,
            bottom: 20,
            left: 10
          },
          fontSize: 10
        },
        fetchAllUrl: '/admin/getLoc?limit=99999',
        currentData: []
      };

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

      // Initialize pagination
      const pagination = new Pagination({
        fetchUrl: '/admin/getLoc',
        defaultSort: {
          column: 'city_id',
          order: 'DESC'
        },
        dataMapper: (location) => `
      <tr class="bg-white border-b hover:bg-gray-100">
          <td>
                        <div class="form-check style-check d-flex align-items-center">
<input class="select-driver form-check-input" type="checkbox" value="${location.city_id}">
                        </div>
                    </td>   
                    
                    
                    
                    <td class="px-4 py-3 text-sm text-gray-700">${location.city_id}</td>
<td class="px-4 py-3">
  <div class="space-y-1">
    <div class="flex items-center">
      <i class="fas fa-city text-gray-500 h-5 w-5"></i>
      <span class="font-semibold ml-2">City Name:</span> <span class="ml-2">${location.city_name || "N/A"}</span>
    </div>
    <div class="flex items-center">
      <i class="fas fa-hashtag text-gray-500 h-5 w-5"></i>
      <span class="font-semibold ml-2">City Code:</span> <span class="ml-2">${location.city_code || "N/A"}</span>
    </div>
    <div class="flex items-center">
      <i class="fas fa-dollar-sign text-gray-500 h-5 w-5"></i>
      <span class="font-semibold ml-2">Currency:</span> <span class="ml-2">${location.city_cur || "N/A"}</span>
    </div>
    <div class="flex items-center">
      <i class="fas fa-money-bill-wave text-gray-500 h-5 w-5"></i>
      <span class="font-semibold ml-2">PG Currency:</span> <span class="ml-2">${location.pg_cur || "N/A"}</span>
    </div>
    <div class="flex items-center">
      <i class="fas fa-ruler text-gray-500 h-5 w-5"></i>
      <span class="font-semibold ml-2">Distance Unit:</span> <span class="ml-2">${location.city_dist_unit || "N/A"}</span>
    </div>
  </div>
</td>
        <td class="px-4 py-3">
          <div class="space-y-1">
            <div class="flex items-center">
              <i class="fas fa-flag text-gray-500 h-5 w-5"></i>
              <span class="font-semibold ml-2">Country Code:</span> <span class="ml-2">${location.country_code || "N/A"}</span>
            </div>
            <div class="flex items-center">
              <i class="fas fa-clock text-gray-500 h-5 w-5"></i>
              <span class="font-semibold ml-2">Timezone:</span> <span class="ml-2">${location.timezone || "N/A"}</span>
            </div>
          </div>
        </td>
        <td class="px-4 py-3">
         <div class="flex items-center">
  <span class="font-semibold">Commission:</span> 
  <span class="ml-2">${location.city_comm || "0"}${location.city_comm_type === 'F' ? ' Fixed' : '%'}</span>
</div>
        </td>
        <td class="px-4 py-3">
          <div class="flex items-center">
            <span class="font-semibold">TAX / VAT:</span> <span class="ml-2">${location.city_tax || "0"}%</span>
          </div>
        </td>
        <td class="px-4 py-3 text-center">
 
     <button 
            class="text-white rounded-md px-3 py-2 toggle-status"
            data-id="${location.city_id}" 
            data-active="${location.city_active}"
            data-tooltip="${location.city_active == 1 ? 'Click to deactivate location' : 'Click to activate location'}"
          >
            <iconify-icon icon="${location.city_active == 1 ? 'mdi:account-check' : 'mdi:account-remove'}" 
              style="font-size: 1.5rem;"
              class="${location.city_active == 1 ? 'text-success' : 'text-danger'}">
            </iconify-icon>
          </button>

            <button class="" 
            data-tooltip="Edit location"
           style="background: transparent; border: none; padding: 0.25rem; margin-left: 0.5rem;">
    <a onclick="window.location.href='/admin/edit-location/${location.city_id}'" data-id="${location.city_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>
        </td>
 
      </tr>
    `
      });


      $(document).ready(function () {
        // Initialize with default limit
        const defaultLimit = $("#pageLength").val();
        pagination.loadData(1, defaultLimit);

        // Handle page length change
        $("#pageLength").change(function () {
          const newLimit = $(this).val();
          pagination.loadData(1, newLimit);
        });

        // Reset form handler
        $("#resetForm").click(function () {
          $("#searchForm")[0].reset();
          pagination.loadData(1, $("#pageLength").val());
        });

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

        // 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/change-location-status`,
            method: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({
              city_id: id
            }),
            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);
            }
          });
        });


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

          if (selectedLocations.length === 0) {
            showToast("Please select at least one location to delete.", "warning");
            return;
          }

          Swal.fire({
            title: "Are you sure?",
            text: "You won't be able to revert this!",
            icon: "warning",
            showCancelButton: true,
            confirmButtonColor: "#d33",
            cancelButtonColor: "#3085d6",
            confirmButtonText: "Yes, delete them!"
          }).then((result) => {
            if (result.isConfirmed) {
              $.ajax({
                url: "/admin/deleteLoc",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({
                  ids: selectedLocations
                }),
                success: function (response) {
                  showToast(response.message || "Locations deleted successfully!", "success");
                  pagination.loadData(pagination.currentPage, $("#pageLength").val());
                },
                error: function () {
                  showToast("Error deleting locations.", "error");
                }
              });
            }
          });
        });
      });


      // Toast notification function
      function showToast(message, type = "error") {
        const Toast = Swal.mixin({
          toast: true,
          position: 'top-end',
          showConfirmButton: false,
          timer: 3000,
          timerProgressBar: true,
        });

        Toast.fire({
          icon: type,
          title: message
        });
      }
    </script>

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