<?php

class RsRoutesController{
    public static function registerRoutes(){
        add_rewrite_tag('%rs_zoddak_property_ref%', '([^&]+)');
        add_rewrite_tag('%rs_zoddak_route_base%', '([01])');
    }

    public static function registerQueryVars($vars){
        $vars[] = 'rs_zoddak_lang';
        $vars[] = 'rs_zoddak_route_base';
        $vars[] = 'rs_zoddak_property_ref';
        return $vars;
    }

    public static function prependRewriteRules($rules){
        $route = trim(get_option('rs_zoddak_custom_route', 'resales'), '/');
        if (empty($route)) return $rules;

        $new = [
            "^{$route}/?$" =>
                "index.php?rs_zoddak_route_base=1",

            "^{$route}/([^/]+)/?$" =>
                "index.php?rs_zoddak_route_base=1&rs_zoddak_property_ref=\$matches[1]",

            "^([a-zA-Z-]{2,10})/{$route}/?$" =>
                "index.php?rs_zoddak_lang=\$matches[1]&rs_zoddak_route_base=1",

            "^([a-zA-Z-]{2,10})/{$route}/([^/]+)/?$" =>
                "index.php?rs_zoddak_lang=\$matches[1]&rs_zoddak_route_base=1&rs_zoddak_property_ref=\$matches[2]",
        ];

        return $new + $rules;
    }
    public static function maybeFlushRoutes() {
        if (get_option('zoddak_needs_flush')) {
            flush_rewrite_rules(false);
            delete_option('zoddak_needs_flush');
        }
    }

    public static function handleCustomRoute($route, $ref) {
        $restrict = get_option('rs_zoddak_restrict_admins', 0);
        if($restrict && !current_user_can('administrator')){
            get_header();
            echo access_denied_message();
            get_footer();
            exit;
        }
        if (!get_query_var('rs_zoddak_route_base')) {
            return;
        }
        if (!empty($ref)) {
            RsPropertiesController::renderPropertyDetail($ref);
            exit;
        }
        RsPropertiesController::renderPropertiesPage($route);
        exit;
    }
}