<?php

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

use Dotenv\Dotenv;

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

$awsAccessKey = $_ENV['CONTABO_S3_ACCESS_KEY'];
$awsSecretKey = $_ENV['CONTABO_S3_SECRET_KEY'];
$awsRegion = $_ENV['CONTABO_S3_REGION'];
$awsSpaceName = $_ENV['CONTABO_S3_SPACE_NAME'];

/**
 * Uploads a file to Contabo Object Storage
 *
 * @param string $bucket The bucket name in Contabo Object Storage
 * @param string $filePath The local path to the file you want to upload
 * @param string $key The name of the file in the bucket (e.g., "folder/filename.ext")
 * @param string $accessKey Your Contabo Access Key ID
 * @param string $secretKey Your Contabo Secret Access Key
 * @param string $region Contabo region (e.g., 'eu2', 'us1')
 * @return string|null Returns the URL of the uploaded file if successful, or null on failure
 */
function uploadFileToSpace($awsAccessKey, $awsSecretKey, $awsRegion, $awsSpaceName, $folderName, $sourceFileName, $filePath)
{
    // Endpoint based on the region
    $endpoint = "https://{$awsRegion}.contabostorage.com";

    // Instantiate the S3 client
    $s3Client = new Aws\S3\S3Client([
        'version'     => 'latest',
        'region'      => $awsRegion,
        'endpoint'    => $endpoint,
        'use_path_style_endpoint' => true,
        '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 {
        // Upload the file
        $s3Client->putObject([
            'Bucket' => $awsSpaceName,
            'Key'    => $fileName,
            // 'SourceFile' => $filePath,
            'Body' => $filePath,
            'ACL'    => 'public-read', // Optional: set the ACL to make the file publicly accessible
        ]);

        // Manually construct the URL with bucket identifier
        $bucketIdentifier = '5adcb23ae613489a9fe4ad4a7bec3e6a';
        $fileUrl = "https://{$awsRegion}.contabostorage.com/{$bucketIdentifier}:{$awsSpaceName}/{$fileName}";
        return $fileUrl;
    } catch (Aws\Exception\AwsException $e) {
        // Output error message if something goes wrong
        return "Error uploading file: " . $e->getMessage() . PHP_EOL;
        return null;
    }
}

function deleteFileFromSpace($awsAccessKey, $awsSecretKey, $awsRegion, $awsSpaceName, $finalFilePath)
{
    // Endpoint based on the region
    $endpoint = "https://{$awsRegion}.contabostorage.com";

    // Instantiate the S3 client
    $s3Client = new Aws\S3\S3Client([
        'version'     => 'latest',
        'region'      => $awsRegion,
        'endpoint'    => $endpoint,
        'use_path_style_endpoint' => true,
        'credentials' => [
            'key'    => $awsAccessKey,
            'secret' => $awsSecretKey,
        ],
    ]);

    try {
        // Delete the file
        $s3Client->deleteObject([
            'Bucket' => $awsSpaceName,
            'Key'    => $finalFilePath,
        ]);

        return "File deleted successfully: {$finalFilePath}" . PHP_EOL;
        return true;
    } catch (Aws\Exception\AwsException $e) {
        // Output error message if something goes wrong
        return "Error deleting file: " . $e->getMessage() . PHP_EOL;
        return false;
    }
}

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

        // Endpoint based on the region
        $endpoint = "https://{$awsRegion}.contabostorage.com";

        // Instantiate the S3 client
        $s3Client = new Aws\S3\S3Client([
            'version'     => 'latest',
            'region'      => $awsRegion,
            'endpoint'    => $endpoint,
            'use_path_style_endpoint' => true,
            'credentials' => [
                'key'    => $awsAccessKey,
                'secret' => $awsSecretKey,
            ],
        ]);

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

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

        // Manually construct the URL with bucket identifier
        $bucketIdentifier = '5adcb23ae613489a9fe4ad4a7bec3e6a';
        $fileUrl = "https://{$awsRegion}.contabostorage.com/{$bucketIdentifier}:{$awsSpaceName}/{$saveToPath}";
        return $fileUrl;
    } catch (Aws\Exception\AwsException $e) {
        return "Error: " . $e->getMessage() . "\n";
    }
}
