# Product Updates Development Guide

**Last Updated**: 2025-11-20  
**Status**: Production Ready ✅

## Overview

This guide provides step-by-step instructions for developers working on the Product Updates CMS system. It covers adding features, modifying functionality, testing procedures, and deployment workflows.

## Development Environment Setup

### Prerequisites

- PHP 7.4+
- Web server (Apache/Nginx)
- Local WordPress installation (for uploads directory)
- Git access to repository

### Local Setup

1. Clone repository
2. Configure web server to serve project root
3. Ensure WordPress is installed (for uploads directory)
4. Set up local database (if needed)
5. Configure admin password in `v2/config/admin_config.php`

## Code Structure

### File Organization

```
v2/
├── pages/                    # Public-facing pages
│   ├── produkt_updates.php          # Main listing page
│   ├── produkt_updates_month.php    # Month archive page
│   ├── post.php                     # Individual post page
│   └── produkt_updates_admin.php    # Admin panel
├── includes/                 # Shared includes
│   └── produkt-updates-paths.php    # Path resolution functions
├── api/                      # API endpoints
│   ├── produkt-updates-upload.php   # Image upload
│   └── serve-produkt-updates-image.php # Image proxy
├── admin/produkt-updates/    # Admin tools
│   ├── discover-writable-directories.php
│   ├── analyze-production-setup.php
│   └── migrate-missing-images.php
└── config/                   # Configuration
    └── admin_config.php      # Admin password hash
```

### Key Files

**Core Files**:

- `v2/pages/produkt_updates_admin.php` - Main admin interface (12,435 lines)
- `v2/includes/produkt-updates-paths.php` - Path resolution logic (939 lines)
- `v2/pages/produkt_updates.php` - Main public page
- `v2/pages/post.php` - Individual post page

**Configuration**:

- `v2/config/admin_config.php` - Admin authentication
- JSON data file - Stored in WordPress uploads directory

## Adding New Features

### 1. Admin Panel Features

**Step 1: Plan the Feature**

- Define data structure changes
- Plan UI/UX
- Consider backward compatibility
- Document in feature spec

**Step 2: Update Data Structure**

If adding new fields to features/improvements:

1. Update JSON schema documentation
2. Add field to admin forms
3. Add validation logic
4. Update public page rendering
5. Consider migration for existing data

**Step 3: Add Admin UI**

1. Add form fields in `produkt_updates_admin.php`
2. Add JavaScript handlers
3. Add validation (client and server)
4. Add to display lists

**Step 4: Add Backend Logic**

1. Add action handler in POST processing
2. Add sanitization
3. Add save logic
4. Add error handling

**Step 5: Update Public Pages**

1. Update data loading
2. Add rendering logic
3. Update SEO elements if needed
4. Test display

**Step 6: Test**

1. Test admin panel functionality
2. Test public page display
3. Test data persistence
4. Test edge cases

### 2. Public Page Features

**Step 1: Identify Target Page**

- Main page (`produkt_updates.php`)
- Month page (`produkt_updates_month.php`)
- Post page (`post.php`)

**Step 2: Add Rendering Logic**

1. Load data from JSON
2. Process data
3. Render HTML
4. Add CSS styling

**Step 3: Update SEO**

1. Update meta tags if needed
2. Update Schema.org markup
3. Update Open Graph tags
4. Test with Google Rich Results Test

**Step 4: Test**

1. Test on multiple browsers
2. Test responsive design
3. Test SEO markup
4. Test performance

## Modifying Existing Functionality

### Data Structure Changes

**Breaking Changes**:

1. **Plan Migration**:

   - Create migration script
   - Test on sample data
   - Backup existing data

2. **Update Code**:

   - Update all data access points
   - Add backward compatibility if needed
   - Update validation logic

3. **Test Thoroughly**:
   - Test with old data format
   - Test with new data format
   - Test migration script

**Non-Breaking Changes**:

1. Add new optional fields
2. Update rendering logic
3. Add fallbacks for missing fields
4. Test backward compatibility

### Path Resolution Changes

**When to Modify**:

- Adding new storage locations
- Changing priority order
- Fixing permission issues

**How to Modify**:

