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

    <% 
    const breadcrumbs = [
      { label: "Dashboard", href: "/admin/dashboard", icon: "bi bi-house-door" },
       { label: "Language 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.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 Languages: <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="languagesTable" 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="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">Language Details</th>
                <th class="px-4 py-2 text-left text-sm font-medium text-gray-600">Properties</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", "Code", "RTL", "Default", "Active", "Created", "Modified"
      ],
      dataMapper: (language) => [
        language.id,
        language.name || "N/A",
        language.code || "N/A",
        language.is_rtl ? "Yes" : "No",
        language.is_default ? "Yes" : "No",
        language.active ? "Active" : "Inactive",
        language.created || "N/A",
        language.modified || "N/A"
      ],
      filename: 'languages.csv'
    },
    pdf: {
      headers: [
        "ID", "Name", "Code", "RTL", "Default", "Active", "Created", "Modified"
      ],
      dataMapper: (language) => [
        language.id,
        language.name || "N/A",
        language.code || "N/A",
        language.is_rtl ? "Yes" : "No",
        language.is_default ? "Yes" : "No",
        language.active ? "Active" : "Inactive",
        language.created || "N/A",
        language.modified || "N/A"
      ],
      title: 'Languages Report',
      filename: 'languages.pdf',
      pageSize: 'A4',
      margin: {
        top: 20,
        right: 10,
        bottom: 20,
        left: 10
      },
      fontSize: 10
    },
    fetchAllUrl: '/admin/language/data?limit=99999',
    currentData: []
  };

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

  // Initialize pagination
  const pagination = new Pagination({
    fetchUrl: '/admin/language/data',
    defaultSort: {
      column: 'id',
      order: 'DESC'
    },
    dataMapper: (language) => `
      <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-language form-check-input" type="checkbox" value="${language.id}">
            </div>
          </td>   
                    
          <td class="px-4 py-3 text-sm text-gray-700">${language.id}</td>
          
          <td class="px-4 py-3">
            <div class="space-y-1">
              <div class="flex items-center">
                <i class="fas fa-language text-gray-500 h-5 w-5"></i>
                <span class="font-semibold ml-2">Name:</span> <span class="ml-2">${language.name || "N/A"}</span>
              </div>
              <div class="flex items-center">
                <i class="fas fa-code text-gray-500 h-5 w-5"></i>
                <span class="font-semibold ml-2">Code:</span> <span class="ml-2">${language.code || "N/A"}</span>
              </div>
            </div>
          </td>
          
          <td class="px-4 py-3">
            <div class="space-y-1">
              <div class="flex items-center">
                <span class="font-semibold">RTL:</span> 
                <span class="ml-2 badge ${language.is_rtl ? 'bg-warning' : 'bg-secondary'}">
                  ${language.is_rtl ? 'Yes' : 'No'}
                </span>
              </div>
              <div class="flex items-center">
                <span class="font-semibold">Default:</span> 
                <span class="ml-2 badge ${language.is_default ? 'bg-success' : 'bg-secondary'}">
                  ${language.is_default ? 'Yes' : 'No'}
                </span>
              </div>
            </div>
          </td>
          
          <td class="px-4 py-3">
            <div class="flex items-center">
              <span class="font-semibold">Status:</span> 
              <span class="ml-2 badge ${language.active ? 'bg-success' : 'bg-danger'}">
                ${language.active ? 'Active' : 'Inactive'}
              </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="${language.id}" 
              data-active="${language.active}"
            >
              <iconify-icon icon="${language.active ? 'mdi:check-circle' : 'mdi:cancel'}" 
                style="font-size: 1.5rem;"
                class="${language.active ? 'text-success' : 'text-danger'}">
              </iconify-icon>
            </button>

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

      // Show loading state
      button.prop('disabled', true);

      // Send AJAX request to update status
      $.ajax({
        url: `/admin/language/toggle-status`,
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
          id: id
        }),
        success: function(response) {
          if (response.success) {
            // Update the button's data attribute and icon
            const newStatus = !currentStatus;
            button.data('active', newStatus);
            const icon = button.find('iconify-icon');
            icon.attr('icon', newStatus ? 'mdi:check-circle' : 'mdi:cancel');
            icon.removeClass(newStatus ? 'text-danger' : 'text-success').addClass(newStatus ? 'text-success' : 'text-danger');
            
            // Update status badge in the table
            const statusBadge = button.closest('tr').find('.badge');
            statusBadge.removeClass(newStatus ? 'bg-danger' : 'bg-success').addClass(newStatus ? 'bg-success' : 'bg-danger');
            statusBadge.text(newStatus ? 'Active' : 'Inactive');
          } else {
            alert('Failed to update status');
          }
        },
        error: function() {
          alert('Something went wrong');
        },
        complete: function() {
          button.prop('disabled', false);
        }
      });
    });

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

      if (selectedLanguages.length === 0) {
        showToast("Please select at least one language 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/language/delete",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify({
              ids: selectedLanguages
            }),
            success: function(response) {
              showToast(response.message || "Languages deleted successfully!", "success");
              pagination.loadData(pagination.currentPage, $("#pageLength").val());
            },
            error: function() {
              showToast("Error deleting languages.", "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') %>