<?php
/**
 * ImageHandler Test & Demo Script
 * 
 * This script demonstrates all features of the ImageHandler class
 * Run via: http://localhost/ecom/test_imagehandler.php
 */

require_once __DIR__ . '/config/image_config.php';

$action = isset($_GET['action']) ? $_GET['action'] : 'info';
?>
<!DOCTYPE html>
<html>
<head>
    <title>ImageHandler Test & Demo</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; }
        h1 { color: #333; }
        .section { margin: 30px 0; padding: 20px; border: 1px solid #ddd; border-radius: 4px; }
        .section h2 { margin-top: 0; color: #555; }
        .code-block { background: #f0f0f0; padding: 15px; border-radius: 4px; font-family: monospace; overflow-x: auto; margin: 10px 0; }
        .btn { display: inline-block; padding: 10px 20px; background: #667eea; color: white; text-decoration: none; border-radius: 4px; border: none; cursor: pointer; margin: 5px 5px 5px 0; }
        .btn:hover { background: #5568d3; }
        .btn.secondary { background: #999; }
        .btn.secondary:hover { background: #777; }
        .success { color: #28a745; }
        .error { color: #dc3545; }
        .info { background: #e7f3ff; padding: 10px; border-left: 4px solid #2196F3; margin: 10px 0; }
        table { width: 100%; border-collapse: collapse; margin: 15px 0; }
        th, td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }
        th { background: #f5f5f5; font-weight: bold; }
        .form-group { margin: 15px 0; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input[type="text"], input[type="file"], select { width: 100%; padding: 8px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; }
        .image-preview { max-width: 300px; margin: 10px 0; border: 1px solid #ddd; border-radius: 4px; }
        .variants-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 20px; margin: 20px 0; }
        .variant-card { border: 1px solid #ddd; border-radius: 4px; padding: 10px; text-align: center; }
        .variant-card img { max-width: 100%; height: auto; margin: 10px 0; }
    </style>
</head>
<body>

<div class="container">
    <h1>🖼️ ImageHandler Test & Demo</h1>
    <p>This page demonstrates the ImageHandler class for managing product images.</p>
    
    <!-- Navigation -->
    <div style="margin-bottom: 20px;">
        <a href="?action=info" class="btn <?php echo $action === 'info' ? 'secondary' : ''; ?>">System Info</a>
        <a href="?action=upload" class="btn <?php echo $action === 'upload' ? 'secondary' : ''; ?>">Upload Image</a>
        <a href="?action=variants" class="btn <?php echo $action === 'variants' ? 'secondary' : ''; ?>">View Variants</a>
        <a href="?action=api" class="btn <?php echo $action === 'api' ? 'secondary' : ''; ?>">API Docs</a>
    </div>
    
    <?php if ($action === 'info'): ?>
    
    <!-- System Information -->
    <div class="section">
        <h2>System Information</h2>
        
        <?php
        $handler = getImageHandler();
        $dirs = $handler->getDirectories();
        ?>
        
        <h3>Directories</h3>
        <table>
            <tr>
                <th>Type</th>
                <th>Path</th>
                <th>Exists</th>
                <th>Writable</th>
            </tr>
            <tr>
                <td>Original</td>
                <td><code><?php echo htmlspecialchars($dirs['original']); ?></code></td>
                <td><?php echo is_dir($dirs['original']) ? '<span class="success">✓</span>' : '<span class="error">✗</span>'; ?></td>
                <td><?php echo is_writable($dirs['original']) ? '<span class="success">✓</span>' : '<span class="error">✗</span>'; ?></td>
            </tr>
            <tr>
                <td>Variants</td>
                <td><code><?php echo htmlspecialchars($dirs['variants']); ?></code></td>
                <td><?php echo is_dir($dirs['variants']) ? '<span class="success">✓</span>' : '<span class="error">✗</span>'; ?></td>
                <td><?php echo is_writable($dirs['variants']) ? '<span class="success">✓</span>' : '<span class="error">✗</span>'; ?></td>
            </tr>
        </table>
        
        <h3>GD Library Status</h3>
        <p>
            <?php
            if (extension_loaded('gd')) {
                echo '<span class="success">✓ GD Library is installed</span>';
                echo '<br>Supported formats: ';
                $formats = [];
                if (function_exists('imagecreatefromjpeg')) $formats[] = 'JPEG';
                if (function_exists('imagecreatefrompng')) $formats[] = 'PNG';
                echo implode(', ', $formats);
            } else {
                echo '<span class="error">✗ GD Library is NOT installed</span>';
                echo '<br>Please enable GD extension in your PHP configuration.';
            }
            ?>
        </p>
        
        <h3>Available Variants</h3>
        <table>
            <tr>
                <th>Key</th>
                <th>Name</th>
                <th>Dimensions</th>
            </tr>
            <?php foreach ($handler->variants as $key => $variant): ?>
            <tr>
                <td><code><?php echo htmlspecialchars($key); ?></code></td>
                <td><?php echo htmlspecialchars($variant['name']); ?></td>
                <td><?php echo $variant['width']; ?>×<?php echo $variant['height']; ?>px</td>
            </tr>
            <?php endforeach; ?>
        </table>
        
        <h3>Usage Examples</h3>
        <div class="info">
            <strong>Basic Setup:</strong>
            <div class="code-block">require_once __DIR__ . '/config/image_config.php';</div>
        </div>
        
        <div class="info">
            <strong>Display Image with Variant:</strong>
            <div class="code-block">&lt;img src="&lt;?php echo getImageForSection('product.jpg', 'shop'); ?&gt;" alt="Product"&gt;</div>
        </div>
        
        <div class="info">
            <strong>Dynamic Resize (Custom Size):</strong>
            <div class="code-block">getImageDynamic('product.jpg', 350, 220)</div>
        </div>
    </div>
    
    <?php elseif ($action === 'upload'): ?>
    
    <!-- Upload Form -->
    <div class="section">
        <h2>Upload Product Image</h2>
        
        <?php
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['image'])) {
            $result = uploadProductImage($_FILES['image'], $_POST['name'] ?? '');
            
            if ($result['success']) {
                echo '<div class="info" style="background: #d4edda; color: #155724; border-left-color: #28a745;">';
                echo '<strong>✓ Upload Successful!</strong><br>';
                echo 'Filename: ' . htmlspecialchars($result['original']) . '<br>';
                echo 'Variants Generated: ' . count($result['variants']) . '<br>';
                echo '</div>';
                
                echo '<div class="section" style="background: #f9f9f9;">';
                echo '<h3>Preview Variants</h3>';
                echo '<div class="variants-grid">';
                
                foreach ($result['variants'] as $key => $variant) {
                    $url = getImageForSection($result['original'], $key);
                    echo '<div class="variant-card">';
                    echo '<strong>' . htmlspecialchars($key) . '</strong>';
                    echo '<img src="' . htmlspecialchars($url) . '" alt="' . htmlspecialchars($key) . '">';
                    echo '</div>';
                }
                
                echo '</div>';
                echo '</div>';
            } else {
                echo '<div class="info" style="background: #f8d7da; color: #721c24; border-left-color: #dc3545;">';
                echo '<strong>✗ Upload Failed</strong><br>';
                echo htmlspecialchars($result['error']);
                echo '</div>';
            }
        }
        ?>
        
        <form method="POST" enctype="multipart/form-data">
            <div class="form-group">
                <label>Image File (JPG or PNG)</label>
                <input type="file" name="image" accept="image/jpeg,image/png" required>
            </div>
            
            <div class="form-group">
                <label>Custom Name (Optional)</label>
                <input type="text" name="name" placeholder="e.g., summer_dress">
            </div>
            
            <button type="submit" class="btn">Upload Image</button>
        </form>
        
        <div class="info">
            <strong>Max File Size:</strong> 5MB<br>
            <strong>Supported Formats:</strong> JPG, PNG<br>
            <strong>Note:</strong> All variants will be generated automatically
        </div>
    </div>
    
    <?php elseif ($action === 'variants'): ?>
    
    <!-- View Existing Variants -->
    <div class="section">
        <h2>Image Variants</h2>
        
        <?php
        $handler = getImageHandler();
        $dirs = $handler->getDirectories();
        $originalFiles = @glob($dirs['original'] . '/*');
        
        if (empty($originalFiles)) {
            echo '<p>No images found. <a href="?action=upload">Upload an image first</a>.</p>';
        } else {
            echo '<p>Found ' . count($originalFiles) . ' image(s)</p>';
            
            foreach ($originalFiles as $originalPath) {
                $filename = basename($originalPath);
                $info = getImageInfo($filename);
                
                if ($info) {
                    echo '<div style="margin: 30px 0; padding: 20px; border: 1px solid #ddd; border-radius: 4px; background: #fafafa;">';
                    echo '<h3>' . htmlspecialchars($filename) . '</h3>';
                    
                    echo '<table>';
                    echo '<tr><th>Property</th><th>Value</th></tr>';
                    echo '<tr><td>Dimensions</td><td>' . $info['width'] . '×' . $info['height'] . 'px</td></tr>';
                    echo '<tr><td>File Size</td><td>' . number_format($info['size'] / 1024, 2) . ' KB</td></tr>';
                    echo '<tr><td>MIME Type</td><td>' . htmlspecialchars($info['mime']) . '</td></tr>';
                    echo '<tr><td>Last Updated</td><td>' . date('Y-m-d H:i:s', $info['updated']) . '</td></tr>';
                    echo '</table>';
                    
                    echo '<h4>Variants</h4>';
                    echo '<div class="variants-grid">';
                    
                    foreach ($handler->variants as $key => $variant) {
                        $url = getImageForSection($filename, $key);
                        if ($url) {
                            echo '<div class="variant-card">';
                            echo '<strong>' . htmlspecialchars($key) . '</strong><br>';
                            echo '(' . $variant['width'] . '×' . $variant['height'] . ')<br>';
                            echo '<img src="' . htmlspecialchars($url) . '" alt="' . htmlspecialchars($key) . '">';
                            echo '<br><small><code>' . htmlspecialchars($url) . '</code></small>';
                            echo '</div>';
                        }
                    }
                    
                    echo '</div>';
                    
                    echo '<h4>Dynamic URLs</h4>';
                    echo '<div style="background: #f0f0f0; padding: 10px; border-radius: 4px; margin: 10px 0;">';
                    echo '<code>' . htmlspecialchars(getImageDynamic($filename, 350, 220)) . '</code><br>';
                    echo '<small>This dynamically resizes to 350×220</small>';
                    echo '</div>';
                    
                    echo '</div>';
                }
            }
        }
        ?>
    </div>
    
    <?php elseif ($action === 'api'): ?>
    
    <!-- API Documentation -->
    <div class="section">
        <h2>API Documentation</h2>
        
        <h3>Helper Functions</h3>
        
        <h4>getImageForSection($filename, $section)</h4>
        <p>Get image URL for a specific section with predefined dimensions.</p>
        <div class="code-block">
$url = getImageForSection('product.jpg', 'shop');
// Returns: /ecom/uploads/variants/product_shop.jpg
        </div>
        <table>
            <tr>
                <th>Section</th>
                <th>Dimensions</th>
            </tr>
            <?php
            $handler = getImageHandler();
            foreach ($handler->variants as $key => $v) {
                echo '<tr><td>' . htmlspecialchars($key) . '</td><td>' . $v['width'] . '×' . $v['height'] . '</td></tr>';
            }
            ?>
        </table>
        
        <h4>getImageDynamic($filename, $width, $height)</h4>
        <p>Get dynamic image URL for custom dimensions (cached).</p>
        <div class="code-block">
$url = getImageDynamic('product.jpg', 350, 220);
// Returns: /ecom/image.php?file=product.jpg&w=350&h=220
        </div>
        
        <h4>uploadProductImage($file, $customName)</h4>
        <p>Upload image from $_FILES and generate all variants.</p>
        <div class="code-block">
$result = uploadProductImage($_FILES['image'], 'product_name');
if ($result['success']) {
    $filename = $result['original'];
    $variants = $result['variants'];
}
        </div>
        
        <h4>deleteProductImage($filename)</h4>
        <p>Delete image and all its variants.</p>
        <div class="code-block">
deleteProductImage('product.jpg');
        </div>
        
        <h4>getImageInfo($filename)</h4>
        <p>Get image information (dimensions, size, MIME type, etc.).</p>
        <div class="code-block">
$info = getImageInfo('product.jpg');
// Returns: ['width' => 800, 'height' => 600, 'size' => 102400, ...]
        </div>
        
        <h4>imageExists($filename)</h4>
        <p>Check if image file exists.</p>
        <div class="code-block">
if (imageExists('product.jpg')) {
    echo 'Image found!';
}
        </div>
    </div>
    
    <?php endif; ?>
    
</div>

</body>
</html>
