<?php

namespace App\Services;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\StreamedResponse;
use ZipArchive;

class ZipDownloadService
{
    public function createZipStream(Collection $mediaItems, string $zipName): StreamedResponse
    {
        return response()->streamDownload(function () use ($mediaItems) {
            $zip = new ZipArchive;
            $outputStream = fopen('php://output', 'w');
            
            // We can't write directly to php://output with ZipArchive
            // So we'll use a temporary file, write the zip there, then stream it
            $tempFile = tempnam(sys_get_temp_dir(), 'zip');
            
            if ($zip->open($tempFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === TRUE) {
                foreach ($mediaItems as $media) {
                    // Get file content securely from storage
                    $disk = Storage::disk($media->disk);
                    if ($disk->exists($media->getDiskPath())) {
                        $content = $disk->get($media->getDiskPath());
                        $zip->addFromString($media->filename . '.' . $media->extension, $content);
                    }
                }
                $zip->close();
            }

            // Stream the file content
            $fileStream = fopen($tempFile, 'r');
            while (!feof($fileStream)) {
                fwrite($outputStream, fread($fileStream, 1024));
                flush();
            }
            fclose($fileStream);
            fclose($outputStream);
            
            // Cleanup
            unlink($tempFile);

        }, $zipName);
    }
}
