<?php
// function awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $keyName, $user_upload_id,$remove_from_user_uploads)
// {
//     try {
//         // Delete the object
//         $s3_learning_bucket->deleteObject([
//             'Bucket' => $learning_bucketName,
//             'Key' => $keyName,
//         ]);
//         // if ($remove_from_user_uploads == true) {
//         //     $sql = "Delete from user_upload where id = ? and workspace_id = ?";
//         //     $delete = $conn->prepare($sql);
//         //     $delete->execute(array($user_upload_id, $workspace_id));
//         // }
//     } catch (Exception $e) {
//         errorreturn('Error: ' . $e->getMessage());
//     }
// }

function awsS3UserUploadDelete($s3_learning_bucket, $learning_bucketName, $conn_rjllearning_specific, $institution_id, $keyName, $user_upload_id, $remove_from_user_uploads)
{
    try {
        // Extract the base name without the extension
        $pathInfo = pathinfo($keyName);
        $baseName = $pathInfo['filename']; // e.g., "image_1"
        $prefix = $pathInfo['dirname'] !== '.' ? $pathInfo['dirname'] . '/' . $baseName : $baseName; 

        // List all objects in the bucket that match the base name
        $objects = $s3_learning_bucket->listObjects([
            'Bucket' => $learning_bucketName,
            'Prefix' => $prefix, // Get all files with the same base name
        ]);

        if (!empty($objects['Contents'])) {
            foreach ($objects['Contents'] as $object) {
                $s3_learning_bucket->deleteObject([
                    'Bucket' => $learning_bucketName,
                    'Key' => $object['Key'],
                ]);
            }
        }
        
        // Optional: Remove from database
        // if ($remove_from_user_uploads) {
        //     $sql = "DELETE FROM user_upload WHERE id = ? AND workspace_id = ?";
        //     $delete = $conn_rjllearning_specific->prepare($sql);
        //     $delete->execute([$user_upload_id, $institution_id]);
        // }
    } catch (Exception $e) {
        errorreturn('Error: ' . $e->getMessage());
    }
}



function awsS3UserUploadInsert($s3_learning_bucket, $learning_bucketName,$file_attached, $keyName, $multiple_files_bool = false, $multiple_file_index = 0)
{

    
    if (!$multiple_files_bool) {
        $active_file_tmp = $file_attached['tmp_name'];
    } else {
        $active_file_tmp = $file_attached['tmp_name'][$multiple_file_index];
    }
 
    try {
        $s3_learning_bucket->putObject([
            'Bucket' => $learning_bucketName,
            'Key' => $keyName,
            'SourceFile' => $active_file_tmp,

        ]);
    } catch (Exception $e) {
        errorreturn($e->getMessage());
    }
    
    
}
// boolean use_cdn 1/0 if 1 use cdn fetch if 0 then work lik this 
// function displayFileFromS3($s3_learning_bucket, $learning_bucketName, $keyName, $link_validity = 2, $validity_type = 'minutes')
// {
//     try {

//         $command = $s3_learning_bucket->getCommand('GetObject', [
//             'Bucket' => $learning_bucketName,
//             'Key' => $keyName,
//         ]);

//         $presignedUrl = $s3_learning_bucket->createPresignedRequest($command, '+' . $link_validity . ' ' . $validity_type)->getUri()->__toString();
        
//         // Output the file data
//         return $presignedUrl;
//     } catch (Exception $e) {
//         // Handle exceptions, e.g., object not found, S3 retrieval failure
//         echo 'Error: ' . $e->getMessage();
//     }
// }


function displayFileFromS3($s3_learning_bucket, $learning_bucketName, $keyName, $use_cdn = 0, $cdn_base_url = '' , $link_validity = 2, $validity_type = 'minutes')
{
    error_log("displayFileFromS3 called with key: " . $keyName);
  
    try {
        if ($use_cdn) {
            error_log("Returning CDN URL");
            // If using CDN, construct the CDN URL with long cache validity (1 year)
            return $cdn_base_url . '/' . $keyName . '?cache-control=max-age=' . (365 * 24 * 60 * 60);
        } else {
            error_log("Generating S3 signed URL");
            // If not using CDN, generate a signed URL from S3
            $command = $s3_learning_bucket->getCommand('GetObject', [
                'Bucket' => $learning_bucketName,
                'Key' => $keyName,
            ]);

            $presignedUrl = $s3_learning_bucket->createPresignedRequest($command, '+' . $link_validity . ' ' . $validity_type)->getUri()->__toString();
            error_log("Generated presigned URL: " . $presignedUrl);
            return $presignedUrl;
        }
    } catch (Exception $e) {
        error_log("S3 ERROR: " . $e->getMessage());
        throw $e; // better than echo
    }
}






function invalidateCloudFrontCache($cloudFrontDistributionId, $image_name, $awsRegion, $awsAccessKey, $awsSecretKey, $id)
{
    if (empty($cloudFrontDistributionId)) {
        errorreturn("CloudFront Invalidation Skipped: Distribution ID is empty.");
        return false;
    }

    try {
        // Initialize CloudFront client
        $cloudFrontClient = new CloudFrontClient([
            'region'      => $awsRegion,
            'version'     => 'latest',
            'credentials' => [
                'key'    => $awsAccessKey,
                'secret' => $awsSecretKey
            ]
        ]);

        // Ensure the path format matches your CloudFront settings
        $imagePath = "/" . ltrim($image_name, '/');

        // Create the invalidation request
        $result = $cloudFrontClient->createInvalidation([
            'DistributionId' => $cloudFrontDistributionId,
            'InvalidationBatch' => [
                'Paths' => [
                    'Quantity' => 1,
                    'Items'    => [$imagePath] // Ensure correct path
                ],
                'CallerReference' => time() . '-' . $id // Unique reference for each request
            ]
        ]);

        errorreturn("CloudFront Invalidation Successful: " . json_encode($result->toArray()));
        return $result->toArray();
    } catch (AwsException $e) {
        // Handle AWS exceptions properly
        error_log("CloudFront Invalidation Failed: " . $e->getMessage());
        errorreturn (['error' => $e->getMessage()]);
    }
}
