# Theme System Architecture

## Current Structure Overview

Your system has **3 theme systems** working together:

### 1. **Legacy Filesystem Themes** (Old System - Being Phased Out)
```
/resources/views/themes/
├── default/
│   ├── layout.blade.php
│   ├── home.blade.php
│   ├── page.blade.php
│   └── product.blade.php (OLD - not used anymore)
└── dynamic/
    └── layout.blade.php (Database-driven theme renderer)
```

**Status**: ❌ Being replaced by unified public templates

---

### 2. **Unified Public Templates** (Current E-Commerce)
```
/resources/views/public/
├── builder-page.blade.php (Builder V2 pages)
├── product-page.blade.php
├── products-page.blade.php
├── cart-page.blade.php
├── checkout-page.blade.php
└── order-confirmation-page.blade.php
```

**Purpose**: ✅ Consistent layout for all e-commerce pages
**Features**:
- Same header/footer across all pages
- Dynamic currency support
- Responsive Bootstrap 5 design
- Works with website's menu system

---

### 3. **Database-Driven Theme System** (Advanced - Partially Implemented)

#### Database Tables

**`themes`** - Master theme library
```
- id, name, slug, version, author
- description, preview_image
- features (JSON): ['responsive', 'dark_mode', 'rtl_support']
- industries (JSON): ['restaurant', 'retail', 'corporate']
- color_schemes (JSON): Multiple color palettes
- fonts (JSON): Typography settings
- settings (JSON): Theme-specific options
- is_premium, price
- installations_count
```

**`theme_components`** - Theme building blocks
```
- theme_id (FK)
- type: 'header', 'footer', 'hero', 'section', 'component'
- name, slug, description
- html_structure, css_styles, js_scripts
- builder_data (JSON): Builder V2 compatible data
- default_settings (JSON)
- variables (JSON): Customizable values
- order, is_required
```

**`theme_presets`** - Pre-configured theme variations
```
- theme_id (FK)
- name, slug, description, preview_image
- color_scheme (JSON)
- font_scheme (JSON)
- component_settings (JSON)
- layout_settings (JSON)
- industry: 'restaurant', 'retail', etc.
- is_default
```

**`website_themes`** - Theme installations per website
```
- website_id (FK)
- theme_id (FK)
- status: 'active', 'draft', 'archived'
- color_overrides, font_overrides (JSON)
- settings_overrides, css_overrides (JSON)
- header_settings, footer_settings (JSON)
- installed_version
- auto_update
```

**`website_theme_components`** - Customized components per website
```
- website_theme_id (FK)
- theme_component_id (FK)
- is_active
- html_override, css_override, js_override
- builder_data_override (JSON)
- settings_override (JSON)
```

**`website_theme_history`** - Version control & rollback
```
- website_id (FK)
- website_theme_id (FK)
- action: 'installed', 'customized', 'updated', 'reverted'
- previous_state, new_state (JSON)
- changed_by, notes
```

---

## Current Page Rendering Flow

```
User visits page → PublicController::renderPage()
                          ↓
   ┌──────────────────────┼──────────────────────┐
   │                      │                      │
   V                      V                      V
Builder V2 Page    Dynamic Theme           Legacy Theme
   │                 System                    System
   │                      │                      │
   V                      V                      V
builder-page.      themes/dynamic/        themes/default/
blade.php          layout.blade.php       layout.blade.php
```

**Priority Order** (in `PublicController.php:315-349`):
1. ✅ **Builder V2 pages** - If `page.isBuilderV2Page()`
2. ✅ **Dynamic theme system** - If `website.activeTheme` exists
3. ❌ **Legacy filesystem themes** - Fallback (being phased out)

---

## Recommended Architecture: Builder-First Theme System

Based on your vision, here's the **ideal workflow**:

### Phase 1: Theme Creation (Design in Builder)

```
1. Admin creates new theme in Builder V2
   ↓
2. Designs components:
   - Header (with navigation)
   - Footer
   - Hero sections (3-4 variants)
   - Content sections (10-15 variants)
   - E-commerce components (product grids, cart, checkout)
   ↓
3. Exports theme as JSON to database
   → Stored in `themes` table
   → Components stored in `theme_components` table with `builder_data`
```

### Phase 2: Theme Presets (Color Variations)

