<?php

function getMimeType($file) {
    $extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));

    switch ($extension) {
        case 'jpg':
        case 'jpeg':
            return 'image/jpeg';
        case 'png':
            return 'image/png';
        case 'gif':
            return 'image/gif';
        default:
            return 'application/octet-stream';
    }
}

if (isset($_GET['path']) && isset($_GET['type'])) {
    $imagePath = $_GET['path'];
    $type = $_GET['type'];

    $allowedDirs = [
        'property' => "../../../data/properties/",
        'profile' => "../../../data/profile_images/",
        'all_images' => "../../../data/all_images/",
    ];

    if (!isset($allowedDirs[$type])) {
        header('HTTP/1.1 400 Bad Request');
        echo 'Invalid image type.';
        exit();
    }

    $allowedDir = $allowedDirs[$type];
    $realPath = realpath($allowedDir . $imagePath);

    if (strpos($realPath, realpath($allowedDir)) !== 0 || !file_exists($realPath)) {
        header('HTTP/1.1 404 Not Found');
        echo 'Image not found.';
        exit();
    }

    $mimeType = getMimeType($realPath);
    header('Content-Type: ' . $mimeType);
    header('Content-Length: ' . filesize($realPath));

    readfile($realPath);
    exit();
} else {
    header('HTTP/1.1 400 Bad Request');
    echo 'No image path or type specified.';
    exit();
}

