tryLimit() - $store->ai_logo_tries);
}
/**
* The name the logo shows: the store header's words, or the store name.
*/
public function name(Store $store): string
{
$plan = $store->published_plan ?? $store->plan ?? [];
$header = $plan['header'] ?? collect($plan['sections'] ?? [])->firstWhere('type', 'header');
$text = trim((string) ($header['content']['logoText'] ?? ''));
return $text !== '' ? $text : $store->name;
}
/**
* What the storefront needs to draw the logo, or null when the store has none.
*
* @return array{type: string, url?: string, width?: int, height?: int, key?: string, svg?: string}|null
*/
public function present(Store $store): ?array
{
$logo = $store->logo;
return match ($logo['type'] ?? null) {
'upload' => ['type' => 'upload', 'url' => Storage::disk('public')->url($logo['path']), 'width' => (int) $logo['width'], 'height' => (int) $logo['height']],
'design' => in_array($logo['key'] ?? null, self::DESIGNS, true) ? ['type' => 'design', 'key' => $logo['key']] : null,
'drawn' => is_string($logo['svg'] ?? null) ? ['type' => 'drawn', 'svg' => $logo['svg']] : null,
default => null,
};
}
/**
* Save an uploaded logo, made smaller when large and saved as WebP, keeping a see-through background.
* Saving it again also drops hidden details in the file. Replaces the old logo.
*
* @throws RuntimeException When the picture cannot be read.
*/
public function upload(Store $store, UploadedFile $file): void
{
$image = @imagecreatefromstring((string) file_get_contents($file->getRealPath()));
if (! $image instanceof GdImage) {
throw new RuntimeException('The picture could not be read.');
}
$width = imagesx($image);
$height = imagesy($image);
$scale = min(1, self::MAX_SIDE / max($width, $height));
$newWidth = max(1, (int) round($width * $scale));
$newHeight = max(1, (int) round($height * $scale));
$canvas = imagecreatetruecolor($newWidth, $newHeight);
imagealphablending($canvas, false);
imagesavealpha($canvas, true);
imagefill($canvas, 0, 0, imagecolorallocatealpha($canvas, 0, 0, 0, 127));
imagecopyresampled($canvas, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
$name = 'logos/'.$store->id.'-'.Str::random(12);
ob_start();
imagewebp($canvas, null, 90);
Storage::disk('public')->put($name.'.webp', (string) ob_get_clean());
$icon = $this->squareIcon($canvas);
if ($icon !== null) {
Storage::disk('public')->put($name.'-icon.png', $icon);
}
$this->replace($store, array_filter([
'type' => 'upload',
'path' => $name.'.webp',
'icon_path' => $icon !== null ? $name.'-icon.png' : null,
'width' => $newWidth,
'height' => $newHeight,
], fn ($value) => $value !== null));
}
/**
* The browser tab icon: the uploaded logo when it is square enough to read at a small size,
* otherwise the store's initials on its main colour. The same icon is used for every logo type,
* and for stores with no logo, so a shop never shows our own icon.
*
* @return array{href: string, type: string, touch: string|null}
*/
public function icon(Store $store): array
{
$logo = $store->logo;
if (($logo['type'] ?? null) === 'upload' && is_string($logo['icon_path'] ?? null)) {
$url = Storage::disk('public')->url($logo['icon_path']);
return ['href' => $url, 'type' => 'image/png', 'touch' => $url];
}
$brand = StoreBrand::for($store);
$initials = $this->initials($brand->name);
$letters = htmlspecialchars($initials, ENT_XML1);
$size = mb_strlen($initials) > 1 ? 28 : 36;
$round = ($logo['type'] ?? null) === 'design' && ($logo['key'] ?? null) === 'monogram-circle';
$radius = $round ? 32 : min(32, (int) round($brand->radius * 1.5));
$font = htmlspecialchars($brand->headingFont, ENT_XML1 | ENT_QUOTES);
$svg = '';
return ['href' => 'data:image/svg+xml,'.rawurlencode($svg), 'type' => 'image/svg+xml', 'touch' => null];
}
/**
* Up to two letters: the first letters of the first two words. Keep in step with initials() in logo.tsx.
*/
public function initials(string $name): string
{
$words = preg_split('/\s+/u', trim((string) preg_replace('/[^\p{L}\p{N}\s]/u', ' ', $name)), -1, PREG_SPLIT_NO_EMPTY) ?: [];
$letters = count($words) > 1
? mb_substr($words[0], 0, 1).mb_substr($words[1], 0, 1)
: mb_substr($words[0] ?? '?', 0, 2);
return mb_strtoupper($letters);
}
/**
* The logo on a square see-through canvas, with plain edges (see-through or one solid colour) cut off first. Null when the logo is too wide to read.
*/
private function squareIcon(GdImage $image): ?string
{
$trimmed = @imagecropauto($image, IMG_CROP_SIDES);
$image = $trimmed instanceof GdImage ? $trimmed : $image;
$width = imagesx($image);
$height = imagesy($image);
if ($width / max(1, $height) > self::ICON_MAX_RATIO || $height / max(1, $width) > self::ICON_MAX_RATIO) {
return null;
}
// A little room around the logo, so it does not touch the edges of the tab icon.
$inner = (int) round(self::ICON_SIDE * 0.9);
$scale = min($inner / $width, $inner / $height);
$newWidth = max(1, (int) round($width * $scale));
$newHeight = max(1, (int) round($height * $scale));
$canvas = imagecreatetruecolor(self::ICON_SIDE, self::ICON_SIDE);
imagealphablending($canvas, false);
imagesavealpha($canvas, true);
imagefill($canvas, 0, 0, imagecolorallocatealpha($canvas, 0, 0, 0, 127));
imagecopyresampled($canvas, $image, intdiv(self::ICON_SIDE - $newWidth, 2), intdiv(self::ICON_SIDE - $newHeight, 2), 0, 0, $newWidth, $newHeight, $width, $height);
ob_start();
imagepng($canvas, null, 9);
return (string) ob_get_clean();
}
public function useDesign(Store $store, string $key): void
{
$this->replace($store, ['type' => 'design', 'key' => $key]);
}
/**
* Use one of the drawings Claude made for this store.
*/
public function useDrawn(Store $store, int $index): bool
{
$svg = $store->logo_drafts[$index] ?? null;
if (! is_string($svg)) {
return false;
}
$this->replace($store, ['type' => 'drawn', 'svg' => $svg]);
return true;
}
public function remove(Store $store): void
{
$this->replace($store, null);
}
/**
* Ask Claude for new logos. A try counts only when at least one usable logo comes back.
* Returns how many new logos were added, or null when the store has no tries left.
*
* @throws AiException
*/
public function draw(Store $store): ?int
{
// Take a try first, in one step, so two quick clicks can never pass the limit.
$taken = DB::table('stores')->where('id', $store->id)->where('ai_logo_tries', '<', $this->tryLimit())->increment('ai_logo_tries');
if ($taken === 0) {
return null;
}
try {
$answer = $this->ai->ask('logo', $this->system(), $this->prompt($store));
$logos = JsonAnswer::decode($answer->text)['logos'] ?? null;
$clean = is_array($logos)
? array_values(array_filter(array_map(fn ($logo) => is_array($logo) && is_string($logo['svg'] ?? null) ? LogoSvg::clean($logo['svg']) : null, $logos)))
: [];
if ($clean === []) {
throw new AiException('The AI did not draw a usable logo.', AiException::INVALID_RESULT);
}
} catch (AiException $e) {
// Nothing usable: give the try back.
DB::table('stores')->where('id', $store->id)->where('ai_logo_tries', '>', 0)->decrement('ai_logo_tries');
$store->refresh();
throw $e;
}
$store->refresh();
$store->logo_drafts = array_slice([...array_slice($clean, 0, self::PER_TRY), ...($store->logo_drafts ?? [])], 0, self::MAX_DRAFTS);
$store->save();
return min(count($clean), self::PER_TRY);
}
/**
* @param array|null $logo
*/
private function replace(Store $store, ?array $logo): void
{
$old = $store->logo;
$store->logo = $logo;
$store->save();
if (($old['type'] ?? null) === 'upload' && ($old['path'] ?? null) !== ($logo['path'] ?? null)) {
Storage::disk('public')->delete(array_filter([$old['path'], $old['icon_path'] ?? null]));
}
}
private function system(): string
{
return <<<'TEXT'
You design simple, professional logos for small online shops in Malaysia. You draw them as SVG.
Answer with JSON only, in this shape: {"logos": [{"svg": ""}, ...]} with exactly 3 logos.
Rules for every logo:
- A wide logo for a website header: viewBox about "0 0 400 100" (width 240 to 600, height 80 to 140). No width or height on the svg element.
- Show the store name exactly as given, spelled exactly, as a element. Do not set font-family: the store's own font is applied. Pick a font-size and positions so the whole name fits inside the viewBox: each letter is about 0.6 times the font-size wide.
- You may add a simple mark or icon on the left made from basic shapes (circle, rect, path, polygon). Keep it simple and clear at small sizes.
- Use only the store's colours given below (as hex values), plus white or none. A linear or radial gradient between them is allowed.
- Allowed elements only: svg, g, path, circle, ellipse, rect, line, polyline, polygon, text, tspan, defs, linearGradient, radialGradient, stop. No images, links, scripts, styles, filters, masks, clip paths, animation or embedded fonts.
- Make the 3 logos clearly different ideas, for example: an icon beside the name, a monogram badge with the name, and a stylish wordmark.
- Fit the brand: what it sells and its mood. Avoid clichés like a generic shopping cart.
TEXT;
}
private function prompt(Store $store): string
{
$plan = $store->published_plan ?? $store->plan ?? [];
$colors = $plan['theme']['colors'] ?? [];
$font = PlanSchema::FONTS[$plan['theme']['fonts']['heading'] ?? ''] ?? 'a clean sans-serif';
$palette = collect(['primary', 'accent', 'foreground', 'surface', 'background'])
->filter(fn (string $key) => is_string($colors[$key] ?? null))
->map(fn (string $key) => "- {$key}: {$colors[$key]}")
->implode("\n");
return implode("\n", [
'Store name: '.$this->name($store),
'What it sells: '.$store->category->value,
'About the brand: '.Str::limit((string) $store->description, 600),
"The store's heading font (applied for you): ".$font,
"The store's colours:",
$palette !== '' ? $palette : '- primary: #1F1F1F',
]);
}
}