$(document).ready(function () {
  loadComingSoonPage("/shared/coming_soon.php", "support_tickets", "#coming_soon_page");
  // getSupportTicketsData();
  // toggleDropdown("/shared/coming_soon.php", "support_tickets", "#coming_soon_page");
});

async function loadComingSoonPage(url, content_tag) {
  $.ajax({
    url:"/shared/coming_soon.php",
    success: function (data) {
      $(`#coming_soon_page`).html(data);
    },
    error: function (xhr, status, error) {
      console.error("Failed to fetch data:", status, error);
    },
  });
}

function getSupportTicketsData() {
  $("#support_ticket_form").hide();
  $("#support_ticket_data").show();
  dataRequest({
    getData: "yes",
    property_id: sessionStorage.getItem("propertyId"),
  });
}

function filterTicketsTableData(responseData) {
  const filteredTickets = {
    Open: [],
    InProgress: [],
    Blocked: [],
    Closed: [],
  };
  // Iterate over the response data and categorize tickets by status
  responseData.forEach((ticket) => {
    switch (ticket.status) {
      case "Open":
        filteredTickets.Open.push(ticket);
        break;
      case "In Progress":
        filteredTickets.InProgress.push(ticket);
        break;
      case "Blocked":
        filteredTickets.Blocked.push(ticket);
        break;
      case "Closed":
        filteredTickets.Closed.push(ticket);
        break;
      default:
        console.warn(`Unknown status: ${ticket.status}`);
        break;
    }
  });
  // create table for open tickets
  createTicketsTable(filteredTickets?.Open, "#open_tickets_table");
  createTicketsTable(filteredTickets?.InProgress, "#In_progress_tickets");
  createTicketsTable(filteredTickets?.Blocked, "#action_required_blocked");
  createTicketsTable(filteredTickets?.Closed, "#closed_tickets_table");
  createTicketsTable(responseData, "#all_tickets_table");
}

function createTicketsTable(responseData, tableId) {
  let data = responseData;
  document.getElementById(tableId).innerHTML=""

  // Start creating the table structure
  let html = `
    <div class="table-responsive p-0">
      <table class="table table-bordered table-head-fixed text-nowrap table-hover">
        <thead>
          <tr>
            <th>ID</th>
            <th>Subject</th>
            <th>Status</th>
            <th>Priority</th>
            <th>Category</th>
            <th>Owner</th>
            <th>Created at</th>
            <th>Action</th>
          </tr>
        </thead>
        <tbody>
  `;

  if (data.length === 0) {
    html +=
      "<tr><td colspan='8' class='text-center'>No data available</td></tr>";
  } else {
    // <td><div style="background-color: green; text-align: center; color: white; padding: 4px 2px; font-size: 0.8rem; border-radius: 3px;">${item.status}</div></td>
    data.forEach(function (item) {
      let statusColorClass = "";
      switch (item.status) {
        case "Open":
          statusColorClass = "bg-success"; // Green background for Open
          break;
        case "In Progress":
          statusColorClass = "bg-primary"; // Blue background for In Progress
          break;
        case "Resolved":
          statusColorClass = "bg-warning"; // Yellow background for Resolved
          break;
        case "Blocked":
          statusColorClass = "bg-danger"; // Red background for Blocked
          break;
        case "Closed":
          statusColorClass = "bg-secondary"; // Gray background for Closed
          break;
        default:
          statusColorClass = "bg-light"; // Default background color
          break;
      }

      html += `
        <tr>
          <td>${item.id}</td>
          <td>${item.subject}</td>
          <td><div class="text-center text-white px-2 py-1 rounded ${statusColorClass}">${item.status}</div></td>
          <td>${item.priority}</td>
          <td>${item.category}</td>
          <td>${item.owner_name}</td>
          <td>${item.ticket_created_at}</td>
          <td>
            <i class='fas fa-eye text-info cursor_pointer view_ticket_button' data-id="${item.id}"></i>
            <i class='fas fa-edit text-primary mx-2 cursor_pointer edit_ticket_button' data-id="${item.id}"></i>
            <i class='fas fa-trash-alt text-danger cursor_pointer delete_ticket_button' data-id="${item.id}"></i>
          </td>
        </tr>
      `;
    });
  }

  // Close the tbody and table tags
  html += `
        </tbody>
      </table>
    </div>
  `;

  // Insert the entire table structure into the specified element
  document.getElementById(tableId).innerHTML=DOMPurify.sanitize(html);
  bindSupportTicketsCardEvents(tableId);
}

function bindSupportTicketsCardEvents(containerId) {
  const $container = $(containerId);
  $container.off("click", ".view_ticket_button");
  $container.off("click", ".delete_ticket_button");
  $container.off("click", ".edit_ticket_button");
  $container.on("click", ".view_ticket_button", function () {
    const id = $(this).data("id");
    viewDetail(id);
  });
  $container.on("click", ".delete_ticket_button", function () {
    const id = $(this).data("id");
    deleteTicket(id);
  });
  $container.on("click", ".edit_ticket_button", function () {
    const id = $(this).data("id");
    editTicket(id);
  });
}

function addNewTicket() {
  $("#support_ticket_form").show();
  $("#support_ticket_data").hide();
}

