<?php 

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

        if (!get_query_var('rs_zoddak_route_base')) {
            return;
        }

        $expected = trim(get_option('rs_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('rs_zoddak_route_base');
        $ref   = get_query_var('rs_zoddak_property_ref') ?: null;
        RsRoutesController::handleCustomRoute($route, $ref);
    }
}