<?php
/** Admin-Menü für AnyWareX Clone Translate */
if (!defined('ABSPATH'))
  exit;

// Editions / Feature-Flags
if (!class_exists('AWXCT_Features')) {
  require_once AWXCT_PATH . 'includes/class-features.php';
}

class AWXCT_Clone_Translate_Admin_Menu
{
  public function __construct()
  {
    add_action('admin_menu', array($this, 'register_menu'));
    add_action('admin_enqueue_scripts', array($this, 'custom_menu_icon_css'));

    // Assets
    add_action('admin_enqueue_scripts', array($this, 'enqueue_mapping_script'));
    add_action('admin_enqueue_scripts', array($this, 'enqueue_global_admin_css'));
    add_action('admin_enqueue_scripts', array($this, 'enqueue_switcher_preview_assets'));
    // add_action('admin_enqueue_scripts', array($this, 'enqueue_upgrade_script'));  // <--- auskommentieren/entfernen

    // Settings
    add_action('admin_init', array($this, 'register_switcher_settings'));
  }

  /* ===================== Menu ===================== */

  public function register_menu()
  {
    $gray_icon = AWXCT_URL . 'assets/images/logo/awxct-icon-20x20-gray.png';

    // Top-level: Welcome page
    add_menu_page(
      __('AnyWareX Clone Translate', 'anywarex-clone-translate'),
      __('AnyWareX Clone Translate', 'anywarex-clone-translate'),
      'manage_options',
      'anywarex-clone-translate',
      array($this, 'render_welcome_page'),
      $gray_icon,
      60
    );

    // 1) Welcome – first submenu entry, same slug as top-level
    add_submenu_page(
      'anywarex-clone-translate',
      __('Welcome', 'anywarex-clone-translate'),
      __('Welcome', 'anywarex-clone-translate'),
      'manage_options',
      'anywarex-clone-translate',
      array($this, 'render_welcome_page')
    );

    // 2) Languages – own slug
    add_submenu_page(
      'anywarex-clone-translate',
      __('Languages', 'anywarex-clone-translate'),
      __('Languages', 'anywarex-clone-translate'),
      'manage_options',
      'anywarex-clone-translate-languages',
      array($this, 'render_languages_page')
    );

    // 3) Mapping – unchanged
    add_submenu_page(
      'anywarex-clone-translate',
      __('Mapping', 'anywarex-clone-translate'),
      __('Mapping', 'anywarex-clone-translate'),
      'manage_options',
      'anywarex-clone-translate-mapping',
      array($this, 'render_mapping_page')
    );

    // NOTE (WP.org repo): No checkout/payment flows in the repository version.
    // If you want an Upgrade entry here, use a simple page that links to the external shop.
  }

  public function custom_menu_icon_css($hook_suffix)
  {
    $gray = esc_url(AWXCT_URL . 'assets/images/logo/awxct-icon-20x20-gray.png');
    $blue = esc_url(AWXCT_URL . 'assets/images/logo/awxct-icon-20x20-blue.png');
    $white = esc_url(AWXCT_URL . 'assets/images/logo/awxct-icon-20x20-white.png');

    $css = ''
      . '#toplevel_page_anywarex-clone-translate .wp-menu-image img{display:none!important}'
      . '#toplevel_page_anywarex-clone-translate .wp-menu-image{'
      . 'background-image:url(' . $gray . ') !important;background-repeat:no-repeat;background-position:center;background-size:20px 20px;'
      . '}'
      . '#toplevel_page_anywarex-clone-translate:hover .wp-menu-image{background-image:url(' . $blue . ') !important}'
      . '#toplevel_page_anywarex-clone-translate.wp-has-current-submenu .wp-menu-image,'
      . '#toplevel_page_anywarex-clone-translate.current .wp-menu-image{background-image:url(' . $white . ') !important}';

    // Small, global admin menu icon CSS (loaded on all admin screens)
    $handle = 'anywarex-clone-translate-menu-icon';
    wp_register_style($handle, false, array(), AWXCT_VERSION);
    wp_enqueue_style($handle);
    wp_add_inline_style($handle, $css);
  }

