<?php

use Aws\S3\S3Client;
use Aws\Exception\AwsException;

class Aws_s3 {

    private $s3;
    private $bucket;

    public function __construct() {
        $CI = &get_instance();
        $CI->config->load('aws_config');
        
        $this->bucket = $CI->config->item('aws_bucket');
        $this->s3 = S3Client::factory([
            'credentials' => [
                'key'    => $CI->config->item('aws_access_key_id'),
                'secret' => $CI->config->item('aws_secret_access_key'),
            ],
            'region' => $CI->config->item('aws_region'),
            'version' => 'latest',
        ]);
    }

    public function startUpload($fileName) {
        try {
            $result = $this->s3->createMultipartUpload([
                'Bucket' => $this->bucket,
                'Key'    => $fileName,
            ]);
            return $result['UploadId'];
        } catch (AwsException $e) {
            return ['error' => $e->getMessage()];
        }
    }

    public function uploadPart($uploadId, $fileName, $partNumber, $fileContent) {
        try {
            $result = $this->s3->uploadPart([
                'Bucket'     => $this->bucket,
                'Key'        => $fileName,
                'UploadId'   => $uploadId,
                'PartNumber' => $partNumber,
                'Body'       => $fileContent,
            ]);
            return $result['ETag'];
        } catch (AwsException $e) {
            return ['error' => $e->getMessage()];
        }
    }

   // application/libraries/Aws_s3.php

   public function completeUpload($uploadId, $fileName, $parts) {
  
    try {
        // Log the data before the S3 call

        if (empty($parts)) {
            log_message('error', 'No parts found. Cannot complete upload.');
            return json_encode(['error' => 'No parts found.']);
        }
        $params = [
            'Bucket'          => $this->bucket,
            'Key'             => $fileName,
            'UploadId'        => $uploadId,
            'MultipartUpload' => [
                'Parts' => array_map(function ($part) {
                    return [
                        'ETag'       => $part['ETag'],       // ETag from uploadPart
                        'PartNumber' => (int) $part['PartNumber'], // Part number must be integer
                    ];
                }, $parts),
            ],
        ];
    
        
        // Call AWS S3 CompleteMultipartUpload API
        $result = $this->s3->completeMultipartUpload($params);

        // Check result
        if (!isset($result['Location'])) {
        
            return json_encode(['error' => 'Failed to complete the upload.']);
        }

        // Return the file URL on success
        $fileUrl = $result['Location'];
        
        return json_encode(['message' => 'Upload complete', 'fileUrl' => $fileUrl]);

    } catch (AwsException $e) {
        // Log the error for debugging
        log_message('error', 'AWS S3 Error: ' . $e->getMessage());
        
        // Return the error message
        return json_encode(['error' => 'Internal Server Error: ' . $e->getMessage()]);
    }
}
public function uploadFile($filePath, $fileName, $bucket, $contentType = 'application/octet-stream') {
    try {
        $fileContent = file_get_contents($filePath);
        $result = $this->s3->putObject([
            'Bucket'      => $bucket,
            'Key'         => $fileName,
            'Body'        => $fileContent,
            'ContentType' => $contentType,
       //     'ACL'         => 'public-read', // Adjust permissions as needed
        ]);

        if (isset($result['ObjectURL'])) {
            return $result['ObjectURL'];
        }

        throw new Exception('Upload failed.');
    } catch (AwsException $e) {
        throw new Exception('AWS S3 Error: ' . $e->getMessage());
    }
}


}
