<?php
require "../protected/src/config.php";

// Assuming private_images is a directory outside public_html
$privateImagePath = ARTICLE_IMAGE_PATH . "/";

// Get the image filename from the query string
if (isset($_GET['image'])) {
    $imageFilename = basename($_GET['image']);
    $pth = $_GET['rel'] ?? false;
    $relPath = match($pth) {
        'fullsize'=>"fullsize/",
        'thumb'=>'thumb/',
        default=>"",
    };    
    
    $imagePath = $privateImagePath . $relPath . $imageFilename;

    // Check if the file exists
    if (file_exists($imagePath)) {
        // Get the file extension
        $fileExtension = pathinfo($imagePath, PATHINFO_EXTENSION);

        // Set the appropriate Content-Type header based on the file extension
        $header = match($fileExtension) {
            'jpg'=>'Content-Type: image/jpeg',
            'jpeg'=>'Content-Type: image/jpeg',
            'gif'=>'Content-Type: image/gif',
            'png'=>'Content-Type: image/png',
            'webp'=>'Content-Type: image/webp',
            default=>'HTTP/1.0 404 Not Found',
        };
        header($header);
        
        if (str_contains($header, "Content-Type:")) {
            // Read and output the image content
            readfile($imagePath);
        }
        exit();
    } else {
        // Image not found, return a 404 error
        header('HTTP/1.0 404 Not Found');
        exit();
    }
}
