<?php

namespace HelpGent\App\Providers;

defined( 'ABSPATH' ) || exit;

use HelpGent\App\Http\Controllers\PageController;
use HelpGent\WpMVC\Contracts\Provider;
use HelpGent\WpMVC\RequestValidator\Validator;
use WP_REST_Request;

class FormShareRouteProvider implements Provider {
    public static string $query_var = 'helpgent_form_share';

    public static string $route_base = 'form';

    public static string $route_version_option = 'helpgent_form_share_route_version';

    public function boot() {
        add_action( 'init', [ $this, 'add_rewrite_rule' ] );
        add_action( 'init', [ $this, 'maybe_flush_rewrite_rules' ], 20 );
        add_filter( 'query_vars', [ $this, 'register_query_var' ] );
        add_action( 'template_redirect', [ $this, 'template_redirect' ] );
    }

    protected static function register_route(): void {
        add_rewrite_rule(
            '^' . self::$route_base . '/([^/]+)/?$',
            'index.php?' . self::$query_var . '=$matches[1]',
            'top'
        );
    }

    public static function after_plugin_activation(): void {
        static::register_route();
        update_option( self::$route_version_option, '1' );
        flush_rewrite_rules();
    }

    public static function after_plugin_deactivation(): void {
        delete_option( self::$route_version_option );
        flush_rewrite_rules();
    }

    public function add_rewrite_rule(): void {
        static::register_route();
    }

    public function maybe_flush_rewrite_rules(): void {
        if ( '1' === get_option( self::$route_version_option ) ) {
            return;
        }

        static::register_route();
        flush_rewrite_rules( false );
        update_option( self::$route_version_option, '1' );
    }

    public function register_query_var( array $query_vars ): array {
        $query_vars[] = self::$query_var;

        return $query_vars;
    }

    public function template_redirect(): void {
        $slug = get_query_var( self::$query_var );

        if ( empty( $slug ) ) {
            return;
        }

        $slug = sanitize_text_field( (string) $slug );
        $request = new WP_REST_Request( 'GET', '/' );
        $request->set_query_params( [ 'slug' => $slug ] );
        $request->set_url_params( [ 'slug' => $slug ] );

        $validator                  = helpgent_singleton( Validator::class );
        $validator->wp_rest_request = $request;
        $validator->errors          = [];

        helpgent_singleton( PageController::class )->share_by_slug(
            $validator,
            $request
        );
    }
}
