<?php
/**
 * PRACTICAL EXAMPLE: Updated Admin Product Upload Handler
 * 
 * This file shows how to update your admin_add_product.php 
 * to use the new ImageHandler system
 * 
 * Copy the relevant sections to your admin_add_product.php
 */

// ==========================================
// AT THE TOP OF YOUR admin_add_product.php
// ==========================================

/*
session_start();

// NEW: Include ImageHandler config
require_once __DIR__ . '/config/image_config.php';
require_once __DIR__ . '/db_config.php';

// ... rest of your existing code
*/

// ==========================================
// IN YOUR FORM HANDLER SECTION
// ==========================================

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
    // Get form data
    $productTitle = trim($_POST['title'] ?? '');
    $productPrice = trim($_POST['price'] ?? '');
    $productDescription = trim($_POST['description'] ?? '');
    $productCategory = trim($_POST['category'] ?? '');
    
    // Validation
    if (empty($productTitle) || empty($productPrice)) {
        $_SESSION['error'] = 'Title and Price are required';
        header('Location: admin_add_product.php');
        exit;
    }
    
    // ============ NEW: Image Upload with Variants ============
    $imageFilename = '';
    
    if (isset($_FILES['productImage']) && $_FILES['productImage']['error'] === UPLOAD_ERR_OK) {
        // Upload and generate variants
        $uploadResult = uploadProductImage($_FILES['productImage'], $productTitle);
        
        if (!$uploadResult['success']) {
            $_SESSION['error'] = 'Image upload failed: ' . $uploadResult['error'];
            header('Location: admin_add_product.php');
            exit;
        }
        
        $imageFilename = $uploadResult['original'];
        
        // Optional: Log generated variants
        error_log('Product ' . $productTitle . ' - Generated variants: ' . implode(', ', array_keys($uploadResult['variants'])));
    }
    
    // =========== Create Product Array ===========
    $product = [
        'id' => 'prod_' . uniqid(),
        'title' => $productTitle,
        'price' => (float)$productPrice,
        'description' => $productDescription,
        'category' => $productCategory,
        'image' => $imageFilename,  // ← Just store the filename
        'featured' => isset($_POST['featured']) ? true : false,
        'colors' => [],  // Will be added via color management
        'created' => date('Y-m-d H:i:s'),
        'updated' => date('Y-m-d H:i:s')
    ];
    
    // =========== Save to Database ===========
    $productsFile = __DIR__ . '/data/products.json';
    $products = [];
    
    if (file_exists($productsFile)) {
        $products = json_decode(file_get_contents($productsFile), true) ?: [];
    }
    
    $products[] = $product;
    
    if (file_put_contents($productsFile, json_encode($products, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))) {
        $_SESSION['success'] = 'Product added successfully!';
        header('Location: admin_dashboard.php');
        exit;
    } else {
        $_SESSION['error'] = 'Failed to save product';
    }
}

// ==========================================
// IN YOUR HTML FORM (if not using AJAX)
// ==========================================

?>
<form method="POST" enctype="multipart/form-data">
    
    <div class="form-group">
        <label>Product Title *</label>
        <input type="text" name="title" required>
    </div>
    
    <div class="form-group">
        <label>Price *</label>
        <input type="number" name="price" step="0.01" required>
    </div>
    
    <div class="form-group">
        <label>Description</label>
        <textarea name="description" rows="4"></textarea>
    </div>
    
    <div class="form-group">
        <label>Category</label>
        <select name="category">
            <option value="">Select Category</option>
            <option value="clothing">Clothing</option>
            <option value="shoes">Shoes</option>
            <option value="accessories">Accessories</option>
        </select>
    </div>
    
    <!-- NEW: Image Upload -->
    <div class="form-group">
        <label>Product Image</label>
        <input type="file" name="productImage" accept="image/jpeg,image/png">
        <small>JPG or PNG, max 5MB. All variants will be generated automatically.</small>
    </div>
    
    <div class="form-group">
        <label>
            <input type="checkbox" name="featured">
            Featured Product
        </label>
    </div>
    
    <button type="submit" class="btn btn-primary">Add Product</button>
</form>

<?php

