<?php
if (!defined('ABSPATH')) {
  exit;
}

/* =========================================================
   Extension Detection
   ========================================================= */
if (!function_exists('awxct_get_edition')) {
  function awxct_get_edition(): string
  {
    $plan = '';

    // 1) Prefer internal license class
    if (class_exists('AWXCT_License')) {
      // a) Dedicated method "get" → array
      if (method_exists('AWXCT_License', 'get')) {
        $lic = AWXCT_License::get();
        if (is_array($lic)) {
          $plan =
            $lic['plan']
            ?? $lic['edition']
            ?? $lic['tier']
            ?? $lic['license_plan']
            ?? '';
        }
      }

      // b) Optional helper method "plan"
      if (!$plan && method_exists('AWXCT_License', 'plan')) {
        $plan = AWXCT_License::plan();
      }
    }

    // 2) Fallback: read stored option directly
    if (!$plan) {
      $opt = get_option('awxct_license_plan', '');
      if (is_string($opt) && $opt !== '') {
        $plan = $opt;
      }
    }

    // 3) Normalize known plans
    if ($plan) {
      $p = strtolower(trim((string) $plan));

      if (in_array($p, ['free', 'plus', 'pro'], true)) {
        return ucfirst($p);  // "Free", "Plus", "Pro"
      }

      // Unknown/custom plan → return as label with first letter uppercase
      return ucfirst($p);
    }

    // 4) No license plan → fall back to build flags
    if (defined('AWXCT_PRO') && AWXCT_PRO) {
      return 'Pro';
    }
    if (defined('AWXCT_PLUS') && AWXCT_PLUS) {
      return 'Plus';
    }

    // Default: Free
    return 'Free';
  }
}

/* =========================================================
   Top 5 suggested languages
   ========================================================= */
if (!function_exists('awxct_get_top_languages')) {
  function awxct_get_top_languages(): array
  {
    return ['de', 'en', 'fr', 'es', 'it'];
  }
}

/* =========================================================
   Render dropdown <option> for languages
   ========================================================= */
if (!function_exists('awxct_render_language_dropdown')) {
  /**
   * @param string $selected   Aktuell ausgewählter Sprachcode
   * @param array  $languages  Array von Objekten oder Arrays mit ['code','name','native_name',...]
   */
  function awxct_render_language_dropdown($selected = '', $languages = []): void
  {
    if (empty($languages)) {
      return;
    }

    foreach ($languages as $lang) {
      $code = is_object($lang) ? ($lang->code ?? '') : ($lang['code'] ?? '');
      if ($code === '') {
        continue;
      }

      // Reihenfolge: name > native_name > CODE
      if (is_object($lang)) {
        $name = $lang->name
          ?? ($lang->native_name ?? strtoupper($code));
      } else {
        $name = $lang['name']
          ?? ($lang['native_name'] ?? strtoupper($code));
      }

      printf(
        '<option value="%s"%s>%s</option>',
        esc_attr($code),
        selected($selected, $code, false),
        esc_html($name)
      );
    }
  }
}

/* =========================================================
   Admin Header (Logo + Title + Edition)
   ========================================================= */
