<?php
/**
 * ImageHandler Class - SIMPLIFIED VERSION
 * Manages product image uploads ONLY
 * 
 * DESIGN PHILOSOPHY:
 * - PHP handles ONLY file upload and storage
 * - NO image variant generation
 * - NO image resizing (this is CSS responsibility)
 * - Store original image paths in database
 * - Frontend (CSS) handles all image display and sizing
 * 
 * This approach gives maximum flexibility:
 * - Upload any image resolution
 * - Reuse same image everywhere
 * - CSS controls appearance for each use case
 * - No server processing overhead
 * - Professional results like Amazon/Shopify
 */

class ImageHandler {
    
    // Configuration
    private $uploadDir = '';
    private $allowedFormats = ['jpg', 'jpeg', 'png'];
    private $maxFileSize = 5242880; // 5MB
    
    /**
     * Constructor - Initialize upload directory
     */
    public function __construct($baseUploadDir = '') {
        $this->uploadDir = !empty($baseUploadDir) ? $baseUploadDir : __DIR__ . '/../uploads';
        $this->createDirectories();
    }
    
    /**
     * Create upload directory if needed
     */
    private function createDirectories() {
        if (!is_dir($this->uploadDir)) {
            @mkdir($this->uploadDir, 0755, true);
        }
    }
    
    /**
     * Upload image file and store original
     * 
     * @param array $file File from $_FILES array
     * @param string $filename Custom filename (without extension)
     * @return array|false Returns ['success' => true, 'filename' => 'name.jpg'] or error array
     */
    public function uploadImage($file, $filename = '') {
        // Validate file upload
        if (!isset($file['tmp_name']) || !isset($file['name'])) {
            return $this->error("Invalid file upload");
        }
        
        // Check file size
        if ($file['size'] > $this->maxFileSize) {
            return $this->error("File size exceeds 5MB limit");
        }
        
        // Get file extension
        $ext = $this->getFileExtension($file['name']);
        if (!$ext) {
            return $this->error("Invalid file format. Only JPG and PNG allowed");
        }
        
        // Validate image
        if (!$this->isValidImage($file['tmp_name'])) {
            return $this->error("File is not a valid image");
        }
        
        // Generate filename if not provided
        if (empty($filename)) {
            $filename = 'product_' . time() . '_' . rand(1000, 9999);
        }
        
        // Clean filename
        $filename = $this->cleanFilename($filename);
        $fullFilename = $filename . '.' . $ext;
        
        // Save image to uploads directory
        $destinationPath = $this->uploadDir . '/' . $fullFilename;
        
        if (!move_uploaded_file($file['tmp_name'], $destinationPath)) {
            return $this->error("Failed to save image");
        }
        
        return [
            'success' => true,
            'filename' => $fullFilename,
            'filepath' => $destinationPath,
            'url' => '/ecom/uploads/' . $fullFilename
        ];
    }
    
    /**
     * Get URL to image for display
     * Simply return the path - CSS handles everything else
     * 
     * @param string $filename Filename (e.g., 'product.jpg')
     * @return string URL to image
     */
    public function getImageUrl($filename) {
        $filename = basename($filename); // Prevent directory traversal
        return '/ecom/uploads/' . $filename;
    }
    
    /**
     * Check if image file exists
     * 
     * @param string $filename Filename
     * @return bool True if exists
     */
    public function imageExists($filename) {
        $filename = basename($filename);
        $path = $this->uploadDir . '/' . $filename;
        return file_exists($path);
    }
    
    /**
     * Delete image file
     * 
     * @param string $filename Filename
     * @return bool True if deleted
     */
    public function deleteImage($filename) {
        $filename = basename($filename);
        $path = $this->uploadDir . '/' . $filename;
        
        if (file_exists($path)) {
            return @unlink($path);
        }
        
        return false;
    }
    
    /**
     * Get file extension safely
     * 
     * @param string $filename Filename
     * @return string|false File extension or false if invalid
     */
    private function getFileExtension($filename) {
        $ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        return in_array($ext, $this->allowedFormats) ? $ext : false;
    }
    
    /**
     * Validate that file is an actual image
     * 
     * @param string $filepath Path to file
     * @return bool True if valid image
     */
    private function isValidImage($filepath) {
        $check = @getimagesize($filepath);
        return $check !== false;
    }
    
    /**
     * Clean filename to prevent security issues
     * 
     * @param string $filename Raw filename
     * @return string Cleaned filename
     */
    private function cleanFilename($filename) {
        // Remove extension if included
        $filename = pathinfo($filename, PATHINFO_FILENAME);
        
        // Replace spaces with underscores
        $filename = preg_replace('/\s+/', '_', $filename);
        
        // Remove special characters, keep only alphanumeric, underscore, hyphen
        $filename = preg_replace('/[^a-zA-Z0-9_-]/', '', $filename);
        
        // Limit length
        $filename = substr($filename, 0, 50);
        
        // Fallback if empty
        if (empty($filename)) {
            $filename = 'image_' . time();
        }
        
        return $filename;
    }
    
    /**
     * Error handler
     * 
     * @param string $message Error message
     * @return array Error response array
     */
    private function error($message) {
        return [
            'success' => false,
            'error' => $message
        ];
    }
    
    /**
     * Get upload directory
     * 
     * @return string Upload directory path
     */
    public function getUploadDir() {
        return $this->uploadDir;
    }
}
?>
