# Google Sheets Template Clearing Process

**Last Updated:** 2026-03-09

## Overview

When updating existing Google Sheets templates, the system now performs a complete sheet clearing process before rebuilding. This ensures that old cells, formatting, and validations that no longer exist in the template definition are removed, preventing layout issues and duplicate content.

## Problem Statement

Previously, when updating Google Sheets templates, the system would:
- Update only cells that existed in the new template definition
- Leave old cells and formatting intact if they weren't explicitly overwritten
- Result in duplicate headers, orphaned formatting, and inconsistent layouts

**Example Issues:**
- Duplicate column headers (e.g., "Katastrophal" appearing twice in G8)
- Old conditional formatting rules persisting alongside new ones
- Cells from previous versions remaining visible
- Inconsistent formatting between old and new cells

## Solution

The `clearSheet()` method in `google-sheets-generator.php` now performs a comprehensive clearing process before rebuilding each sheet:

### Clearing Process

1. **Delete Conditional Formatting Rules**
   - Retrieves current sheet to identify all conditional formatting rules
   - Deletes rules in reverse order (to avoid index shifting issues)
   - Ensures old color-coding rules don't persist

2. **Clear Cell Values**
   - Uses `batchClear` API to remove all cell content
   - Clears range `A1:ZZ1000` to ensure comprehensive coverage
   - Removes all formulas, text, and numbers

3. **Clear Formatting and Validations**
   - Uses `updateCells` with empty format fields
   - Removes all user-entered formatting (colors, fonts, borders, alignment)
   - Removes all data validation rules

4. **Clear Filters**
   - Removes any basic filters that may have been applied
   - Ensures clean sheet state

5. **Rebuild from Template Definition**
   - After clearing, `populateSheet()` rebuilds the sheet from the template definition
   - All cells, formatting, validations, and conditional formatting are applied fresh

## Implementation

### Code Location

**File:** `v2/systems/excel-template-generator/helpers/google-sheets-generator.php`

**Method:** `clearSheet($sheetId, $sheetName)`

**Called From:** `updateSpreadsheet()` method when updating existing sheets

### Key Code Snippet

```php
if (isset($existingSheets[$sheetName])) {
    // Update existing sheet - clear it first to remove old cells and formatting
    $sheetId = $existingSheets[$sheetName];
    $this->clearSheet($sheetId, $sheetName);
    $this->populateSheet($sheetId, $sheetDef, $requests, $data);
}
```

## Benefits

✅ **Clean Updates** - Each update results in a fresh, clean sheet structure  
✅ **No Duplicates** - Prevents duplicate headers, labels, or content  
✅ **Consistent Formatting** - All formatting matches the template definition exactly  
✅ **No Orphaned Cells** - Old cells that no longer exist are removed  
✅ **Proper Conditional Formatting** - Old rules are removed before new ones are applied  

## Error Handling

The clearing process uses try-catch error handling:

- **Best Effort Clearing** - If clearing fails, the update continues
- **Error Logging** - Failures are logged with full context for debugging
- **Graceful Degradation** - Sheet population still works even if clearing fails (may leave some old formatting)

## When Clearing Happens

- ✅ **On Template Updates** - When `updateGoogleSheetsTemplate()` is called for existing templates
- ❌ **On New Templates** - New templates are created fresh, no clearing needed
- ❌ **On User Copies** - User copies are independent and never cleared by the system

## Testing

To test the clearing process:

```bash
# Update a template (will trigger clearing)
php v2/scripts/templates/generate-google-sheets-template.php --template=TEMPLATE_ID

# Verify the sheet is clean:
# 1. Open the Google Sheet
# 2. Check for duplicate headers/labels
# 3. Verify conditional formatting matches template definition
# 4. Confirm no orphaned cells or formatting
```

## Related Documentation

- `GOOGLE_SHEETS_INTEGRATION.md` - Main integration guide
- `MANUAL_SHEET_CREATION.md` - Manual sheet creation workflow
- `AUDIT_REPORT.md` - Template audit procedures

## Future Improvements

Potential enhancements:
- [ ] Configurable clearing range (currently fixed at A1:ZZ1000)
- [ ] Option to preserve specific ranges during clearing
- [ ] Clearing progress logging for large sheets
- [ ] Dry-run mode to preview clearing impact