if (!function_exists('awxct_admin_header')) {
  function awxct_admin_header($subtitle = ''): void
  {
    if (!defined('AWXCT_URL') || !defined('AWXCT_FILE')) {
      return;
    }

    $logo_url    = AWXCT_URL . 'assets/images/logo/logo-anywarex.svg';
    $ct_icon_url = AWXCT_URL . 'assets/images/logo/awxct-icon-64x48-blue.png';

    $plugin_data = get_file_data(
      AWXCT_FILE,
      [
        'Version' => 'Version',
      ]
    );
    $version = isset($plugin_data['Version']) ? (string) $plugin_data['Version'] : '';

    // Free only provides its own badge. Active add-ons may inject additional
    // edition/version badges through the filter without Free knowing about them.
    $version_badges = [
      [
        'edition' => 'free',
        'label'   => __('Free', 'anywarex-clone-translate'),
        'version' => $version,
      ],
    ];
    $version_badges = apply_filters('awxct_admin_version_badges', $version_badges);

    ?>
    <div class="awxwp-core-header">
      <div class="awxwp-core-brand">
        <img
          src="<?php echo esc_url($logo_url); ?>"
          alt="<?php esc_attr_e('AnyWareX Logo', 'anywarex-clone-translate'); ?>"
          width="212"
          height="53"
          class="logo-awx awxwp-core-logo"
        >
        <img
          src="<?php echo esc_url($ct_icon_url); ?>"
          alt="<?php esc_attr_e('AnyWareX Clone Translate Icon', 'anywarex-clone-translate'); ?>"
          width="48"
          height="36"
          class="awxwp-core-product-icon"
        >
      </div>
      <div class="awxwp-core-heading">
        <div class="awxwp-core-title-row">
          <div class="awxwp-core-title">
            <?php echo esc_html__('Clone Translate', 'anywarex-clone-translate'); ?>
          </div>
          <?php if (!empty($version_badges) && is_array($version_badges)) : ?>
            <div class="awxwp-core-version-badges" aria-label="<?php esc_attr_e('Installed plugin versions', 'anywarex-clone-translate'); ?>">
              <?php foreach ($version_badges as $badge) : ?>
                <?php
                if (!is_array($badge)) {
                  continue;
                }
                $badge_label   = isset($badge['label']) ? trim((string) $badge['label']) : '';
                $badge_version = isset($badge['version']) ? trim((string) $badge['version']) : '';
                $badge_edition = isset($badge['edition']) ? sanitize_html_class((string) $badge['edition']) : 'default';
                if ($badge_label === '' || $badge_version === '') {
                  continue;
                }
                ?>
                <span class="awxwp-core-version-badge awxwp-core-version-badge--<?php echo esc_attr($badge_edition); ?>">
                  <span class="awxwp-core-version-badge__label"><?php echo esc_html($badge_label); ?></span>
                  <span class="awxwp-core-version-badge__number">v<?php echo esc_html($badge_version); ?></span>
                </span>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </div>
        <?php if ($subtitle) : ?>
          <div class="awxwp-core-subtitle">
            <?php echo esc_html($subtitle); ?>
          </div>
        <?php endif; ?>
      </div>
    </div>
    <?php
  }
}

/* =========================================================
   Get Default Language Code
   ========================================================= */
if (!function_exists('awxct_get_default_lang_code')) {
  function awxct_get_default_lang_code(): string
  {
    // Prefer frontend class if available
    if (class_exists('AWXCT_Frontend') && method_exists('AWXCT_Frontend', 'get_default_lang')) {
      $c = strtolower(AWXCT_Frontend::get_default_lang());
      if ($c) {
        return sanitize_key($c);
      }
    }

    $cache_group = 'awxct';
    $blog_id     = function_exists('get_current_blog_id') ? (int) get_current_blog_id() : 0;
    $cache_key   = 'default_lang_code_' . $blog_id;

    $cached = wp_cache_get($cache_key, $cache_group);
    if ($cached !== false && is_string($cached) && $cached !== '') {
      return $cached;
    }

    global $wpdb;
    $tbl_raw = $wpdb->prefix . 'awxct_languages';
    $tbl     = esc_sql($tbl_raw);

    /*
     * Direct DB query is intentional (plugin table).
     * Table name is schema-derived and escaped via esc_sql().
     */
    $code = $wpdb->get_var("SELECT code FROM {$tbl} WHERE is_default = 1 LIMIT 1"); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter

    $out = $code ? sanitize_key(strtolower((string) $code)) : 'de';

    wp_cache_set($cache_key, $out, $cache_group, 300);

    return $out;
  }
}

/* =========================================================
   Load Active Languages
   ========================================================= */
