<?php
/**
 * Image Configuration and Helper Functions - SIMPLIFIED VERSION
 * 
 * NEW PHILOSOPHY:
 * - Upload: Simple file upload to /uploads
 * - Display: Return image URL only
 * - Sizing: All sizing handled by CSS with object-fit: cover
 * - No variants, no caching, no resizing
 */

// Initialize ImageHandler singleton
$GLOBALS['imageHandler'] = null;

/**
 * Detect web base path that works on both localhost (/emporio-sport)
 * and cPanel root (/).
 *
 * @return string Base path prefix starting with "" or "/emporio-sport"
 */
function getWebBasePath() {
    static $basePath = null;
    if ($basePath !== null) {
        return $basePath;
    }

    $scriptName = $_SERVER['SCRIPT_NAME'] ?? '';
    // If project is in /emporio-sport on localhost, keep that segment as base
    if (strpos($scriptName, '/emporio-sport/') === 0 || $scriptName === '/emporio-sport' || $scriptName === '/emporio-sport/index.php') {
        $basePath = '/emporio-sport';
    } else {
        // On cPanel the site will usually be at domain root
        $basePath = '';
    }

    return $basePath;
}

/**
 * Get ImageHandler instance
 * 
 * @return ImageHandler
 */
function getImageHandler() {
    if ($GLOBALS['imageHandler'] === null) {
        require_once __DIR__ . '/../classes/ImageHandler.php';
        $GLOBALS['imageHandler'] = new ImageHandler(__DIR__ . '/../uploads');
    }
    return $GLOBALS['imageHandler'];
}

/**
 * Get image URL for display
 * SIMPLIFIED: Just returns the image URL - CSS handles all sizing
 * 
 * @param string $filename Original filename
 * @param string $section Section name (optional, kept for backward compatibility but not used)
 * @return string Image URL
 */
function getImageForSection($filename, $section = 'product') {
    // Handle empty or null
    if (empty($filename)) {
        return getWebBasePath() . '/pics_ecom/placeholder.png';
    }
    
    // Handle base64 (display as-is)
    if (strpos($filename, 'data:image') === 0) {
        return $filename;
    }
    
    // Handle full URLs
    if (strpos($filename, 'http') === 0) {
        return $filename;
    }
    
    // Remove leading slashes
    $filename = ltrim($filename, '/');
    
  // For sport-pics paths, always serve from project root (works on localhost + cPanel)
    if (strpos($filename, 'sport-pics/') === 0) {
        return getWebBasePath() . '/' . $filename;
    }
    
  // Normalize any legacy "ecoms/" prefixes from older data
  if (strpos($filename, 'ecoms/') === 0) {
        $filename = substr($filename, strlen('ecoms/'));
  }
  
  // For paths that already have 'pics_ecom' in them, attach correct base path
    if (strpos($filename, 'pics_ecom/') === 0) {
        return getWebBasePath() . '/' . $filename;
    }
    
  // For simple filenames without folder, assume pics_ecom location under project root
  return getWebBasePath() . '/pics_ecom/' . $filename;
}

/**
 * Get carousel image URL - Works on both localhost and cPanel
 * Automatically adds /ecoms/ prefix if needed
 * 
 * @param string $imagePath The image path from carousel.json or database
 * @return string Usable image URL
 */
function getCarouselImageUrl($imagePath) {
    if (empty($imagePath)) {
        return getWebBasePath() . '/pics_ecom/placeholder.png';
    }
    
    // If it's a full URL, return as-is
    if (strpos($imagePath, 'http') === 0) {
        return $imagePath;
    }
    
    // If it's base64, return as-is
    if (strpos($imagePath, 'data:image') === 0) {
        return $imagePath;
    }
    
    $imagePath = ltrim($imagePath, '/');

  // Strip legacy "ecoms/" prefix if present
  if (strpos($imagePath, 'ecoms/') === 0) {
        $imagePath = substr($imagePath, strlen('ecoms/'));
  }

  // If path already starts with sport-pics or pics_ecom or uploads, just prepend base path
  if (strpos($imagePath, 'sport-pics/') === 0 ||
        strpos($imagePath, 'pics_ecom/') === 0 ||
        strpos($imagePath, 'uploads/') === 0) {
        return getWebBasePath() . '/' . $imagePath;
  }

  // Fallback: treat it as relative to project root
  return getWebBasePath() . '/' . $imagePath;
}

/**
 * Upload product image
 * SIMPLIFIED: No variant generation, just stores original
 * 
 * @param array $file File from $_FILES
 * @param string $customName Custom filename (optional)
 * @return array Result array with success status and image details
 */
function uploadProductImage($file, $customName = '') {
    $handler = getImageHandler();
    return $handler->uploadImage($file, $customName);
}

/**
 * Delete product image
 * SIMPLIFIED: No variants to delete, just the original
 * 
 * @param string $filename Original filename
 * @return bool Success status
 */
function deleteProductImage($filename) {
    $handler = getImageHandler();
    return $handler->deleteImage($filename);
}

/**
 * Check if image file exists
 * 
 * @param string $filename Original filename
 * @return bool True if image exists
 */
function imageExists($filename) {
    $handler = getImageHandler();
    return $handler->imageExists($filename);
}

/**
 * Get image information (dimensions, size, mime type)
 * 
 * @param string $filename Original filename
 * @return array|false Image info array or false if not found
 */
function getImageInfo($filename) {
    $handler = getImageHandler();
    $uploadDir = $handler->getUploadDir();
    $path = $uploadDir . '/' . basename($filename);
    
    if (!file_exists($path)) {
        return false;
    }
    
    $info = @getimagesize($path);
    if (!$info) {
        return false;
    }
    
    return [
        'width' => $info[0],
        'height' => $info[1],
        'type' => $info[2],
        'size' => filesize($path),
        'mime' => $info['mime'] ?? 'unknown',
        'updated' => filemtime($path)
    ];
}

/**
 * Generate simple img tag
 * Let CSS handle all styling and sizing
 * 
 * @param string $filename Original filename
 * @param array $attrs Additional HTML attributes (alt, class, id, etc.)
 * @return string Simple img HTML tag
 */
function imageTag($filename, $attrs = []) {
    if (!imageExists($filename)) {
        return '<img src="/ecom/pics_ecom/placeholder.png" alt="Image not found" />';
    }
    
    $src = getImageForSection($filename);
    $alt = isset($attrs['alt']) ? htmlspecialchars($attrs['alt']) : 'Product image';
    $class = isset($attrs['class']) ? htmlspecialchars($attrs['class']) : '';
    $id = isset($attrs['id']) ? htmlspecialchars($attrs['id']) : '';
    
    $classAttr = !empty($class) ? " class=\"{$class}\"" : '';
    $idAttr = !empty($id) ? " id=\"{$id}\"" : '';
    
    return "<img src=\"{$src}\" alt=\"{$alt}\"{$classAttr}{$idAttr} />";
}
?>
