# System Architecture Overview

> **Last verified:** 2026-10-31 — component names, routes, Prompts.chat community importer, interactive prompt engine, End-to-End Withdrawal & Payout Management (`WDR-XXXXXX`), and Decoupled Instant Vendor Access + 3-Step Onboarding Survey Wizard (`/vendor/onboarding`) audited against the working tree. Where this document and the code disagree, the code wins; please update both together.

## 1. Overview & Technology Stack
**PromptBase Clone** is a modern, high-performance digital marketplace application built for discovering, buying, testing, and selling AI prompts with multi-vendor panel capabilities and creator storefronts.

- **Backend Framework**: Laravel 13.x — requires **PHP `^8.3`** (verified on PHP 8.5.4)
- **Required PHP Extensions** (Composer-enforced): `dom`, `mbstring`, `curl`, `intl`, `xml`, `xmlreader`, `xmlwriter`, `simplexml`, `zip`, `fileinfo`, `filter`, `ctype`, `hash`, `openssl`, `session`, `tokenizer`
- **Also required at runtime**: `pdo_mysql`, `gd`, `bcmath`/`gmp` (Filament images & `Number::format`)
- **Multi-Panel Engine**: Filament v3 (Admin Panel `/admin` & Vendor Panel `/vendor/dashboard`) with real-time Database Notifications & Polling
- **Storage Driver**: Cloudflare R2 Object Storage (AWS S3 Flysystem v3) with CDN edge asset delivery
- **Auth UI Engine**: `diogogpinto/filament-auth-ui-enhancer` (Split-Screen Auth) + Custom Blade
- **Frontend / Styling**: Blade Templating + Tailwind CSS + Alpine.js (Vite compiled)
- **Database**: MySQL 8 (port `3306`) via Eloquent ORM with compound performance indexes — on this workstation MySQL is provided by **XAMPP** (`/opt/lampp`, socket `/opt/lampp/var/mysql/mysql.sock`), start it with `sudo /opt/lampp/lampp start`
- **Payment Gateway**: Stripe PHP SDK (`stripe/stripe-php`) with Hosted Checkout & Webhooks
- **Asset Bundling**: Vite 8.x

---

## 2. System Architecture Layers

```
                                +---------------------------+
                                |      Browser Client       |
                                +-------------+-------------+
                                              |
                        +---------------------+---------------------+
                        |                                           |
                        v                                           v
          +-------------+-------------+               +-------------+-------------+
          |  Public Web Routes &      |               |   Filament Multi-Panel      |
          |  Blade Templates / Alpine |               |  (/admin & /vendor)       |
          +-------------+-------------+               +-------------+-------------+
                        |                                           |
                        v                                           v
          +-------------+-------------+               +-------------+-------------+
          |    ProductController,     |               |  VendorResource, Product, |
          |    SellerController &     |               |  Payout, Ticket &         |
          | StripeWebhookController   |               |  VendorSalesResource      |
          +------+--------------+------+               +-------------+-------------+
                 |              |                                   |
  +--------------+              +--------------+                    |
  v                                            v                    v
+-+-----------+-------------+          +-------+-----+     +--------+----+
|    Eloquent Models        |          |  Stripe API |     |  Database   |
| (Product, User, Order)    |          | (Checkout)  |     | Notification|
+-------------+-------------+          +-------------+     +-------------+
              |                                                     |
              v                                                     v
+-------------+-------------+                         +-------------+-------------+
|     Database (MySQL)      |                         | Cloudflare R2 Edge Storage|
+---------------------------+                         +---------------------------+
```

---

## 3. Core Components

