<?php
    ini_set('memory_limit', '512M'); // Increase memory limit for large files
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    require_once('config.php');
    require '../aws/app/start.php'; // AWS S3 SDK initialization

    // List objects in the bucket
    $objects = $s3->getIterator('ListObjects', [
        'Bucket' => $config['s3']['bucket']
    ]);

    // Handle bulk download request
    if (isset($_POST['download_all'])) {
        // Headers to initiate file download
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename="images_' . time() . '.zip"');
        header('Pragma: no-cache');
        header('Expires: 0');

        // Open the output stream
        $zip = fopen('php://output', 'w');

        // Loop through each file in the S3 bucket and add it to the zip stream
        foreach ($objects as $object) {
            $fileKey = $object['Key']; // Get the file key (name)

            // Fetch the file from S3
            $result = $s3->getObject([
                'Bucket' => $config['s3']['bucket'],
                'Key' => $fileKey
            ]);

            // Get the file content
            $fileContent = $result['Body']->getContents();

            // Create a zip entry (a basic manual zip-like approach)
            fwrite($zip, "--boundary\n");
            fwrite($zip, "Content-Disposition: file; filename=\"$fileKey\"\n");
            fwrite($zip, "Content-Type: application/octet-stream\n\n");
            fwrite($zip, $fileContent);
            fwrite($zip, "\n--boundary--\n");
        }

        // Close the stream
        fclose($zip);
        exit;
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Download Images</title>
</head>
<body>
    <h1>Download All Images from S3 Bucket</h1>
    <form method="post">
        <button type="submit" name="download_all">Download All Images at Once</button>
    </form>
</body>
</html>