  /* ===================== Global admin CSS ===================== */

  /**
   * Enqueue shared admin.css on all AnyWareX Clone Translate admin screens.
   */
  public function enqueue_global_admin_css($hook_suffix)
  {
    // Limit to our own screens for performance
    if (strpos($hook_suffix, 'anywarex-clone-translate') === false && strpos($hook_suffix, 'awxct-') === false) {
      return;
    }

    $base_dir = AWXCT_PATH;
    $base_url = AWXCT_URL;

    // Shared AnyWareX WordPress Core UI.
    $core_rel = 'assets/css/awxwp-core.css';
    $core_path = $base_dir . $core_rel;
    $core_url = function_exists('awxct_get_style_url')
      ? awxct_get_style_url($core_rel)
      : $base_url . $core_rel;
    $core_ver = defined('AWXCT_VERSION')
      ? AWXCT_VERSION
      : (file_exists($core_path) ? filemtime($core_path) : time());

    wp_enqueue_style(
      'awxwp-core',
      $core_url,
      array(),
      $core_ver
    );

    // Clone Translate-specific admin styles.
    $rel = 'assets/css/admin.css';
    $path = $base_dir . $rel;
    $url = function_exists('awxct_get_style_url')
      ? awxct_get_style_url($rel)
      : $base_url . $rel;
    $ver = defined('AWXCT_VERSION')
      ? AWXCT_VERSION
      : (file_exists($path) ? filemtime($path) : time());

    wp_enqueue_style(
      'awxct-admin',
      $url,
      array('awxwp-core'),
      $ver
    );
  

// Flag Icons (used by the switcher preview and can also be reused in admin UI)
$flags_rel  = 'assets/vendor/flag-icons/css/flag-icons.min.css';
$flags_path = $base_dir . $flags_rel;

$flags_url = function_exists('awxct_get_style_url')
  ? awxct_get_style_url($flags_rel)
  : $base_url . $flags_rel;

$flags_ver = defined('AWXCT_VERSION')
  ? AWXCT_VERSION
  : (file_exists($flags_path) ? filemtime($flags_path) : time());

wp_enqueue_style(
  'awxct-flag-icons',
  $flags_url,
  array(),
  $flags_ver
);
}

  

  /* ===================== Switcher preview (admin only) ===================== */

