<?php
defined('ABSPATH') || exit;

/**
 * Health check endpoint for the WPFort Security Suite
 * Returns basic information about the plugin's status
 */
function wpsec_health_check_endpoint($request) {
    $response = [
        'success' => true,
        'data' => [
            'plugin_version' => '1.3.1',
            'plugin_active' => true,
            'wordpress_version' => get_bloginfo('version'),
            'php_version' => phpversion(),
            'timestamp' => current_time('mysql'),
            'firewall_status' => [
                'active' => false,
                'rules_count' => 0
            ]
        ]
    ];
    
    // Get firewall status if available
    if (class_exists('WPSEC_Firewall')) {
        $firewall = WPSEC_Firewall::get_instance();
        $response['data']['firewall_status']['active'] = $firewall->is_active();
        
        // Get recent blocks as a proxy for rules activity
        $recent_blocks = $firewall->get_recent_blocks(1);
        $response['data']['firewall_status']['rules_count'] = count($recent_blocks);
        
        // Add firewall stats
        $stats = $firewall->get_stats();
        if (!empty($stats) && isset($stats['summary'])) {
            $response['data']['firewall_status']['total_blocks'] = $stats['summary']['total_blocks'] ?? 0;
            $response['data']['firewall_status']['critical_attacks'] = $stats['summary']['critical_attacks'] ?? 0;
        }
    }
    
    // Check database connectivity
    global $wpdb;
    $db_check = $wpdb->get_var("SELECT 1");
    $response['data']['database_connected'] = ($db_check === '1');
    
    // Check if we can write to the logs directory
    $logs_dir = WP_CONTENT_DIR . '/wpsec-logs';
    if (!file_exists($logs_dir)) {
        wp_mkdir_p($logs_dir);
    }
    
    // Initialize WordPress Filesystem
    global $wp_filesystem;
    if (empty($wp_filesystem)) {
        require_once(ABSPATH . '/wp-admin/includes/file.php');
        WP_Filesystem();
    }
    
    $response['data']['logs_writable'] = $wp_filesystem->is_writable($logs_dir);
    
    return new WP_REST_Response($response, 200);
}

/**
 * Public health check endpoint that doesn't require authentication
 * Returns minimal information to verify the plugin is installed and reachable
 */
function wpsec_public_health_check_endpoint($request) {
    return new WP_REST_Response([
        'success' => true,
        'data' => [
            'plugin_active' => true,
            'plugin_version' => '1.3.1'
        ]
    ], 200);
}

// Add debugging to track REST API registration
add_action('init', function() {
    wpsec_debug_log('WPFort Debug: REST API init hook running', 'debug');
    
    // Test if REST API is properly configured
    $rest_url = get_rest_url(null, '/wp/v2/posts');
    wpsec_debug_log('WPFort Debug: REST API URL format: ' . $rest_url, 'debug');
    
    // Check if permalink structure is set
    $permalink_structure = get_option('permalink_structure');
    wpsec_debug_log('WPFort Debug: Permalink structure: ' . ($permalink_structure ? $permalink_structure : 'Plain/Default'), 'debug');
});

// Register endpoints
add_action('rest_api_init', function () {
    wpsec_debug_log('WPFort Debug: REST API routes being registered', 'debug');
    // Standard health check endpoint (requires authentication)
    register_rest_route('wpsec/v1', '/health', [
        'methods' => 'GET',
        'callback' => 'wpsec_health_check_endpoint',
        'permission_callback' => 'wpsec_authenticate_request'
    ]);
    
    // Public health check endpoint (no authentication required)
    register_rest_route('wpsec/v1', '/ping', [
        'methods' => 'GET',
        'callback' => 'wpsec_public_health_check_endpoint',
        'permission_callback' => function() { return true; }
    ]);
});
