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

/**
 * WPFort Connectivity API Functions
 * 
 * This file contains functions for checking connectivity with the WPFort SAAS platform
 * and retrieving site connection status information.
 */

/**
 * Get the connectivity status of the current site
 * 
 * @return array|WP_Error The connectivity data or WP_Error on failure
 */
function wpsec_get_site_connectivity() {
    wpsec_debug_log('🔄 WPFort Connectivity: Checking connectivity status', 'info');
    
    // Check if we have cached connectivity data
    $cached_data = get_transient('wpsec_site_connectivity');
    
    // If we have cached data that's less than 5 minutes old, use it
    if (!empty($cached_data)) {
        wpsec_debug_log('✅ WPFort Connectivity: Using cached data (age < 5 minutes)', 'info');
        $data = json_decode($cached_data, true);
        wpsec_debug_log('📊 WPFort Connectivity: Cached data content: ' . json_encode($data), 'info');
        return $data;
    }
    
    // Get the current site domain
    $site_url = get_site_url();
    $domain = wp_parse_url($site_url, PHP_URL_HOST);
    
    wpsec_debug_log('🌐 WPFort Connectivity: Site URL: ' . $site_url, 'info');
    wpsec_debug_log('🌐 WPFort Connectivity: Domain: ' . $domain, 'info');
    
    // Make request to get connectivity status
    $connectivity_url = 'http://62.171.130.143:3000/api/sites/' . $domain . '/connectivity';
    
    $args = [
        'timeout' => 15,
        'sslverify' => false,
        'headers' => [
            'User-Agent' => 'WordPress/' . get_bloginfo('version') . '; ' . get_bloginfo('url'),
            'X-WPSec-Version' => defined('WPSEC_VERSION') ? WPSEC_VERSION : '1.0.0',
            'x-wpfort-token' => '123123123'
        ]
    ];
    
    wpsec_debug_log('🔄 WPFort Connectivity: Making API request to ' . $connectivity_url, 'info');
    wpsec_debug_log('📋 WPFort Connectivity: Request arguments: ' . json_encode($args), 'info');
    
    $response = wp_remote_get($connectivity_url, $args);
    
    if (is_wp_error($response)) {
        $error_message = $response->get_error_message();
        $error_code = $response->get_error_code();
        wpsec_debug_log('❌ WPFort Connectivity: API request failed with error code: ' . $error_code, 'error');
        wpsec_debug_log('❌ WPFort Connectivity: Error message: ' . $error_message, 'error');
        
        // Log additional system information that might help diagnose the issue
        wpsec_debug_log('📊 WPFort Connectivity: PHP version: ' . PHP_VERSION, 'info');
        wpsec_debug_log('📊 WPFort Connectivity: WordPress version: ' . get_bloginfo('version'), 'info');
        wpsec_debug_log('📊 WPFort Connectivity: Plugin version: ' . (defined('WPSEC_VERSION') ? WPSEC_VERSION : '1.0.0'), 'info');
        
        return $response;
    }
    
    $status_code = wp_remote_retrieve_response_code($response);
    $headers = wp_remote_retrieve_headers($response);
    
    wpsec_debug_log('📊 WPFort Connectivity: API response status code: ' . $status_code, 'info');
    wpsec_debug_log('📊 WPFort Connectivity: API response headers: ' . json_encode($headers), 'info');
    
    if ($status_code !== 200) {
        wpsec_debug_log('❌ WPFort Connectivity: API request returned non-200 status code: ' . $status_code, 'error');
        wpsec_debug_log('❌ WPFort Connectivity: Response body: ' . wp_remote_retrieve_body($response), 'error');
        return new WP_Error('connectivity_error', 'Failed to fetch connectivity data. Status code: ' . $status_code);
    }
    
    $body = wp_remote_retrieve_body($response);
    if (empty($body)) {
        wpsec_debug_log('❌ WPFort Connectivity: API request returned empty body', 'error');
        return new WP_Error('connectivity_error', 'Empty response when fetching connectivity data');
    }
    
    wpsec_debug_log('📄 WPFort Connectivity: API response body: ' . $body, 'info');
    
    $data = json_decode($body, true);
    if (json_last_error() !== JSON_ERROR_NONE) {
        wpsec_debug_log('❌ WPFort Connectivity: Failed to parse JSON response: ' . json_last_error_msg(), 'error');
        return new WP_Error('connectivity_error', 'Invalid JSON response: ' . json_last_error_msg());
    }
    
    wpsec_debug_log('✅ WPFort Connectivity: Successfully retrieved and parsed connectivity data', 'info');
    
    // Cache the data for 5 minutes
    set_transient('wpsec_site_connectivity', $body, 5 * MINUTE_IN_SECONDS);
    wpsec_debug_log('💾 WPFort Connectivity: Data cached for 5 minutes', 'info');
    
    return $data;
}

/**
 * Check if a specific layer is active and fresh
 * 
 * @param string $layer_name Name of the layer to check
 * @param array $connectivity_data Optional connectivity data to use
 * @return array Status information with 'active', 'fresh', and 'last_updated' keys
 */
function wpsec_check_layer_status($layer_name, $connectivity_data = null) {
    if ($connectivity_data === null) {
        $connectivity_data = wpsec_get_site_connectivity();
    }
    
    // Default response if we can't find the layer
    $default = array(
        'active' => false,
        'fresh' => false,
        'last_updated' => null
    );
    
    // If we have an error or no layers data
    if (is_wp_error($connectivity_data) || !isset($connectivity_data['layers']) || !is_array($connectivity_data['layers'])) {
        return $default;
    }
    
    // Find the requested layer
    foreach ($connectivity_data['layers'] as $layer) {
        if (isset($layer['name']) && $layer['name'] === $layer_name) {
            // A layer is considered active if data_available is true, regardless of fresh status
            $is_active = isset($layer['data_available']) ? (bool)$layer['data_available'] : false;
            
            return array(
                'active' => $is_active,
                'fresh' => isset($layer['fresh']) ? (bool)$layer['fresh'] : false,
                'last_updated' => isset($layer['last_updated']) ? $layer['last_updated'] : null
            );
        }
    }
    
    return $default;
}

