<?php
/**
 * Emergency Lockdown Mode
 * 
 * One-toggle protection that instantly locks down the site
 * with 451 responses and optional login requirement.
 */

namespace HumanGate;

class EmergencyLockdown {
    
    /**
     * Initialize lockdown mode
     */
    public function init() {
        if (!get_option('humang_lockdown_mode', false)) {
            return;
        }
        
        // Check before template redirect
        add_action('template_redirect', [$this, 'enforce_lockdown'], 1);
        
        // Also check for admin/ajax/cron
        if (!is_admin() && !wp_doing_ajax() && !wp_doing_cron()) {
            add_action('init', [$this, 'enforce_lockdown'], 1);
        }
    }
    
    /**
     * Enforce lockdown restrictions
     */
    public function enforce_lockdown() {
        // Allow logged-in users if option is set
        $require_login = get_option('humang_lockdown_require_login', false);
        
        if ($require_login && is_user_logged_in()) {
            return; // Allow logged-in users
        }
        
        // Allow admin pages for logged-in admins
        if (is_admin() && current_user_can('manage_options')) {
            return;
        }
        
        // Sanitize user agent
        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '';
        
        // Validate user agent length
        if (strlen($user_agent) > 512) {
            $user_agent = ''; // Ignore suspiciously long user agents
        }
        
        // Whitelist common legitimate bots (for emergency communications)
        $allowed_agents = [
            'FeedValidator',
            'WordPress',
        ];
        
        $is_allowed = false;
        foreach ($allowed_agents as $allowed) {
            if (stripos($user_agent, $allowed) !== false) {
                $is_allowed = true;
                break;
            }
        }
        
        if (!$is_allowed) {
            // Send 451 Unavailable For Legal Reasons
            http_response_code(451);
            header('Retry-After: 3600');
            
            // Also force noindex in headers
            header('X-Robots-Tag: noindex, nofollow');
            
            // Send minimal HTML response
            $title_text = esc_html__('Unavailable', 'humangate');
            $heading_text = esc_html__('451 - Unavailable For Legal Reasons', 'humangate');
            $message_text = esc_html__('This content is currently unavailable.', 'humangate');
            
            echo '<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="robots" content="noindex, nofollow">
    <title>' . esc_html($title_text) . '</title>
</head>
<body>
    <h1>' . esc_html($heading_text) . '</h1>
    <p>' . esc_html($message_text) . '</p>
</body>
</html>';
            
            exit;
        }
    }
}