if (!function_exists('awxct_get_active_languages')) {
  function awxct_get_active_languages(): array
  {
    $cache_group = 'awxct';
    $blog_id     = function_exists('get_current_blog_id') ? (int) get_current_blog_id() : 0;

    global $wpdb;
    $tbl_raw = $wpdb->prefix . 'awxct_languages';
    $tbl     = esc_sql($tbl_raw);

    /*
     * Cache columns and result set to avoid repeated schema + data queries.
     */
    $cols_key = 'langs_cols_' . $blog_id . '_' . md5($tbl_raw);
    $rows_key = 'langs_rows_' . $blog_id . '_' . md5($tbl_raw);

    $cached_rows = wp_cache_get($rows_key, $cache_group);
    if ($cached_rows !== false && is_array($cached_rows)) {
      return $cached_rows;
    }

    $cols = wp_cache_get($cols_key, $cache_group);
    if ($cols === false || !is_array($cols)) {
      /*
       * Direct DB query is intentional (plugin table).
       * Table name is schema-derived and escaped via esc_sql().
       */
      $cols = $wpdb->get_col("SHOW COLUMNS FROM {$tbl}", 0); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
      $cols = is_array($cols) ? $cols : [];
      wp_cache_set($cols_key, $cols, $cache_group, 300);
    }

    $has_native  = in_array('native_name', $cols, true);
    $has_english = in_array('english_name', $cols, true);
    $has_name    = in_array('name', $cols, true);
    $has_active  = in_array('active', $cols, true);

    /*
     * Only allow known-safe SQL fragments (no user input):
     * - column names are from a hardcoded list decided by schema detection above
     * - all other fragments are literals
     */
    $select_native  = $has_native
      ? 'native_name'
      : ($has_name ? 'name AS native_name' : "'' AS native_name");
    $select_english = $has_english ? 'english_name' : "'' AS english_name";
    $select_active  = $has_active ? 'active AS active' : '1 AS active';

    $sql = "SELECT LOWER(code) AS code, {$select_english}, {$select_native}, {$select_active}
              FROM {$tbl}";
    if ($has_active) {
      $sql .= ' WHERE active = 1';
    }
    $sql .= " ORDER BY CASE WHEN code='en' THEN 0 ELSE 1 END, code ASC";

    /*
     * Direct DB query is intentional (plugin table).
     * Table name is schema-derived and escaped via esc_sql().
     * SQL fragments are whitelisted (no user-controlled input).
     */
    $rows = $wpdb->get_results($sql, ARRAY_A); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
    if (!$rows) {
      wp_cache_set($rows_key, [], $cache_group, 300);
      return [];
    }

    foreach ($rows as &$r) {
      $r['code'] = sanitize_key($r['code']);
      if (empty($r['native_name'])) {
        $r['native_name'] = $r['english_name'] ?: strtoupper($r['code']);
      }
    }
    unset($r);

    wp_cache_set($rows_key, $rows, $cache_group, 300);

    return $rows;
  }
}

/* =========================================================
   JSON Config + Caching
   ========================================================= */

if (!defined('AWXCT_CACHE_GROUP')) {
  define('AWXCT_CACHE_GROUP', 'awxct');
}

if (!function_exists('awxct_flush_config_cache')) {
  function awxct_flush_config_cache($old = null, $new = null, $option = null): void
  {
    if (function_exists('wp_cache_delete')) {
      wp_cache_delete('config', AWXCT_CACHE_GROUP);
    }
  }

  add_action('update_option_awxct_json_config', 'awxct_flush_config_cache', 10, 3);
  add_action('add_option_awxct_json_config', 'awxct_flush_config_cache');
  add_action('delete_option_awxct_json_config', 'awxct_flush_config_cache');
}

if (!function_exists('awxct_get_config')) {
  function awxct_get_config(): array
  {
    if (function_exists('wp_cache_get')) {
      $cached = wp_cache_get('config', AWXCT_CACHE_GROUP);
      if ($cached !== false) {
        return $cached;
      }
    }

    $json = get_option('awxct_json_config', '{}');
    $cfg  = json_decode($json, true);
    if (!is_array($cfg)) {
      $cfg = [];
    }

    if (function_exists('wp_cache_set')) {
      wp_cache_set('config', $cfg, AWXCT_CACHE_GROUP);
    }

    return $cfg;
  }
}

if (!function_exists('awxct_config')) {
  /**
   * Dot-Notation Zugriff auf JSON-Config.
   *
   * @param string $path    z.B. "frontend.flags"
   * @param mixed  $default Fallback
   */
  function awxct_config(string $path, $default = null)
  {
    $cfg = awxct_get_config();

    if ($path === '' || $path === '.') {
      return $cfg;
    }

    $node = $cfg;
    foreach (explode('.', $path) as $seg) {
      if (!is_array($node) || !array_key_exists($seg, $node)) {
        return $default;
      }
      $node = $node[$seg];
    }

    return $node;
  }
}

if (!function_exists('awxct_update_config')) {
  function awxct_update_config(array $patch): bool
  {
    $orig   = awxct_get_config();
    $merged = array_replace_recursive($orig, $patch);

    $encoded = wp_json_encode(
      $merged,
      JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE
    );

    $ok = update_option('awxct_json_config', $encoded);

    awxct_flush_config_cache();

    return (bool) $ok;
  }
}

/* =========================================================
   Asset helpers (minified JS/CSS)
   ========================================================= */

/**
 * Return URL to minified or regular JS file inside the plugin.
 *
 * Example:
 *   awxct_get_script_url('assets/js/admin.js')
 */