1. Edit `v2/includes/produkt-updates-paths.php`
2. Update priority order in location arrays
3. Add directory creation logic if needed
4. Test on production-like environment
5. Update documentation

**Testing**:

- Test with existing data
- Test with missing directories
- Test permission scenarios
- Verify fallback logic

## Testing Procedures

### Manual Testing Checklist

**Admin Panel**:

- [ ] Login/logout functionality
- [ ] Create/edit/delete months
- [ ] Create/edit/delete features
- [ ] Create/edit/delete improvements
- [ ] Image upload and optimization
- [ ] Bulk operations
- [ ] Search and filter
- [ ] Storage status display

**Public Pages**:

- [ ] Main page displays correctly
- [ ] Month pages display correctly
- [ ] Post pages display correctly
- [ ] Images load correctly
- [ ] Navigation works
- [ ] SEO markup valid
- [ ] Responsive design

**Storage**:

- [ ] Data saves to persistent location
- [ ] Images save to persistent location
- [ ] Data survives server restart (if testable)
- [ ] Path resolution works correctly

### Automated Testing

**Test Endpoints**:

1. **Comprehensive Test**:

   ```
   GET /v2/admin/produkt-updates/comprehensive-production-test.php?password=...
   ```

2. **Storage Health Check**:

   ```
   GET /v2/api/produkt-updates-storage-health.php
   ```

3. **Diagnostics**:
   ```
   GET /v2/api/produkt-updates-diagnostics.php
   ```

### Browser Testing

**Required Browsers**:

- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Mobile browsers (iOS Safari, Chrome Mobile)

**Test Scenarios**:

- Admin panel functionality
- Public page rendering
- Image loading
- Form submissions
- Navigation

## Deployment Checklist

### Pre-Deployment

- [ ] All tests passing
- [ ] Code reviewed
- [ ] Documentation updated
- [ ] No console.log statements
- [ ] No debug code
- [ ] Backup existing data (if data structure changes)

### Deployment Steps

1. **Commit Changes**:

   ```bash
   git add .
   git commit -m "Description of changes"
   git push
   ```

2. **Deploy to Production**:

   - Via GitLab CI/CD or manual deployment
   - Verify files deployed correctly

3. **Post-Deployment Verification**:
   - Test admin panel login
   - Test data save
   - Test image upload
   - Test public pages
   - Run comprehensive test endpoint

### Post-Deployment Monitoring

- Monitor error logs
- Check storage status
- Verify data persistence
- Test critical functionality

## Common Development Tasks

### Adding a New Field to Features

**Example**: Adding "priority" field

1. **Update Admin Form** (`produkt_updates_admin.php`):

   ```php
   <input type="number" name="priority" value="<?php echo htmlspecialchars($feature['priority'] ?? '0'); ?>">
   ```

2. **Update Save Logic**:

   ```php
   $priority = (int)sanitizeInput($_POST['priority'] ?? '0');
   $feature['priority'] = $priority;
   ```

3. **Update Public Display** (if needed):
   ```php
   <?php if (!empty($feature['priority'])): ?>
       <span class="priority-badge">Priority: <?php echo $feature['priority']; ?></span>
   <?php endif; ?>
   ```

### Adding a New Tag

1. **Update Tag Functions** (`produkt_updates_admin.php`):

   ```php
   function getTagLabel($tag_key) {
       $labels = [
           // ... existing tags ...
           'new-tag' => 'New Tag Label'
       ];
       return $labels[$tag_key] ?? '';
   }
   ```

2. **Update Tag Icons**:

   ```php
   function getTagIcon($tag_key) {
       $icons = [
           // ... existing icons ...
           'new-tag' => '<svg>...</svg>'
       ];
       return $icons[$tag_key] ?? '';
   }
   ```

3. **Update Admin Form**:
   ```html
   <option value="new-tag">New Tag Label</option>
   ```

### Modifying Display Limits

**Update Settings**:

1. **In Admin Panel** (if UI exists):

   - Update settings form
   - Save to JSON `settings` object

2. **In Code** (`produkt_updates.php`):
   ```php
   $display_limits = getDisplayLimits($updates_data);
   // Limits come from settings or defaults
   ```

## Code Patterns

### Data Loading Pattern