function cancelEditing() {
  $("#support_ticket_data").show();
  $("#support_ticket_form").hide();
  $("#ticketForm")?.[0]?.reset();
  // Reset the submit button to default state
  $("#ticketSubmitButton").text("Submit").removeAttr("data-ticket-id");
}

function viewDetail(itemId) {
  window.location.href = "support_tickets_detail.php?id=" + itemId;
}

function submitTicketForm() {
  const subject = document.getElementById("subject").value;
  const type = document.getElementById("ticketType").value;
  const category = document.getElementById("Category").value;
  const priority = document.getElementById("Priority").value;
  const description = document.getElementById("description").value;
  const owner = document.getElementById("Owner").value;
  const property = sessionStorage.getItem("propertyId");

  if (!subject || !type || !priority || !owner) {
    console.log("please fill the require fields ");
    return;
  }
  var ticketId = $("#ticketSubmitButton").attr("data-ticket-id");
  if (ticketId) {
    let dataToSend = {
      subject,
      type,
      category,
      priority,
      description,
      owner,
      property,
      updateTicketData: "yes",
      updated_at: new Date(),
      id: ticketId,
    };
    dataRequest(dataToSend);
  } else {
    let dataToSend = {
      subject,
      type,
      category,
      priority,
      description,
      owner,
      property,
      status: "Open",
      saveTicketData: "yes",
    };
    dataRequest(dataToSend);
  }
}

function dataRequest(data) {
  $.ajax({
    url: "include/support_tickets/support_tickets_requests.php",
    type: "post",
    data,
    success: function (response) {
      if (data?.getData) {
        filterTicketsTableData(response);
      }
      if (data?.getFilteredData) {
        $("#filterModal").modal("hide");
        filterTicketsTableData(response);
      }
      if (data?.deleteSupportTicket) {
        getSupportTicketsData();
      }
      if (response?.error && (data?.saveTicketData || data?.updateTicketData)) {
        $("#formError").text(response?.error).addClass("alert alert-danger");
      } else {
        if (data?.getTicketDataWithId) {
          bindDataForEditing(response);
        }
        if (data?.saveTicketData || data?.updateTicketData) {
          getSupportTicketsData();
          cancelEditing();
        }
        if (data?.statusChange) {
          window.location.reload(); // to get the updated data
        }
      }
    },
    error: function (xhr, status, error) {
    console.error("Failed to fetch data:", status, error);
    },
  });
}

function deleteTicket(id) {
  dataRequest({
    id,
    deleteSupportTicket: "yes",
  });
}

function editTicket(id) {
  addNewTicket();
  dataRequest({ getTicketDataWithId: "yes", id });
}

function changeTicketStatus(id) {
  let dataToSend = {
    updateTicketStatus: "yes",
    statusChange: "yes",
    status: $("#statusSelect").val(),
    id: id,
  };
  dataRequest(dataToSend);
}

function toggleDropdown(status) {
  $("#statusSelect").val(status);
  if ($("#statusDropdown").is(":visible")) {
    $("#statusText").show();
  } else {
    $("#statusText").hide();
  }
  $("#statusDropdown").toggle();
}

function bindDataForEditing(data) {
  $("#subject").val(data.subject);
  $("#ticketType").val(data.type);
  $("#Category").val(data.category);
  $("#Priority").val(data.priority);
  $("#description").val(data.description);
  $("#Owner").val(data.owner);
  $("#Properties").val(data.property);
  // Change the button text to "Update" and set the ticket ID as a data attribute
  $("#ticketSubmitButton").text("Update").attr("data-ticket-id", data.id);
}

function filterTickets() {
  var category = $("#filterCategory").val();
  var type = $("#filterTicketType").val();
  var priority = $("#filterPriority").val();
  var owner = $("#filterOwner").val();
  var property = $("#filterProperties").val();

  var filterObject = {};

  // Check each property and add it to the object if it has a value
  if (category) filterObject.category = category;
  if (type) filterObject.type = type; // Corrected variable name
  if (priority) filterObject.priority = priority;
  if (owner) filterObject.owner = owner;
  if (property) filterObject.property = property;

  // Example log to console (you can modify this to suit your needs)
  if (Object.keys(filterObject).length === 0) return;
  filterObject.getFilteredData = "yes";
  addClearFilterButton();
  dataRequest(filterObject);
}

function addClearFilterButton() {
  if ($("#clearFilter").length > 0) return;
  var clearFilterButton = `
    <button class="btn btn-dark mr-3" id="clearFilter" type="button">
      <i class="fas fa-times"></i> Clear Filter
    </button>`;
  $("#filterDiv").append(clearFilterButton);

  // Event listener for the Clear Filter button
  $("#clearFilter").click(function () {
    $("#filterCategory").val("");
    $("#filterTicketType").val("");
    $("#filterPriority").val("");
    $("#filterOwner").val("");
    $("#filterProperties").val("");
    $("#clearFilter").hide();
    getSupportTicketsData(); // Assuming this function refreshes the ticket data without filters
  });
}

function addComment(ticketId) {
  var comment = $("#commentText").val();
  dataRequest({ comment, ticketId, saveComment: "yes" });
  $("#commentText").val("");
  window.location.reload();
}
