<?php

?>



<?php

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

<?php

?>
<form method="POST" enctype="multipart/form-data">
    <input type="file" name="productImage" accept="image/jpeg,image/png" required>
    <button type="submit">Upload</button>
</form>

<?php
/**
 * 3. HANDLE UPLOAD
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['productImage'])) {
    $result = uploadProductImage($_FILES['productImage'], 'my_product');
    
    if ($result['success']) {
        $filename = $result['original'];
        // Save $filename to database
    } else {
        echo 'Error: ' . $result['error'];
    }
}
?>

<?php

// Option A: For specific section (predefined size)
echo getImageForSection('product.jpg', 'shop');
// Returns: /ecom/uploads/variants/product_shop.jpg

// Option B: For custom dimensions (dynamic)
echo getImageDynamic('product.jpg', 350, 220);
// Returns: /ecom/image.php?file=product.jpg&w=350&h=220

// Option C: Complete img tag
echo imageTag('product.jpg', 'product', ['alt' => 'My Product', 'class' => 'img-responsive']);
?>

<?php
/**
 * 5. IN HTML TEMPLATES
 */
?>

<!-- Using in product listing -->
<div class="product">
    <img src="<?php echo getImageForSection($product['image'], 'shop'); ?>" alt="Product">
</div>

<!-- Using in featured section -->
<div class="featured">
    <img src="<?php echo getImageForSection($product['image'], 'featured'); ?>" alt="Featured">
</div>

<!-- Using in cart -->
<div class="cart-item">
    <img src="<?php echo getImageForSection($product['image'], 'thumbnail'); ?>" alt="Item">
</div>

<?php
/**
 * 6. DELETE PRODUCT & IMAGES
 */
function deleteProduct($productId) {
    global $products;
    
    // Find and delete product
    foreach ($products as $key => $product) {
        if ($product['id'] === $productId) {
            // Delete image variants
            deleteProductImage($product['image']);
            
            // Remove product
            unset($products[$key]);
            
           
            return true;
        }
    }
    return false;
}
?>

<?php

if (imageExists('product.jpg')) {
    echo getImageForSection('product.jpg', 'shop');
} else {
    echo '<img src="/placeholder.png" alt="No image">';
}
?>

<?php
/**
 * 8. GET IMAGE INFORMATION
 */
$info = getImageInfo('product.jpg');
echo 'Size: ' . $info['width'] . 'x' . $info['height'];
echo 'File size: ' . number_format($info['size'] / 1024, 2) . ' KB';
echo 'Type: ' . $info['mime'];
?>

<?php
/**
 * 9. AVAILABLE SECTIONS
 */
$sections = [
    'home'       => '400×250',   // Homepage cards
    'shop'       => '300×300',   // Shop grid
    'featured'   => '600×400',   // Featured products
    'latest'     => '200×200',   // Latest products
    'product'    => '350×350',   // Product detail
    'thumbnail'  => '150×150',   // Cart, sidebar
    'featured-cat' => '216×269', // Featured category

];

foreach ($sections as $key => $size) {
    echo getImageForSection('product.jpg', $key);
}
?>

<?php

echo getImageDynamic('product.jpg', 500, 350);

?>

<?php

?>
<script>

async function uploadImage(file) {
    const formData = new FormData();
    formData.append('image', file);
    formData.append('name', 'product_name');
    
    const response = await fetch('/ecom/api/api_upload_image.php', {
        method: 'POST',
        body: formData
    });
    
    const result = await response.json();
    
    if (result.success) {
        console.log('Image uploaded:', result.image);
        console.log('URLs:', result.image.urls);
    } else {
        console.error('Upload failed:', result.error);
    }
}
</script>

<?php
/**
 * 12. RESPONSIVE IMAGE WITH SRCSET
 */
?>
<img src="<?php echo getImageForSection('product.jpg', 'shop'); ?>" 
     srcset="<?php echo getImageDynamic('product.jpg', 300, 300); ?> 1x,
             <?php echo getImageDynamic('product.jpg', 600, 600); ?> 2x"
     alt="Product">

<?php
/**
 * 13. LOOP THROUGH PRODUCT ARRAY
 */
foreach ($products as $product) {
    ?>
    <div class="product-card">
        <?php if (!empty($product['image']) && imageExists($product['image'])): ?>
            <img src="<?php echo getImageForSection($product['image'], 'shop'); ?>" 
                 alt="<?php echo htmlspecialchars($product['title']); ?>">
        <?php else: ?>
            <img src="/placeholder.png" alt="No image">
        <?php endif; ?>
        
        <h3><?php echo htmlspecialchars($product['title']); ?></h3>
        <p>$<?php echo htmlspecialchars($product['price']); ?></p>
    </div>
    <?php
}
?>

