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); $path = 'logos/'.$store->id.'-'.Str::random(12).'.webp'; ob_start(); imagewebp($canvas, null, 90); Storage::disk('public')->put($path, (string) ob_get_clean()); $this->replace($store, ['type' => 'upload', 'path' => $path, 'width' => $newWidth, 'height' => $newHeight]); } 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($old['path']); } } 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', ]); } }