<?php
if (!defined('ABSPATH')) {
    exit;
}

class Cloud_Uploads_Client {
    
    private $s3_client;
    private $settings;
    private $bucket;
    private $region;
    private $b2_account_id;
    private $b2_application_key_id;
    private $b2_application_key_secret;
    private $use_aws_sdk = false;

    public function __construct($settings) {
        $this->settings = $settings;
        $this->bucket = $settings->get_option('bucket_name');
        $this->region = $settings->get_option('region');
        $this->b2_application_key_id = $settings->get_option('access_key');
        $this->b2_application_key_secret = $settings->get_option('secret_key');
        $this->initialize_s3_client();
    }
    
    private function initialize_s3_client() {
        try {
            // Check if AWS SDK is available, otherwise use minimal S3 client
            if (class_exists('Aws\S3\S3Client')) {
                //error_log('Debug Error: Initializing AWS SDK S3 Client');
                $this->use_aws_sdk = true;
                $this->initialize_aws_sdk();
            } else {
                //error_log('Debug Error: Initializing Minimal S3 Client');
                $this->use_aws_sdk = false;
                $this->initialize_minimal_s3_client();
            }
        } catch (Exception $e) {
            error_log('Cloud Uploads: Failed to initialize S3 client - ' . $e->getMessage());
            throw new Exception('Failed to initialize S3 client: ' . $e->getMessage());
        }
    }
    
    private function initialize_aws_sdk() {
        $args = array(
            'version' => 'latest',
            'region'  => $this->region,
            'credentials' => array(
                'key'    => $this->settings->get_option('access_key'),
                'secret' => $this->settings->get_option('secret_key'),
            ),
            'signature_version' => 'v4' // Force AWS Signature Version 4
        );
        
        // Add custom endpoint for S3 compatible services
        $endpoint = $this->settings->get_option('endpoint');
        if (!empty($endpoint)) {
            $args['endpoint'] = $endpoint;
            $args['use_path_style_endpoint'] = true;
        }
        
        $this->s3_client = new Aws\S3\S3Client($args);
    }
    
    private function initialize_minimal_s3_client() {
        // Fallback to using WordPress HTTP API for S3 operations
        $this->s3_client = null;
    }
    
    /**
     * Validate region and endpoint settings
     */
    private function validate_region_and_endpoint() {
        $region = $this->settings->get_option('region');
        $endpoint = $this->settings->get_option('endpoint');
        
        if (empty($region)) {
            throw new Exception('Region is required for AWS Signature Version 4');
        }
        
        if (empty($endpoint)) {
            throw new Exception('Endpoint is required for S3 compatible services');
        }
        
        // Check for Backblaze B2
        if (strpos($endpoint, 'backblazeb2.com') !== false) {
            $backblaze_regions = array('us-west-001', 'us-west-002', 'us-east-005', 'eu-central-003');
            if (!in_array($region, $backblaze_regions)) {
                throw new Exception('Invalid region for Backblaze B2. Valid regions: ' . implode(', ', $backblaze_regions));
            }
            return array('service' => 'backblaze', 'region' => $region);
        }
        
        // Check for DigitalOcean Spaces
        if (strpos($endpoint, 'digitaloceanspaces.com') !== false) {
            $do_regions = array('nyc3', 'sfo2', 'sfo3', 'ams3', 'sgp1', 'fra1', 'tor1', 'blr1');
            if (!in_array($region, $do_regions)) {
                throw new Exception('Invalid region for DigitalOcean Spaces. Valid regions: ' . implode(', ', $do_regions));
            }
            return array('service' => 'digitalocean', 'region' => $region);
        }
        
        // Validate standard AWS regions
        $aws_regions = array(
            'us-east-1', 'us-east-2', 'us-west-1', 'us-west-2',
            'ca-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3',
            'eu-central-1', 'eu-north-1', 'ap-northeast-1', 'ap-northeast-2',
            'ap-northeast-3', 'ap-southeast-1', 'ap-southeast-2', 'ap-south-1',
            'sa-east-1', 'cn-north-1', 'cn-northwest-1'
        );
        
        if (!in_array($region, $aws_regions)) {
            error_log('Cloud Uploads: Warning - Unknown region "' . $region . '". AWS Signature v4 may not work correctly.');
        }
        
        return array('service' => 'aws', 'region' => $region);
    }