<?php
/**
 * 14. VALIDATION IN FORM
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate required fields
    if (empty($_POST['title']) || empty($_POST['price'])) {
        $error = 'Title and Price required';
    } else if (!isset($_FILES['image']) || $_FILES['image']['error'] !== UPLOAD_ERR_OK) {
        $error = 'Image upload failed';
    } else {
        // Upload image
        $result = uploadProductImage($_FILES['image'], $_POST['title']);
        
        if (!$result['success']) {
            $error = 'Image error: ' . $result['error'];
        } else {
            // Create product
            $product = [
                'id' => uniqid('prod_'),
                'title' => $_POST['title'],
                'price' => $_POST['price'],
                'image' => $result['original'],
            ];
            // Save product...
        }
    }
}
?>

<?php

$deleted = cleanupOldVariants(90);
echo "Deleted $deleted old image files";
?>



<?php

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $price = trim($_POST['price'] ?? '');
    $errors = [];
    
    // Validate
    if (empty($title)) $errors[] = 'Title required';
    if (empty($price)) $errors[] = 'Price required';
    
    $imageFilename = '';
    
    // Upload image if provided
    if (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $result = uploadProductImage($_FILES['image'], $title);
        if ($result['success']) {
            $imageFilename = $result['original'];
        } else {
            $errors[] = 'Image: ' . $result['error'];
        }
    }
    
    // If no errors, save product
    if (empty($errors)) {
        $product = [
            'id' => 'prod_' . uniqid(),
            'title' => $title,
            'price' => (float)$price,
            'image' => $imageFilename,
        ];
        
        // Save to products.json
        $products = json_decode(file_get_contents('data/products.json'), true) ?: [];
        $products[] = $product;
        file_put_contents('data/products.json', json_encode($products, JSON_PRETTY_PRINT));
        
        header('Location: admin_dashboard.php');
        exit;
    }
}
?>
<form method="POST" enctype="multipart/form-data">
    <?php if (!empty($errors)): ?>
        <div class="error-list">
            <?php foreach ($errors as $error): ?>
                <p><?php echo htmlspecialchars($error); ?></p>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
    
    <input type="text" name="title" placeholder="Product Title" required>
    <input type="number" name="price" step="0.01" placeholder="Price" required>
    <input type="file" name="image" accept="image/jpeg,image/png">
    <button type="submit">Add Product</button>
</form>

<!-- ======================================
     COMMON ISSUES & SOLUTIONS
     ====================================== -->

<?php
/**
 * Issue 1: Image not showing
 * Solution: Check file exists
 */
if (!file_exists('/uploads/original/product.jpg')) {
    echo 'Original image not found';
}

/**
 * Issue 2: Variant not generated
 * Solution: Check directory permissions
 */
if (!is_writable('/uploads/variants')) {
    echo 'Variants directory not writable';
}

/**
 * Issue 3: GD not available
 * Solution: Check PHP extension
 */
if (!extension_loaded('gd')) {
    die('GD Library required - enable in php.ini');
}

/**
 * Issue 4: Image shows 404
 * Solution: Verify image was actually uploaded
 */
if (!imageExists('product.jpg')) {
    echo 'Use placeholder image';
}
?>

<!-- ======================================
     TESTING
     ====================================== -->

<?php
/**
 * Visit this URL to test the system:
 * http://localhost/ecom/test_imagehandler.php
 * 
 * Test includes:
 * - System diagnostics
 * - Upload test images
 * - View generated variants
 * - Check API endpoints
 */
?>

<!-- ======================================
     KEY POINTS
     ====================================== -->

<?php
/*
1. ALWAYS include config file first:
   require_once __DIR__ . '/config/image_config.php';

2. STORE only filename in database:
   $product['image'] = 'product.jpg';  ✓ Correct
   $product['image'] = '/uploads/...'; ✗ Wrong

3. USE helper functions for URLs:
   getImageForSection()     ✓ Correct
   hardcoded paths          ✗ Wrong

4. NEVER delete images manually:
   deleteProductImage()     ✓ Correct
   unlink()                 ✗ Wrong

5. SUPPORT fallback images:
   if (imageExists(...)) { ... } else { placeholder }

6. RUN maintenance monthly:
   cleanupOldVariants(90);

7. TEST everything:
   Visit /test_imagehandler.php before production
*/
?>
