<?php

namespace App\Services;

use Illuminate\Support\Facades\Storage;
use ZipArchive;

class ProofDownloadService
{
    public function downloadProofs($model, $ids, $filePathColumn = 'proof')
    {
        // Validate IDs
        if (empty($ids)) {
            return [
                'error' => 'No items selected',
            ];
        }

        // Fetch records with proofs
        $responses = $model::whereIn('id', $ids)
            ->whereNotNull($filePathColumn)
            ->get();

        if ($responses->isEmpty()) {
            return [
                'error' => 'No valid proofs found',
            ];
        }

        // Create a temporary zip file
        $zipFileName = 'proofs_' . time() . '.zip';
        $zipFilePath = storage_path('app/public/temp/' . $zipFileName);

        // Ensure the temp directory exists
        if (!Storage::disk('public')->exists('temp')) {
            Storage::disk('public')->makeDirectory('temp');
        }

        $zip = new ZipArchive();

        if ($zip->open($zipFilePath, ZipArchive::CREATE) !== true) {
            return [
                'error' => 'Could not create zip file',
            ];
        }

        $fileCount = 0;

        foreach ($responses as $response) {
            if (Storage::disk('public')->exists($response->$filePathColumn)) {
                $fileContent = Storage::disk('public')->get($response->$filePathColumn);

                // Get original filename from path
                $originalName = basename($response->$filePathColumn);

                // Add file to the zip with a prefix to avoid duplicate names
                $fileNameInZip = $response->id . '_' . $originalName;
                $zip->addFromString($fileNameInZip, $fileContent);
                $fileCount++;
            }
        }

        $zip->close();

        if ($fileCount === 0) {
            // Delete the empty zip file
            if (file_exists($zipFilePath)) {
                unlink($zipFilePath);
            }
            return [
                'error' => 'No files found to download',
            ];
        }

        return [
            'success' => true,
            'filePath' => $zipFilePath,
            'fileName' => $zipFileName,
        ];
    }
}
