<?php
/**
 * Product Image Manager - Manages product images from sport-pics folder
 * Allows admins to easily update product images
 */

class ProductImageManager {
    private $sportPicsFolder = __DIR__ . '/../sport-pics';
    private $defaultImages = [
        'logo' => 'logo-1.png',
        'placeholder' => 'logo-1.png'
    ];
    
    /**
     * Get all available images from sport-pics folder
     */
    public function getAllImages() {
        $images = [];
        
        if (is_dir($this->sportPicsFolder)) {
            $files = scandir($this->sportPicsFolder);
            
            foreach ($files as $file) {
                if ($file !== '.' && $file !== '..') {
                    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                    if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp'])) {
                        $images[] = [
                            'name' => $file,
                            'path' => '/sport-pics/' . $file,
                            'size' => filesize($this->sportPicsFolder . '/' . $file),
                            'type' => mime_content_type($this->sportPicsFolder . '/' . $file)
                        ];
                    }
                }
            }
        }
        
        usort($images, function($a, $b) {
            return strcmp($a['name'], $b['name']);
        });
        
        return $images;
    }
    
    /**
     * Get image path for a product
     */
    public function getProductImage($imageName) {
        if (empty($imageName)) {
            return '/sport-pics/' . $this->defaultImages['placeholder'];
        }
        
        $imagePath = $this->sportPicsFolder . '/' . basename($imageName);
        
        if (file_exists($imagePath)) {
            return '/sport-pics/' . basename($imageName);
        }
        
        return '/sport-pics/' . $this->defaultImages['placeholder'];
    }
    
    /**
     * Get logo path
     */
    public function getLogo() {
        return '/sport-pics/' . $this->defaultImages['logo'];
    }
    
    /**
     * Check if image exists
     */
    public function imageExists($imageName) {
        return file_exists($this->sportPicsFolder . '/' . basename($imageName));
    }
    
    /**
     * Get image URL with proper domain detection
     */
    public function getImageUrl($imageName, $includeHost = false) {
        $imagePath = $this->getProductImage($imageName);
        
        if ($includeHost) {
            $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'http://';
            $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
            return $protocol . $host . $imagePath;
        }
        
        return $imagePath;
    }
    
    /**
     * Get image info
     */
    public function getImageInfo($imageName) {
        $imagePath = $this->sportPicsFolder . '/' . basename($imageName);
        
        if (!file_exists($imagePath)) {
            return null;
        }
        
        $imageSize = getimagesize($imagePath);
        
        return [
            'name' => basename($imageName),
            'path' => '/sport-pics/' . basename($imageName),
            'width' => $imageSize[0] ?? 0,
            'height' => $imageSize[1] ?? 0,
            'size' => filesize($imagePath),
            'modified' => filemtime($imagePath)
        ];
    }
    
    /**
     * Get responsive image HTML
     */
    public function renderImage($imageName, $alt = 'Product Image', $classes = '', $lazy = true) {
        $imagePath = $this->getProductImage($imageName);
        
        $lazyAttr = $lazy ? 'loading="lazy"' : '';
        
        return sprintf(
            '<img src="%s" alt="%s" class="%s" %s>',
            htmlspecialchars($imagePath),
            htmlspecialchars($alt),
            htmlspecialchars($classes),
            $lazyAttr
        );
    }
    
    /**
     * Get image gallery HTML for admin
     */
    public function renderGallery($selectedImage = '') {
        $images = $this->getAllImages();
        
        $html = '<div class="image-gallery" style="display:grid; grid-template-columns:repeat(auto-fill, minmax(120px, 1fr)); gap:10px; padding:10px; background:#f5f5f5; border-radius:8px;">';
        
        foreach ($images as $image) {
            $selected = ($image['name'] === $selectedImage) ? 'style="border:3px solid #F07E2D;"' : '';
            $html .= sprintf(
                '<div class="image-item" %s style="cursor:pointer; border:2px solid #ddd; padding:5px; border-radius:4px; text-align:center;">
                    <img src="%s" alt="%s" style="max-width:100%; max-height:100px; object-fit:contain;">
                    <p style="font-size:10px; margin:5px 0 0; word-break:break-word;">%s</p>
                </div>',
                $selected,
                htmlspecialchars($image['path']),
                htmlspecialchars($image['name']),
                htmlspecialchars($image['name'])
            );
        }
        
        $html .= '</div>';
        
        return $html;
    }
}

// Create global instance
$productImageManager = new ProductImageManager();
?>
