<?php

class RoutesController {
    public static function registerRoutes() {
        add_rewrite_tag('%zoddak_property_ref%', '([^&]+)');
        add_rewrite_tag('%zoddak_route_base%', '([01])');

        $route = trim(get_option('zoddak_custom_route', 'new-devs'), '/');
        if (!$route) return;

        add_rewrite_rule("^{$route}/?$", 'index.php?zoddak_route_base=1', 'top');

        add_rewrite_rule(
            "^{$route}/([^/]+)/?$",
            'index.php?zoddak_route_base=1&zoddak_property_ref=$matches[1]',
            'top'
        );

        add_rewrite_rule(
            "^([a-zA-Z-]{2,10})/{$route}/?$",
            'index.php?zoddak_lang=$matches[1]&zoddak_route_base=1',
            'top'
        );

        add_rewrite_rule(
            "^([a-zA-Z-]{2,10})/{$route}/([^/]+)/?$",
            'index.php?zoddak_lang=$matches[1]&zoddak_route_base=1&zoddak_property_ref=$matches[2]',
            'top'
        );
    }

    public static function registerQueryVars($vars) {
        $vars[] = 'zoddak_lang';
        $vars[] = 'zoddak_route_base';
        $vars[] = 'zoddak_property_ref';
        return $vars;
    }

    public static function prependRewriteRules($rules) {

        $route = trim(get_option('zoddak_custom_route', 'new-devs'), '/');
        if (empty($route)) return $rules;

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

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

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

            "^([a-zA-Z-]{2,10})/{$route}/([^/]+)/?$" =>
                "index.php?zoddak_lang=\$matches[1]&zoddak_route_base=1&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('zoddak_restrict_admins', 0);
        if($restrict && !current_user_can('administrator')){
            get_header();
            echo access_denied_message();
            get_footer();
            exit;
        }
        if (!get_query_var('zoddak_route_base')) {
            return;
        }
        if (!empty($ref)) {
            PropertiesController::renderPropertyDetail($ref);
            exit;
        }
        PropertiesController::renderPropertiesPage($route);
        exit;
    }
}