### A. Presentation Layer (Blade Views & Alpine.js UI)
- **`layouts/app.blade.php`**: Master layout with dark navbar (`#0B0F19`), responsive navigation, interactive Alpine.js **User Profile Dropdown**, and global **PromptBase-Style Quick Preview Modal** (`x-data="quickPreviewModal()"`).
- **`auth/login.blade.php`**: Single Centralized Login page for all roles (Admin, Vendor, Customer) featuring the exact Filament `#0B0F19` dark theme, `#111827` surface card, 60/40 desktop AI preview banner, Remember me, Forgot Password, and Vendor/Customer registration links. `auth/custom-login.blade.php` forwards to this unified view.
- **`products/index.blade.php`**: Marketplace explore page with hero section, Item ID & keyword search bar, category filter pills, and dynamic product grid collections.
- **`products/partials/product-card.blade.php`**: Reusable product card component featuring 1:1 cover image (R2 CDN URL or dark-mode SVG cover placeholder), Item ID badge (`PRD-XXXXXX`), AJAX wishlist favorite toggle, star ratings, creator badges, and image hover **Quick View** preview modal dispatcher (`@click="$dispatch('open-quick-preview', ...)"`).
- **`products/show.blade.php`**: 2-Column single product detail page with copyable Item ID, favorite toggle, sticky pricing sidebar, Stripe payment form, customer reviews breakdown, and automatic **Interactive Prompt Engine** rendering when the prompt is Free (`$0.00`) or already purchased by the logged-in buyer.
- **`products/partials/interactive-prompt-engine.blade.php`**: Reusable Alpine.js Interactive Prompt Playground that automatically parses `${variable:default}`, `${variable}`, and `[Variable]` placeholders inside prompt text, renders `#111827` dark-themed input fields above `#promptText` for live real-time substitution, provides a 1-Click **Copy Prompt** button with instant toast feedback, and includes **Open in ChatGPT** (`https://chatgpt.com/?q=...`), **Open in Claude** (`https://claude.ai/new?q=...`), and **Open in Perplexity** (`https://www.perplexity.ai/search?q=...`) quick launchers.
- **`sellers/show.blade.php`**: Public creator storefront featuring creator avatar with **Verified Seller Badge**, Seller Unique ID (`VND-XXXXXX`), live follower count, **Real-Time Dynamic Filter & Sorting Toolbar** (Sort By, Pricing Type, Category, AI Model, debounced instant search), and tabbed views for Prompts and Customer Reviews.
- **`sellers/partials/prompts-grid.blade.php`**: Async prompt grid and empty state renderer loaded dynamically via AJAX without full page reloads.
- **`customer/library.blade.php`**: Customer purchased library with Item ID badges, lifetime reveal access, and 1-5 star review dialogs.
- **`customer/favorites.blade.php`**: Customer saved favorites wishlist with live AJAX heart toggles.
- **`customer/following.blade.php`**: Followed creators list with live prompt counts and one-click AJAX unfollow.
- **`customer/profile.blade.php`**: Account settings, avatar upload, password security, and optional Hybrid 2FA (TOTP + Email OTP) management.
- **`products/reveal.blade.php`**: Secure prompt reveal screen integrating `products.partials.interactive-prompt-engine` for interactive variable customization, 1-click copy, AI launchers, and package file downloads.

