<?php
/**
 * Test Certificate URL System
 * 
 * Run this to test if certificate URLs are working properly
 */

// Load WordPress
require_once __DIR__ . '/../../../wp-load.php';

// Check if user is admin
if (!current_user_can('manage_options')) {
    wp_die('Access denied');
}

echo "<h1>Certificate URL System Test</h1>";
echo "<pre>";

// 1. Check if URL handler is loaded
echo "=== URL HANDLER CHECK ===\n";
if (class_exists('HVAC_Certificate_URL_Handler')) {
    echo "✅ HVAC_Certificate_URL_Handler class exists\n";
    $handler = HVAC_Certificate_URL_Handler::instance();
    echo "✅ URL Handler instance created\n";
} else {
    echo "❌ HVAC_Certificate_URL_Handler class NOT found!\n";
}

// 2. Check if security class is loaded
echo "\n=== SECURITY CLASS CHECK ===\n";
if (class_exists('HVAC_Certificate_Security')) {
    echo "✅ HVAC_Certificate_Security class exists\n";
    $security = HVAC_Certificate_Security::instance();
    echo "✅ Security instance created\n";
} else {
    echo "❌ HVAC_Certificate_Security class NOT found!\n";
}

// 3. Create a test token
echo "\n=== TOKEN GENERATION TEST ===\n";
if (isset($security)) {
    $test_data = array(
        'file_path' => 'test/certificate.pdf',
        'event_name' => 'Test Event',
        'attendee_name' => 'Test Attendee',
        'certificate_id' => 999
    );
    
    $test_url = $security->generate_download_token(999, $test_data, 300); // 5 minute expiry
    echo "Generated test URL: $test_url\n";
    
    // Extract token
    if (preg_match('/hvac-certificate\/([^\/]+)/', $test_url, $matches)) {
        $token = $matches[1];
        echo "Token: $token\n";
        
        // Verify token exists in database
        $transient = get_transient('hvac_certificate_token_' . $token);
        if ($transient) {
            echo "✅ Token transient exists\n";
            echo "Token data:\n";
            print_r($transient);
            
            // Test direct access URL
            echo "\n=== DIRECT ACCESS TEST ===\n";
            echo "Test this URL in your browser: $test_url\n";
            echo "(Should show 'Certificate file not found' since we're using a test file path)\n";
        } else {
            echo "❌ Token transient NOT found!\n";
        }
    }
}

// 4. Check hooks
echo "\n=== HOOK REGISTRATION CHECK ===\n";
$init_callbacks = $GLOBALS['wp_filter']['init'] ?? array();
$found_url_handler = false;

foreach ($init_callbacks as $priority => $callbacks) {
    foreach ($callbacks as $callback) {
        if (is_array($callback['function']) && 
            is_object($callback['function'][0]) && 
            get_class($callback['function'][0]) === 'HVAC_Certificate_URL_Handler') {
            $found_url_handler = true;
            echo "✅ URL Handler init hook found at priority: $priority\n";
        }
    }
}

if (!$found_url_handler) {
    echo "❌ URL Handler init hook NOT found!\n";
}

// 5. List recent certificate tokens
echo "\n=== RECENT CERTIFICATE TOKENS ===\n";
global $wpdb;
$recent_tokens = $wpdb->get_results(
    "SELECT option_name, option_value 
     FROM {$wpdb->options} 
     WHERE option_name LIKE '_transient_hvac_certificate_token_%' 
     ORDER BY option_id DESC 
     LIMIT 5"
);

if (empty($recent_tokens)) {
    echo "No recent certificate tokens found\n";
} else {
    foreach ($recent_tokens as $token_row) {
        $token_key = str_replace('_transient_hvac_certificate_token_', '', $token_row->option_name);
        echo "\nToken: $token_key\n";
        $data = maybe_unserialize($token_row->option_value);
        if (is_array($data)) {
            echo "  URL: " . home_url('hvac-certificate/' . $token_key) . "\n";
            echo "  Event: " . ($data['event_name'] ?? 'N/A') . "\n";
            echo "  Attendee: " . ($data['attendee_name'] ?? 'N/A') . "\n";
        }
    }
}

// 6. Test a real certificate if available
echo "\n=== REAL CERTIFICATE TEST ===\n";
require_once HVAC_CE_PLUGIN_DIR . 'includes/certificates/class-certificate-manager.php';
$cert_manager = HVAC_Certificate_Manager::instance();

// Get a recent certificate
$recent_cert = $wpdb->get_row(
    "SELECT * FROM {$wpdb->prefix}hvac_certificates 
     WHERE file_path IS NOT NULL AND file_path != '' 
     ORDER BY certificate_id DESC 
     LIMIT 1"
);

if ($recent_cert) {
    echo "Found certificate ID: {$recent_cert->certificate_id}\n";
    echo "File path: {$recent_cert->file_path}\n";
    
    // Check if file exists
    $upload_dir = wp_upload_dir();
    $full_path = $upload_dir['basedir'] . '/' . $recent_cert->file_path;
    
    if (file_exists($full_path)) {
        echo "✅ Certificate file exists at: $full_path\n";
        
        // Generate download URL
        $cert_data = array(
            'certificate_id' => $recent_cert->certificate_id,
            'file_path' => $recent_cert->file_path,
            'event_name' => 'Test Event',
            'attendee_name' => 'Test Attendee'
        );
        
        $download_url = $security->generate_download_token($recent_cert->certificate_id, $cert_data, 300);
        echo "\nGenerated download URL: $download_url\n";
        echo "✅ Test this URL in your browser - it should download the certificate!\n";
    } else {
        echo "❌ Certificate file NOT found at: $full_path\n";
    }
} else {
    echo "No certificates with file paths found in database\n";
}

echo "\n=== SUMMARY ===\n";
echo "Certificate URL system should now be working.\n";
echo "URLs in format: " . home_url('hvac-certificate/[token]') . " will be handled directly.\n";
echo "No rewrite rules needed!\n";

echo "</pre>";