/**
 * SGAccount Global JS
 * -------------------------------------------------------------
 * Shared frontend utilities for AdminLTE 3.2 interface.
 * Handles DataTables, Toast notifications, modals, and AJAX.
 * -------------------------------------------------------------
 * Author: SGAccount (Home Renovation Accounting)
 */

(function ($) {
  "use strict";

  // ============================================================
  // 🧩 GLOBAL INITIALIZATION
  // ============================================================

  $(function () {
    // Activate AdminLTE Sidebar & Tooltips
    $('[data-toggle="tooltip"]').tooltip();
    $('[data-widget="pushmenu"]').PushMenu();
  });

  // ============================================================
  // 📊 DATATABLES DEFAULT SETTINGS
  // ============================================================
  window.sgInitDataTables = function (selector = ".datatable") {
    if (!$.fn.DataTable) return;

    $(selector).each(function () {
      const $table = $(this);

      // Skip re-init
      if ($.fn.DataTable.isDataTable($table)) return;

      $table.DataTable({
        responsive: true,
        autoWidth: false,
        pageLength: 10,
        lengthMenu: [5, 10, 25, 50],
        order: [[0, "asc"]],
        language: {
          emptyTable: "No records available.",
          zeroRecords: "No matching records found.",
          info: "Showing _START_ to _END_ of _TOTAL_ entries",
          paginate: { previous: "‹", next: "›" },
        },
      });
    });
  };

  // ============================================================
  // 🔔 TOASTR CONFIGURATION
  // ============================================================
  if (typeof toastr !== "undefined") {
    toastr.options = {
      closeButton: true,
      progressBar: true,
      positionClass: "toast-bottom-right",
      timeOut: 3000,
      extendedTimeOut: 2000,
      showDuration: 300,
      hideDuration: 300,
    };

    window.sgToast = {
      success: (msg) => toastr.success(msg || "Operation successful."),
      error: (msg) => toastr.error(msg || "Something went wrong."),
      info: (msg) => toastr.info(msg || "Notice"),
      warning: (msg) => toastr.warning(msg || "Warning"),
    };
  }

  // ============================================================
  // 💾 UNIVERSAL AJAX HELPERS
  // ============================================================
  window.sgAjax = {
    post: function (url, data, successCb, failCb) {
      $.ajax({
        url,
        method: "POST",
        data,
        dataType: "json",
        success: function (res) {
          if (res.success) {
            sgToast.success(res.message);
            if (typeof successCb === "function") successCb(res);
          } else {
            sgToast.error(res.message || "Failed to process request.");
            if (typeof failCb === "function") failCb(res);
          }
        },
        error: function (xhr) {
          sgToast.error("Server error (" + xhr.status + ")");
        },
      });
    },
    get: function (url, data, successCb) {
      $.get(url, data, function (res) {
        if (typeof successCb === "function") successCb(res);
      }).fail(() => sgToast.error("Failed to load data."));
    },
  };

  // ============================================================
  // 🧱 MODAL HANDLER
  // ============================================================
  window.sgModal = {
    load: function (modalId, url, params = {}) {
      const $modal = $(modalId);
      const $body = $modal.find(".modal-body");

      $body.html(
        '<div class="p-5 text-center text-muted"><i class="fas fa-spinner fa-spin fa-2x mb-2"></i><br>Loading...</div>'
      );
      $modal.modal("show");

      $.get(url, params, function (html) {
        $body.html(html);
      }).fail(() => {
        $body.html(
          '<div class="alert alert-danger m-3">Failed to load content.</div>'
        );
      });
    },
  };

  // ============================================================
  // 🧹 AUTO INITIALIZATION
  // ============================================================
  $(document).ready(function () {
    sgInitDataTables(".datatable, #journalTable");
  });
})(jQuery);
