# Theme Management Duplicate Global Sections Fix

## Issue Summary

When importing/updating themes with different versions, duplicate header and footer global sections were created for websites.

### What Happened

1. **Initial Theme Activation**: Corporate theme activated → created header & footer global sections
2. **Theme Re-import**: Same theme with different version imported → system detected as update
3. **Theme Deletion**: Old theme deleted from master theme management
4. **Theme Re-upload**: Theme uploaded again with NEW theme_id
5. **Theme Re-activation**: System couldn't find existing installation (due to new theme_id)
6. **Problem**: `installForWebsite()` created NEW global sections without checking if they already existed → **DUPLICATES**

### Root Cause

The `installForWebsite()` method in `app/Models/Theme.php` (lines 139-164) was creating global sections and pages without checking if they already existed for the website.

## Fix Applied

### 1. Updated `Theme::installForWebsite()` Method

**File**: `/app/Models/Theme.php` (lines 139-200)

**Changes**:
- Added check for existing global sections before creating new ones
- Updates existing sections instead of creating duplicates
- Added check for existing pages before creating new ones
- Added logging for better debugging

**Key Logic**:
```php
// For global sections (header/footer)
$existingSection = $website->globalSections()
    ->where('type', $themePage->page_type)
    ->where('is_custom', false)
    ->first();

if ($existingSection) {
    // Update existing section with new data
    $existingSection->update([
        'builder_data' => $themePage->builder_data,
    ]);
} else {
    // Create new section
    $website->globalSections()->create([...]);
}

// For regular pages
$existingPage = $website->pages()->where('slug', $themePage->slug)->first();

if (!$existingPage) {
    // Only create if doesn't exist
    $website->pages()->create([...]);
}
```

### 2. Created Cleanup Command

**File**: `/app/Console/Commands/CleanupDuplicateGlobalSections.php`

**Purpose**: Clean up any existing duplicate global sections

**Usage**:
```bash
# Preview what would be deleted (dry run)
php artisan global-sections:cleanup-duplicates --dry-run

# Clean up all websites
php artisan global-sections:cleanup-duplicates

# Clean up specific website
php artisan global-sections:cleanup-duplicates --website-id=30
```

**Logic**:
- Finds all non-custom global sections of same type for each website
- Keeps the oldest one (first created)
- Deletes the duplicates
- Shows detailed report of actions taken

## Prevention

The fix ensures that:

1. **Theme Updates**: When updating a theme, existing global sections are updated, not duplicated
2. **Theme Re-installation**: Re-installing the same theme won't create duplicates
3. **Version Changes**: Different theme versions update the same global sections
4. **Page Protection**: Existing pages with same slug won't be duplicated

## Testing

### Test Case 1: Fresh Theme Installation
```bash
# Should create new header and footer
$theme->installForWebsite($website);
```

### Test Case 2: Re-installation of Same Theme
```bash
# Should update existing header and footer, not duplicate
$theme->installForWebsite($website);
$theme->installForWebsite($website); // Run again
```

### Test Case 3: Theme Update (Different Version)
```bash
# Import theme v1.0.0 → creates sections
# Import theme v1.0.1 with same slug → updates sections
# Re-activate theme → updates sections, no duplicates
```

## Migration Path

If duplicates already exist:

1. **Run cleanup command** (dry run first):
   ```bash
   php artisan global-sections:cleanup-duplicates --dry-run
   php artisan global-sections:cleanup-duplicates
   ```

2. **Verify results**:
   ```bash
   php artisan tinker --execute="
   echo \App\Models\GlobalSection::selectRaw('website_id, type, COUNT(*) as count')
       ->where('is_custom', false)
       ->groupBy('website_id', 'type')
       ->having('count', '>', 1)
       ->count() . ' websites with duplicates';
   "
   ```

3. **Manual verification** (optional):
   - Check each website's header/footer in Website Customizer
   - Ensure only one header and one footer appear

## Important Notes

### Theme Import Service

The `ThemeImportService` (when overwrite=true) deletes and recreates themes:
- **Line 48-50**: Deletes existing theme with all relationships
- **Line 54**: Creates new theme with NEW theme_id
- **Issue**: Old `WebsiteTheme` records point to deleted theme_id

### Future Enhancement Needed

Consider updating `ThemeImportService::importTheme()` to:
1. Update existing theme instead of delete + recreate
2. Preserve theme_id across imports
3. Update version number only

**Pseudocode**:
```php
if ($existingTheme && $overwrite) {
    // Instead of deleting and recreating
    $existingTheme->update([
        'version' => $themeData['version'],
        'description' => $themeData['description'],
        // ... other fields
    ]);

    // Update components, presets, pages
    $this->updateComponents($existingTheme, $themeData['components']);
    $this->updatePresets($existingTheme, $themeData['presets']);
    $this->updatePages($existingTheme, $themeData['pages']);
}
```

## Related Files

- **Theme Model**: `app/Models/Theme.php` (line 109-200)
- **Theme Import Service**: `app/Services/ThemeImportService.php` (line 24-84)
- **Theme Gallery Controller**: `app/Http/Controllers/ThemeGalleryController.php` (line 95-164)
- **Cleanup Command**: `app/Console/Commands/CleanupDuplicateGlobalSections.php`

## Status

✅ **FIXED** - The issue has been resolved and prevention measures are in place.

- Duplicate prevention: ✅ Implemented
- Cleanup command: ✅ Created
- Documentation: ✅ Complete
- Testing: ⏳ Pending real-world verification

## Next Steps

1. Test the fix with actual theme import workflow
2. Consider implementing the "Future Enhancement" for ThemeImportService
3. Add unit tests for duplicate prevention logic
4. Monitor logs for "Updated existing global section" vs "Created new global section" messages