if (!function_exists('awxct_get_script_url')) {
  function awxct_get_script_url(string $relativePath): string
  {
    if (!defined('AWXCT_FILE')) {
      return '';
    }

    $plugin_file = AWXCT_FILE;
    $base_dir    = plugin_dir_path($plugin_file);

    // Build .min.js path
    $min_rel = preg_replace('/\.js$/', '.min.js', $relativePath);
    $min_abs = $min_rel !== null ? $base_dir . $min_rel : '';

    if ($min_rel !== null && $min_abs && file_exists($min_abs)) {
      return plugins_url($min_rel, $plugin_file);
    }

    // Fallback: non-minified version
    return plugins_url($relativePath, $plugin_file);
  }
}

/**
 * Return URL to minified or regular CSS file inside the plugin.
 *
 * Example:
 *   awxct_get_style_url('assets/css/admin.css')
 */
if (!function_exists('awxct_get_style_url')) {
  function awxct_get_style_url(string $relativePath): string
  {
    if (!defined('AWXCT_FILE')) {
      return '';
    }

    $plugin_file = AWXCT_FILE;
    $base_dir    = plugin_dir_path($plugin_file);

    // Build .min.css path
    $min_rel = preg_replace('/\.css$/', '.min.css', $relativePath);
    $min_abs = $min_rel !== null ? $base_dir . $min_rel : '';

    if ($min_rel !== null && $min_abs && file_exists($min_abs)) {
      return plugins_url($min_rel, $plugin_file);
    }

    // Fallback: non-minified version
    return plugins_url($relativePath, $plugin_file);
  }
}

// =====================================================================
//  Activation: seed default languages
// =====================================================================

if (!function_exists('awxct_seed_languages')) {
	/**
	 * Seed the bundled languages list into the DB (idempotent).
	 *
	 * @return void
	 */
	function awxct_seed_languages(): void
	{
		global $wpdb;

		$table = defined('AWXCT_TABLE_LANGUAGES')
			? (string) AWXCT_TABLE_LANGUAGES
			: (string) ($wpdb->prefix . 'awxct_languages');

		// Load bundled language list.
		$data_file = defined('AWXCT_PATH')
			? (string) (AWXCT_PATH . 'includes/languages-data.php')
			: '';

		$langs = ($data_file && file_exists($data_file)) ? include $data_file : array();
		if (!is_array($langs) || empty($langs)) {
			return;
		}

		// Determine best matching default locale.
		$site_locale = function_exists('get_locale') ? (string) get_locale() : '';
		$site_locale = str_replace('_', '-', $site_locale);

		if (!isset($langs[$site_locale])) {
			$base = strtolower(explode('-', $site_locale)[0] ?? '');
			foreach (array_keys($langs) as $k) {
				if (strtolower(explode('-', (string) $k)[0] ?? '') === $base) {
					$site_locale = (string) $k;
					break;
				}
			}
		}

		if (!isset($langs[$site_locale])) {
			$keys = array_keys($langs);
			$site_locale = (string) ($keys[0] ?? '');
		}

		// Only seed on a fresh installation. If the table already contains rows,
		// preserve the existing language setup exactly as it is.
		$existing_rows_cache_key = 'awxct_language_rows_' . md5( (string) $table );
		$existing_rows = wp_cache_get( $existing_rows_cache_key, 'awxct' );
		if ( false === $existing_rows ) {
			// Table name is derived from $wpdb->prefix / plugin constant (not user input).
			// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			$existing_rows = (int) $wpdb->get_var( "SELECT COUNT(*) FROM `{$table}`" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
			wp_cache_set( $existing_rows_cache_key, $existing_rows, 'awxct', HOUR_IN_SECONDS );
		}

		if ( $existing_rows > 0 ) {
			return;
		}

		$has_default = 0;

		foreach ($langs as $code => $names) {
			$code = (string) $code;
			if ($code === '' || !is_array($names)) {
				continue;
			}
			$native  = (string) ($names['native'] ?? '');
			$english = (string) ($names['english'] ?? '');
			if ($native === '' || $english === '') {
				continue;
			}

			$is_default = (!$has_default && $code === $site_locale) ? 1 : 0;
			$active     = ($code === $site_locale) ? 1 : 0;

			$wpdb->replace( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
				$table,
				array(
					'code'         => $code,
					'english_name' => $english,
					'native_name'  => $native,
					'active'       => $active,
					'is_default'   => $is_default,
				),
				array('%s', '%s', '%s', '%d', '%d')
			);
		}

		wp_cache_delete( $existing_rows_cache_key, 'awxct' );

		// Ensure one default language is set after the initial seed.
		if ($has_default === 0 && $site_locale !== '') {
			$wpdb->update( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
				$table,
				array('is_default' => 1, 'active' => 1),
				array('code' => $site_locale),
				array('%d', '%d'),
				array('%s')
			);

		}
	}
}