  /**
   * Adds a tiny inline script for the switcher preview on the Languages page.
   * This reacts instantly to the "Display style" selection, without needing to save.
   */
  public function enqueue_switcher_preview_assets($hook_suffix)
  {
    // Only on our Languages screen.
    if (strpos($hook_suffix, 'anywarex-clone-translate-languages') === false) {
      return;
    }

    // Attach to an existing script handle; if none exists on this screen, register a tiny one.
    $handle = 'awxct-switcher-preview';
    wp_register_script($handle, '', array(), AWXCT_VERSION, true);
    wp_enqueue_script($handle);

    $js = implode("\n", array(
      '(function(){',
      '  function qs(sel){ return document.querySelector(sel); }',
      '  function qsa(sel){ return Array.prototype.slice.call(document.querySelectorAll(sel)); }',
      '',
      '  var selStyle = qs(\'#awxct_switcher_label_style\');',
      '  var box = qs(\'.awxct-plg-ct-switcher-preview\');',
      '  if(!selStyle || !box) return;',
      '',
      '  var btn = box.querySelector(\'.awxct-plg-ct-switcher-preview__btn\');',
      '  var items = qsa(\'.awxct-plg-ct-switcher-preview__item\');',
      '',
      '  function countryFromCode(code){',
      '    if(!code) return \'\';',
      '    code = String(code);',
      '    var parts = code.split(\'-\');',
      '    if(parts.length >= 2 && parts[1]) return parts[1].toLowerCase();',
      '    // fallback: use language code',
      '    return parts[0].toLowerCase();',
      '  }',
      '',
      '  function textFor(style, data){',
      '    var code = data.code || \'\';',
      '    var lang = (data.lang || \'\').toUpperCase();',
      '    var nativeName = data.native || data.lang || \'\';',
      '    var englishName = data.english || data.lang || \'\';',
      '    switch(style){',
      '      case \'locale\': return code;',
      '      case \'lang\': return lang;',
      '      case \'native\': return nativeName;',
      '      case \'english\': return englishName;',
      '      default: return lang;',
      '    }',
      '  }',
      '',
      '  function htmlFor(style, data){',
      '    var cc = data.country || countryFromCode(data.code);',
      '    var hasFlag = (style === \'flag\' || style.indexOf(\'flag+\') === 0);',
      '    var t = \'\';',
      '    if(style === \'flag\') t = \'\';',
      '    else if(style === \'flag+native\') t = textFor(\'native\', data);',
      '    else if(style === \'flag+english\') t = textFor(\'english\', data);',
      '    else if(style === \'flag+lang\') t = textFor(\'lang\', data);',
      '    else t = textFor(style, data);',
      '',
      '    var flagHtml = hasFlag ? \'<span class="fi fi-\' + cc + \'" aria-hidden="true"></span>\' : \'\';',
      '    var textHtml = (t ? \'<span class="awxct-plg-ct-switcher-preview__txt">\' + String(t).replace(/</g,\'&lt;\').replace(/>/g,\'&gt;\') + \'</span>\' : \'\');',
      '    return flagHtml + textHtml;',
      '  }',
      '',
      '  function apply(){',
      '    var style = selStyle.value || \'flag+lang\';',
      '    items.forEach(function(li){',
      '      var data = {',
      '        code: li.getAttribute(\'data-code\') || \'\',',
      '        lang: li.getAttribute(\'data-lang\') || \'\',',
      '        native: li.getAttribute(\'data-native\') || \'\',',
      '        english: li.getAttribute(\'data-english\') || \'\',',
      '        country: li.getAttribute(\'data-country\') || \'\'',
      '      };',
      '      li.innerHTML = htmlFor(style, data);',
      '    });',
      '',
      '    // Button uses the "selected" item if present, else first item.',
      '    var first = items[0];',
      '    var selected = box.querySelector(\'.awxct-plg-ct-switcher-preview__item.is-active\') || first;',
      '    if(selected && btn){',
      '      btn.innerHTML = selected.innerHTML;',
      '    }',
      '  }',
      '',
      '  selStyle.addEventListener(\'change\', apply);',
      '  apply();',
      '})();',
    ));

    wp_add_inline_script($handle, $js);
  }

/* ===================== Views ===================== */

  public function render_welcome_page()
  {
    if (!current_user_can('manage_options')) {
      return;
    }

    $view = AWXCT_PATH . 'admin/views/welcome-page.php';

    if (file_exists($view)) {
      include $view;
    } else {
      echo '<div class="wrap"><h1>' . esc_html__('Welcome', 'anywarex-clone-translate') . '</h1><p>';
      esc_html_e('Missing file: admin/views/welcome-page.php', 'anywarex-clone-translate');
      echo '</p></div>';
    }
  }

  public function render_languages_page()
  {
    include AWXCT_PATH . 'admin/views/languages-page.php';
  }

  public function render_mapping_page()
  {
    include AWXCT_PATH . 'admin/views/mapping-page.php';
  }

  public function render_translate_page()
  {
    include AWXCT_PATH . 'admin/views/translate-page.php';
  }

  public function render_settings_page()
  {
    include AWXCT_PATH . 'admin/views/settings-page.php';
  }

  public function render_overview_page()
  {
    include AWXCT_PATH . 'admin/views/overview-page.php';
  }

  /* ===================== JSON Info Pages (JS/PHP) ===================== */
  /* Werden aktuell über die Tabs der Welcome-Page eingebunden,
     bleiben aber als Fallback-Renderer erhalten. */

  public function render_json_js_info_page()
  {
    if (!current_user_can('manage_options')) {
      return;
    }

    $view = AWXCT_PATH . 'admin/views/json-js-based-page.php';
    if (file_exists($view)) {
      include $view;
    } else {
      echo '<div class="wrap"><h1>' . esc_html__('JSON (JS-based)', 'anywarex-clone-translate') . '</h1><p>';
      esc_html_e('Info view missing: admin/views/json-js-based-page.php', 'anywarex-clone-translate');
      echo '</p></div>';
    }
  }

