<?php

declare(strict_types=1);

require_once __DIR__ . '/../includes/admin_download_resolve.php';
require_once __DIR__ . '/../includes/registration_wizard.php';

auth_require();

$token = trim((string)($_GET['token'] ?? ''));
$id = (int)($_GET['id'] ?? 0);

if ($token === '' && $id <= 0) {
    http_response_code(400);
    exit('Missing contract token.');
}

try {
    $contract = admin_resolve_download_contract($token, $id);
} catch (Throwable) {
    http_response_code(502);
    exit('Unable to load contract.');
}

if (!$contract) {
    http_response_code(404);
    exit('Contract not found.');
}

$exports = contract_signature_download_exports($contract);
$tempFiles = [];

foreach ($exports as $export) {
    if (!empty($export['temporary'])) {
        $tempFiles[] = $export['path'];
    }
}

if ($exports === []) {
    http_response_code(404);
    exit('No signature files found for this contract.');
}

$sendZip = contract_signature_download_as_zip($contract, $exports);

if (!$sendZip && count($exports) === 1) {
    $file = $exports[0];
    header('Content-Type: image/png');
    header('Content-Disposition: attachment; filename="' . $file['filename'] . '"');
    header('Content-Length: ' . (string)filesize($file['path']));
    header('Cache-Control: private, max-age=3600');
    header('X-Content-Type-Options: nosniff');
    readfile($file['path']);

    foreach ($tempFiles as $tempFile) {
        @unlink($tempFile);
    }

    exit;
}

if (!class_exists(ZipArchive::class)) {
    foreach ($tempFiles as $tempFile) {
        @unlink($tempFile);
    }

    http_response_code(500);
    exit('ZIP extension is not available on this server.');
}

$zipPath = tempnam(sys_get_temp_dir(), 'karvi_sig_');
if ($zipPath === false) {
    foreach ($tempFiles as $tempFile) {
        @unlink($tempFile);
    }

    http_response_code(500);
    exit('Could not prepare download.');
}

$zip = new ZipArchive();
if ($zip->open($zipPath, ZipArchive::OVERWRITE) !== true) {
    @unlink($zipPath);
    foreach ($tempFiles as $tempFile) {
        @unlink($tempFile);
    }

    http_response_code(500);
    exit('Could not create ZIP archive.');
}

foreach ($exports as $export) {
    $zip->addFile($export['path'], $export['filename']);
}

$zip->close();

$zipFilename = contract_reference($contract) . '_signatures.zip';

header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename="' . $zipFilename . '"');
header('Content-Length: ' . (string)filesize($zipPath));
header('Cache-Control: private, max-age=3600');
header('X-Content-Type-Options: nosniff');

readfile($zipPath);
@unlink($zipPath);

foreach ($tempFiles as $tempFile) {
    @unlink($tempFile);
}

exit;