```
1. Select base theme
   ↓
2. Create presets with different:
   - Color schemes (Primary, Secondary, Dark, Light)
   - Font pairings
   - Spacing/padding settings
   ↓
3. Save as theme_presets
   Examples:
   - "Creative - Vibrant" (Bold colors)
   - "Creative - Minimal" (Monochrome)
   - "Creative - Corporate" (Professional blues)
```

### Phase 3: User Selection & Customization

```
1. User creates website
   ↓
2. Chooses theme: "Creative"
   ↓
3. Chooses preset: "Vibrant"
   ↓
4. System installs:
   - Creates website_themes record
   - Copies theme_components to website_theme_components
   - Applies preset colors/fonts
   ↓
5. User customizes in Builder V2:
   - Edits header
   - Changes colors
   - Adds/removes sections
   ↓
6. Customizations stored in:
   - website_theme_components.builder_data_override
   - website_themes.color_overrides
```

---

## Implementation Plan

### Step 1: Create Theme Export Feature

Create a **Theme Builder** interface where you can:
1. Design header, footer, and page sections in Builder V2
2. Click "Export as Theme"
3. Name it (e.g., "Creative")
4. System creates:
   - `themes` record
   - `theme_components` records with builder_data
   - Default `theme_preset`

### Step 2: Create Theme Preset Manager

Interface to create variations:
1. Select base theme
2. Customize colors, fonts, spacing
3. Save as new preset
4. Each theme can have multiple presets

### Step 3: Update Website Creation Flow

```php
// When user creates website:
1. Show theme gallery (from `themes` table)
2. User selects "Creative"
3. Show available presets
4. User selects "Vibrant"
5. System installs theme + preset
6. Redirects to Builder V2 for customization
```

### Step 4: Update Page Rendering

Modify `PublicController::renderPage()`:
```php
// PRIORITY 1: Builder V2 pages (custom user pages)
if ($page->isBuilderV2Page()) {
    return view('public.builder-page', ...);
}

// PRIORITY 2: Dynamic theme system with components
if ($website->activeTheme) {
    $theme = $website->activeTheme->getMergedThemeData();
    $components = $website->activeTheme->getActiveComponents();
    return view('themes.dynamic.layout', ...);
}

// PRIORITY 3: Legacy fallback (remove eventually)
return view('themes.' . $website->theme . '.page', ...);
```

---

## Directory Structure (Proposed)

```
resources/views/
├── public/                          # Unified system templates
│   ├── builder-page.blade.php       # Builder V2 renderer
│   ├── product-page.blade.php       # E-commerce pages
│   ├── cart-page.blade.php
│   ├── checkout-page.blade.php
│   └── order-confirmation-page.blade.php
│
├── themes/
│   ├── dynamic/                     # Database-driven renderer
│   │   └── layout.blade.php         # Renders from theme_components
│   │
│   └── default/                     # Legacy fallback (to be removed)
│       └── layout.blade.php
│
└── admin/
    └── themes/                      # Theme management UI
        ├── index.blade.php          # Theme gallery
        ├── builder.blade.php        # Theme design interface
        └── presets.blade.php        # Preset manager

database/
└── migrations/
    └── 2025_09_24_create_theme_management_tables.php ✅ (Already exists)

app/
├── Models/
│   ├── Theme.php                    ✅ Already exists
│   ├── ThemeComponent.php           ✅ Already exists
│   ├── ThemePreset.php              ✅ Already exists
│   ├── WebsiteTheme.php             ✅ Already exists
│   └── WebsiteThemeComponent.php    ✅ Already exists
│
└── Services/
    ├── ThemeExportService.php       🔨 TO BUILD: Export builder design as theme
    ├── ThemeInstallService.php      ✅ Already in Theme.php::installForWebsite()
    └── ThemeCustomizationService.php 🔨 TO BUILD: Handle user customizations
```

---

## Example: Creating "Creative" Theme

### Step 1: Design in Builder
```javascript
// Design components in Builder V2 UI
{
  "header": {
    "type": "Container",
    "props": {
      "backgroundColor": "{{theme.colors.primary}}",
      "padding": "20px"
    },
    "children": [/* navigation */]
  },
  "footer": {/* ... */},
  "hero_modern": {/* ... */},
  "hero_minimal": {/* ... */}
}
```