// ==========================================
// IN YOUR PRODUCT LISTING (admin_products.php)
// ==========================================

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

foreach ($products as $product) {
    ?>
    <div class="product-row">
        <div class="product-image">
            <?php if (!empty($product['image']) && imageExists($product['image'])): ?>
                <img src="<?php echo getImageForSection($product['image'], 'thumbnail'); ?>" 
                     alt="<?php echo htmlspecialchars($product['title']); ?>">
            <?php else: ?>
                <img src="/ecom/pics_ecom/placeholder.png" alt="No image">
            <?php endif; ?>
        </div>
        <div class="product-info">
            <h3><?php echo htmlspecialchars($product['title']); ?></h3>
            <p>$<?php echo htmlspecialchars($product['price']); ?></p>
        </div>
        <div class="product-actions">
            <a href="admin_edit_product.php?id=<?php echo $product['id']; ?>" class="btn btn-sm">Edit</a>
            <a href="admin_delete_product.php?id=<?php echo $product['id']; ?>" class="btn btn-sm btn-danger">Delete</a>
        </div>
    </div>
    <?php
}
*/

// ==========================================
// IN YOUR DELETE HANDLER (admin_delete_product.php)
// ==========================================

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

$productId = $_GET['id'] ?? '';

// Load products
$productsFile = __DIR__ . '/data/products.json';
$products = json_decode(file_get_contents($productsFile), true) ?: [];

// Find and delete product
foreach ($products as $key => $product) {
    if ($product['id'] === $productId) {
        // NEW: Delete associated images and variants
        if (!empty($product['image'])) {
            deleteProductImage($product['image']);
        }
        
        // Remove product
        unset($products[$key]);
        break;
    }
}

// Save updated list
file_put_contents($productsFile, json_encode($products, JSON_PRETTY_PRINT));

$_SESSION['success'] = 'Product deleted';
header('Location: admin_products.php');
*/

// ==========================================
// IN YOUR FRONTEND SHOP PAGE (shop.php)
// ==========================================

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

foreach ($products as $product) {
    ?>
    <div class="product-card">
        <div class="product-image">
            <?php if (!empty($product['image']) && imageExists($product['image'])): ?>
                <img src="<?php echo getImageForSection($product['image'], 'shop'); ?>" 
                     alt="<?php echo htmlspecialchars($product['title']); ?>"
                     loading="lazy">
            <?php else: ?>
                <img src="/ecom/pics_ecom/placeholder.png" alt="Product">
            <?php endif; ?>
        </div>
        <h3><?php echo htmlspecialchars($product['title']); ?></h3>
        <p class="price">$<?php echo htmlspecialchars($product['price']); ?></p>
        <a href="product.php?id=<?php echo $product['id']; ?>" class="btn">View Details</a>
    </div>
    <?php
}
*/

// ==========================================
// IN FEATURED PRODUCTS (index.php)
// ==========================================

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

foreach ($featuredProducts as $product) {
    ?>
    <div class="featured-product-card">
        <?php if (!empty($product['image']) && imageExists($product['image'])): ?>
            <img src="<?php echo getImageForSection($product['image'], 'featured'); ?>" 
                 alt="<?php echo htmlspecialchars($product['title']); ?>"
                 loading="lazy">
        <?php else: ?>
            <img src="/ecom/pics_ecom/placeholder.png" alt="Product">
        <?php endif; ?>
        <h3><?php echo htmlspecialchars($product['title']); ?></h3>
    </div>
    <?php
}
*/

// ==========================================
// KEY CHANGES SUMMARY
// ==========================================

/*
1. ADD AT TOP:
   require_once __DIR__ . '/config/image_config.php';

2. WHEN UPLOADING:
   $result = uploadProductImage($_FILES['productImage'], $productTitle);
   $imageFilename = $result['original'];

3. WHEN DISPLAYING:
   <img src="<?php echo getImageForSection($product['image'], 'shop'); ?>" alt="">

4. WHEN DELETING:
   deleteProductImage($product['image']);

5. SUPPORTS CUSTOM SIZES:
   echo getImageDynamic('product.jpg', 350, 220);

That's it! Images are automatically optimized for different card sizes.
*/

?>