  public function render_json_php_info_page()
  {
    if (!current_user_can('manage_options')) {
      return;
    }

    $view = AWXCT_PATH . 'admin/views/json-php-based-page.php';
    if (file_exists($view)) {
      include $view;
    } else {
      echo '<div class="wrap"><h1>' . esc_html__('JSON (PHP-based)', 'anywarex-clone-translate') . '</h1><p>';
      esc_html_e('Info view missing: admin/views/json-php-based-page.php', 'anywarex-clone-translate');
      echo '</p></div>';
    }
  }

  /* ===================== Mapping assets ===================== */

  public function enqueue_mapping_script($hook_suffix)
  {
    if ($hook_suffix !== 'anywarex-clone-translate_page_anywarex-clone-translate-mapping') {
      return;
    }

    $base_dir = AWXCT_PATH;
    $base_url = AWXCT_URL;

    $rel_js = 'assets/js/mapping.js';
    $path_js = $base_dir . $rel_js;

    // Prefer minified file via helper if available
    $url_js = function_exists('awxct_get_script_url')
      ? awxct_get_script_url($rel_js)
      : $base_url . $rel_js;

    $version = defined('AWXCT_VERSION')
      ? AWXCT_VERSION
      : (file_exists($path_js) ? filemtime($path_js) : '1.0.0');

    wp_enqueue_script(
      'awxct-mapping-script',
      $url_js,
      array('jquery'),
      $version,
      true
    );

    wp_localize_script('awxct-mapping-script', 'awxctMappingData', array(
      'ajax_url' => admin_url('admin-ajax.php'),
    ));
  }

  /* ===================== Switcher settings ===================== */