```php
// Load path resolution functions
require_once __DIR__ . '/../includes/produkt-updates-paths.php';

// Load data
$data_file = findReadableDataFile();
$updates_data = [];
if (file_exists($data_file)) {
    $content = file_get_contents($data_file);
    $updates_data = json_decode($content, true) ?: [];
}
```

### Data Saving Pattern

```php
// Get writable location
$writable_data_file = findWritableDataFile();

// Save data
if (saveUpdatesData($writable_data_file, $updates_data)) {
    // Success
    header('Location: ' . getRedirectUrl());
    exit;
} else {
    // Error handling
    $action_result = "Error: Could not save data.";
}
```

### Image Upload Pattern

```php
// Get writable image directory
$image_location = findWritableImageDir();
$upload_dir = $image_location['path'];
$url_prefix = $image_location['url_prefix'];

// Process upload
// ... upload logic ...

// Return URL
$image_url = $url_prefix . $filename;
```

### Image Display Pattern

```php
// Get featured image
$feature_image = !empty($feature['featured_image'])
    ? $feature['featured_image']
    : (isset($feature['images'][0]) ? $feature['images'][0] : '');

// Display image
if (!empty($feature_image)) {
    echo '<img src="' . htmlspecialchars($feature_image) . '" alt="...">';
}
```

## Error Handling

### Standard Error Pattern

```php
try {
    // Operation
} catch (Exception $e) {
    error_log('[Product Updates] Error: ' . $e->getMessage());
    // User-friendly error message
    $action_result = "Error: Operation failed.";
    $action_result_type = 'error';
}
```

### Validation Pattern

```php
// Validate required fields
if (empty($title) || empty($published_date)) {
    $action_result = "Error: Please fill in all required fields.";
    $action_result_type = 'error';
    // Don't proceed
}

// Validate format
if (!preg_match('/^[a-z0-9\-]+$/', $slug)) {
    $action_result = "Error: Invalid slug format.";
    $action_result_type = 'error';
    // Don't proceed
}
```

## Performance Considerations

### Image Optimization

- Always optimize images on upload
- Use WebP when possible
- Lazy load below-fold images
- Use appropriate image sizes

### Data Loading

- Load JSON once per request
- Cache processed data in memory
- Minimize file system operations
- Use efficient data structures

### Code Optimization

- Avoid N+1 queries (not applicable - JSON-based)
- Minimize external API calls
- Use efficient algorithms
- Profile performance-critical code

## Security Best Practices

### Input Validation

- Always sanitize user input
- Validate data types
- Check required fields
- Validate file uploads

### Output Escaping

- Use `htmlspecialchars()` for HTML output
- Sanitize HTML content with `sanitizeHtmlInput()`
- Escape URLs properly
- Prevent XSS attacks

### File Upload Security

- Validate MIME types
- Check file sizes
- Validate dimensions
- Prevent directory traversal
- Optimize images (removes embedded scripts)

## Debugging

### Enable Debug Mode

**In `produkt_updates_admin.php`**:

```php
define('ADMIN_DEBUG_MODE', true);
```

**Effects**:

- More verbose error messages
- Debug logging enabled
- Additional diagnostic output

### Log Locations

- **PHP Error Log**: Standard PHP error_log()
- **Storage Log**: `v2/logs/produkt-updates-storage.log`
- **Admin Log**: `v2/logs/produkt_updates_admin_YYYY-MM-DD.log`

### Common Debugging Steps

1. **Check Error Logs**:

   - PHP error log
   - Storage log
   - Browser console

2. **Run Diagnostics**:

   - Storage health check
   - Comprehensive test
   - List images

3. **Verify Data**:

   - Check JSON file location
   - Verify JSON structure
   - Test path resolution

4. **Test Endpoints**:
   - Test API endpoints
   - Test admin endpoints
   - Verify authentication

## Related Documentation

- [Code Standards](./PRODUCT_UPDATES_CODE_STANDARDS.md) - Coding conventions
- [Testing](./PRODUCT_UPDATES_TESTING.md) - Testing procedures
- [Troubleshooting](./PRODUCT_UPDATES_TROUBLESHOOTING.md) - Common issues
- [System Overview](./PRODUCT_UPDATES_SYSTEM_OVERVIEW.md) - Architecture
