# Remote Image Caching System

## Overview

The POS system now supports automatic caching of remote product images. When admins/managers add remote image URLs to products, the system will automatically download and cache these images locally for better performance.

## How It Works

### 1. Admin/Manager Workflow
- Admins can add remote image URLs when creating or editing items in the inventory
- The system stores the remote URL directly in the existing `image_path` column
- Images are automatically cached locally when first accessed

### 2. User Experience
- When users access the POS product grid, remote images are automatically cached
- Cached images are served from local storage for faster loading
- If caching fails, the system falls back to serving the remote image directly

### 3. Caching Strategy
- **Cache Location**: `assets/images/products/{branch_code}/cached/`
- **Cache Duration**: 7 days (configurable)
- **Filename**: MD5 hash of the remote URL + original extension
- **Automatic Cleanup**: Expired cached images are automatically removed

## Database Changes

### Enhanced Existing Column
The existing `image_path` column now supports both local paths and remote URLs:

```sql
ALTER TABLE `{branch_code}_items` 
MODIFY COLUMN `image_path` varchar(500) DEFAULT NULL 
COMMENT 'Local image path or remote URL (will be cached if remote)';
```

### No Additional Columns Needed
- Uses existing `image_path` column for both local and remote images
- Remote URLs are detected automatically by checking if they start with `http://` or `https://`
- Local paths continue to work as before

## Implementation Details

### Files Modified/Created

1. **`includes/image_cache_helper.php`** (NEW)
   - Core caching functionality
   - Remote image detection and downloading
   - Cache management utilities

2. **`pos/image.php`** (UPDATED)
   - Enhanced to handle remote images
   - Automatic caching on first access
   - Fallback to direct remote serving

3. **`pos/items.php`** (UPDATED)
   - Uses optimized image path function
   - Supports both local and remote images

4. **`pos/inventory.php`** (UPDATED)
   - Added remote image URL input fields
   - Enhanced forms for both upload and URL input

5. **`pos/inventory_handler.php`** (UPDATED)
   - Handles remote image URL storage in existing image_path column
   - Supports both local uploads and remote URLs

6. **`includes/branch_helper.php`** (UPDATED)
   - Enhanced image_path column definition to support longer URLs
   - No additional columns needed

### Key Functions

#### `isRemoteImage($image_path)`
Checks if an image path is a remote URL (starts with http:// or https://)

#### `cacheRemoteImage($remote_url, $branch_code)`
Downloads and caches a remote image locally

#### `getOptimizedImagePath($image_path, $branch_code)`
Returns the appropriate image path (local or cached remote)

#### `cleanupExpiredCachedImages($branch_code, $max_age)`
Removes expired cached images to save disk space

## Setup Instructions

### 1. Optional: Update Image Path Column Length
If your existing `image_path` column is shorter than 500 characters, you may want to extend it:

```sql
ALTER TABLE `{branch_code}_items` 
MODIFY COLUMN `image_path` varchar(500) DEFAULT NULL 
COMMENT 'Local image path or remote URL (will be cached if remote)';
```

### 2. Verify Installation
- Test adding a remote image URL to a product
- Verify the image is cached locally
- Check that existing local images continue to work

### 3. No Migration Required
- Existing local image paths continue to work unchanged
- Remote URLs can be added directly to the `image_path` column
- The system automatically detects and caches remote URLs

## Usage Examples

### Adding Remote Images via Admin Interface
1. Go to Inventory Management
2. Click "Add New Item" or edit an existing item
3. In the "Or Remote Image URL" field, enter a valid image URL
4. Save the item
5. The image will be automatically cached when first accessed

### Programmatic Usage
```php
// Check if an image is remote
if (isRemoteImage($image_path)) {
    // Cache the remote image
    $cache_result = cacheRemoteImage($image_path);
    if ($cache_result['success']) {
        $local_path = $cache_result['path'];
    }
}

// Get optimized image path (handles both local and remote)
$optimized_path = getOptimizedImagePath($image_path);
```

## Performance Benefits

### Before Implementation
- Remote images loaded directly from external servers
- Slower loading times, especially with many products
- Dependent on external server availability
- No browser caching for remote images

### After Implementation
- Remote images cached locally after first access
- Faster subsequent loads from local storage
- Reduced dependency on external servers
- Proper HTTP caching headers for browser caching
- Automatic fallback if caching fails

## Cache Management

### Automatic Cleanup
The system automatically removes cached images older than 30 days to prevent disk space issues.

### Manual Cleanup
```php
// Clean up expired cached images
$stats = cleanupExpiredCachedImages('m001', 30 * 24 * 60 * 60);
echo "Deleted {$stats['deleted']} expired images";
```

### Cache Statistics
```php
// Get cache statistics
$stats = getCacheStatistics('m001');
echo "Total cached files: {$stats['total_files']}";
echo "Total cache size: " . number_format($stats['total_size'] / 1024 / 1024, 2) . " MB";
```

## Security Considerations

### Input Validation
- Remote URLs are validated before caching
- Only image files are accepted (jpg, jpeg, png, gif, webp)
- File size limits prevent abuse

### Directory Security
- Cache directories include `index.php` files to prevent direct access
- Proper file permissions (755) on cache directories
- MD5 hashing prevents filename conflicts

### Error Handling
- Graceful fallback to remote serving if caching fails
- Comprehensive error logging for debugging
- Timeout protection for remote downloads

## Troubleshooting

### Common Issues

1. **Caching Fails**
   - Check server has write permissions to cache directory
   - Verify remote URL is accessible
   - Check error logs for specific error messages

2. **Images Not Loading**
   - Verify remote URL is valid and accessible
   - Check if image format is supported
   - Ensure proper file permissions

3. **Cache Directory Issues**
   - Verify cache directory exists: `assets/images/products/{branch_code}/cached/`
   - Check directory permissions (755)
   - Ensure `index.php` file exists in cache directory

### Debug Mode
Enable debug logging in `pos/image.php` by adding `?debug=1` to image URLs:
```
image.php?img=https://example.com/image.jpg&debug=1
```

## Future Enhancements

1. **Image Optimization**
   - Automatic image compression
   - WebP format conversion
   - Thumbnail generation

2. **CDN Integration**
   - Support for CDN URLs
   - Automatic CDN cache invalidation
   - Multi-CDN support

3. **Advanced Caching**
   - Cache warming for popular images
   - Predictive caching based on usage patterns
   - Cache sharing between branches

4. **Monitoring**
   - Cache hit/miss statistics
   - Performance metrics
   - Disk usage monitoring 