<?php
// Массив ссылок на файлы для скачивания


$fileUrls = explode(",", $_GET['doc_json']);

// Создание временной директории для хранения скачанных файлов
$tempDir = $_SERVER['DOCUMENT_ROOT'] . '/upload/tmp_zip';
if (!is_dir($tempDir)) {
    mkdir($tempDir);
}
function downloadFile($url, $savePath) {
    $ch = curl_init($url);
    $fp = fopen($savePath, 'w');

    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);

    $success = curl_exec($ch);

    if (!$success) {
        error_log("Ошибка загрузки $url: " . curl_error($ch));
    }

    curl_close($ch);
    fclose($fp);

    return $success;
}

// Скачивание файлов и сохранение их во временной директории
foreach ($fileUrls as $index => $url) {
    $fileName = basename(parse_url($url, PHP_URL_PATH)) ?: "file_$index.pdf";
    $fileName = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', $fileName);
    $filePath = $tempDir . '/' . $fileName;

    if (!downloadFile($url, $filePath)) {
        error_log("Ошибка при скачивании: $url");
        continue;
    }
}

// Создание zip-архива
$zipFile = 'download_files.zip';
$zip = new ZipArchive();
if ($zip->open($zipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {
    $files = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($tempDir),
        RecursiveIteratorIterator::LEAVES_ONLY
    );

    foreach ($files as $name => $file) {
        if (!$file->isDir()) {
            $filePath = $file->getRealPath();
            $relativePath = substr($filePath, strlen($tempDir) + 1);

            $zip->addFile($filePath, $relativePath);
        }
    }

    $zip->close();
}

// Удаление временной директории
array_map('unlink', glob("$tempDir/*"));
rmdir($tempDir);

// Отправка zip-архива пользователю
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $zipFile . '"');
header('Content-Length: ' . filesize($zipFile));
readfile($zipFile);

// Удаление zip-архива после отправки
unlink($zipFile);
?>