<?php
function logo_storage_dir(): string {
    $dir = __DIR__ . '/../storage/logos';
    if (!is_dir($dir)) mkdir($dir, 0755, true);
    return $dir;
}
function validate_slug(string $slug): string {
    $slug = trim($slug);
    if ($slug === '') return '';
    if (!preg_match('/^[A-Za-z0-9_-]{4,32}$/', $slug)) {
        throw new InvalidArgumentException('Der Slug darf nur Buchstaben, Zahlen, Bindestrich und Unterstrich enthalten und muss 4 bis 32 Zeichen lang sein.');
    }
    return $slug;
}
function ensure_code_available(PDO $pdo, string $code, ?int $ignoreId = null): bool {
    $sql = 'SELECT id FROM '.qtbl('qr_codes').' WHERE code = ?';
    $params = [$code];
    if ($ignoreId) { $sql .= ' AND id <> ?'; $params[] = $ignoreId; }
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    return !$stmt->fetch();
}
function generate_available_code(PDO $pdo): string {
    do { $code = random_code(); } while (!ensure_code_available($pdo, $code));
    return $code;
}
function handle_logo_upload(array $file, ?string $oldPath = null): ?string {
    if (empty($file['name']) || ($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) return $oldPath;
    if (($file['error'] ?? UPLOAD_ERR_OK) !== UPLOAD_ERR_OK) throw new RuntimeException('Logo konnte nicht hochgeladen werden.');
    if (($file['size'] ?? 0) > 1024 * 1024) throw new RuntimeException('Das Logo darf maximal 1 MB gross sein.');
    $tmp = $file['tmp_name'] ?? '';
    $info = @getimagesize($tmp);
    if (!$info || empty($info['mime'])) throw new RuntimeException('Bitte ein gültiges Bild als Logo hochladen.');
    $allowed = ['image/png' => 'png', 'image/jpeg' => 'jpg', 'image/gif' => 'gif', 'image/webp' => 'webp'];
    if (!isset($allowed[$info['mime']])) throw new RuntimeException('Logo erlaubt: PNG, JPEG, GIF oder WebP.');
    if (($info[0] ?? 0) > 2000 || ($info[1] ?? 0) > 2000) throw new RuntimeException('Das Logo ist zu gross. Maximal 2000 x 2000 px.');
    $name = bin2hex(random_bytes(16)) . '.' . $allowed[$info['mime']];
    $target = logo_storage_dir() . '/' . $name;
    if (!move_uploaded_file($tmp, $target)) throw new RuntimeException('Logo konnte nicht gespeichert werden.');
    @chmod($target, 0644);
    if ($oldPath) delete_logo_file($oldPath);
    return 'logos/' . $name;
}
function delete_logo_file(?string $path): void {
    if (!$path || !preg_match('/^logos\/[A-Za-z0-9]+\.(png|jpg|gif|webp)$/', $path)) return;
    $file = __DIR__ . '/../storage/' . $path;
    if (is_file($file)) @unlink($file);
}
function delete_user_logos(PDO $pdo, int $userId): void {
    $stmt = $pdo->prepare('SELECT logo_path FROM '.qtbl('qr_codes').' WHERE user_id=? AND logo_path IS NOT NULL');
    $stmt->execute([$userId]);
    foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $path) delete_logo_file($path);
}