    public function upload_file($local_path, $s3_path) {
    try {
        // Validate region and endpoint first
        $service_info = $this->validate_region_and_endpoint();
        
        if (is_object($this->s3_client) && method_exists($this->s3_client, 'putObject')) {
            // Use AWS SDK
            $result = $this->s3_client->putObject([
                'Bucket' => $this->bucket,
                'Key'    => $s3_path,
                'Body'   => fopen($local_path, 'rb'),
                'ACL'    => 'public-read'
            ]);
            
            return $result->get('ObjectURL');
        } else {
            // Use appropriate upload method based on service
            if ($service_info['service'] === 'backblaze') {
                return $this->upload_to_backblaze_b2($local_path, $s3_path);
            } else {
                return $this->upload_via_http_aws4($local_path, $s3_path);
            }
        }
        } catch (Exception $e) {
            error_log('Cloud Uploads: Failed to upload file - ' . $e->getMessage());
            throw new Exception('Failed to upload file to S3: ' . $e->getMessage());
        }
    }
    
    // Add to your Cloud_Uploads_Client class
    private function validate_region() {
        $region = $this->settings->get_option('region');
        
        if (empty($region)) {
            throw new Exception('Region is required for AWS Signature Version 4');
        }
        
        // Check if this is a Backblaze B2 region
        $backblaze_regions = array('us-west-001', 'us-west-002', 'us-east-005', 'eu-central-003');
        if (in_array($region, $backblaze_regions)) {
            return $region; // Backblaze regions are valid
        }
        
        // Validate standard AWS regions
        $aws_regions = array(
            'us-east-1', 'us-east-2', 'us-west-1', 'us-west-2',
            'ca-central-1', 'eu-west-1', 'eu-west-2', 'eu-west-3',
            'eu-central-1', 'eu-north-1', 'ap-northeast-1', 'ap-northeast-2',
            'ap-northeast-3', 'ap-southeast-1', 'ap-southeast-2', 'ap-south-1',
            'sa-east-1', 'cn-north-1', 'cn-northwest-1'
        );
        
        if (!in_array($region, $aws_regions)) {
            error_log('Cloud Uploads: Warning - Unknown region "' . $region . '". AWS Signature v4 may not work correctly.');
        }
        
        return $region;
    }

