<?php
namespace PrimeLink\Modules\Imports\DataSources;

if ( ! defined( 'ABSPATH' ) ) { exit; }

final class FtpSource implements DataSourceInterface {

    private $settings = array();

    public function __construct( array $settings = array() ) {
        $this->settings = $settings;
    }

    public function handle( array $payload ) {
        try {
            $protocol = $payload['protocol'] ?? ( $this->settings['ftp_protocol'] ?? 'ftp' );
            $host     = $payload['host'] ?? ( $this->settings['ftp_host'] ?? '' );
            $port     = isset( $payload['port'] ) ? absint( $payload['port'] ) : ( isset( $this->settings['ftp_port'] ) ? absint( $this->settings['ftp_port'] ) : 0 );
            $user     = $payload['user'] ?? ( $this->settings['ftp_user'] ?? '' );
            $pass     = $payload['pass'] ?? ( $this->settings['ftp_pass'] ?? '' );
            $root     = $payload['root'] ?? ( $this->settings['ftp_root'] ?? '' );
            $file     = $payload['path'] ?? ( $this->settings['ftp_default_file'] ?? '' );
            $passive  = isset( $payload['passive'] ) ? (bool) $payload['passive'] : ! empty( $this->settings['ftp_passive'] );
            $test_only = ! empty( $payload['test_only'] );

            // For test only, we only need host, user, and pass
            if ( $test_only ) {
                if ( ! $host || ! $user || ! $pass ) {
                    return array( 'error' => 'Missing FTP/SFTP credentials. Please provide host, username, and password.' );
                }
                return $this->test_connection( $protocol, $host, $port, $user, $pass, $passive );
            }

            // For actual file download, we need the file path
            if ( ! $host || ! $user || ! $pass || ! $file ) {
                return array( 'error' => 'Missing FTP/SFTP credentials or file path.' );
            }

            $file_path_remote = $this->normalize_path( $root, $file );

            if ( 'sftp' === strtolower( $protocol ) ) {
                return $this->handle_sftp( $host, $port ?: 22, $user, $pass, $file_path_remote );
            }

            // Check if FTP functions are available, otherwise use cURL
            if ( ! function_exists( 'ftp_connect' ) ) {
                // Fallback to cURL for FTP
                if ( ! function_exists( 'curl_init' ) ) {
                    return array( 'error' => 'FTP functions and cURL are not available. Please enable either the FTP extension or cURL in PHP.' );
                }
                return $this->handle_ftp_with_curl( $protocol, $host, $port, $user, $pass, $file_path_remote, $passive );
            }

            // FTP / FTPS using native functions
            $port = $port ?: ( 'ftps' === strtolower( $protocol ) ? 990 : 21 );
            
            if ( 'ftps' === strtolower( $protocol ) ) {
                if ( ! function_exists( 'ftp_ssl_connect' ) ) {
                    // Fallback to cURL for FTPS
                    if ( ! function_exists( 'curl_init' ) ) {
                        return array( 'error' => 'FTPS (SSL) is not supported. Please enable OpenSSL support for FTP in PHP or enable cURL.' );
                    }
                    return $this->handle_ftp_with_curl( $protocol, $host, $port, $user, $pass, $file_path_remote, $passive );
                }
                $conn = @ftp_ssl_connect( $host, $port, 20 );
            } else {
                $conn = @ftp_connect( $host, $port, 20 );
            }
            
            if ( ! $conn ) {
                // Fallback to cURL if native FTP fails
                if ( function_exists( 'curl_init' ) ) {
                    return $this->handle_ftp_with_curl( $protocol, $host, $port, $user, $pass, $file_path_remote, $passive );
                }
                $last_error = error_get_last();
                $error_msg = $last_error ? $last_error['message'] : 'Unknown connection error';
                return array( 'error' => 'FTP connection failed: ' . $error_msg );
            }
            
            if ( ! @ftp_login( $conn, $user, $pass ) ) {
                @ftp_close( $conn );
                return array( 'error' => 'FTP login failed. Check username/password.' );
            }
            
            if ( $passive ) {
                @ftp_pasv( $conn, true );
            }

            $upload_dir = wp_upload_dir();
            if ( isset( $upload_dir['error'] ) && $upload_dir['error'] ) {
                @ftp_close( $conn );
                return array( 'error' => 'Cannot access upload directory: ' . $upload_dir['error'] );
            }
            
            $dest_dir   = trailingslashit( $upload_dir['basedir'] ) . 'primelink/';
            $dest_url   = trailingslashit( $upload_dir['baseurl'] ) . 'primelink/';
            
            if ( ! \PrimeLink\Helpers\FilesystemHelper::directory_exists( $dest_dir ) ) {
                $mkdir_result = \PrimeLink\Helpers\FilesystemHelper::create_directory( $dest_dir );
                if ( ! $mkdir_result ) {
                    @ftp_close( $conn );
                    return array( 'error' => 'Cannot create destination directory: ' . $dest_dir );
                }
            }
            
            if ( ! is_writable( $dest_dir ) ) {
                @ftp_close( $conn );
                return array( 'error' => 'Destination directory is not writable: ' . $dest_dir );
            }

            // Extract filename from remote path
            $name = basename( $file_path_remote );
            // If basename is empty or just a slash, try to extract from the full path
            if ( empty( $name ) || $name === '/' || $name === '\\' ) {
                // Remove trailing slashes and get the last part
                $clean_path = rtrim( $file_path_remote, '/\\' );
                $name = basename( $clean_path );
            }
            // If still empty, try to get from the path segments
            if ( empty( $name ) || $name === '/' || $name === '\\' ) {
                $path_parts = array_filter( explode( '/', trim( $file_path_remote, '/' ) ) );
                $name = ! empty( $path_parts ) ? end( $path_parts ) : '';
            }
            // If still empty, return error - don't generate a default filename
            if ( empty( $name ) || $name === '/' || $name === '\\' ) {
                return array( 'error' => 'Invalid file path. Please provide a valid file path with a filename.' );
            }
            
            $dest_name = time() . '-' . sanitize_file_name( $name );
            $dest_path = $dest_dir . $dest_name;

            $ok = @ftp_get( $conn, $dest_path, $file_path_remote, FTP_BINARY );
            @ftp_close( $conn );

            if ( ! $ok ) {
                // Fallback to cURL if native download fails
                if ( function_exists( 'curl_init' ) ) {
                    return $this->handle_ftp_with_curl( $protocol, $host, $port, $user, $pass, $file_path_remote, $passive );
                }
                $last_error = error_get_last();
                $error_msg = $last_error ? $last_error['message'] : 'Unknown download error';
                return array( 'error' => 'FTP download failed. Check file path and permissions. Error: ' . $error_msg );
            }
            
            if ( ! \PrimeLink\Helpers\FilesystemHelper::file_exists( $dest_path ) ) {
                return array( 'error' => 'File was not downloaded successfully. File does not exist at: ' . $dest_path );
            }

            $ext  = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );
            $type = in_array( $ext, array( 'xml', 'xlsx', 'xls', 'json', 'csv' ), true ) ? $ext : 'csv';

            return array(
                'path'          => $dest_path,
                'url'           => $dest_url . $dest_name,
                'type'          => $type,
                'original_name' => $name,
                'source'        => 'ftp',
                'downloaded_at' => current_time( 'mysql' ),
            );
        } catch ( \Exception $e ) {
            return array( 'error' => 'FTP error: ' . $e->getMessage() );
        } catch ( \Error $e ) {
            return array( 'error' => 'FTP fatal error: ' . $e->getMessage() );
        }
    }

    private function handle_sftp( $host, $port, $user, $pass, $remote_path ) {
        try {
            if ( ! function_exists( 'ssh2_connect' ) ) {
                return array( 'error' => 'SFTP requires the SSH2 PHP extension. Please enable it on the server.' );
            }

            $connection = @ssh2_connect( $host, $port );
            if ( ! $connection ) {
                $last_error = error_get_last();
                $error_msg = $last_error ? $last_error['message'] : 'Unknown connection error';
                return array( 'error' => 'SFTP connection failed: ' . $error_msg );
            }

            if ( ! @ssh2_auth_password( $connection, $user, $pass ) ) {
                return array( 'error' => 'SFTP login failed. Check username/password.' );
            }

            $sftp = @ssh2_sftp( $connection );
            if ( ! $sftp ) {
                return array( 'error' => 'Unable to initialize SFTP subsystem.' );
            }

            $upload_dir = wp_upload_dir();
            if ( isset( $upload_dir['error'] ) && $upload_dir['error'] ) {
                return array( 'error' => 'Cannot access upload directory: ' . $upload_dir['error'] );
            }
            
            $dest_dir   = trailingslashit( $upload_dir['basedir'] ) . 'primelink/';
            $dest_url   = trailingslashit( $upload_dir['baseurl'] ) . 'primelink/';
            
            if ( ! file_exists( $dest_dir ) ) {
                $mkdir_result = wp_mkdir_p( $dest_dir );
                if ( ! $mkdir_result ) {
                    return array( 'error' => 'Cannot create destination directory: ' . $dest_dir );
                }
            }
            
            if ( ! is_writable( $dest_dir ) ) {
                return array( 'error' => 'Destination directory is not writable: ' . $dest_dir );
            }

            // Extract filename from remote path
            $name = basename( $remote_path );
            // If basename is empty or just a slash, try to extract from the full path
            if ( empty( $name ) || $name === '/' || $name === '\\' ) {
                // Remove trailing slashes and get the last part
                $clean_path = rtrim( $remote_path, '/\\' );
                $name = basename( $clean_path );
            }
            // If still empty, try to get from the path segments
            if ( empty( $name ) || $name === '/' || $name === '\\' ) {
                $path_parts = array_filter( explode( '/', trim( $remote_path, '/' ) ) );
                $name = ! empty( $path_parts ) ? end( $path_parts ) : '';
            }
            // If still empty, return error - don't generate a default filename
            if ( empty( $name ) || $name === '/' || $name === '\\' ) {
                return array( 'error' => 'Invalid file path. Please provide a valid file path with a filename.' );
            }
            
            $dest_name = time() . '-' . sanitize_file_name( $name );
            $dest_path = $dest_dir . $dest_name;

            $remote_stream = @fopen( 'ssh2.sftp://' . intval( $sftp ) . $remote_path, 'r' );
            if ( ! $remote_stream ) {
                $last_error = error_get_last();
                $error_msg = $last_error ? $last_error['message'] : 'Unknown file read error';
                return array( 'error' => 'Cannot read remote SFTP file: ' . $error_msg );
            }
            
            $local_stream = @fopen( $dest_path, 'w' );
            if ( ! $local_stream ) {
                @fclose( $remote_stream );
                $last_error = error_get_last();
                $error_msg = $last_error ? $last_error['message'] : 'Unknown file write error';
                return array( 'error' => 'Cannot write local file: ' . $error_msg );
            }
            
            $copied = stream_copy_to_stream( $remote_stream, $local_stream );
            fclose( $remote_stream );
            fclose( $local_stream );
            
            if ( false === $copied ) {
                return array( 'error' => 'Failed to copy file from SFTP server.' );
            }
            
            if ( ! \PrimeLink\Helpers\FilesystemHelper::file_exists( $dest_path ) ) {
                return array( 'error' => 'File was not downloaded successfully. File does not exist at: ' . $dest_path );
            }

            $ext  = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );
            $type = in_array( $ext, array( 'xml', 'xlsx', 'xls', 'json', 'csv' ), true ) ? $ext : 'csv';

            return array(
                'path'          => $dest_path,
                'url'           => $dest_url . $dest_name,
                'type'          => $type,
                'original_name' => $name,
                'source'        => 'ftp',
                'downloaded_at' => current_time( 'mysql' ),
            );
        } catch ( \Exception $e ) {
            return array( 'error' => 'SFTP error: ' . $e->getMessage() );
        } catch ( \Error $e ) {
            return array( 'error' => 'SFTP fatal error: ' . $e->getMessage() );
        }
    }

    private function handle_ftp_with_curl( $protocol, $host, $port, $user, $pass, $remote_path, $passive ) {
        try {
            $upload_dir = wp_upload_dir();
            if ( isset( $upload_dir['error'] ) && $upload_dir['error'] ) {
                return array( 'error' => 'Cannot access upload directory: ' . $upload_dir['error'] );
            }
            
            $dest_dir   = trailingslashit( $upload_dir['basedir'] ) . 'primelink/';
            $dest_url   = trailingslashit( $upload_dir['baseurl'] ) . 'primelink/';
            
            if ( ! file_exists( $dest_dir ) ) {
                $mkdir_result = wp_mkdir_p( $dest_dir );
                if ( ! $mkdir_result ) {
                    return array( 'error' => 'Cannot create destination directory: ' . $dest_dir );
                }
            }
            
            if ( ! is_writable( $dest_dir ) ) {
                return array( 'error' => 'Destination directory is not writable: ' . $dest_dir );
            }

            // Extract filename from remote path
            $name = basename( $remote_path );
            // If basename is empty or just a slash, try to extract from the full path
            if ( empty( $name ) || $name === '/' || $name === '\\' ) {
                // Remove trailing slashes and get the last part
                $clean_path = rtrim( $remote_path, '/\\' );
                $name = basename( $clean_path );
            }
            // If still empty, try to get from the path segments
            if ( empty( $name ) || $name === '/' || $name === '\\' ) {
                $path_parts = array_filter( explode( '/', trim( $remote_path, '/' ) ) );
                $name = ! empty( $path_parts ) ? end( $path_parts ) : '';
            }
            // If still empty, return error - don't generate a default filename
            if ( empty( $name ) || $name === '/' || $name === '\\' ) {
                return array( 'error' => 'Invalid file path. Please provide a valid file path with a filename.' );
            }
            
            $dest_name = time() . '-' . sanitize_file_name( $name );
            $dest_path = $dest_dir . $dest_name;

            // Build FTP URL
            $port = $port ?: ( 'ftps' === strtolower( $protocol ) ? 990 : 21 );
            $scheme = ( 'ftps' === strtolower( $protocol ) ) ? 'ftps' : 'ftp';
            $ftp_url = sprintf( '%s://%s:%s@%s:%d%s', $scheme, rawurlencode( $user ), rawurlencode( $pass ), $host, $port, $remote_path );

            $ch = curl_init();
            if ( ! $ch ) {
                return array( 'error' => 'Failed to initialize cURL.' );
            }

            $fp = fopen( $dest_path, 'w' );
            if ( ! $fp ) {
                curl_close( $ch );
                return array( 'error' => 'Cannot create local file for writing.' );
            }

            curl_setopt_array( $ch, array(
                CURLOPT_URL            => $ftp_url,
                CURLOPT_FILE           => $fp,
                CURLOPT_FTPSSLAUTH     => CURLFTPSSL_ALL,
                CURLOPT_USE_SSL        => ( 'ftps' === strtolower( $protocol ) ) ? CURLUSESSL_ALL : CURLUSESSL_NONE,
                CURLOPT_FTP_USE_EPSV   => $passive ? 1 : 0,
                CURLOPT_FTPPORT        => $passive ? '' : '-',
                CURLOPT_TIMEOUT        => 60,
                CURLOPT_CONNECTTIMEOUT => 30,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_VERBOSE        => false,
                CURLOPT_FTP_USE_EPRT   => 0, // Use EPRT instead of PORT for better compatibility
            ) );

            $result = curl_exec( $ch );
            $error  = curl_error( $ch );
            $errno  = curl_errno( $ch );
            $http_code = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
            curl_close( $ch );
            fclose( $fp );

            if ( false === $result ) {
                if ( \PrimeLink\Helpers\FilesystemHelper::file_exists( $dest_path ) ) {
                    \PrimeLink\Helpers\FilesystemHelper::delete_file( $dest_path );
                }
                $error_msg = $error ?: 'Unknown cURL error';
                if ( $errno ) {
                    $error_msg .= ' (cURL error code: ' . $errno . ')';
                }
                return array( 'error' => 'FTP download failed via cURL: ' . $error_msg );
            }
            
            if ( ! empty( $error ) ) {
                // Warning but not fatal - check if file was downloaded
                $file_size = \PrimeLink\Helpers\FilesystemHelper::file_size( $dest_path );
                if ( ! \PrimeLink\Helpers\FilesystemHelper::file_exists( $dest_path ) || false === $file_size || $file_size === 0 ) {
                    if ( \PrimeLink\Helpers\FilesystemHelper::file_exists( $dest_path ) ) {
                        \PrimeLink\Helpers\FilesystemHelper::delete_file( $dest_path );
                    }
                    return array( 'error' => 'FTP download failed via cURL: ' . $error );
                }
            }

            $file_size = \PrimeLink\Helpers\FilesystemHelper::file_size( $dest_path );
            if ( ! \PrimeLink\Helpers\FilesystemHelper::file_exists( $dest_path ) || false === $file_size || $file_size === 0 ) {
                if ( \PrimeLink\Helpers\FilesystemHelper::file_exists( $dest_path ) ) {
                    \PrimeLink\Helpers\FilesystemHelper::delete_file( $dest_path );
                }
                return array( 'error' => 'File was not downloaded successfully or file is empty.' );
            }

            $ext  = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );
            $type = in_array( $ext, array( 'xml', 'xlsx', 'xls', 'json', 'csv' ), true ) ? $ext : 'csv';

            return array(
                'path'          => $dest_path,
                'url'           => $dest_url . $dest_name,
                'type'          => $type,
                'original_name' => $name,
                'source'        => 'ftp',
                'downloaded_at' => current_time( 'mysql' ),
            );
        } catch ( \Exception $e ) {
            return array( 'error' => 'FTP cURL error: ' . $e->getMessage() );
        } catch ( \Error $e ) {
            return array( 'error' => 'FTP cURL fatal error: ' . $e->getMessage() );
        }
    }

    private function normalize_path( $root, $file ) {
        $root = trim( (string) $root );
        $file = trim( (string) $file );
        if ( $root && '/' !== $root[0] ) {
            $root = '/' . $root;
        }
        if ( $file && '/' !== $file[0] ) {
            $file = '/' . $file;
        }
        $path = $root . $file;
        $path = preg_replace( '#/+#', '/', $path );
        return $path ?: $file;
    }

    /**
     * Test FTP/SFTP connection without downloading a file
     */
    private function test_connection( $protocol, $host, $port, $user, $pass, $passive ) {
        try {
            if ( 'sftp' === strtolower( $protocol ) ) {
                return $this->test_sftp_connection( $host, $port ?: 22, $user, $pass );
            }

            // Check if FTP functions are available
            if ( ! function_exists( 'ftp_connect' ) ) {
                // Try with cURL as fallback
                if ( function_exists( 'curl_init' ) ) {
                    return $this->test_ftp_with_curl( $protocol, $host, $port, $user, $pass, $passive );
                }
                return array( 'error' => 'FTP functions and cURL are not available. Please enable either the FTP extension or cURL in PHP.' );
            }

            // FTP / FTPS using native functions
            $port = $port ?: ( 'ftps' === strtolower( $protocol ) ? 990 : 21 );
            
            if ( 'ftps' === strtolower( $protocol ) ) {
                if ( ! function_exists( 'ftp_ssl_connect' ) ) {
                    // Fallback to cURL for FTPS
                    if ( ! function_exists( 'curl_init' ) ) {
                        return array( 'error' => 'FTPS (SSL) is not supported. Please enable OpenSSL support for FTP in PHP or enable cURL.' );
                    }
                    return $this->test_ftp_with_curl( $protocol, $host, $port, $user, $pass, $passive );
                }
                // Increased timeout from 20 to 30 seconds for better compatibility
                $conn = @ftp_ssl_connect( $host, $port, 30 );
            } else {
                // Increased timeout from 20 to 30 seconds for better compatibility
                $conn = @ftp_connect( $host, $port, 30 );
            }
            
            if ( ! $conn ) {
                // Fallback to cURL if native FTP fails
                if ( function_exists( 'curl_init' ) ) {
                    return $this->test_ftp_with_curl( $protocol, $host, $port, $user, $pass, $passive );
                }
                $last_error = error_get_last();
                $error_msg = $last_error ? $last_error['message'] : 'Unknown connection error';
                return array( 'error' => 'FTP connection failed: ' . $error_msg );
            }
            
            if ( ! @ftp_login( $conn, $user, $pass ) ) {
                @ftp_close( $conn );
                return array( 'error' => 'FTP login failed. Check username/password.' );
            }
            
            if ( $passive ) {
                @ftp_pasv( $conn, true );
            }

            // Try to get current directory to verify we can interact with the server
            $pwd = @ftp_pwd( $conn );
            @ftp_close( $conn );

            return array( 
                'success' => true,
                'message' => 'Connection successful' . ( $pwd ? ' (current directory: ' . $pwd . ')' : '' )
            );
        } catch ( \Exception $e ) {
            return array( 'error' => 'FTP test error: ' . $e->getMessage() );
        } catch ( \Error $e ) {
            return array( 'error' => 'FTP test fatal error: ' . $e->getMessage() );
        }
    }

    /**
     * Test SFTP connection
     */
    private function test_sftp_connection( $host, $port, $user, $pass ) {
        try {
            if ( ! function_exists( 'ssh2_connect' ) ) {
                return array( 'error' => 'SFTP requires the SSH2 PHP extension. Please enable it on the server.' );
            }

            $connection = @ssh2_connect( $host, $port );
            if ( ! $connection ) {
                $last_error = error_get_last();
                $error_msg = $last_error ? $last_error['message'] : 'Unknown connection error';
                return array( 'error' => 'SFTP connection failed: ' . $error_msg );
            }

            if ( ! @ssh2_auth_password( $connection, $user, $pass ) ) {
                return array( 'error' => 'SFTP login failed. Check username/password.' );
            }

            $sftp = @ssh2_sftp( $connection );
            if ( ! $sftp ) {
                return array( 'error' => 'Unable to initialize SFTP subsystem.' );
            }

            // Try to get current directory
            $realpath = @ssh2_sftp_realpath( $sftp, '.' );
            $pwd = $realpath !== false ? $realpath : '';

            return array( 
                'success' => true,
                'message' => 'SFTP connection successful' . ( $pwd ? ' (current directory: ' . $pwd . ')' : '' )
            );
        } catch ( \Exception $e ) {
            return array( 'error' => 'SFTP test error: ' . $e->getMessage() );
        } catch ( \Error $e ) {
            return array( 'error' => 'SFTP test fatal error: ' . $e->getMessage() );
        }
    }

    /**
     * Test FTP connection with cURL
     */
    private function test_ftp_with_curl( $protocol, $host, $port, $user, $pass, $passive ) {
        try {
            $port = $port ?: ( 'ftps' === strtolower( $protocol ) ? 990 : 21 );
            $scheme = ( 'ftps' === strtolower( $protocol ) ) ? 'ftps' : 'ftp';
            // Test with root directory
            $ftp_url = sprintf( '%s://%s:%s@%s:%d/', $scheme, rawurlencode( $user ), rawurlencode( $pass ), $host, $port );

            $ch = curl_init();
            if ( ! $ch ) {
                return array( 'error' => 'Failed to initialize cURL.' );
            }

            curl_setopt_array( $ch, array(
                CURLOPT_URL            => $ftp_url,
                CURLOPT_NOBODY         => true, // HEAD request only
                CURLOPT_FTPSSLAUTH     => CURLFTPSSL_ALL,
                CURLOPT_USE_SSL        => ( 'ftps' === strtolower( $protocol ) ) ? CURLUSESSL_ALL : CURLUSESSL_NONE,
                CURLOPT_FTP_USE_EPSV   => $passive ? 1 : 0,
                CURLOPT_FTPPORT        => $passive ? '' : '-',
                CURLOPT_TIMEOUT        => 60, // Increased from 30 to 60 seconds
                CURLOPT_CONNECTTIMEOUT => 30, // Increased from 15 to 30 seconds
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_VERBOSE        => false,
                CURLOPT_FTP_USE_EPRT   => 0,
            ) );

            $result = curl_exec( $ch );
            $error  = curl_error( $ch );
            $errno  = curl_errno( $ch );
            curl_close( $ch );

            if ( false === $result || ! empty( $error ) ) {
                $error_msg = $error ?: 'Unknown cURL error';
                if ( $errno ) {
                    // Provide more user-friendly error messages for common errors
                    if ( $errno === 28 ) {
                        $error_msg = 'Connection timeout. The FTP server did not respond within 60 seconds. Please check if the host, port, and firewall settings are correct.';
                    } elseif ( $errno === 7 ) {
                        $error_msg = 'Failed to connect to host. Please verify the host address and port number.';
                    } elseif ( $errno === 67 ) {
                        $error_msg = 'Login denied. Please check your username and password.';
                    } else {
                        $error_msg .= ' (cURL error code: ' . $errno . ')';
                    }
                }
                return array( 'error' => 'FTP connection test failed via cURL: ' . $error_msg );
            }

            return array( 
                'success' => true,
                'message' => 'FTP connection successful (tested via cURL)'
            );
        } catch ( \Exception $e ) {
            return array( 'error' => 'FTP cURL test error: ' . $e->getMessage() );
        } catch ( \Error $e ) {
            return array( 'error' => 'FTP cURL test fatal error: ' . $e->getMessage() );
        }
    }
}
