jQuery(function ($) {
  function toggleScheduleFields() {
    const val = $("#easy_gpt_edit_publish_action").val();
    if (val === "schedule") {
      $("#easy_gpt_edit_schedule_options").show();
    } else {
      $("#easy_gpt_edit_schedule_options").hide();
    }
  }

  $(document).on("change", "#easy_gpt_edit_publish_action", toggleScheduleFields);

  // Abrir modal
  $(document).on("click", ".easy-gpt-edit-generation", function () {
    const generationId = $(this).data("generation-id");

    $("#easy_gpt_edit_generation_id").val(generationId);

    $.post(easyGptBulkEdit.ajaxUrl, {
      action: "easy_gpt_get_bulk_generation_edit",
      nonce: easyGptBulkEdit.nonce,
      generation_id: generationId
    }).done(function (res) {
      if (!res || !res.success) {
        alert(res?.data?.message || "Failed loading data");
        return;
      }

      const g = res.data.generation;

      $("#easy_gpt_edit_publish_action").val(g.publish_action || "save_draft");
      $("#easy_gpt_edit_publish_frequency").val(g.publish_frequency || "daily");
      $("#easy_gpt_edit_start_date").val(g.start_date || "");
      $("#easy_gpt_edit_start_time").val(g.start_time || "");
      $("#easy_gpt_edit_articles_per_interval").val(g.articles_per_interval || 1);
      $("#easy_gpt_edit_minutes_between_articles").val(g.minutes_between_articles || 0);

      toggleScheduleFields();

      $("#easy-gpt-edit-modal").dialog({
        title: "Edit publishing options (pending only)",
        modal: true,
        width: 520,
		  create: function () {
			const $dlg = $(this).closest(".ui-dialog");
			const $btn = $dlg.find(".ui-dialog-titlebar-close");

			// quita tooltip
			$btn.removeAttr("title");

			// elimina nodos de texto (como "Close")
			$btn.contents().filter(function () {
			  return this.nodeType === 3; // TEXT_NODE
			}).remove();

			// por si el theme mete spans
			$btn.find(".ui-button-text, .ui-button-icon-space").remove();

			// opcional: accesibilidad (si quieres mantener label)
			$btn.attr("aria-label", "Close");
		  },
        buttons: {
          "Save": function () {
            const dialogRef = $(this);

            const payload = {
              action: "easy_gpt_save_bulk_generation_edit",
              nonce: easyGptBulkEdit.nonce,
              generation_id: $("#easy_gpt_edit_generation_id").val(),
              publish_action: $("#easy_gpt_edit_publish_action").val(),
              publish_frequency: $("#easy_gpt_edit_publish_frequency").val(),
              start_date: $("#easy_gpt_edit_start_date").val(),
              start_time: $("#easy_gpt_edit_start_time").val(),
              articles_per_interval: $("#easy_gpt_edit_articles_per_interval").val(),
              minutes_between_articles: $("#easy_gpt_edit_minutes_between_articles").val()
            };

            $.post(easyGptBulkEdit.ajaxUrl, payload).done(function (saveRes) {
              if (!saveRes || !saveRes.success) {
                alert(saveRes?.data?.message || "Failed saving");
                return;
              }
              dialogRef.dialog("close");
              // refrescar para ver cambios en la tabla
              window.location.reload();
            });
          },
          "Cancel": function () {
            $(this).dialog("close");
          }
        }
      });

    });
  });
});
			
jQuery(function ($) {

  function toggleTaskSchedule() {
    const val = $("#easy_gpt_edit_task_publish_action").val();
    if (val === "schedule") {
      $("#easy_gpt_edit_task_schedule_wrap").show();
    } else {
      $("#easy_gpt_edit_task_schedule_wrap").hide();
    }
  }

  $(document).on("change", "#easy_gpt_edit_task_publish_action", toggleTaskSchedule);

  // Click Edit task
  $(document).on("click", ".easy-gpt-edit-task", function () {
    const taskId = $(this).data("task-id");
    $("#easy_gpt_edit_task_id").val(taskId);

    $.post(easyGptBulkEdit.ajaxUrl, {
      action: "easy_gpt_get_task_edit",
      nonce: easyGptBulkEdit.nonce,
      task_id: taskId
    }).done(function (res) {
      if (!res || !res.success) {
        alert(res?.data?.message || "Failed loading task");
        return;
      }

      const t = res.data.task;

      $("#easy_gpt_edit_task_prompt").val(t.prompt || "");
      $("#easy_gpt_edit_task_keywords").val(t.keywords || "");
      $("#easy_gpt_edit_task_publish_action").val(t.publish_action || "save_draft");

      // datetime-local: "YYYY-MM-DDTHH:MM"
      $("#easy_gpt_edit_task_scheduled_for").val(t.scheduled_for_local || "");

      toggleTaskSchedule();

      $("#easy-gpt-edit-task-modal").dialog({
        title: "Edit task (pending only)",
        modal: true,
        width: 600,
        create: function () {
          const $dlg = $(this).closest(".ui-dialog");
          const $btn = $dlg.find(".ui-dialog-titlebar-close");
          $btn.removeAttr("title");
          $btn.contents().filter(function () { return this.nodeType === 3; }).remove();
          $btn.find(".ui-button-text, .ui-button-icon-space").remove();
          $btn.attr("aria-label", "Close");
        },
        buttons: {
          "Save": function () {
            const dialogRef = $(this);

            const payload = {
              action: "easy_gpt_save_task_edit",
              nonce: easyGptBulkEdit.nonce,
              task_id: $("#easy_gpt_edit_task_id").val(),
              prompt: $("#easy_gpt_edit_task_prompt").val(),
              keywords: $("#easy_gpt_edit_task_keywords").val(),
              publish_action: $("#easy_gpt_edit_task_publish_action").val(),
              scheduled_for_local: $("#easy_gpt_edit_task_scheduled_for").val()
            };

            $.post(easyGptBulkEdit.ajaxUrl, payload).done(function (saveRes) {
              if (!saveRes || !saveRes.success) {
                alert(saveRes?.data?.message || "Failed saving task");
                return;
              }
              dialogRef.dialog("close");
              window.location.reload();
            });
          },
          "Cancel": function () { $(this).dialog("close"); }
        }
      });

    });
  });

});