<?php
if (const_or_default("WP_DEBUG_LOG_JS")) {
  function inoby_js_log() {
    $message = $_POST["message"] ?? "";
    $lines = $_POST["lines"] ?? "";
    $path = const_or_default("ABSPATH");

    if ($path && $message) {
      $date = wp_date("c");
      $error_message = str_replace("\n\r", "\n", "{$message}\n{$lines}");
      error_log("[{$date}]  " . trim(str_replace("\n", "\n    ", $error_message)) . "\n", 3, "{$path}/wp-content/debug_js.log");
    }

    wp_send_json_success();
  }

  add_action("wp_ajax_inoby_js_log", "inoby_js_log");
  add_action("wp_ajax_nopriv_inoby_js_log", "inoby_js_log");

  add_action(
    "wp_head",
    function () {
      ?>
          <script id="inoby-js-logging" type="text/javascript" async="">

            window.inoby_js_log = function(mesasge, data = null) {
              const url = window.ajaxUrl ?? "/wp-admin/admin-ajax.php";

              const formData = new FormData();
              formData.append("action", "inoby_js_log");
              formData.append("message", mesasge);
              const lines = [];
              if(data != null) {
                Object.entries(data).forEach((value, key) => {
                  lines.push(`${value[0]}: ${value[1]}`);
                });
              }
              formData.append("lines", lines.join("\n"));

              fetch(url, {
                method: "POST",
                credentials: 'same-origin', 
                body: formData,
              }).catch(res => {
                console.error(res.body);
                // nevadi co uz...
              });
            }

            window.addEventListener("error", function(ev) {
              window.inoby_js_log(ev.message, {
                filename: ev.filename,
                line: ev.lineno,
                callStack: ev.error.stack
              })
            })
          </script>
        <?php
    },
    0,
  );
} else {
  add_action(
    "wp_head",
    function () {
      ?>
              <script id="inoby-js-logging" type="text/javascript" async="">window.inoby_js_log = function(mesasge, data = null) {}</script>
          <?php
    },
    0,
  );
}
