<?php
namespace ZS_SEO\AuditOptimization\Core;

defined( 'ABSPATH' ) || exit;

class RedirectRouter {

    public function __construct() {
        add_action( 'template_redirect', [ $this, 'maybe_redirect' ], 5 );
    }

    public function maybe_redirect(): void {
        // Do not redirect in WP Admin or for AJAX/REST/CLI
        if ( is_admin() || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) || ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) ) {
            return;
        }

        global $wpdb;

        // Get the requested URL path without query arguments
        $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash
        $path        = wp_parse_url( $request_uri, PHP_URL_PATH );
        if ( ! $path ) {
            return;
        }

        // Normalize path: clean trailing slash but keep leading slash
        $normalized_path = '/' . trim( $path, '/' );

        // Check if there is an active redirect matching this path
        // Check for both exact path and path with or without trailing slash
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $redirect = $wpdb->get_row( $wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}zs_seo_redirects WHERE source_url = %s OR source_url = %s OR source_url = %s LIMIT 1",
            $normalized_path,
            rtrim( $normalized_path, '/' ),
            rtrim( $normalized_path, '/' ) . '/'
        ) );

        if ( $redirect ) {
            // Increment redirect hit counter
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $wpdb->query( $wpdb->prepare(
                "UPDATE {$wpdb->prefix}zs_seo_redirects SET hits = hits + 1 WHERE id = %d",
                $redirect->id
            ) );

            $target = $redirect->target_url;
            $type   = (int) $redirect->type;

            // Ensure redirect type is valid
            if ( ! in_array( $type, [ 301, 302, 307, 308 ], true ) ) {
                $type = 301;
            }

            // Perform secure redirect and exit
            // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect
            wp_redirect( $target, $type );
            exit;
        }
    }
}
