<?php
require 'external/aws/aws-autoloader.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
function GUID()
{
    if (function_exists('com_create_guid') === true) {
        return trim(com_create_guid(), '{}');
    }

    return sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}

function generateUploadedPresignedURL($clgId, $courseId, $sectionId, $userId, $uploadfile, $activityId, $fileExtension)
{
    $credentials = [
        'key' => 'AKIA4ROQEOUP4XZNNHHA',
        'secret' => '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',
    ];

    $bucket = 'quiklrnreports';
    $region = 'ap-south-1';

    $s3 = new S3Client([
        'version' => 'latest',
        'region' => $region,
        'credentials' => $credentials,
    ]);

    // $file = "../../../tmp/uploadedFile.csv";
    $file = $uploadfile;

    // Specify the key (name) under which the file will be stored in the S3 bucket
    $gUid = GUID();
    $key = $clgId . "/" . $courseId . "/" . $sectionId . "/" . "/" . $activityId . "/" . $userId . "/" . $gUid . "." . $fileExtension;

    try {
        $result = $s3->putObject([
            'Bucket' => $bucket,
            'Key' => $key,
            'SourceFile' => $file,
        ]);

        // Get a pre-signed URL for the uploaded file
        $cmd = $s3->getCommand('GetObject', [
            'Bucket' => $bucket,
            'Key' => $key,
        ]);

        $request = $s3->createPresignedRequest($cmd, '+7 days');
        $presignedUrl = (string) $request->getUri();

        // echo 'File uploaded successfully. Pre-signed URL: ' . $presignedUrl;
    } catch (AwsException $e) {
        // echo 'Error uploading file: ' . $e->getMessage();
        $api_error = $e->getMessage();
    }

    if (empty($api_error)) {
        $status = 'success';
        $statusMsg = ['status_code' => 200, 'msg' => "File was uploaded to the S3 bucket successfully!", 'objectURI' => $presignedUrl];
        unlink($file);
    } else {
        $statusMsg = ['status_code' => 401, 'msg' => $api_error, 'objectURI' => ''];
    }
    echo "<pre>";
    var_dump($statusMsg);
    return json_encode($statusMsg);

}




function listFilesForUser($clgId, $courseId, $sectionId, $activityId, $userId)
{

    // die('aaa');
    $credentials = [
        'key' => 'AKIA4ROQEOUP4XZNNHHA',
        'secret' => '05KHd2piuTd/mGWC/SJcqxNQ59zes5MG/p/A9zSH',
    ];

    $bucket = 'quiklrnreports'; // Your S3 bucket name
    $region = 'ap-south-1'; // Your region

    $s3 = new S3Client([
        'version' => 'latest',
        'region' => $region,
        'credentials' => $credentials,
    ]);



    $prefix = $clgId . '/' . $courseId . '/' . $sectionId . '/' . '/' . $activityId . '/' . $userId . '/';

    try {
        // List objects in the specified folder (user's directory)
        $result = $s3->listObjectsV2([
            'Bucket' => $bucket,
            'Prefix' => $prefix,  // List objects in the folder for this user
            'Delimiter' => '/',   // Use '/' to simulate folder structure
        ]);

        // Prepare an array to hold file names and their corresponding download URLs
        $files = [];

        // Check if objects exist
        if (isset($result['Contents']) && count($result['Contents']) > 0) {

            $fileIndex = 1; // Counter to rename files as file1, file2, etc.

            foreach ($result['Contents'] as $object) {
                // Get the key (filename) of each file
                $key = $object['Key'];
                $fileName = "file" . $fileIndex++; // Rename files as file1, file2, file3, etc.

                // Generate pre-signed URL for the file to allow downloading
                $cmd = $s3->getCommand('GetObject', [
                    'Bucket' => $bucket,
                    'Key' => $key,
                ]);

                // Set the expiration time to 5 minutes (300 seconds)
                $expiration = '+1 minutes'; // 5 minutes expiration
                // Create pre-signed URL for the file (valid for 1 minute in this case)
                $request = $s3->createPresignedRequest($cmd, $expiration);
                $presignedUrl = (string) $request->getUri();

                // Add file info to the array
                $files[] = [
                    'file_name' => $fileName,
                    'uri' => $presignedUrl
                ];
            }

            // Return the file information as a JSON response
            echo json_encode($files);

        } else {
            echo json_encode(['message' => 'No files found for this user.']);
        }

    } catch (AwsException $e) {
        // Handle any errors that occurred during the API request
        echo json_encode(['error' => 'Error listing files: ' . $e->getMessage()]);
    }

    die;



    // Define the folder prefix to look for files by user ID
    // $prefix = $clgId . '/' . $courseId . '/' . $sectionId . '/' . '/' . $activityId . '/' . $userId . '/';

    // try {
    //     // List objects in the specified folder (user's directory)
    //     $result = $s3->listObjectsV2([
    //         'Bucket' => $bucket,
    //         'Prefix' => $prefix,  // List objects in the folder for this user
    //         'Delimiter' => '/',   // Use '/' to simulate folder structure
    //     ]);

    //     // Check if objects exist
    //     if (isset($result['Contents']) && count($result['Contents']) > 0) {
    //         echo "<h2>Files for User ID: $userId</h2>";
    //         echo "<table border='1'>
    //                 <tr>
    //                     <th>File Name</th>
    //                     <th>Download Link</th>
    //                 </tr>";

    //         $fileIndex = 1; // Counter to rename files as file1, file2, etc.

    //         foreach ($result['Contents'] as $object) {
    //             // Get the key (filename) of each file
    //             $key = $object['Key'];
    //             $fileName = "file" . $fileIndex++; // Rename files as file1, file2, file3, etc.

    //             // Generate pre-signed URL for the file to allow downloading
    //             $cmd = $s3->getCommand('GetObject', [
    //                 'Bucket' => $bucket,
    //                 'Key' => $key,
    //             ]);

    //             // Set the expiration time to 5 minutes (300 seconds)
    //             $expiration = '+1 minutes'; // 5 minutes expiration
    //             // '+7 days'
    //             // Create pre-signed URL for the file (valid for 7 days in this case)
    //             $request = $s3->createPresignedRequest($cmd, $expiration);
    //             $presignedUrl = (string) $request->getUri();

    //             // Output the file name and download link in a table row
    //             echo "<tr>
    //                     <td>$fileName</td>
    //                     <td><a href='$presignedUrl' target='_blank'>Download</a></td>
    //                   </tr>";
    //         }

    //         echo "</table>";
    //     } else {
    //         echo "No files found for this user.";
    //     }

    // } catch (AwsException $e) {
    //     // Handle any errors that occurred during the API request
    //     echo "Error listing files: " . $e->getMessage();
    // }
}
?>