<?php
/**
 * Blocked IP Sync Class - Sync Blocked IPs from API
 *
 * @package VMPFence
 * @since 2.1.0
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Blocked IP Sync Class (matches Signature_Sync pattern)
 *
 * @since 2.1.0
 */
class VMPFence_Blocked_IP_Sync {

    /**
     * Get JSON file path
     *
     * @since 2.1.0
     * @return string
     */
    public static function get_json_file_path() {
        return VMPFENCE_PLUGIN_DIR . 'data/blocked-ips.json';
    }

    /**
     * Sync blocked IPs from API server (PRIMARY METHOD)
     *
     * @since 2.1.0
     * @return array Result with 'success', 'imported', 'errors', 'total_count' keys
     */
    public static function sync_from_api() {
        // Get API key
        $api_key = VMPFence_Config::get('central_api_key');
        
        if (empty($api_key)) {
            return array(
                'success' => false,
                'imported' => 0,
                'errors' => array('API key not configured'),
                'total_count' => 0
            );
        }
        
        // Initialize API client
        require_once VMPFENCE_PLUGIN_DIR . 'lib/class-api-client.php';
        $api_client = new VMPFence_API_Client();
        
        // Backend returns max 1000 IPs per request by default
        // So we just fetch once - the backend already limits to prevent timeout
        $response = $api_client->get_blocked_ips($api_key, true); // active_only = true
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'imported' => 0,
                'errors' => array('API error: ' . $response->get_error_message()),
                'total_count' => 0
            );
        }
        
        // Extract blocked IPs and metadata
        $blocked_ips = isset($response['blocked_ips']) ? $response['blocked_ips'] : array();
        $total_count = isset($response['total_count']) ? $response['total_count'] : 0;
        $active_count = isset($response['active_count']) ? $response['active_count'] : 0;
        
        if (empty($blocked_ips)) {
            return array(
                'success' => true,
                'imported' => 0,
                'errors' => array(),
                'total_count' => 0
            );
        }
        
        // Save blocked IPs to JSON file
        $result = self::save_blocked_ips_to_file($blocked_ips, $total_count, $active_count);
        
        if ($result['success']) {
            // Update WordPress options metadata
            update_option('vmpfence_blocked_ip_last_sync', current_time('mysql'));
            update_option('vmpfence_blocked_ip_count', count($blocked_ips));
            update_option('vmpfence_blocked_ip_total', $total_count);
            
            VMPFence_Secure_Logger::log('info', 'Synced blocked IPs from API', [
                'imported' => count($blocked_ips),
                'total_available' => $total_count,
                'active_count' => $active_count
            ]);
        }
        
        return array(
            'success' => $result['success'],
            'imported' => count($blocked_ips),
            'errors' => $result['errors'],
            'total_count' => $total_count,
            'active_count' => $active_count
        );
    }
    
    /**
     * Save blocked IPs to JSON file
     *
     * @since 2.1.0
     * @param array $blocked_ips Blocked IPs array from API
     * @param int $total_count Total count from API
     * @param int $active_count Active count from API
     * @return array Result with 'success' and 'errors' keys
     */
    public static function save_blocked_ips_to_file($blocked_ips, $total_count, $active_count) {
        $errors = array();
        
        try {
            $file_path = self::get_json_file_path();
            $dir = dirname($file_path);
            
            // Ensure directory exists
            if (!file_exists($dir)) {
                if (!wp_mkdir_p($dir)) {
                    return array(
                        'success' => false,
                        'errors' => array('Failed to create data directory')
                    );
                }
            }
            
            // Prepare data structure matching API response
            $data = array(
                'blocked_ips' => $blocked_ips,
                'total_count' => $total_count,
                'active_count' => $active_count,
                'synced_at' => current_time('mysql'),
                'synced_timestamp' => time()
            );
            
            // Convert to JSON with pretty print for readability
            $json = wp_json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
            
            if ($json === false) {
                return array(
                    'success' => false,
                    'errors' => array('Failed to encode JSON: ' . json_last_error_msg())
                );
            }
            
            // Use WordPress filesystem API for security
            global $wp_filesystem;
            if (empty($wp_filesystem)) {
                require_once ABSPATH . 'wp-admin/includes/file.php';
                WP_Filesystem();
            }
            
            if (!$wp_filesystem->put_contents($file_path, $json, FS_CHMOD_FILE)) {
                // Fallback to file_put_contents if WP_Filesystem fails
                if (file_put_contents($file_path, $json) === false) {
                    return array(
                        'success' => false,
                        'errors' => array('Failed to write JSON file')
                    );
                }
            }
            
            // Verify file was written correctly
            if (!file_exists($file_path)) {
                return array(
                    'success' => false,
                    'errors' => array('JSON file not found after write')
                );
            }
            
            VMPFence_Secure_Logger::debug('Blocked IPs saved to JSON', [
                'file' => basename($file_path),
                'count' => count($blocked_ips),
                'size' => filesize($file_path)
            ]);
            
            return array(
                'success' => true,
                'errors' => array()
            );
            
        } catch (Exception $e) {
            return array(
                'success' => false,
                'errors' => array('Exception: ' . $e->getMessage())
            );
        }
    }
    
    /**
     * Load blocked IPs from JSON file
     *
     * @since 2.1.0
     * @return array|false Blocked IPs array or false on failure
     */
    public static function load_blocked_ips_from_file() {
        $file_path = self::get_json_file_path();
        
        if (!file_exists($file_path)) {
            return false;
        }
        
        $json = file_get_contents($file_path);
        
        if ($json === false) {
            return false;
        }
        
        $data = json_decode($json, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            VMPFence_Secure_Logger::error('Failed to parse blocked IPs JSON', [
                'error' => json_last_error_msg()
            ]);
            return false;
        }
        
        return $data;
    }
    
    /**
     * Get blocked IPs (from cache or file)
     *
     * @since 2.1.0
     * @return array Blocked IPs data with metadata
     */
    public static function get_blocked_ips() {
        // Try to load from file
        $data = self::load_blocked_ips_from_file();
        
        if ($data === false) {
            return array(
                'blocked_ips' => array(),
                'total_count' => 0,
                'active_count' => 0,
                'synced_at' => null
            );
        }
        
        return $data;
    }
    
    /**
     * Check if sync is needed (based on last sync time)
     *
     * @since 2.1.0
     * @param int $max_age_hours Maximum age in hours before resync needed
     * @return bool True if sync needed
     */
    public static function is_sync_needed($max_age_hours = 1) {
        $last_sync = get_option('vmpfence_blocked_ip_last_sync');
        
        if (!$last_sync) {
            return true; // Never synced
        }
        
        $last_sync_time = strtotime($last_sync);
        $age_hours = (time() - $last_sync_time) / 3600;
        
        return $age_hours >= $max_age_hours;
    }
}