### B. Controller & Routing Layer
- **`AuthController.php`**: Single entry controller managing unified central authentication (`/login`), user registration (`/register`), role-based redirection, 2FA interception preservation, and safe fallback redirects for `/admin/login` and `/vendor/login`.
- **`ProductController.php`**: Handles sectioned catalog queries, search across Item ID (`product_code`), title, category, AI model, checkout initialization, payment success redirect, and secure token reveal.
- **`SellerController.php`**: Manages public seller profiles supporting dynamic real-time sorting, category/model/price filtering, search, pagination with query strings (`->withQueryString()`), and AJAX partial rendering.
- **`CustomerController.php`**: Manages customer library, wishlist favorites, followed creators list, and account profile settings.
- **`EngagementController.php`**: Handles AJAX follow/unfollow actions, wishlist favorite toggles, and customer review submissions.
- **`StripeWebhookController.php`**: Listens for asynchronous Stripe webhooks (`checkout.session.completed`, `charge.refunded`, `charge.dispute.created`) and updates order states securely.
- **`SupportChatController.php`**: JSON live-chat API (`GET /chat/messages`, `POST /chat/send`) that finds or creates a `Ticket` and appends `TicketMessage` rows; admins are notified through `TicketMessageObserver`.
- **`KycPreviewController.php`**: Serves private KYC documents (`GET /vendor/kyc/preview/{file}`, base64-encoded path) only to the document's owner or an admin — 403 for anyone else, 404 for traversal/invalid/missing paths.
- **`ImportPromptsChatCommand.php`**: Artisan command (`php artisan prompts:import-community`) and programmatic service (`runImport()`) that fetches and merges `https://prompts.chat/prompts.json` + GitHub `prompts.csv`, assigns prompts to the verified `Prompts.chat Community` (`@promptschat`) vendor, deduplicates via chunked `Product::upsert`, maps categories & AI models, and generates dark-mode SVG cover placeholders.
- **`routes/web.php`**: Single centralized login (`/login`), safe fallback redirects (`/admin/login` and `/vendor/login` → `/login` or respective dashboard), named route aliases (`filament.admin.auth.login` / `filament.vendor.auth.login`), smart model binding (`Product::resolveRouteBinding()` resolves slug, `PRD-XXXXXX` or numeric ID), legacy redirects (`/vendor` → `/vendor/dashboard`, `/vendor/vendor-profile` → `/vendor/profile`, `/vendor/products/create` → `/vendor/upload`), customer portal routes (incl. `/customer/purchases` alias), the public storefront `/seller/{user:username}`, live-chat endpoints (`/chat/messages`, `/chat/send`), the private KYC preview route (`/vendor/kyc/preview/{file}`) and the Stripe webhook (`/api/stripe/webhook`).

### C. Multi-Panel Administration Layer (Filament v3)
- **Admin Panel (`/admin`)**:
  - `ProductResource` (`/admin/products`): Full prompt management with seller creator mapping, copyable Item ID badge (`PRD-XXXXXX`), dedicated action icons, approval/rejection with automated vendor notifications, and **1-Click `Import from Prompts.chat` Header Action** (`ListProducts.php`) with modal options for Limit (`50`, `100`, `500`, `1000`, `all`), Default Price, Target Seller/Vendor, and Image Download mode.
  - `VendorResource` (`/admin/vendors`): Dedicated Vendor Control resource scoped to `role = 'vendor'` with 360° telemetry (`ViewVendor`), `VendorStatsOverviewWidget`, **Contact, Billing Location & Creator Onboarding Survey** inspection & edit section, KYC modal, Verify/Unverify, Freeze/Unfreeze Payouts, Suspend/Activate toggles, and 6 Relation Managers (`PromptsRelationManager`, `OrdersRelationManager`, `PayoutsRelationManager`, `PayoutMethodsRelationManager`, `ReviewsRelationManager`, `TicketsRelationManager`).
  - `UserResource` (`/admin/users`): Scoped customer management (`role = 'customer'`) with account restriction (`is_banned`, `ban_reason`) and SoftDeletes support.
  - `PayoutResource` (`/admin/payouts`): End-to-End Payout Management ledger with `WDR-XXXXXX` reference code, immutable destination credential snapshot preview, and `Mark as Processing`, `Complete & Mark Paid`, and `Reject & Refund Balance` actions with automated vendor notifications.
  - `TicketResource`: Global vendor support ticket oversight (`/admin/tickets`) with priority badges, status updates, conversational response thread, and real-time vendor notification dispatching.
  - `ReviewResource`: Customer review moderation with instant approve/reject actions.
  - `OrderResource` (`/admin/orders`): **Orders & Refunds** ledger under the "Financials" group with commission snapshots (`commission_rate`, `vendor_earning`, `platform_fee`, `coupon_code`, `discount_amount`) and Mark Paid / Open Dispute / Refund actions (create/edit/delete disabled; `canViewAny()` admin-only).
  - `CategoryResource`: Nested category management (`parent_id` + `type` levels, auto-slug generation, `heroicon-o-tag`).
  - `ManageSiteSettings` (page): **Community & Social Links** (`/admin/site-settings`) persisting `telegram_link`, `discord_link`, `community_title`, `community_description` in `site_settings`.
  - **User restriction controls**: `UserResource` and `VendorResource` expose `is_banned` / `is_suspended` toggles and `ban_reason`; `AuthController` rejects banned or suspended accounts at login.
  - **Header Notification Bell**: Real-time database notification dropdown alerting admins on new vendor tickets and inquiries.
