<?php
// CoreFlux/core/ImageRender.php

namespace Core\Utilities;

class ImageRender
{
    /**
     * Converts an image file to a Base64 encoded data URI.
     *
     * @param string $imagePath The absolute file system path to the image.
     * @return string|null The Base64 encoded data URI (e.g., "data:image/png;base64,...") on success, or null on failure.
     */
    public static function toBase64(string $imagePath): ?string
    {
        // 1. Check if the file exists and is readable.
        if (!file_exists($imagePath) || !is_readable($imagePath)) {
            error_log("ImageRender Error: Image file not found or not readable at '{$imagePath}'");
            return null;
        }

        // 2. Get the image MIME type.
        // This is crucial for the data URI format (e.g., image/jpeg, image/png).
        $finfo = finfo_open(FILEINFO_MIME_TYPE); // Return the MIME type
        if ($finfo === false) {
            error_log("ImageRender Error: Could not open fileinfo database.");
            return null;
        }
        $mimeType = finfo_file($finfo, $imagePath);
        finfo_close($finfo);

        if ($mimeType === false || !str_starts_with($mimeType, 'image/')) {
            error_log("ImageRender Error: Could not determine MIME type or it's not an image for '{$imagePath}' (MIME: {$mimeType})");
            return null;
        }

        // 3. Read the image file content.
        $imageData = file_get_contents($imagePath);
        if ($imageData === false) {
            error_log("ImageRender Error: Could not read image data from '{$imagePath}'");
            return null;
        }

        // 4. Encode the image data to Base64.
        $base64EncodedData = base64_encode($imageData);

        // 5. Construct the data URI.
        // Format: data:[<MIME-type>][;charset=<charset>][;base64],<data>
        return "data:{$mimeType};base64,{$base64EncodedData}";
    }

    public static function toUrl(string $relativePath, string $baseUrl = APP_URL, string $prefix = '/media'): string
    {
        // Normalize slashes
        $relativePath = ltrim($relativePath, '/');

        // Ensure base URL has no trailing slash
        $baseUrl = rtrim($baseUrl, '/');

        // Ensure prefix has leading slash
        $prefix = '/' . trim($prefix, '/');

        // Return secure full URL
        return "{$baseUrl}{$prefix}/{$relativePath}";
    }
}