<?php
// Logo upload endpoint — relations admin only
// Requires a valid X-Admin-Key header (same admin guard as write operations).
require_once __DIR__ . '/_cors.php';
require_once __DIR__ . '/_admin_guard.php';

api_guard_require_admin_with_rate_limit('relation_upload');

$uploadDir = __DIR__ . '/../relations';
if (!is_dir($uploadDir)) {
    mkdir($uploadDir, 0755, true);
}

$filesResponse = [];
$errors = [];

// Support both 'images' and 'images[]' field naming
$found = null;
foreach (['images', 'images[]'] as $f) {
    if (isset($_FILES[$f])) { $found = $f; break; }
}

if ($found === null && empty($_FILES)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'No files uploaded']);
    exit;
}

$uploaded = $found ? $_FILES[$found] : $_FILES;

// Normalise single-file upload to array form
if (!is_array($uploaded['name'])) {
    $uploaded = [
        'name'     => [$uploaded['name']],
        'type'     => [$uploaded['type']],
        'tmp_name' => [$uploaded['tmp_name']],
        'error'    => [$uploaded['error']],
        'size'     => [$uploaded['size']],
    ];
}

for ($i = 0; $i < count($uploaded['name']); $i++) {
    $origName = $uploaded['name'][$i];
    $tmp      = $uploaded['tmp_name'][$i];
    $err      = $uploaded['error'][$i];

    if ($err !== UPLOAD_ERR_OK) {
        $errors[] = "$origName: upload error code $err";
        continue;
    }

    // Validate MIME — images only
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime  = finfo_file($finfo, $tmp);
    finfo_close($finfo);

    if (strpos($mime, 'image/') !== 0) {
        $errors[] = "$origName: not an image (mime: $mime)";
        continue;
    }

    // Sanitise filename — keep original name, append timestamp only
    $ext      = strtolower(pathinfo($origName, PATHINFO_EXTENSION)) ?: 'jpg';
    $baseName = preg_replace('/[^A-Za-z0-9_\-]/', '_', pathinfo($origName, PATHINFO_FILENAME));
    $filename = $baseName . '_' . time() . '.' . $ext;
    $dest     = $uploadDir . '/' . $filename;

    if (move_uploaded_file($tmp, $dest)) {
        // Build the accessible URL
        if (defined('UPLOAD_BASE_URL') && UPLOAD_BASE_URL) {
            $url = rtrim(UPLOAD_BASE_URL, '/') . '/relations/' . $filename;
        } else {
            $baseUrl = (isset($_SERVER['REQUEST_SCHEME']) ? $_SERVER['REQUEST_SCHEME'] : 'http') . '://' . ($_SERVER['HTTP_HOST'] ?? 'localhost') . rtrim(dirname(dirname($_SERVER['SCRIPT_NAME'])), '\\/');
            $url = $baseUrl . '/relations/' . $filename;
        }

        $filesResponse[] = [
            'url'           => $url,
            'filename'      => $filename,
            'original_name' => $origName,
        ];
    } else {
        $errors[] = "$origName: failed to move file";
    }
}

http_response_code(count($filesResponse) > 0 ? 200 : 422);
echo json_encode(
    ['success' => count($filesResponse) > 0, 'files' => $filesResponse, 'errors' => $errors],
    JSON_UNESCAPED_UNICODE
);
exit;
