<?php

if (!defined('ABSPATH')) {
    exit;
}

class AIEO_WPDT_Enhancements {

    const OPTION = 'aieo_wpdt_enhance_pages';

    
    const DEFAULT_PAGE_IDS = array(204717, 205185, 205209, 213175, 214639, 214641, 214643);

    public static function register() {
        add_action('wp_enqueue_scripts', array(__CLASS__, 'enqueue_assets'));
        add_action('wp_ajax_wdt_save_table_frontend', array(__CLASS__, 'tag_origin'), 0);
        add_action('wp_ajax_nopriv_wdt_save_table_frontend', array(__CLASS__, 'tag_origin'), 0);
    }

    
    public static function allowed_page_ids() {
        $ids = get_option(self::OPTION, null);
        if (!is_array($ids) || empty($ids)) {
            $ids = self::DEFAULT_PAGE_IDS;
        }
        $ids = array_values(array_unique(array_filter(array_map('intval', $ids))));
        
        return (array) apply_filters('aieo_wpdt_enhance_page_ids', $ids);
    }

    public static function enqueue_assets() {
        $pages = self::allowed_page_ids();
        if (empty($pages) || !is_page($pages)) {
            return;
        }

        wp_register_style('aieo-wpdt-tooltips', false);
        wp_enqueue_style('aieo-wpdt-tooltips');
        wp_add_inline_style('aieo-wpdt-tooltips', self::tooltip_css());

        wp_register_script('aieo-wpdt-tooltips', false, array('jquery'), null, true);
        wp_add_inline_script('aieo-wpdt-tooltips', self::tooltip_js());
        wp_enqueue_script('aieo-wpdt-tooltips');
    }

    private static function tooltip_css() {
        return <<<CSS
.wpDataTable td.column-logger, .wpDataTable th.column-logger{display:none!important;}
.aieo-tip{
  position:fixed; z-index:99999; pointer-events:none;
  color: var(--os-colour, #002147);
  font-size:14px; line-height:1.5;
  font-family: Manrope, SFMono-Regular, Menlo, Consolas, monospace;
  padding:14px 18px; border-radius:30px; white-space:pre;
  max-width:90vw; max-height:60vh; overflow:auto;
  background: rgba(200,140,150,0.15);
  background-image: linear-gradient(to right, rgba(255,255,255,0.10), rgba(255,255,255,0.05));
  border:1px solid rgba(255,255,255,0.40);
  box-shadow:0 10px 26px rgba(0,0,0,.10), 0 2px 6px rgba(0,0,0,.06);
  backdrop-filter: blur(5px) saturate(180%);
  -webkit-backdrop-filter: blur(5px) saturate(180%);
}
@supports not ((backdrop-filter: blur(5px)) or (-webkit-backdrop-filter: blur(5px))) {
  .aieo-tip{ background: rgba(255,255,255,0.92); border:1px solid rgba(0,0,0,0.06); }
}
CSS;
    }

    private static function tooltip_js() {
        return <<<'JS'
jQuery(function($){
  function br2nl(html){ return (html || '').replace(/<br\s*\/?>/gi, '\n'); }
  function html2text(html){ return $('<div>').html(html).text(); }

  var $tip = $('<div class="aieo-tip" style="display:none"></div>').appendTo(document.body);
  var showTimer = null;

  function showTip(html, e){
    var text = html2text( br2nl(html||'') ).trim();
    if (!text) { $tip.hide(); return; }
    $tip.text(text).show();
    moveTip(e);
  }
  function moveTip(e){
    var x = e.clientX + 14, y = e.clientY + 36;
    var w = $tip.outerWidth(), h = $tip.outerHeight();
    var vw = window.innerWidth, vh = window.innerHeight;
    if (x + w + 10 > vw) x = vw - w - 10;
    if (y + h + 10 > vh) y = vh - h - 10;
    $tip.css({left:x+'px', top:y+'px'});
  }
  function hideTip(){ clearTimeout(showTimer); showTimer = null; $tip.hide(); }

  var EXCLUDE = '.column-existing_stock, .column-desired_qty, .column-status';

  function wireRow($row){
    var $log = $row.find('td.column-logger');
    if (!$log.length) return;
    var html = $log.html();
    var $targets = $row.children('td:visible').not(EXCLUDE);
    var idx = $row.index();
    $('table.DTFC_Cloned').each(function(){
      var $cloneRow = $(this).find('tbody > tr').eq(idx);
      $targets = $targets.add( $cloneRow.children('td:visible').not(EXCLUDE) );
    });
    $targets.off('.aieotip')
      .on('mouseenter.aieotip', function(e){
        clearTimeout(showTimer);
        var ev = e;
        showTimer = setTimeout(function(){ showTip(html, ev); }, 150);
      })
      .on('mousemove.aieotip', moveTip)
      .on('mouseleave.aieotip', hideTip)
      .on('focusin.aieotip', hideTip);
  }

  function applyTooltips($scope){
    var $tables = ($scope && $scope.length ? $scope : $(document)).find('.wpDataTable');
    $tables.each(function(){
      $(this).find('tbody > tr').each(function(){ wireRow($(this)); });
    });
  }
  function applyWithDelay($scope){
    applyTooltips($scope);
    setTimeout(function(){ applyTooltips($scope); }, 150);
  }

  applyWithDelay($(document));
  $(document).on('wpdt.initComplete wpdt.tableLoaded wpdt.drawTable draw.dt', function(e){
    var $root = $(e.target).closest('.wpDataTable');
    applyWithDelay($root.length ? $root : $(document));
  });

  if (window.MutationObserver){
    var mo = new MutationObserver(function(muts){
      for (var i=0;i<muts.length;i++){
        var $t = $(muts[i].target);
        if ($t.closest('.wpDataTable, table.DTFC_Cloned').length){
          applyWithDelay($(document));
          break;
        }
      }
    });
    mo.observe(document.body, {childList:true, subtree:true});
  }
});
JS;
    }

    
    public static function tag_origin() {
        $ref     = wp_get_referer();
        $post_id = $ref ? url_to_postid($ref) : 0;
        if (!$post_id || !in_array((int) $post_id, self::allowed_page_ids(), true)) {
            return;
        }
        if (!function_exists('wp_get_current_user')) {
            require_once ABSPATH . 'wp-includes/pluggable.php';
        }
        $user        = wp_get_current_user();
        $origin_user = ($user && $user->exists() && !empty($user->user_login)) ? $user->user_login : 'anonymous';

        global $wpdb;
        $wpdb->query($wpdb->prepare("SET @ORIGIN_USER = %s", $origin_user));
        $wpdb->query("SET @ORIGIN_TYPE = 'table_entry'"); 
    }
}