  public function register_switcher_settings()
  {
    // 1) Label style option
    register_setting('anywarex-clone-translate', 'awxct_switcher_label_style', array(
      'type' => 'string',
      'sanitize_callback' => function ($v) {
        $allowed = array('locale', 'lang', 'native', 'english', 'flag', 'flag+lang', 'flag+native', 'flag+english');
        // Fallback: Flag + EN
        return in_array($v, $allowed, true) ? $v : 'flag+lang';
      },
      // Default: Flag + EN
      'default' => 'flag+lang',
    ));

    // 2) Position option
    register_setting('anywarex-clone-translate', 'awxct_switcher_position', array(
      'type' => 'string',
      'sanitize_callback' => function ($v) {
        $allowed = array('floating_top_left', 'floating_top_right', 'menu_end');
        return in_array($v, $allowed, true) ? $v : 'floating_top_left';
      },
      'default' => 'floating_top_left',
    ));

    // 3) Optional custom CSS for the frontend switcher
    register_setting('anywarex-clone-translate', 'awxct_switcher_custom_css', array(
      'type' => 'string',
      'sanitize_callback' => function ($v) {
        $v = is_string($v) ? $v : '';
        $v = wp_kses_no_null($v);
        return trim($v);
      },
      'default' => '',
    ));

    add_settings_section(
      'awxct_switcher_section',
      __('Language Switcher', 'anywarex-clone-translate'),
      function () {
        echo '<p>' . esc_html__('Display of the frontend language switcher.', 'anywarex-clone-translate') . '</p>';
      },
      'anywarex-clone-translate'
    );

    // Single field that renders both <select> elements
    add_settings_field(
      'awxct_switcher_label_style',
      __('Display & Position', 'anywarex-clone-translate'),
      function () {
        $style_option = 'awxct_switcher_label_style';
        $pos_option = 'awxct_switcher_position';

        $style_val = get_option($style_option, 'flag+lang');
        $pos_val = get_option($pos_option, 'floating_top_left');

        $style_choices = array(
          // Flag-based (prioritized at top)
          'flag+lang' => __('Flag + EN', 'anywarex-clone-translate'),
          'flag' => __('Flag only', 'anywarex-clone-translate'),
          'flag+native' => __('Flag + English (native)', 'anywarex-clone-translate'),
          'flag+english' => __('Flag + English (English)', 'anywarex-clone-translate'),
          // Non-flag variants
          'locale' => __('EN-US (Locale)', 'anywarex-clone-translate'),
          'lang' => __('EN (Short)', 'anywarex-clone-translate'),
          'native' => __('English (Native name)', 'anywarex-clone-translate'),
          'english' => __('English (English name)', 'anywarex-clone-translate'),
        );

        $pos_choices = array(
          'floating_top_left' => __('Floating (top left)', 'anywarex-clone-translate'),
          'floating_top_right' => __('Floating (top right)', 'anywarex-clone-translate'),
          'menu_end' => __('At end of main menu', 'anywarex-clone-translate'),
        );

        echo '<div class="awxct-plg-ct-switcher-layout">';
        echo '<div class="awxct-plg-ct-switcher-controls">';

        // Style
        echo '<p><label for="' . esc_attr($style_option) . '"><strong>' . esc_html__('Display style', 'anywarex-clone-translate') . '</strong></label><br />';
        echo '<select name="' . esc_attr($style_option) . '" id="' . esc_attr($style_option) . '" class="awxct-plg-ct-select">';
        foreach ($style_choices as $k => $label) {
          printf('<option value="%s" %s>%s</option>', esc_attr($k), selected($style_val, $k, false), esc_html($label));
        }
        echo '</select></p>';

        // Position
        echo '<p><label for="' . esc_attr($pos_option) . '"><strong>' . esc_html__('Placement', 'anywarex-clone-translate') . '</strong></label><br />';
        echo '<select name="' . esc_attr($pos_option) . '" id="' . esc_attr($pos_option) . '" class="awxct-plg-ct-select">';
        foreach ($pos_choices as $k => $label) {
          printf('<option value="%s" %s>%s</option>', esc_attr($k), selected($pos_val, $k, false), esc_html($label));
        }
        echo '</select></p>';

        echo '</div>';

        // Preview (admin-only, visual helper)
$sample = array(
  array('code' => 'de-DE', 'native' => 'Deutsch',  'english' => 'German'),
  array('code' => 'en-US', 'native' => 'English',  'english' => 'English'),
  array('code' => 'fr-FR', 'native' => 'Français', 'english' => 'French'),
);

$country_from_code = function($code) {
  $code = (string) $code;
  $parts = explode('-', $code);
  if (count($parts) >= 2 && !empty($parts[1])) {
    return strtolower((string) $parts[1]);
  }
  return strtolower(substr($code, 0, 2));
};

$text_for = function($style, $row) {
  $code = isset($row['code']) ? (string) $row['code'] : '';
  $lang = strtoupper(substr($code, 0, 2));
  $native = isset($row['native']) ? (string) $row['native'] : $lang;
  $english = isset($row['english']) ? (string) $row['english'] : $lang;

  switch ($style) {
    case 'locale': return $code;
    case 'native': return $native;
    case 'english': return $english;
    case 'lang':
    default: return $lang;
  }
};

$html_for = function($style, $row) use ($country_from_code, $text_for) {
  $code = isset($row['code']) ? (string) $row['code'] : '';
  $cc   = $country_from_code($code);

  $has_flag = ( 'flag' === $style ) || ( 0 === strpos($style, 'flag+') );
  $flag_html = $has_flag ? '<span class="fi fi-' . esc_attr($cc) . '" aria-hidden="true"></span>' : '';

  $txt = '';
  if ('flag' === $style) {
    $txt = '';
  } elseif ('flag+native' === $style) {
    $txt = $text_for('native', $row);
  } elseif ('flag+english' === $style) {
    $txt = $text_for('english', $row);
  } elseif ('flag+lang' === $style) {
    $txt = $text_for('lang', $row);
  } else {
    $txt = $text_for($style, $row);
  }

  $txt_html = $txt ? '<span class="awxct-plg-ct-switcher-preview__txt">' . esc_html($txt) . '</span>' : '';
  return $flag_html . $txt_html;
};

echo '<div class="awxct-plg-ct-switcher-preview" aria-label="' . esc_attr__('Preview', 'anywarex-clone-translate') . '">';
echo '<div class="awxct-plg-ct-switcher-preview__title">' . esc_html__('Preview', 'anywarex-clone-translate') . '</div>';
echo '<div class="awxct-plg-ct-switcher-preview__note">' . esc_html__('This is a visual preview in the admin area. The frontend switcher may look slightly different depending on your theme.', 'anywarex-clone-translate') . '</div>';
echo '<button type="button" class="awxct-plg-ct-switcher-preview__btn" aria-haspopup="listbox" aria-expanded="false">' . wp_kses_post( $html_for($style_val, $sample[1]) ) . '</button>';
echo '<ul class="awxct-plg-ct-switcher-preview__list" role="listbox">';
foreach ($sample as $i => $row) {
  $code = isset($row['code']) ? (string) $row['code'] : '';
  $lang = strtolower(substr($code, 0, 2));
  $cc   = $country_from_code($code);

  $cls = 'awxct-plg-ct-switcher-preview__item' . (1 === (int) $i ? ' is-active' : '');
  echo '<li class="' . esc_attr($cls) . '" role="option"'
    . ' data-code="' . esc_attr($code) . '"'
    . ' data-lang="' . esc_attr($lang) . '"'
    . ' data-native="' . esc_attr(isset($row['native']) ? (string) $row['native'] : '') . '"'
    . ' data-english="' . esc_attr(isset($row['english']) ? (string) $row['english'] : '') . '"'
    . ' data-country="' . esc_attr($cc) . '">'
    . wp_kses_post( $html_for($style_val, $row) )
    . '</li>';
}
echo '</ul>';
echo '</div>'; // .awxct-plg-ct-switcher-preview
echo '</div>'; // .awxct-plg-ct-switcher-layout


      },
      'anywarex-clone-translate',
      'awxct_switcher_section'
    );

    add_settings_field(
      'awxct_switcher_custom_css',
      __('Custom CSS', 'anywarex-clone-translate'),
      function () {
        $option_name = 'awxct_switcher_custom_css';
        $value = (string) get_option($option_name, '');

        echo '<div class="awxct-switcher-css-field">';
        echo '<p style="margin:0 0 8px 0;">' . esc_html__('Paste your own CSS for the frontend language switcher here. It will be loaded automatically on the website.', 'anywarex-clone-translate') . '</p>';
        echo '<div class="awxct-switcher-css-field__hint">';
        echo '<strong>' . esc_html__('Need help with selectors and examples?', 'anywarex-clone-translate') . '</strong><br>';
        echo esc_html__('See:', 'anywarex-clone-translate') . ' <a href="' . esc_url(admin_url('admin.php?page=anywarex-clone-translate&tab=css')) . '">' . esc_html__('Welcome → Custom CSS (Switcher)', 'anywarex-clone-translate') . '</a>';
        echo '</div>';
        echo '<div class="awxct-switcher-css-field__editor">';
        echo '<textarea name="' . esc_attr($option_name) . '" id="' . esc_attr($option_name) . '" class="large-text awxct-code awxct-switcher-css-field__textarea" rows="12" spellcheck="false" placeholder=".menu-item-awxct-lang .awxct-plg-ct-btn {
  background: #151515;
  color: #fff;
}

#awxct-plg-ct-switcher-root .awxct-plg-ct-menu {
  border-radius: 12px;
}">' . esc_textarea($value) . '</textarea>';
        echo '</div>';
        echo '<p class="description">' . esc_html__('Tip: You can target the header menu switcher via .menu-item-awxct-lang ... and the floating switcher via #awxct-plg-ct-switcher-root ...', 'anywarex-clone-translate') . '</p>';
        echo '</div>';
      },
      'anywarex-clone-translate',
      'awxct_switcher_section'
    );
  }

  /* ===================== JSON-Option + Editor (nur Plus/Pro) ===================== */
  /* In der Free-Edition bewusst NICHT implementiert */
}