    private function upload_via_http($local_path, $s3_path) {
        $endpoint = $this->settings->get_option('endpoint');
        $url = "https://{$this->bucket}.{$endpoint}/{$s3_path}";
        
        $file_content = file_get_contents($local_path);
        $file_type = wp_check_filetype($local_path)['type'];
        
        $headers = array(
            'Authorization' => 'AWS ' . $this->settings->get_option('access_key') . ':' . 
                              $this->generate_signature('PUT', $s3_path),
            'Date' => gmdate('D, d M Y H:i:s T'),
            'Content-Type' => $file_type,
            'Content-Length' => filesize($local_path)
        );
        
        $response = wp_remote_request($url, array(
            'method' => 'PUT',
            'headers' => $headers,
            'body' => $file_content,
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            error_log('Cloud Uploads: HTTP upload failed - ' . $response->get_error_message());
            throw new Exception('HTTP upload failed: ' . $response->get_error_message());
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            $response_body = wp_remote_retrieve_body($response);
            error_log('Cloud Uploads: HTTP upload failed with code ' . $response_code . ' - ' . $response_body);
            throw new Exception('HTTP upload failed with code ' . $response_code . ': ' . $response_body);
        }
        
        return $url;
    }
    
    private function generate_signature($method, $path) {
        $string_to_sign = $method . "\n\n\n" . 
                         gmdate('D, d M Y H:i:s T') . "\n" . 
                         "/{$this->bucket}/{$path}";
        
        $signature = base64_encode(
            hash_hmac('sha1', $string_to_sign, $this->settings->get_option('secret_key'), true)
        );
        
        return $signature;
    }
    
    /**
     * Upload file using AWS Signature Version 4
     */
    private function upload_via_http_aws4($local_path, $s3_path) {
        $endpoint = $this->settings->get_option('endpoint');
        $region = $this->settings->get_option('region');
        $url = "https://{$this->bucket}.{$endpoint}/{$s3_path}";
        
        $file_content = file_get_contents($local_path);
        $file_type = wp_check_filetype($local_path)['type'];
        $file_size = filesize($local_path);
        
        // Generate AWS Signature Version 4
        $amz_date = gmdate('Ymd\THis\Z');
        $date_stamp = gmdate('Ymd');
        
        // Prepare canonical request
        $canonical_uri = "/{$s3_path}";
        $canonical_querystring = '';
        $canonical_headers = "host:{$this->bucket}.{$endpoint}\nx-amz-date:{$amz_date}\n";
        $signed_headers = 'host;x-amz-date';
        $payload_hash = hash('sha256', $file_content);
        
        $canonical_request = "PUT\n{$canonical_uri}\n{$canonical_querystring}\n{$canonical_headers}\n{$signed_headers}\n{$payload_hash}";
        
        // Prepare string to sign
        $algorithm = 'AWS4-HMAC-SHA256';
        $credential_scope = "{$date_stamp}/{$region}/s3/aws4_request";
        $canonical_request_hash = hash('sha256', $canonical_request);
        
        $string_to_sign = "{$algorithm}\n{$amz_date}\n{$credential_scope}\n{$canonical_request_hash}";
        
        // Calculate signature
        $signing_key = $this->get_signature_key($this->settings->get_option('secret_key'), $date_stamp, $region, 's3');
        $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
        
        // Prepare authorization header
        $authorization_header = "{$algorithm} Credential={$this->settings->get_option('access_key')}/{$credential_scope}, SignedHeaders={$signed_headers}, Signature={$signature}";
        
        $headers = array(
            'Authorization' => $authorization_header,
            'x-amz-date' => $amz_date,
            'x-amz-content-sha256' => $payload_hash,
            'Content-Type' => $file_type,
            'Content-Length' => $file_size
        );
        
        $response = wp_remote_request($url, array(
            'method' => 'PUT',
            'headers' => $headers,
            'body' => $file_content,
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            $error_message = 'HTTP upload failed - ' . $response->get_error_message();
            error_log('Cloud Uploads: ' . $error_message);
            throw new Exception($error_message);
        }
    
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            $response_body = wp_remote_retrieve_body($response);
            $error_message = 'HTTP upload failed with code ' . $response_code . ' - ' . $response_body;
            error_log('Cloud Uploads: ' . $error_message);
            
            // Check for specific signature errors
            if (strpos($response_body, 'SignatureDoesNotMatch') !== false) {
                $error_message .= ' [Signature Error: Please check your credentials and region settings]';
            } elseif (strpos($response_body, 'InvalidAccessKeyId') !== false) {
                $error_message .= ' [Invalid Access Key: Please check your Access Key ID]';
            } elseif (strpos($response_body, 'AccessDenied') !== false) {
                $error_message .= ' [Access Denied: Please check your bucket permissions]';
            }
            
            throw new Exception($error_message);
        }
        
        return $url;
    }

    /**
     * Generate AWS Signature Version 4 signing key
     */
    private function get_signature_key($key, $date_stamp, $region, $service) {
        $kDate = hash_hmac('sha256', $date_stamp, 'AWS4' . $key, true);
        $kRegion = hash_hmac('sha256', $region, $kDate, true);
        $kService = hash_hmac('sha256', $service, $kRegion, true);
        $kSigning = hash_hmac('sha256', 'aws4_request', $kService, true);
        
        return $kSigning;
    }

    /**
     * Backblaze B2 specific upload implementation
     */
    private function upload_to_backblaze_b2($local_path, $s3_path) {
        $endpoint = $this->settings->get_option('endpoint');
        $region = $this->settings->get_option('region');
        $url = "https://{$this->bucket}.{$endpoint}/{$s3_path}";
        
        $file_content = file_get_contents($local_path);
        $file_type = wp_check_filetype($local_path)['type'];
        $file_size = filesize($local_path);
        
        // Backblaze B2 requires a different approach
        // First, get the upload URL
        $upload_url_response = $this->get_b2_upload_url();
        
        if (!$upload_url_response['success']) {
            throw new Exception('Failed to get B2 upload URL: ' . $upload_url_response['message']);
        }
        
        $upload_url = $upload_url_response['uploadUrl'];
        $auth_token = $upload_url_response['authorizationToken'];
        
        // Upload the file directly to the upload URL
        $headers = array(
            'Authorization' => $auth_token,
            'Content-Type' => $file_type,
            'Content-Length' => $file_size,
            'X-Bz-File-Name' => $s3_path,
            'X-Bz-Content-Sha1' => sha1($file_content)
        );
        
        $response = wp_remote_request($upload_url, array(
            'method' => 'POST',
            'headers' => $headers,
            'body' => $file_content,
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            error_log('Cloud Uploads: B2 upload failed - ' . $response->get_error_message());
            throw new Exception('B2 upload failed: ' . $response->get_error_message());
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            $response_body = wp_remote_retrieve_body($response);
            error_log('Cloud Uploads: B2 upload failed with code ' . $response_code . ' - ' . $response_body);
            throw new Exception('B2 upload failed with code ' . $response_code . ': ' . $response_body);
        }
        
        $response_data = json_decode(wp_remote_retrieve_body($response), true);
        
        if (isset($response_data['fileId'])) {
            return "https://f000.backblazeb2.com/file/{$this->bucket}/{$s3_path}";
        }
        
        throw new Exception('B2 upload failed: No file ID in response');
    }

    /**
     * B2 v3 API - Authorize account
     */
    private function b2_authorize_account() {
        $credentials = base64_encode($this->b2_application_key_id . ':' . $this->b2_application_key_secret);
        
        $response = wp_remote_get('https://api.backblazeb2.com/b2api/v3/b2_authorize_account', array(
            'headers' => array(
                'Authorization' => 'Basic ' . $credentials
            )
        ));
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => $response->get_error_message()
            );
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        
        if ($response_code !== 200) {
            return array(
                'success' => false,
                'message' => "HTTP $response_code: $response_body"
            );
        }
        
        $data = json_decode($response_body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            return array(
                'success' => false,
                'message' => 'Invalid JSON response: ' . json_last_error_msg()
            );
        }
        
        if (!isset($data['apiInfo']['storageApi']['apiUrl']) || !isset($data['authorizationToken'])) {
            return array(
                'success' => false,
                'message' => 'Invalid auth response: missing apiUrl or authorizationToken'
            );
        }
        
        return array(
            'success' => true,
            'apiUrl' => $data['apiInfo']['storageApi']['apiUrl'],
            'bucketId' => $data['apiInfo']['storageApi']['bucketId'],
            'authorizationToken' => $data['authorizationToken'],
            'accountId' => isset($data['accountId']) ? $data['accountId'] : '',
            'allowed' => isset($data['allowed']) ? $data['allowed'] : array()
        );
    }

    /**
     * Get Backblaze B2 upload URL
     */
    private function get_b2_upload_url() {    
        $auth_response = $this->b2_authorize_account();
            
        if (!$auth_response['success']) {
            return array(
                'success' => false,
                'message' => 'B2 authorization failed: ' . $auth_response['message']
            );
        }
        
        // Now get the upload URL
        $api_url = $auth_response['apiUrl'];
        $auth_token = $auth_response['authorizationToken'];
        
        $base_url = $api_url . '/b2api/v4/b2_get_upload_url';
        
        $bucket_id = $auth_response['bucketId'];

        $query_params = array(
            'bucketId' => $bucket_id
        );
        $url = add_query_arg( $query_params, $base_url );
        $upload_url_response = wp_remote_get($url, array(
            'headers' => array(
                'Authorization' => $auth_token
            )
        ));
        
        if (is_wp_error($upload_url_response)) {
            return array('success' => false, 'message' => $upload_url_response->get_error_message());
        }
        
        $upload_url_data = json_decode(wp_remote_retrieve_body($upload_url_response), true);
        //error_log(print_r($upload_url_response, true));
        //error_log(print_r($url, true));
        if (isset($upload_url_data['uploadUrl']) && isset($upload_url_data['authorizationToken'])) {
            return array(
                'success' => true,
                'uploadUrl' => $upload_url_data['uploadUrl'],
                'authorizationToken' => $upload_url_data['authorizationToken']
            );
        }
        
        return array('success' => false, 'message' => 'Failed to get upload URL from B2');
    }

    /**
     * B2 v3 API - Get bucket ID by name
     */
    private function b2_get_bucket_id($api_url, $auth_token) {
        $response = wp_remote_post($api_url . '/b2api/v3/b2_list_buckets', array(
            'headers' => array(
                'Authorization' => $auth_token,
                'Content-Type' => 'application/json',
                'User-Agent' => 'WordPress-S3-Upload-Sync/1.0'
            ),
            'body' => json_encode(array(
                'accountId' => $this->settings->get_option('access_key'),
                'bucketName' => $this->bucket
            )),
            'timeout' => 30,
            'redirection' => 5,
            'httpversion' => '1.1'
        ));
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => $response->get_error_message()
            );
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        
        if ($response_code !== 200) {
            return array(
                'success' => false,
                'message' => "HTTP $response_code: $response_body"
            );
        }
        
        $data = json_decode($response_body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            return array(
                'success' => false,
                'message' => 'Invalid JSON response: ' . json_last_error_msg()
            );
        }
        
        // Find the bucket by name
        if (isset($data['buckets']) && is_array($data['buckets'])) {
            foreach ($data['buckets'] as $bucket) {
                if ($bucket['bucketName'] === $this->bucket) {
                    return array(
                        'success' => true,
                        'bucketId' => $bucket['bucketId'],
                        'bucketName' => $bucket['bucketName'],
                        'bucketType' => $bucket['bucketType']
                    );
                }
            }
        }
        
        return array(
            'success' => false,
            'message' => 'Bucket not found: ' . $this->bucket
        );
    }

