<?php
/**
 * MU Plugin: HVAC Certificate URL Handler
 * 
 * This MUST-USE plugin handles certificate URLs at the earliest possible stage
 * to prevent 404 errors.
 * 
 * Place this file in wp-content/mu-plugins/
 */

// Only run on frontend
if (!defined('ABSPATH') || defined('WP_ADMIN')) {
    return;
}

// Check for certificate URLs immediately
add_action('muplugins_loaded', function() {
    $request_uri = $_SERVER['REQUEST_URI'] ?? '';
    $parsed = parse_url($request_uri);
    $path = rtrim($parsed['path'] ?? '', '/');
    
    // Check if this is a certificate URL
    if (preg_match('#^/hvac-certificate/([a-zA-Z0-9]{32})$#', $path, $matches)) {
        $token = $matches[1];
        
        // Load WordPress to access functions
        if (!function_exists('get_transient')) {
            return;
        }
        
        // Hook into the earliest possible action to handle the certificate
        add_action('plugins_loaded', function() use ($token) {
            // Check if token exists
            $certificate_data = get_transient('hvac_certificate_token_' . $token);
            
            if (!$certificate_data) {
                // Invalid token - show 404
                status_header(404);
                wp_die('Certificate not found', 'Not Found', array('response' => 404));
            }
            
            // Delete token to prevent reuse
            delete_transient('hvac_certificate_token_' . $token);
            
            // Get file path
            $upload_dir = wp_upload_dir();
            $file_path = $upload_dir['basedir'] . '/' . $certificate_data['file_path'];
            
            if (!file_exists($file_path)) {
                status_header(404);
                wp_die('Certificate file not found', 'Not Found', array('response' => 404));
            }
            
            // Serve the file
            $file_name = basename($file_path);
            $file_size = filesize($file_path);
            
            // Set headers
            nocache_headers();
            header('Content-Type: application/pdf');
            header('Content-Disposition: attachment; filename="certificate.pdf"');
            header('Content-Transfer-Encoding: binary');
            header('Content-Length: ' . $file_size);
            
            // Clear any output buffers
            while (ob_get_level()) {
                ob_end_clean();
            }
            
            // Output file
            readfile($file_path);
            exit;
        }, 1);
    }
}, 1);