/**
 * Get overall connectivity status
 * 
 * @param array $connectivity_data Optional connectivity data to use
 * @return array Status information with 'connected', 'status', and 'last_check' keys
 */
function wpsec_get_overall_connectivity($connectivity_data = null) {
    if ($connectivity_data === null) {
        $connectivity_data = wpsec_get_site_connectivity();
    }
    
    // Default response if we can't get data
    $default = array(
        'connected' => false,
        'status' => 'error',
        'status_text' => 'Inactive',
        'last_check' => null
    );
    
    // If we have an error or no uptime data
    if (is_wp_error($connectivity_data) || !isset($connectivity_data['uptime'])) {
        return $default;
    }
    
    // Determine status text based on the status field
    $status_text = 'Inactive';
    if (isset($connectivity_data['uptime']['status'])) {
        if ($connectivity_data['uptime']['status'] === 'healthy') {
            $status_text = 'Active';
        } elseif ($connectivity_data['uptime']['status'] === 'warning') {
            $status_text = 'Warning';
        } elseif ($connectivity_data['uptime']['status'] === 'error') {
            $status_text = 'Error';
        }
    }
    
    return array(
        // Keep the connected field for backward compatibility but use status for display
        'connected' => (isset($connectivity_data['uptime']['status']) && $connectivity_data['uptime']['status'] === 'healthy'),
        'status' => isset($connectivity_data['uptime']['status']) ? $connectivity_data['uptime']['status'] : 'error',
        'status_text' => $status_text,
        'last_check' => isset($connectivity_data['uptime']['last_check']) ? $connectivity_data['uptime']['last_check'] : null
    );
}

/**
 * Get ping status
 * 
 * @param array $connectivity_data Optional connectivity data to use
 * @return array Ping status information with 'connected', 'plugin_active', and 'plugin_version' keys
 */
function wpsec_get_ping_status($connectivity_data = null) {
    if ($connectivity_data === null) {
        $connectivity_data = wpsec_get_site_connectivity();
    }
    
    // Default response if we can't get data
    $default = array(
        'connected' => false,
        'plugin_active' => false,
        'plugin_version' => ''
    );
    
    // If we have an error or no ping data
    if (is_wp_error($connectivity_data) || !isset($connectivity_data['ping'])) {
        return $default;
    }
    
    return array(
        'connected' => isset($connectivity_data['ping']['connected']) ? (bool)$connectivity_data['ping']['connected'] : false,
        'plugin_active' => isset($connectivity_data['ping']['plugin_active']) ? (bool)$connectivity_data['ping']['plugin_active'] : false,
        'plugin_version' => isset($connectivity_data['ping']['plugin_version']) ? sanitize_text_field($connectivity_data['ping']['plugin_version']) : ''
    );
}

/**
 * Get subscription tier information
 * 
 * @param array $connectivity_data Optional connectivity data to use
 * @return string Tier (free, pro, business, enterprise) or empty if not available
 */
function wpsec_get_subscription_tier($connectivity_data = null) {
    if ($connectivity_data === null) {
        $connectivity_data = wpsec_get_site_connectivity();
    }
    
    // If we have an error or no user_plan data
    if (is_wp_error($connectivity_data)) {
        return 'free';
    }
    
    // Check if user_plan.plan exists in the response
    if (isset($connectivity_data['user_plan']) && isset($connectivity_data['user_plan']['plan'])) {
        return sanitize_text_field($connectivity_data['user_plan']['plan']);
    }
    
    // Default to free if plan is not specified
    return 'free';
}

/**
 * Check if subscription is free tier
 * 
 * @param array $connectivity_data Optional connectivity data to use
 * @return bool True if free tier or no tier information available
 */
function wpsec_is_free_tier($connectivity_data = null) {
    $tier = wpsec_get_subscription_tier($connectivity_data);
    return ($tier === 'free' || empty($tier));
}

/**
 * Check if this site needs initial connection to WPFort platform
 * 
 * @param array $connectivity_data Optional connectivity data to use
 * @return bool True if site needs initial connection (initial_install.installed = false)
 */
function wpsec_needs_initial_connection($connectivity_data = null) {
    if ($connectivity_data === null) {
        $connectivity_data = wpsec_get_site_connectivity();
    }
    
    // If we have an error with API, we can't determine status
    if (is_wp_error($connectivity_data)) {
        // Default to needing connection if we can't verify
        return true;
    }
    
    // Check if initial_install exists and installed is false
    if (isset($connectivity_data['initial_install']) && isset($connectivity_data['initial_install']['installed'])) {
        return $connectivity_data['initial_install']['installed'] === false;
    }
    
    // Default to needing connection if we can't determine
    return true;
}

/**
 * Format date in human-readable format
 * 
 * @param string $date_string ISO8601 date string
 * @return string Human-readable date
 */
function wpsec_format_date($date_string) {
    if (empty($date_string)) {
        return 'Unknown';
    }
    
    try {
        $date = new DateTime($date_string);
        return $date->format('F j, Y \a\t g:i a');
    } catch (Exception $e) {
        return 'Invalid date';
    }
}