- **Vendor Panel (`/vendor/dashboard`)**:
  - `Dashboard`: Custom vendor dashboard page (`App\Filament\Vendor\Pages\Dashboard`) registered at `/vendor/dashboard`.
  - `VendorOnboarding`: 3-step first-time Vendor Onboarding Survey & Store Setup Wizard (`App\Filament\Vendor\Pages\VendorOnboarding`, `/vendor/onboarding`, `shouldRegisterNavigation = false`). Captures *Step 1: Store & Identity* (avatar, `store_name`, live `@username` availability check, bio), *Step 2: Contact & Location* (`phone`, `country`, `address`, `city`, `postal_code`), and *Step 3: Creator Survey* (`primary_ai_models`, `focus_categories`, `experience_level`, `referral_source`).
  - `VendorStatsOverview`: 6 interactive click-through cards featuring **7-day mini sparkline trend charts** (Total Earnings, Prompts Sold, Active Prompts, Pending Prompts, Total Followers, Average Rating).
  - `VendorRevenueChart`: Area chart with dual metrics tracking monthly Gross Sales ($) and Net 80% Vendor Cut ($).
  - `VendorSalesDistributionChart`: Doughnut chart visualizing product catalog and sales distribution across AI Models.
  - `VendorRecentSales`: Lazy-loaded table widget listing recent sales.
  - **Admin & Vendor Prompt Integration**:
  - Updated Admin Product Resource (`/admin/products`), Vendor Upload Prompt Page (`/vendor/upload`), and Vendor Product Resource (`/vendor/products`).
  - **Dynamic Selection & Inline Creation**: Vendors can select from existing categories/subcategories **OR** click the `+` button directly inside the dropdown modal to create a new category/subcategory on the fly! Newly created categories are saved instantly into the database and selected for the prompt.
  - `TicketResource`: Dedicated Support Ticket system (`/vendor/tickets`, "Community & Support" group) with Open Ticket form, file attachments, and conversational chat thread UI (`ViewTicket.php`).
  - `VendorFollowers`: Dedicated page (`/vendor/followers`, "Community & Support" group) listing followers with avatars, timestamps, and direct profile links.
  - `VendorReviewResource`: Received reviews and ratings management resource (`/vendor/reviews`, "Community & Support" group).
  - `Profile` (page): **Singleton** Vendor Profile & Verification page (`/vendor/profile`, "Shop Management" group, no route parameters — always binds `auth()->user()`) with unified `#0B0F19` / `#111827` dark FinTech header card, 4 KPI overview cards, interactive **Profile Settings / Storefront Preview** switcher, and 5 tabs: Public Profile, Personal & Location, KYC Verification, Storefront (banner, announcement, vacation mode, refund/license policies) and Security (password change & Hybrid 2FA). Header shows the copyable Seller Unique ID (`VND-XXXXXX`) and "View Public Profile"; the topbar avatar displays the verified checkmark badge (`✓`). The sidebar link is labeled **"Profile & Verification"** while the topbar user-menu entry for the same URL is labeled **"Verification Status (…)"** so the two never render duplicate link text.
  - `CouponResource` (`/vendor/coupons`): Vendor-managed discount coupons (percent/fixed, min-order, usage limit, expiry) under the "Shop Management" navigation group, scoped to `where('user_id', auth()->id())`; validated server-side during checkout.
  - **No vendor category resource**: category CRUD lives only in the admin panel (`App\Filament\Resources\CategoryResource`); vendors can still create a category on the fly from the upload form (`Category::firstOrCreate`).
  - `VendorKycNoticeWidget`: Top-of-dashboard notice for `unverified` / `pending` / `rejected` vendors linking to `/vendor/profile`.
  - **First-Time Onboarding & Decoupled Instant Access (`VendorPanelProvider::authMiddleware()`)**:
    - `App\Http\Middleware\EnsureVendorOnboardingCompleted` routes new vendors (`onboarding_completed_at === null`) to `/vendor/onboarding` before accessing other `/vendor/*` routes, and redirects already-onboarded vendors away from `/vendor/onboarding` to `/vendor/dashboard`.
    - `App\Http\Middleware\EnsureVendorIsVerified` enforces account suspension/ban checks while granting unverified vendors full operational freedom across all 10 Vendor Panel pages (KYC approval only gates the Verified Seller Badge `✓`).
  - `VendorBilling`: Vendor Withdraw & Payouts page (`/vendor/payouts`, "Finances" group) with saved payment methods, real-time balance locks (`available_balance`, `pending_withdrawal_balance`, `withdrawn_total`), interactive Request Withdrawal modal (`WDR-XXXXXX` reference code, `MARKETPLACE_MIN_WITHDRAWAL` env, default $20 via `config/marketplace.php`), and payout history table.
  - `App\Filament\Vendor\Resources\ProductResource`: Dedicated vendor product resource (`/vendor/products`, "Shop Management" group) strictly scoped via `where('user_id', auth()->id())` with dedicated Operations icon buttons (View, Edit, Delete), 3-word title truncation, and disabled row clicks.
  - `VendorSalesResource`: Unified Financial & Order Management transaction history resource (`/vendor/sales-and-earnings`, "Finances" group) with Net 80% Vendor Cut calculations.
  - **Dynamic Sidebar Badges**: Dynamic badges with unread counters on **My Prompts** (`warning`), **Sales & Earnings** (`success`), **Support Tickets** (`success`), **Customer Reviews** (`warning`), and **My Followers** (`primary`).
  - **View-to-Clear Mechanism**: Auto-clears navigation badges and marks corresponding database notifications as read when the vendor visits any resource list page.
  - **Header Notification Bell**: Real-time database notifications (`30s` polling) for ticket responses, prompt reviews, KYC updates, and payout approvals.

