<?php

require '../vendor/autoload.php';

use Dotenv\Dotenv;

// Load the .env file
$dotenv = Dotenv::createImmutable(__DIR__ . "/../");
$dotenv->load();

$awsAccessKey = $_ENV['OCEAN_S3_ACCESS_KEY'];
$awsSecretKey = $_ENV['OCEAN_S3_SECRET_KEY'];
$awsRegion = $_ENV['OCEAN_S3_REGION'];
$awsSpaceName = $_ENV['OCEAN_S3_SPACE_NAME'];

// Function to list all files in the Space
function ListFileInSpace($awsAccessKey, $awsSecretKey, $awsRegion, $awsSpaceName)
{

    $s3Client = new Aws\S3\S3Client([
        'version' => 'latest',
        'region'  => $awsRegion,
        'endpoint' => "https://{$awsRegion}.digitaloceanspaces.com",
        'credentials' => [
            'key'    => $awsAccessKey,
            'secret' => $awsSecretKey,
        ],
    ]);

    // Example: List all objects in the Space
    try {
        $result = $s3Client->listObjectsV2([
            'Bucket' => $awsSpaceName,
        ]);

        foreach ($result['Contents'] as $object) {
            echo $object['Key'] . "\n";
        }
    } catch (Aws\Exception\AwsException $e) {
        echo "Error: " . $e->getMessage() . "\n";
    }
}

// Function to upload a file to DigitalOcean Space
function uploadFileToSpace($awsAccessKey, $awsSecretKey, $awsRegion, $awsSpaceName, $folderName, $sourceFileName, $filePath)
{
    $s3Client = new Aws\S3\S3Client([
        'version' => 'latest',
        'region'  => $awsRegion,
        'endpoint' => "https://{$awsRegion}.digitaloceanspaces.com",
        'credentials' => [
            'key'    => $awsAccessKey,
            'secret' => $awsSecretKey,
        ],
    ]);

    // Ensure the folder name ends with a slash
    if (substr($folderName, -1) !== '/') {
        $folderName .= '/';
    }

    // Get file extension
    $fileExtension = pathinfo($sourceFileName, PATHINFO_EXTENSION);

    // Generate a unique file name to avoid overwriting
    $uniqueFileName = uniqid() . '.' . $fileExtension;
    $fileName = $folderName . $uniqueFileName;

    try {
        $result = $s3Client->putObject([
            'Bucket' => $awsSpaceName,
            'Key'    => $fileName,
            // 'SourceFile' => $filePath,
            'Body'   => $filePath,
            'ACL' => 'public-read', // Make the file publicly accessible
        ]);

        // return "File uploaded successfully. File URL: " . $result['ObjectURL'] . "\n";
        return $result['ObjectURL'];
    } catch (Aws\Exception\AwsException $e) {
        return "Error: " . $e->getMessage() . "\n";
    }
}

// Function to delete a file from the Space
function deleteFileFromSpace($awsAccessKey, $awsSecretKey, $awsRegion, $awsSpaceName, $finalFilePath)
{

    $s3Client = new Aws\S3\S3Client([
        'version' => 'latest',
        'region'  => $awsRegion,
        'endpoint' => "https://{$awsRegion}.digitaloceanspaces.com",
        'credentials' => [
            'key'    => $awsAccessKey,
            'secret' => $awsSecretKey,
        ],
    ]);

    try {
        $result = $s3Client->deleteObject([
            'Bucket' => $awsSpaceName,
            'Key'    => $finalFilePath,
        ]);

        return "File deleted successfully.\n";
    } catch (Aws\Exception\AwsException $e) {
        return "Error: " . $e->getMessage() . "\n";
    }
}

// Function to download a file from the Space
function downloadFileFromSpace($awsAccessKey, $awsSecretKey, $awsRegion, $awsSpaceName, $fileName, $pathToSave)
{

    $s3Client = new Aws\S3\S3Client([
        'version' => 'latest',
        'region'  => $awsRegion,
        'endpoint' => "https://{$awsRegion}.digitaloceanspaces.com",
        'credentials' => [
            'key'    => $awsAccessKey,
            'secret' => $awsSecretKey,
        ],
    ]);

    try {
        $result = $s3Client->getObject([
            'Bucket' => $awsSpaceName,
            'Key'    => $fileName,
            'SaveAs' => $pathToSave,
        ]);

        return "File downloaded successfully to " . $pathToSave . "\n";
    } catch (Aws\Exception\AwsException $e) {
        return "Error: " . $e->getMessage() . "\n";
    }
}



// Function to upload a file to DigitalOcean Space
function uploadFileToSpaceFromHtml2canvas($awsAccessKey, $awsSecretKey, $awsRegion, $awsSpaceName, $decodedImage, $sale_id)
{
    try {

        // Initialize S3 client for DigitalOcean Spaces
        $s3Client = new Aws\S3\S3Client([
            'version' => 'latest',
            'region'  => $awsRegion,
            'endpoint' => "https://{$awsRegion}.digitaloceanspaces.com",
            'credentials' => [
                'key'    => $awsAccessKey,
                'secret' => $awsSecretKey,
            ],
        ]);

        // Generate a unique file name to avoid overwriting
        // $fileName = 'ticket_' . time() . '.png';
        $fileName = "ticket_{$sale_id}.png";
        $saveToPath = 'tickets/' . $fileName;

        // Upload the image to DigitalOcean Space
        $result = $s3Client->putObject([
            'Bucket' => $awsSpaceName,
            'Key'    => $saveToPath,
            'Body'   => $decodedImage,
            'ACL' => 'public-read', // Make the file publicly accessible
            'ContentType' => 'image/png',
        ]);

        // return "File uploaded successfully. File URL: " . $result['ObjectURL'] . "\n";
        return $result['ObjectURL'];
    } catch (Aws\Exception\AwsException $e) {
        return "Error: " . $e->getMessage() . "\n";
    }
}
