<?php
/**
 * Carousel Image Handler
 * Specifically designed for carousel/slider image loading
 * Handles numeric IDs and partial filenames
 */

// Don't output errors
error_reporting(0);
ini_set('display_errors', 0);

// Set proper headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, X-Requested-With');
header('Content-Type: application/json');

// Get the request
$action = isset($_GET['action']) ? $_GET['action'] : '';
$imageId = isset($_GET['id']) ? basename($_GET['id']) : '';
$imageId = str_replace(['..', '\\'], '', $imageId);

// 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/',
];

$result = [
    'success' => false,
    'path' => null,
    'error' => 'Not found',
    'searched_dirs' => []
];

if (empty($imageId)) {
    http_response_code(400);
    echo json_encode(['error' => 'No image ID provided']);
    exit;
}

// Find image by ID (with or without extension)
function findCarouselImage($imageId, $searchDirs) {
    // 1. Try exact match with extension
    foreach ($searchDirs as $dir) {
        if (file_exists($dir . $imageId)) {
            return $dir . $imageId;
        }
    }
    
    // 2. Try with common extensions
    $commonExts = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp'];
    foreach ($searchDirs as $dir) {
        foreach ($commonExts as $ext) {
            if (file_exists($dir . $imageId . '.' . $ext)) {
                return $dir . $imageId . '.' . $ext;
            }
        }
    }
    
    // 3. Try case-insensitive match
    foreach ($searchDirs as $dir) {
        if (is_dir($dir)) {
            $files = array_diff(scandir($dir), ['.', '..']);
            foreach ($files as $file) {
                if (strtolower($file) === strtolower($imageId)) {
                    return $dir . $file;
                }
                $nameNoExt = pathinfo($file, PATHINFO_FILENAME);
                if (strtolower($nameNoExt) === strtolower($imageId)) {
                    return $dir . $file;
                }
            }
        }
    }
    
    // 4. Try partial match (for IDs like "ai1" -> "ai1-xxx.jpg")
    foreach ($searchDirs as $dir) {
        if (is_dir($dir)) {
            $files = array_diff(scandir($dir), ['.', '..']);
            foreach ($files as $file) {
                $nameNoExt = pathinfo($file, PATHINFO_FILENAME);
                if (stripos($nameNoExt, $imageId) === 0) {
                    return $dir . $file;
                }
            }
        }
    }
    
    return null;
}

// Handle different actions
switch ($action) {
    case 'find':
        // Find and return path for carousel image
        $path = findCarouselImage($imageId, $searchDirs);
        if ($path && file_exists($path)) {
            $result['success'] = true;
            // Normalize to a web-accessible path under /emporio/
            $rel = str_replace(PHP_EOL, '', str_replace(__DIR__, '', $path));
            $rel = str_replace('\\', '/', $rel);
            $rel = ltrim($rel, '/');
            $result['path'] = '/emporio/' . $rel;
            $result['error'] = null;
        } else {
            http_response_code(404);
            $result['error'] = 'Image not found: ' . $imageId;
        }
        break;
        
    case 'list':
        // List all images in a directory
        $dir = isset($_GET['dir']) ? basename($_GET['dir']) : '';
        $targetDir = __DIR__ . '/sport-pics/' . $dir;
        
        if (is_dir($targetDir)) {
            $files = array_diff(scandir($targetDir), ['.', '..']);
            $result['success'] = true;
            $result['images'] = [];
            
            foreach ($files as $file) {
                $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
                if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg', 'ico'])) {
                    $result['images'][] = [
                        'name' => $file,
                        'path' => 'sport-pics/' . ($dir ? $dir . '/' : '') . $file
                    ];
                }
            }
        } else {
            http_response_code(404);
            $result['error'] = 'Directory not found';
        }
        break;
        
    default:
        // Default: find image
        $path = findCarouselImage($imageId, $searchDirs);
        if ($path && file_exists($path)) {
            $result['success'] = true;
            $rel = str_replace(PHP_EOL, '', str_replace(__DIR__, '', $path));
            $rel = str_replace('\\', '/', $rel);
            $rel = ltrim($rel, '/');
            $result['path'] = '/emporio/' . $rel;
            $result['error'] = null;
        } else {
            http_response_code(404);
            $result['error'] = 'Image not found: ' . $imageId;
        }
}

echo json_encode($result);
?>
