<?php
/**
 * Test page to verify certificate rewrite rules
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

add_action('init', function() {
    if (is_admin() && current_user_can('manage_options') && isset($_GET['test_certificate_rewrite'])) {
        global $wp_rewrite;
        
        echo '<h1>Certificate Rewrite Rules Test</h1>';
        echo '<pre>';
        
        // Check if our rewrite rule exists
        $rules = $wp_rewrite->wp_rewrite_rules();
        $found = false;
        
        echo "Looking for certificate rewrite rule...\n\n";
        
        foreach ($rules as $pattern => $redirect) {
            if (strpos($pattern, 'hvac-certificate') !== false) {
                echo "✅ FOUND: $pattern => $redirect\n";
                $found = true;
            }
        }
        
        if (!$found) {
            echo "❌ Certificate rewrite rule NOT FOUND!\n\n";
            echo "Attempting to add rule and flush...\n";
            
            // Try to add the rule
            add_rewrite_rule(
                'hvac-certificate/([^/]+)/?$',
                'index.php?certificate_token=$matches[1]',
                'top'
            );
            
            // Flush rules
            flush_rewrite_rules();
            
            echo "Rules flushed. Refresh to check again.\n";
        }
        
        // Check query vars
        echo "\n\nRegistered Query Vars:\n";
        global $wp;
        if (in_array('certificate_token', $wp->public_query_vars)) {
            echo "✅ certificate_token is registered\n";
        } else {
            echo "❌ certificate_token is NOT registered\n";
        }
        
        // Show all rewrite rules (limited)
        echo "\n\nFirst 20 Rewrite Rules:\n";
        $count = 0;
        foreach ($rules as $pattern => $redirect) {
            echo "$pattern => $redirect\n";
            if (++$count >= 20) break;
        }
        
        echo '</pre>';
        
        echo '<p><a href="' . admin_url() . '">Return to Admin</a></p>';
        
        die();
    }
});