<?php
/**
 * Image Handler v3 - CRITICAL FIX
 * Serves images without returning 404 errors
 * Fixes: Double encoding, missing files, carousel images
 */

error_reporting(0);
ini_set('display_errors', 0);

// CORS headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Get image name and decode properly
$imageName = isset($_GET['img']) ? $_GET['img'] : '';

// Remove directory traversal attempts
$imageName = basename($imageName);
$imageName = str_replace(['../', '..\\', '%2e%2e'], '', $imageName);

// Decode URL-encoded characters
$imageName = urldecode($imageName);

// Double-decode if needed (handles %2520 → %20 → space)
if (strpos($imageName, '%') !== false) {
    $imageName = urldecode($imageName);
}

// Keep filename as-is - parentheses and other chars are important for lookup
// We already removed directory traversal attempts above

if (empty($imageName)) {
    serveTransparentGif();
}

// Search directories
$searchDirs = [
    __DIR__ . '/sport-pics/',
    __DIR__ . '/sport-pics/soccer/',
    __DIR__ . '/sport-pics/tennis/',
    __DIR__ . '/sport-pics/rugby/',
    __DIR__ . '/pics/',
    __DIR__ . '/pics_ecom/',
    __DIR__ . '/uploads/',
];

// MIME types
$mimeTypes = [
    'jpg'  => 'image/jpeg',
    'jpeg' => 'image/jpeg',
    'png'  => 'image/png',
    'gif'  => 'image/gif',
    'webp' => 'image/webp',
    'bmp'  => 'image/bmp',
    'svg'  => 'image/svg+xml',
    'ico'  => 'image/x-icon'
];

$filePath = null;
$fileType = 'image/jpeg';

// STEP 1: Exact match with extension
foreach ($searchDirs as $dir) {
    $testPath = $dir . $imageName;
    if (file_exists($testPath) && is_file($testPath)) {
        $filePath = $testPath;
        $ext = strtolower(pathinfo($imageName, PATHINFO_EXTENSION));
        if (isset($mimeTypes[$ext])) {
            $fileType = $mimeTypes[$ext];
        }
        break;
    }
}

// STEP 2: No extension? Try adding common ones
if (!$filePath && !preg_match('/\.\w+$/', $imageName)) {
    foreach ($searchDirs as $dir) {
        foreach (['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'] as $ext) {
            $testPath = $dir . $imageName . '.' . $ext;
            if (file_exists($testPath) && is_file($testPath)) {
                $filePath = $testPath;
                $fileType = $mimeTypes[$ext];
                break 2;
            }
        }
    }
}

// STEP 3: Case-insensitive search
if (!$filePath) {
    foreach ($searchDirs as $dir) {
        if (!is_dir($dir)) continue;
        
        $files = @scandir($dir);
        if (!is_array($files)) continue;
        
        foreach ($files as $file) {
            if ($file === '.' || $file === '..') continue;
            
            // Full filename match (case-insensitive)
            if (strtolower($file) === strtolower($imageName)) {
                $testPath = $dir . $file;
                if (file_exists($testPath) && is_file($testPath)) {
                    $filePath = $testPath;
                    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                    if (isset($mimeTypes[$ext])) {
                        $fileType = $mimeTypes[$ext];
                    }
                    break 2;
                }
            }
            
            // Filename without extension match
            $fileNoExt = pathinfo($file, PATHINFO_FILENAME);
            if (strtolower($fileNoExt) === strtolower($imageName)) {
                $testPath = $dir . $file;
                if (file_exists($testPath) && is_file($testPath)) {
                    $filePath = $testPath;
                    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                    if (isset($mimeTypes[$ext])) {
                        $fileType = $mimeTypes[$ext];
                    }
                    break 2;
                }
            }
        }
    }
}

// STEP 4: Partial match (carousel IDs like "ai1" → "ai1-xxx.jpg")
if (!$filePath && !preg_match('/\.\w+$/', $imageName)) {
    foreach ($searchDirs as $dir) {
        if (!is_dir($dir)) continue;
        
        $files = @scandir($dir);
        if (!is_array($files)) continue;
        
        foreach ($files as $file) {
            if ($file === '.' || $file === '..') continue;
            
            $fileNoExt = pathinfo($file, PATHINFO_FILENAME);
            
            // Check if filename starts with the search term (case-insensitive)
            if (stripos($fileNoExt, $imageName) === 0) {
                $testPath = $dir . $file;
                if (file_exists($testPath) && is_file($testPath)) {
                    $filePath = $testPath;
                    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                    if (isset($mimeTypes[$ext])) {
                        $fileType = $mimeTypes[$ext];
                    }
                    break 2;
                }
            }
        }
    }
}

// File found - serve it
if ($filePath && file_exists($filePath)) {
    serveImage($filePath, $fileType);
} else {
    // File not found - serve transparent GIF (NOT 404)
    serveTransparentGif();
}

/**
 * Serve the image file with proper cache headers
 */
function serveImage($filePath, $mimeType) {
    header('Content-Type: ' . $mimeType);
    header('Content-Length: ' . filesize($filePath));
    
    // 30-day cache
    header('Cache-Control: public, max-age=2592000');
    header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2592000) . ' GMT');
    
    // ETag support
    $etag = md5_file($filePath);
    header('ETag: "' . $etag . '"');
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($filePath)) . ' GMT');
    
    // Check If-None-Match
    if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) {
        $clientETag = str_replace('"', '', $_SERVER['HTTP_IF_NONE_MATCH']);
        if ($clientETag === $etag) {
            http_response_code(304);
            exit;
        }
    }
    
    // Check If-Modified-Since
    if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
        $clientTime = strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']);
        if ($clientTime >= filemtime($filePath)) {
            http_response_code(304);
            exit;
        }
    }
    
    // Serve file
    readfile($filePath);
    exit;
}

/**
 * Serve transparent 1x1 GIF (NOT 404!)
 */
function serveTransparentGif() {
    header('Content-Type: image/gif');
    header('Content-Length: 43');
    header('Cache-Control: public, max-age=86400');
    header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 86400) . ' GMT');
    echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
    exit;
}
?>
