<?php 

class Routes {
    public static function init(): void
    {
        add_action('template_redirect', [self::class, 'handleRequest'], 1);
        add_action('init', ['RoutesController', 'registerRoutes']);
        add_filter('query_vars', ['RoutesController', 'registerQueryVars']);
        add_filter('rewrite_rules_array', ['RoutesController', 'prependRewriteRules']);
        add_action('init', ['RoutesController', 'maybeFlushRoutes']);
        add_filter('wpml_is_redirected', [self::class, 'preventWpmlRedirect']);
    }
    public static function handleRequest(): void
    {
        if (is_admin() || is_preview()) {
            return;
        }
        if (get_query_var('rs_zoddak_route_base')) {
            return;
        }

        $expected = trim(get_option('zoddak_custom_route', 'resales'), '/');
        $path     = trim(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), '/');

        $segments = $path === '' ? [] : explode('/', $path);
        $is_valid =
            (isset($segments[0]) && $segments[0] === $expected) ||
            (isset($segments[1]) && $segments[1] === $expected);

        if (!$is_valid) {
            return;
        }

        $route = (int) get_query_var('zoddak_route_base');
        $ref   = get_query_var('zoddak_property_ref') ?: null;
        RoutesController::handleCustomRoute($route, $ref);
    }
    public static function preventWpmlRedirect($is_redirected, $url): bool
    {
        $route = trim(get_option('zoddak_custom_route', 'new-devs'), '/');
        if(strpos($url, '/' . $route) !== false)
        {
            return false;
        }
        return $is_redirected;
    }
}