<?php
/**
 * Pure URL-path helpers for LangForge.
 *
 * No WordPress dependencies, so the directory-mode rewrite — which has
 * historically been bug-prone — can be unit-tested in isolation.
 * See tests/class-url-helper-test.php.
 *
 * @package LangForge
 */

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

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound -- LF_ is the established plugin class prefix
class LF_Url_Helper {

    /**
 * Directory-mode path rewrite: ensure exactly one /<code>/ language segment
 * sits right after the site's home subdirectory.
 *
 * Pure function of its inputs (no $this, no WP calls) so it is directly
 * testable. `$active_languages` is the keyed map from
 * LF_Core::get_active_languages; only its keys matter here.
 *
 * @param string $path URL path, e.g. "/shop/about/".
 * @param string $home_prefix Home subdirectory, slash-trimmed, e.g. "shop" ("" for root installs).
 * @param array $active_languages Keyed language map (code => data).
 * @param string $code Target language code.
 * @param bool $is_default Whether $code is the site default language.
 * @return string Rewritten path with a leading slash.
 */
    public static function localize_dir_path($path, $home_prefix, array $active_languages, $code, $is_default) {
        $rel = ltrim($path, '/');

        // Strip the home subdirectory, but only on a path-segment boundary — a
        // bare strpos===0 would mangle top-level paths that merely share the
        // prefix string (home "/shop" + "/shopping-cart/" -> "ping-cart/").
        if ($home_prefix !== '' && ($rel === $home_prefix || strpos($rel, $home_prefix . '/') === 0)) {
            $rel = ltrim(substr($rel, strlen($home_prefix)), '/');
        }

        $segs = $rel === '' ? [] : explode('/', $rel);

        // Drop a language segment that is already present so we never stack two.
        if ($segs && isset($active_languages[$segs[0]])) {
            array_shift($segs);
        }
        if (!$is_default) {
            array_unshift($segs, $code);
        }

        $new_path = '/' . ($home_prefix !== '' ? $home_prefix . '/' : '') . implode('/', $segs);

        // Preserve a trailing slash (WP permalinks are trailing-slashed).
        if (substr($path, -1) === '/' && substr($new_path, -1) !== '/') {
            $new_path .= '/';
        }

        return $new_path;
    }
}