    /**
     * Backblaze B2 specific signature generation
     */
    private function generate_backblaze_signature($secret_key, $date_stamp, $region, $string_to_sign) {
        // Backblaze B2 uses a slightly different approach
        $signing_key = hash_hmac('sha256', 'aws4_request', 
                        hash_hmac('sha256', 's3', 
                        hash_hmac('sha256', $region, 
                        hash_hmac('sha256', $date_stamp, 'AWS4' . $secret_key, true), true), true), true);
        
        return hash_hmac('sha256', $string_to_sign, $signing_key);
    }

    public function delete_file($s3_path) {
        try {
            if (is_object($this->s3_client) && method_exists($this->s3_client, 'deleteObject')) {
                $this->s3_client->deleteObject([
                    'Bucket' => $this->bucket,
                    'Key'    => $s3_path
                ]);
            } else {
                // Fallback to HTTP API with AWS4 signature for delete
                $this->delete_via_http_aws4($s3_path);
            }
            return true;
        } catch (Exception $e) {
            error_log('Cloud Uploads: Failed to delete file - ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * Delete file using AWS Signature Version 4
     */
    private function delete_via_http_aws4($file_name) {
        try {
            $url = $this->seetings->get_option('endpoint'). '/' . $settings->get_option('bucket_name') . '/' . rawurlencode($file_name);
            
            $headers = $this->generate_s3_headers('DELETE', $file_name);
            
            $response = wp_remote_request($url, array(
                'method' => 'DELETE',
                'headers' => $headers,
                'timeout' => 30
            ));
            
            if (is_wp_error($response)) {
                throw new Exception('HTTP Error: ' . $response->get_error_message());
            }
            
            $response_code = wp_remote_retrieve_response_code($response);
            
            if ($response_code === 204) {
                return true; // Success - 204 No Content
            } else {
                $body = wp_remote_retrieve_body($response);
                throw new Exception('Delete failed. Code: ' . $response_code . ' - Body: ' . $body);
            }
            
        } catch (Exception $e) {
            error_log('B2 S3 Delete Error: ' . $e->getMessage());
            return false;
        }
    }

    public function test_connection() {
        try {
            if (is_object($this->s3_client) && method_exists($this->s3_client, 'listBuckets')) {
                $result = $this->s3_client->listBuckets();
                $buckets = $result->get('Buckets');
                
                foreach ($buckets as $bucket) {
                    if ($bucket['Name'] === $this->bucket) {
                        return array('success' => true, 'message' => 'Connection successful and bucket exists');
                    }
                }
                
                return array('success' => false, 'message' => 'Bucket not found');
            } else {
                // Fallback test for minimal client with AWS4 signature
                $test_path = 'test-connection.txt';
                $test_content = 'Cloud Uploads Test';
                
                $endpoint = $this->settings->get_option('endpoint');
                $region = $this->settings->get_option('region');
                $url = "https://{$this->bucket}.{$endpoint}/{$test_path}";
                
                // Generate AWS Signature Version 4
                $amz_date = gmdate('Ymd\THis\Z');
                $date_stamp = gmdate('Ymd');
                
                // Prepare canonical request
                $canonical_uri = "/{$test_path}";
                $canonical_querystring = '';
                $canonical_headers = "host:{$this->bucket}.{$endpoint}\nx-amz-date:{$amz_date}\n";
                $signed_headers = 'host;x-amz-date';
                $payload_hash = hash('sha256', $test_content);
                
                $canonical_request = "PUT\n{$canonical_uri}\n{$canonical_querystring}\n{$canonical_headers}\n{$signed_headers}\n{$payload_hash}";
                
                // Prepare string to sign
                $algorithm = 'AWS4-HMAC-SHA256';
                $credential_scope = "{$date_stamp}/{$region}/s3/aws4_request";
                $canonical_request_hash = hash('sha256', $canonical_request);
                
                $string_to_sign = "{$algorithm}\n{$amz_date}\n{$credential_scope}\n{$canonical_request_hash}";
                
                // Calculate signature
                $signing_key = $this->get_signature_key($this->settings->get_option('secret_key'), $date_stamp, $region, 's3');
                $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
                
                // Prepare authorization header
                $authorization_header = "{$algorithm} Credential={$this->settings->get_option('access_key')}/{$credential_scope}, SignedHeaders={$signed_headers}, Signature={$signature}";
                
                $headers = array(
                    'Authorization' => $authorization_header,
                    'x-amz-date' => $amz_date,
                    'x-amz-content-sha256' => $payload_hash,
                    'Content-Type' => 'text/plain',
                    'Content-Length' => strlen($test_content)
                );
                
                $response = wp_remote_request($url, array(
                    'method' => 'PUT',
                    'headers' => $headers,
                    'body' => $test_content,
                    'timeout' => 30
                ));
                
                if (is_wp_error($response)) {
                    return array('success' => false, 'message' => $response->get_error_message());
                }
                
                $response_code = wp_remote_retrieve_response_code($response);
                if ($response_code !== 200) {
                    $response_body = wp_remote_retrieve_body($response);
                    return array('success' => false, 'message' => 'HTTP test failed with code ' . $response_code . ': ' . $response_body);
                }
                
                // Try to delete the test file
                $payload_hash = hash('sha256', '');
                $canonical_request = "DELETE\n{$canonical_uri}\n{$canonical_querystring}\n{$canonical_headers}\n{$signed_headers}\n{$payload_hash}";
                $canonical_request_hash = hash('sha256', $canonical_request);
                $string_to_sign = "{$algorithm}\n{$amz_date}\n{$credential_scope}\n{$canonical_request_hash}";
                $signature = hash_hmac('sha256', $string_to_sign, $signing_key);
                $authorization_header = "{$algorithm} Credential={$this->settings->get_option('access_key')}/{$credential_scope}, SignedHeaders={$signed_headers}, Signature={$signature}";
                
                $headers = array(
                    'Authorization' => $authorization_header,
                    'x-amz-date' => $amz_date,
                    'x-amz-content-sha256' => $payload_hash
                );
                
                wp_remote_request($url, array(
                    'method' => 'DELETE',
                    'headers' => $headers,
                    'timeout' => 30
                ));
                
                return array('success' => true, 'message' => 'Connection successful using AWS Signature v4');
            }
        } catch (Exception $e) {
            return array('success' => false, 'message' => $e->getMessage());
        }
    }

    /**
     * Check if AWS SDK is being used
     */
    public function is_using_aws_sdk() {
        return $this->use_aws_sdk;
    }
    
    /**
     * Check if S3 client is properly initialized
     */
    public function is_initialized() {
        return !is_null($this->s3_client);
    }
}