<?php
/**
 * Custom Auth Suite – Access Control
 */

if (!defined('WPINC')) {
    die;
}
/**
 * Return the unique list of protected paths.
 * Source of truth: protected.paths
 * Compatibility: merge with routes.protected_paths when present.
 */
function custausu_get_protected_paths(): array {
    // Source of truth: protected.paths.
    $p = (array) custausu_config('protected.paths', []);

    // Compatibility with legacy keys.
    $a = (array) custausu_config('access.protected_paths', []);
    $b = (array) custausu_config('routes.protected_paths', []); // compat legacy

    $paths = array_merge($p, $a, $b);

    // Normalize strings, trim empty values, remove leading slashes, and de-duplicate.
    $out = [];
    foreach ($paths as $p) {
        if (!is_string($p)) continue;
        $p = trim($p);
        if ($p === '') continue;
        $p = trim($p, '/');
        if ($p === '') continue;
        $out[$p] = true;
    }

    return array_keys($out);
}

/**
 * Check whether a path is protected using exact or prefix matching.
 * $path may be absolute-style or relative-style, for example /it/page/ or it/page/.
 */
function custausu_is_protected_path(string $path, string $lang = ''): bool {
    $path_norm = '/' . ltrim($path, '/');
    $path_trim = rtrim($path_norm, '/');

    $protected = custausu_get_protected_paths();
    foreach ($protected as $p) {
        $p_norm = '/' . ltrim($p, '/');
        $p_trim = rtrim($p_norm, '/');
        if ($p_trim === '') continue;

        if ($path_trim === $p_trim) return true;
        if (strpos($path_trim, $p_trim . '/') === 0) return true;
    }

    return false;
}
add_action('template_redirect', function () {

    /* ========= GUARD ========= */

    if (
        is_admin() ||
        wp_doing_ajax() ||
        wp_doing_cron() ||
        is_user_logged_in()
    ) {
        return;
    }

    // Exclude auth templates (login/register/lostpassword)
    if (function_exists('custausu_is_auth_template') && custausu_is_auth_template()) {
        return;
    }

        $request_uri = isset($_SERVER['REQUEST_URI'])
            ? esc_url_raw((string) wp_unslash($_SERVER['REQUEST_URI']))
            : '';
    if ($request_uri === '') return;

    // Plain path without query string.
    $path = (string) wp_parse_url($request_uri, PHP_URL_PATH);
    $path = $path !== '' ? $path : '/';
    $uri  = trim($path, '/');

    $protected = function_exists('custausu_get_protected_paths') ? custausu_get_protected_paths() : [];
    if (empty($protected)) return;

    // Match against the normalized list using exact or prefix matching.
    $matched_root = '';
    foreach ($protected as $p) {
        $pp = trim((string)$p, '/');
        if ($pp === '') continue;

        if ($uri === $pp || strpos($uri, $pp . '/') === 0) {
            $matched_root = $pp;
            break;
        }
    }

    if ($matched_root === '') return;

    if (function_exists('custausu_log')) {
        custausu_log('redirect', 'protected path matched', [
            'request_uri'  => $request_uri,
            'path'         => $path,
            'uri'          => $uri,
            'matched_root' => $matched_root,
        ], 'info');
    }

    if (function_exists('custausu_safe_mode_is_enabled') && custausu_safe_mode_is_enabled()) {
        $redirect_to_target = home_url($request_uri);
        $dest = wp_login_url($redirect_to_target);

        if (function_exists('custausu_log')) {
            custausu_log('redirect', 'safe mode protected path fallback to wp-login.php', [
                'matched_root'       => $matched_root,
                'redirect_to_target' => $redirect_to_target,
                'dest'               => $dest,
                'source'             => function_exists('custausu_safe_mode_source') ? custausu_safe_mode_source() : 'unknown',
            ], 'warn');
        }

        wp_safe_redirect($dest);
        exit;
    }

    /* ========= LANGUAGE DETECTION ========= */
    $default = strtolower(trim((string) custausu_config('routes.policy.default_lang', 'en')));
    if ($default === '') $default = 'en';

    $lang = $default;

    // Prefer detection from the requested path prefix when available.
    if (function_exists('custausu_lang_from_path')) {
        $det = (string) custausu_lang_from_path($path);
        $det = strtolower(trim($det));
        if ($det !== '') $lang = $det;
    }

    if (function_exists('custausu_log')) {
        custausu_log('redirect', 'protected path language detected', [
            'path' => $path,
            'lang' => $lang,
        ], 'debug');
    }

    /* ========= LOGIN PAGE ========= */
    $login_url = function_exists('custausu_login_url_for_lang')
        ? custausu_login_url_for_lang($lang)
        : (
            function_exists('custausu_route_url')
              ? (string) custausu_route_url('login', $lang)
              : wp_login_url()
          );

    if (function_exists('custausu_log')) {
        custausu_log('redirect', 'login url resolved for protected path', [
            'lang'      => $lang,
            'login_url' => $login_url,
        ], 'debug');
    }

    /* ========= REDIRECT ========= */
    $redirect_to_target = home_url($request_uri);

    $dest = function_exists('custausu_login_url_with_redirect')
        ? custausu_login_url_with_redirect(
            $redirect_to_target,
            $lang
          )
        : (
            function_exists('custausu_url_with_redirect_to')
              ? custausu_url_with_redirect_to(
                  $login_url,
                  $redirect_to_target
                )
              : add_query_arg(
                  'redirect_to',
                  $redirect_to_target,
                  $login_url
                )
          );

    if (function_exists('custausu_log')) {
        custausu_log('redirect', 'redirect to login prepared', [
            'matched_root'       => $matched_root,
            'login_url'          => $login_url,
            'redirect_to_target' => $redirect_to_target,
            'dest'               => $dest,
        ], 'info');
    }

    wp_safe_redirect($dest);
    exit;

});