### Step 2: Export to Database
```php
// ThemeExportService.php
public function exportTheme($builderData, $themeName)
{
    $theme = Theme::create([
        'name' => $themeName,
        'slug' => Str::slug($themeName),
        'version' => '1.0.0',
        'author' => auth()->user()->name,
        'features' => ['responsive', 'builder_v2_compatible'],
        'industries' => ['creative', 'agency', 'portfolio'],
    ]);

    // Save header component
    ThemeComponent::create([
        'theme_id' => $theme->id,
        'type' => 'header',
        'name' => 'Creative Header',
        'slug' => 'header-creative',
        'builder_data' => $builderData['header'], // ← Builder V2 JSON
        'order' => 1,
        'is_required' => true,
    ]);

    // Save footer component
    ThemeComponent::create([...]);

    // Create default preset
    ThemePreset::create([
        'theme_id' => $theme->id,
        'name' => 'Default',
        'slug' => 'default',
        'color_scheme' => [
            'primary' => '#667eea',
            'secondary' => '#764ba2',
        ],
        'font_scheme' => [
            'heading' => 'Playfair Display',
            'body' => 'Inter',
        ],
        'is_default' => true,
    ]);
}
```

### Step 3: User Installs Theme
```php
// When user creates website
$theme = Theme::where('slug', 'creative')->first();
$preset = $theme->presets()->where('slug', 'vibrant')->first();

// Install theme
$websiteTheme = $theme->installForWebsite($website, $preset);

// Set as active
$website->update(['active_theme_id' => $websiteTheme->id]);
```

### Step 4: User Customizes
```php
// When user edits header in Builder V2
$websiteThemeComponent = $websiteTheme->components()
    ->whereHas('themeComponent', function($q) {
        $q->where('type', 'header');
    })
    ->first();

$websiteThemeComponent->update([
    'builder_data_override' => $customizedBuilderData, // User's changes
]);
```

### Step 5: Rendering
```php
// PublicController.php
$components = $websiteTheme->getActiveComponents();
// Returns merged data: theme default + user overrides

return view('themes.dynamic.layout', compact('components'));
```

---

## Benefits of This Architecture

✅ **Separation of Concerns**:
- **Public templates**: System pages (cart, checkout) - rarely change
- **Dynamic themes**: User-customizable designs
- **Builder V2**: Custom page building

✅ **Scalability**:
- Add unlimited themes without touching code
- Each theme can have unlimited presets
- Users can't break system functionality

✅ **Version Control**:
- Theme updates don't affect user customizations
- Rollback capability via `website_theme_history`
- Track who changed what

✅ **Monetization Ready**:
- Premium themes with pricing
- Track installations
- License management possible

✅ **Builder V2 Integration**:
- Themes are built IN the builder
- Users customize themes WITH the builder
- All using same component system

---

## Migration Path: Current → Ideal

### Phase 1: ✅ **COMPLETED**
- [x] Create unified public e-commerce templates
- [x] Dynamic currency support
- [x] Consistent headers/footers

### Phase 2: 🔨 **TO BUILD**
- [ ] Build Theme Builder UI (design interface)
- [ ] Build Theme Export Service
- [ ] Build Theme Gallery (for users to select)
- [ ] Build Preset Manager

### Phase 3: 🔨 **TO BUILD**
- [ ] Migrate existing "default" theme to database
- [ ] Create 2-3 demo themes ("Modern", "Creative", "Minimal")
- [ ] Test installation flow

### Phase 4: 🔨 **TO BUILD**
- [ ] Remove legacy filesystem themes
- [ ] Full Builder V2 integration
- [ ] Theme marketplace (optional)

---

## Next Steps

**Option A: Quick Win** - Create one sample theme manually in database
```bash
php artisan make:command CreateSampleTheme
# Manually insert theme, components, presets
# Test installation on demo website
```

**Option B: Build Theme Builder** - Full UI for designing themes
```
1. Create admin/themes/builder route
2. Load Builder V2 in "theme mode"
3. Add "Export as Theme" button
4. Build ThemeExportService
```

**Option C: Hybrid** - Use Builder V2 for pages, filesystem for system templates
```
Keep current structure:
- Builder V2 for user pages ✅
- Public templates for e-commerce ✅
- Add theme selection UI later
```

---

## Recommendation

**Start with Option A** (Quick Win):
1. Create one "Creative" theme manually
2. Test the installation flow
3. Verify rendering works
4. Then build the Theme Builder UI

This validates the architecture before investing time in the full UI.

Would you like me to create a sample theme to demonstrate the flow?