### D. Event Observers & Real-Time Notification Pipeline
- **`FollowObserver`**: Listens on `Follow::created` -> dispatches notification with `heroicon-o-user-plus` and link to `/vendor/vendor-followers`.
- **`OrderObserver`**: Listens on `Order::created` / `Order::updated` (`status === 'paid'`) -> dispatches sale alert notification with `heroicon-o-currency-dollar` and link to `/vendor/sales-and-earnings`.
- **`ReviewObserver`**: Listens on `Review::created` / `Review::updated` (`status === 'approved'`) -> dispatches new rating alert with `heroicon-o-star` and link to `/vendor/vendor-reviews`.
- **`ProductObserver`**: Listens on `Product::created` (alerts admins for review) and `Product::updated` (alerts vendor on approval/rejection) with `heroicon-o-check-badge` / `heroicon-o-x-circle`.
- **`TicketMessageObserver`**: Listens on `TicketMessage::created` -> dispatches instant notification to recipient (Vendor or Admins).

### E. Data Layer (Eloquent Models & MySQL)
- **`users`**: Base authentication, unique `username` + `seller_code` (`VND-XXXXXX`), `store_name`, contact & billing location (`phone`, `country`, `address`, `city`, `postal_code`), creator onboarding survey (`primary_ai_models`, `focus_categories`, `experience_level`, `referral_source`, `onboarding_completed_at`), roles (`admin`, `vendor`, `customer`), profile bio/avatar/social links, KYC verification flags (`is_verified`, `verification_status`, `id_document`, `id_document_back`, `id_document_selfie`, `verification_note`), moderation & financial flags (`is_banned`, `ban_reason`, `is_suspended`, `is_payout_frozen`, `custom_commission_rate`), Hybrid 2FA columns (`two_factor_secret`, `two_factor_recovery_codes`, `two_factor_confirmed_at`, `email_otp_code`, `email_otp_expires_at`, `preferred_2fa_method`, `trusted_devices`), unread-tracking timestamps (`last_read_sales_at`, `last_read_reviews_at`, `last_read_followers_at`), and `deleted_at` (`SoftDeletes`).
- **`products`**: `product_code` (Item ID e.g. `PRD-XXXXXX`), `slug`, `ai_model`, `category` / `sub_category` / `class_category` (nested taxonomy), `instructions`, `prompt_text` (nullable), `prompt_file`, `cover_image`, `gallery_images` (JSON array), `preview_video`, price + `compare_price`, `license_type` (`personal` default), `is_original_confirmed`, `views_count` (incremented on every `/product/*` view), `rejection_reason`, `last_reviewed_at`, `status` (`pending`, `approved`, `rejected`), `is_active`, `is_featured`, `user_id` foreign key, `deleted_at` (`SoftDeletes`).
- **`tickets`**: `ticket_id` (e.g. `TCK-XXXXXX`), `user_id`, `subject`, `category`, `priority`, `status` (`open`, `answered`, `closed`), timestamps.
- **`ticket_messages`**: `ticket_id`, `user_id` (author), `message`, `attachment`, timestamps.
- **`notifications`**: Laravel database notifications polymorphic table.
- **`categories`**: Self-referencing taxonomy (`parent_id`, `type`, `name`, `slug`, `icon`, `description`, `is_active`, `sort_order`, `deleted_at`) — populated by `CategorySeeder` and `ImportPromptsChatCommand`.
- **`site_settings`**: Simple `key` / `value` store (`telegram_link`, `discord_link`, `community_title`, `community_description`).
- **`orders`**: Transaction records with `user_id`, customer email, amount, commission snapshot (`commission_rate`, `vendor_earning`, `platform_fee`), coupon fields (`coupon_code`, `discount_amount`), access tokens, Stripe session IDs, and status (`pending`, `paid`, `failed`, `refunded`, `partially_refunded`, `disputed`).
- **`follows`**: Composite unique index on `user_id` (follower) and `vendor_id` (followed creator).
- **`favorites`**: Composite unique index on `user_id` and `product_id` (wishlist).
- **`reviews`**: Ratings (1-5), comments, polymorphic target (`product_id` / `vendor_id`), moderation status (`approved`, `pending`, `rejected`), public vendor replies (`vendor_reply`, `replied_at`), and `deleted_at`.
- **`vendor_settings`**: Seller profile KYC details (`store_name`, `phone`, `country`, `city`, `address`, `zip_code`, `postal_code`, `date_of_birth`, `nid_passport_number`), creator survey fields (`primary_ai_models`, `focus_categories`, `experience_level`, `referral_source`, `onboarding_completed_at`), storefront customization (`store_banner`, `announcement`, `vacation_mode`, `refund_policy`, `license_policy`) and payment credentials payload.
- **`vendor_payouts`**: End-to-End withdrawal request ledger (`reference_id` `WDR-XXXXXX`, `user_id`, `payout_method_id`, `payout_method`, `payout_details` JSON snapshot, `amount`, `status` [`pending`, `processing`, `completed`, `rejected`], `vendor_note`, `rejection_reason`, `admin_notes`, `reference_no`, `processed_at`).
- **`coupons`**: Vendor-issued discount codes (`code` unique uppercase, `percent`/`fixed`, `value`, `min_order_amount`, `usage_limit`, `used_count`, `expires_at`, `is_active`, `deleted_at`) scoped by `user_id`; created via `CouponResource` and consumed at checkout.

