# Template Caching System

**Last Updated:** 2025-11-20

## Overview

The template caching system provides efficient caching for template definitions and generated Excel files to improve performance and reduce server load.

## Features

- **Template Definition Caching**: Cache parsed template definitions (24-hour TTL)
- **Generated File Caching**: Cache generated Excel files (7-day TTL)
- **Cache Invalidation**: Manual and automatic cache invalidation
- **Cache Statistics**: Track hit rates, cache size, and performance metrics
- **Automatic Cleanup**: Remove expired cache entries automatically

## Cache Structure

```
v2/systems/excel-template-generator/data/template-cache/
├── definitions/     # Cached template definitions (JSON)
├── generated/       # Cached generated Excel files (.xlsx)
└── metadata/        # Cache metadata (JSON)
```

## Usage

### Basic Caching

```php
require_once __DIR__ . '/helpers/template-cache.php';

$cache = new OrdioTemplateCache();

// Generate cache key
$cacheKey = $cache->generateCacheKey($templateDefinition);

// Check cache
$cachedFile = $cache->getGeneratedFile($cacheKey);
if ($cachedFile) {
    // Use cached file
    $fileContent = file_get_contents($cachedFile);
} else {
    // Generate and cache
    $generator = new OrdioTemplateGenerator($templateDefinition);
    $generator->generate();
    $tempFile = tempnam(sys_get_temp_dir(), 'ordio_template_');
    $generator->save($tempFile);
    $cache->setGeneratedFile($cacheKey, $tempFile);
}
```

### Cache Management

```php
// Invalidate specific cache entry
$cache->invalidate($cacheKey);

// Invalidate all cache entries
$cache->invalidateAll();

// Clean expired entries
$deleted = $cache->cleanExpired();

// Get cache statistics
$stats = $cache->getStats();
// Returns: hits, misses, sets, invalidations, hit_rate, cache_size
```

## API Endpoints

### Get Cache Statistics

```
GET /v2/systems/excel-template-generator/api/cache.php?action=stats
```

Response:

```json
{
  "success": true,
  "stats": {
    "hits": 150,
    "misses": 50,
    "sets": 200,
    "invalidations": 10,
    "hit_rate": "75%",
    "total_requests": 200,
    "cache_size": 52428800,
    "cache_size_formatted": "50.00 MB"
  }
}
```

### Clean Expired Cache

```
GET /v2/systems/excel-template-generator/api/cache.php?action=clean&max_age=86400
```

### Invalidate Specific Cache Entry

```
POST /v2/systems/excel-template-generator/api/cache.php
Content-Type: application/json

{
  "cache_key": "abc123..."
}
```

### Invalidate All Cache

```
DELETE /v2/systems/excel-template-generator/api/cache.php
```

## Cache Key Generation

Cache keys are generated from:

- Template name
- Template version
- Last modified date
- Template definition hash (MD5)

This ensures that:

- Different template versions have different cache keys
- Updated templates automatically invalidate old cache
- Identical templates share the same cache key

## Cache TTL (Time To Live)

- **Template Definitions**: 24 hours
- **Generated Files**: 7 days
- **Metadata**: 24 hours

## Performance Benefits

- **Reduced Generation Time**: Cached files are served instantly
- **Lower Server Load**: Avoid regenerating identical templates
- **Better User Experience**: Faster download times
- **Cost Savings**: Reduced CPU and memory usage

## Monitoring

Cache statistics are tracked automatically:

- Hit rate: Percentage of cache hits vs total requests
- Cache size: Total size of cached files
- Performance metrics: Generation time, memory usage

## Best Practices

1. **Cache Key Strategy**: Use consistent cache key generation for identical templates
2. **Cache Invalidation**: Invalidate cache when templates are updated
3. **Regular Cleanup**: Run `cleanExpired()` periodically to free disk space
4. **Monitor Hit Rates**: Track cache hit rates to optimize TTL settings
5. **Disk Space**: Monitor cache directory size and set up alerts

## Integration with Template Generator

The caching system is automatically integrated into the template generation API (`/v2/systems/excel-template-generator/api/generate.php`):

- Cache is checked before generation
- Generated files are automatically cached
- Cache hit/miss status is included in API response
- Cache statistics available via `?stats=true` parameter

## Maintenance

### Manual Cache Cleanup

```bash
# Clean expired cache entries
php -r "require 'v2/systems/excel-template-generator/helpers/template-cache.php'; \$cache = new OrdioTemplateCache(); echo \$cache->cleanExpired();"

# Invalidate all cache
php -r "require 'v2/systems/excel-template-generator/helpers/template-cache.php'; \$cache = new OrdioTemplateCache(); echo \$cache->invalidateAll();"
```

### Cron Job Setup

Add to crontab for automatic cleanup:

```bash
# Clean expired cache entries daily at 2 AM
0 2 * * * php /path/to/v2/scripts/clean-template-cache.php
```

## Troubleshooting

### Cache Not Working

1. Check cache directory permissions (should be 755)
2. Verify disk space availability
3. Check cache directory exists and is writable

### High Cache Miss Rate

1. Review cache key generation logic
2. Check if templates are being modified frequently
3. Consider increasing cache TTL for stable templates

### Disk Space Issues

1. Run `cleanExpired()` more frequently
2. Reduce cache TTL for generated files
3. Implement cache size limits