---

## 4. Workflows & Lifecycle Sequences

### A. Support Ticket & Real-Time Notification Lifecycle
1. Vendor opens a ticket at `/vendor/tickets/create` selecting category, priority, message, and optional attachment.
2. System creates `Ticket` (`TCK-XXXXXX`) and initial `TicketMessage`, and dispatches real-time database notifications to platform Admins.
3. Admin views ticket at `/admin/tickets/{id}`, replies in the conversational thread, and marks status as `answered`.
4. System creates `TicketMessage` from Admin and dispatches real-time database notification directly to the vendor with a 1-click jump link.
5. Vendor sees red badge counter on the **Header Notification Bell**, opens the slide-over notification center, and jumps straight into the support conversation.

### B. Payment & Prompt Reveal Workflow
1. User browses marketplace (`/`) and views prompt details (`/product/{product:slug}` or `/product/{product:product_code}`).
2. **Paid Prompts ($1.99+)**: User enters email at checkout and may apply a vendor coupon code — `ProductController@checkout` validates it (`code` belongs to the product's creator, `Coupon::isActive()`/expiry/usage-limit/min-order via `Coupon::isValid()`) and rejects invalid codes with an "Invalid or expired coupon code" flash. A `pending` `Order` record is created with the discounted amount, `coupon_code`/`discount_amount`, a unique 32-character `access_token`, and the buyer is redirected to the Stripe Checkout Session URL. After payment completion, order is marked `paid`, the coupon's `used_count` is incremented, and user is sent to `/prompt/reveal/{token}` (refunds/disputes later move the status to `refunded` / `partially_refunded` / `disputed` via the admin `OrderResource`).
3. **Free Prompts ($0.00)**: Free prompts render the **Interactive Prompt Playground** (`products/partials/interactive-prompt-engine.blade.php`) directly on `/product/{slug}` AND allow users to click *"Get Free Prompt Instantly"* to claim a `paid` `Order` ($0.00) and visit `/prompt/reveal/{token}`.
4. On `/prompt/reveal/{token}` (and unlocked `/product/{slug}` pages), the user can customize `${variable:default}` and `[Variable]` placeholders live, copy the prompt with 1 click, launch directly in ChatGPT/Claude/Perplexity, or download attached prompt package files (.zip, .txt, .json, .pdf, .docx) via `/prompt/download/{token}`.

### C. Cloudflare R2 Object Storage & CDN Asset Delivery
1. All FileUpload components upload to the configured `r2` disk using S3-compatible driver (`league/flysystem-aws-s3-v3`).
2. Directory structure isolates assets:
   - Cover Images: `prompts/covers/` (plus `prompts/covers/placeholders/*.svg` for category-based dark SVG covers)
   - Video Previews: `prompts/videos/`
   - Prompt Package Files: `prompts/files/` (.zip, .txt, .json, .pdf, .docx, .rar, .7z)
   - User Avatars: `users/avatars/`
   - KYC Verification Documents: `kyc-documents/` (vendor-side, **private `local` disk** — see below) and legacy `users/documents/` (admin-side/legacy, `r2` or `public` disk)
   - Ticket Attachments: `tickets/attachments/`
   - Store Banners: `vendor/store/`
3. Model accessors (`cover_image_url`, `preview_video_url`, `avatar_url`, `attachment_url`, `id_document_url`) automatically construct CDN URLs via `Storage::disk($disk)->url($path)` (or direct `https://` URLs for fast-imported remote assets).
4. **Private KYC delivery:** vendor KYC uploads (Profile page) use `disk('local')` + `visibility('private')`, so `User::signedKycUrl()` builds an owner-or-admin-gated `/vendor/kyc/preview/{file}` route (base64 path) instead of a public URL — configured by `config('marketplace.kyc_disk')`.
5. **Ticket attachment fallback:** `App\Filament\Vendor\Resources\TicketResource` writes to the `r2` disk only when `FILESYSTEM_DISK=r2`, otherwise it falls back to the `public` disk (`tickets/attachments/`), so attachments keep working in local-only setups.

### D. Public Seller Storefront & Real-Time Filtering
1. Visitors access `/seller/{username}` (e.g. `/seller/demo-vendor` or `/seller/promptschat`).
2. The route binds explicitly on the `username` column, so numeric-ID (`/seller/2`) and Seller-Code (`/seller/VND-334901`) URLs are **not** resolvable and return `404` (verified). `User::resolveRouteBinding()` still resolves `username`, `seller_code`, `id` and `email` for routes that do not pin the field. `SellerController::show` then evaluates active/approved prompts with rating & sales aggregates.
3. Alpine.js manages state for Search, Pricing Type, Category, AI Model, and Sort By.
4. Filter changes fetch partial HTML (`sellers/partials/prompts-grid.blade.php`) via AJAX with `?ajax=1` and dynamically swap `#prompts-grid-container`.
5. Browser address bar is updated synchronously with `window.history.pushState` ensuring shareable search URLs without full-page reloads.

### E. Prompts.chat Open-Source Importer & Interactive Prompt Engine
1. Admin triggers import via CLI (`php artisan prompts:import-community`) or 1-Click Admin Action (`Import from Prompts.chat` on `/admin/products`).
2. `ImportPromptsChatCommand` fetches structured prompt metadata from `https://prompts.chat/prompts.json` and merges full untruncated prompt texts + additional fallback items from `https://raw.githubusercontent.com/f/prompts.chat/main/prompts.csv`.
3. Target vendor `Prompts.chat Community` (`@promptschat`, verified badge `true`) is resolved or created automatically.
4. Categories and AI Models (`ChatGPT`, `Claude`, `Gemini`, `Midjourney`, `DALL-E`, `Flux`, `Veo`, `Stable Diffusion`) are inferred from prompt `type` (`TEXT`, `IMAGE`, `STRUCTURED`, `VIDEO`, `SKILL`, `TASTE`) and tags, and byte-capped `Product::upsert` batches persist the prompts without duplicates.
5. On `/product/{slug}` (for free/unlocked prompts) and `/prompt/reveal/{token}`, `interactive-prompt-engine.blade.php` parses `${variable:default}` and `[Variable]` tokens into live Alpine.js input fields and powers 1-click Copy and `Open in ChatGPT` / `Open in Claude` / `Open in Perplexity` buttons.

### F. First-Time Vendor Onboarding & Decoupled KYC Access Lifecycle
1. New vendor registers at `/vendor/register` (or upgrades role) and receives `role = 'vendor'`, `seller_code = 'VND-XXXXXX'`, and `onboarding_completed_at = null`.
2. Upon authentication, `EnsureVendorOnboardingCompleted` intercepts any request to `/vendor/*` and redirects to `/vendor/onboarding` (`App\Filament\Vendor\Pages\VendorOnboarding`).
3. The vendor completes the 3-step `#0B0F19` dark-themed onboarding wizard:
   - **Step 1 (Store & Identity)**: Store Name, `@username` (with real-time availability check), Profile Avatar, and Short Bio.
   - **Step 2 (Contact & Billing Location)**: Phone/WhatsApp, Country, Street Address, City/State, and Postal/ZIP Code.
   - **Step 3 (Creator Survey)**: Primary AI Models (`Midjourney`, `ChatGPT`, `Claude`, `Gemini`, `Flux`, etc.), Focus Categories, Experience Level, and Referral Source.
4. Completing Step 3 saves the fields to both `users` and `vendor_settings`, stamps `onboarding_completed_at = now()`, and redirects to `/vendor/dashboard` with full operational access across all 10 Vendor Panel pages — while Admin KYC approval independently governs the **Verified Seller Badge (`✓`)**.

## Analytics & Exports (Phase 37–38)
`product_view_logs` (24h SHA-256 IP/user dedup) feeds `AnalyticsDashboard` (`/admin/analytics`, `analytics.view`). Queued exporters in `app/Filament/Exports/` (Orders, Payouts, Users, Coupons) use the `exports` table. Scheduled alerts: `products:moderation-sla-alert` (hourly), `payouts:stale-reminder` (daily). Audit gaps tracked in `admin-panel-blueprint.md` §7.


## Admin & Vendor Security Layer
Admin panel `authMiddleware`: `RedirectToCentralLogin` → `RevalidateAdminSession` → `AdminSecurityGate` (IP allowlist, idle timeout, mandatory TOTP 2FA). Vendor panel `authMiddleware`: `RedirectToCentralLogin` → `TwoFactorMiddleware` (session `2fa_verified` persistence + 30-day `trusted_device_{user_id}` cookie) → `EnsureVendorOnboardingCompleted` → `EnsureVendorIsVerified`. Both Admin and Vendor panels share `authGuard('web')`. 2FA routes live at `/admin-security/2fa/*` and `/2fa/*`. Global `SecurityHeaders` middleware. TOTP in `app/Support/Security/Totp.php`. Unified logout response via `CustomLogoutResponse` ensuring 2FA session clearance.
