<?php

namespace App\Helpers;

use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;

class CompanyMedia
{
    /**
     * Absolute filesystem path for DomPDF (reads file directly, no temp copy needed).
     */
    public static function absolutePath(?string $relativePath): ?string
    {
        if (! $relativePath) {
            return null;
        }

        $relativePath = self::normalizePath($relativePath);
        $absolute = Storage::disk('public')->path($relativePath);

        return is_readable($absolute) ? $absolute : null;
    }

    /**
     * JPEG path for DomPDF (full color; PNG via DomPDF often renders greyscale).
     */
    public static function pdfImagePath(?string $relativePath): ?string
    {
        if (! $relativePath) {
            return null;
        }

        $absolute = self::absolutePath($relativePath);
        if (! $absolute) {
            return null;
        }

        if (! extension_loaded('gd')) {
            return $absolute;
        }

        $cacheDir = storage_path('framework/dompdf/images');
        if (! is_dir($cacheDir)) {
            @mkdir($cacheDir, 0755, true);
        }

        $cacheKey = md5_file($absolute) ?: md5($relativePath);
        $cached = $cacheDir.'/'.$cacheKey.'.jpg';
        if (is_readable($cached) && filesize($cached) > 0) {
            return $cached;
        }

        $info = @getimagesize($absolute);
        if (! $info) {
            return $absolute;
        }

        $source = match ($info[2]) {
            IMAGETYPE_PNG => @imagecreatefrompng($absolute),
            IMAGETYPE_JPEG => @imagecreatefromjpeg($absolute),
            IMAGETYPE_GIF => @imagecreatefromgif($absolute),
            IMAGETYPE_WEBP => function_exists('imagecreatefromwebp') ? @imagecreatefromwebp($absolute) : false,
            default => false,
        };

        if (! $source) {
            return $absolute;
        }

        $width = imagesx($source);
        $height = imagesy($source);

        // Flatten transparency: white background for signatures, corner color for logos.
        $bgR = $bgG = $bgB = 255;
        $isSignature = str_contains(str_replace('\\', '/', $relativePath), '/signatures/');
        if (! $isSignature) {
            $corner = imagecolorat($source, 0, 0);
            $alpha = ($corner >> 24) & 0x7F;
            $bgR = ($corner >> 16) & 0xFF;
            $bgG = ($corner >> 8) & 0xFF;
            $bgB = $corner & 0xFF;
            if ($alpha > 100) {
                $bgR = $bgG = $bgB = 255;
            }
        }

        $canvas = imagecreatetruecolor($width, $height);
        $background = imagecolorallocate($canvas, $bgR, $bgG, $bgB);
        imagefill($canvas, 0, 0, $background);
        imagealphablending($canvas, true);
        imagecopy($canvas, $source, 0, 0, 0, 0, $width, $height);
        imagedestroy($source);

        if (@imagejpeg($canvas, $cached, 100)) {
            imagedestroy($canvas);

            return $cached;
        }

        imagedestroy($canvas);

        return $absolute;
    }

    /** Drop cached PDF images after logo/signature upload. */
    public static function clearPdfImageCache(): void
    {
        $cacheDir = storage_path('framework/dompdf/images');
        if (is_dir($cacheDir)) {
            File::cleanDirectory($cacheDir);
        }
    }

    /**
     * Image source for browser preview: base64 data URI when the file exists.
     */
    public static function imageSource(?string $relativePath): ?string
    {
        if (! $relativePath) {
            return null;
        }

        $relativePath = self::normalizePath($relativePath);
        $disk = Storage::disk('public');

        if (! $disk->exists($relativePath)) {
            return null;
        }

        $absolute = $disk->path($relativePath);

        if (! is_readable($absolute)) {
            return null;
        }

        $mime = mime_content_type($absolute) ?: 'image/png';
        $contents = file_get_contents($absolute);

        if ($contents === false) {
            return null;
        }

        return 'data:'.$mime.';base64,'.base64_encode($contents);
    }

    /**
     * Public URL for browser display (fallback when embed is not passed).
     */
    public static function publicUrl(?string $relativePath): ?string
    {
        $relativePath = $relativePath ? self::normalizePath($relativePath) : null;

        if (! $relativePath || ! Storage::disk('public')->exists($relativePath)) {
            return null;
        }

        return asset('storage/'.$relativePath);
    }

    private static function normalizePath(string $path): string
    {
        $path = str_replace('\\', '/', trim($path));
        $path = ltrim($path, '/');

        foreach (['storage/app/public/', 'app/public/', 'public/'] as $prefix) {
            if (str_starts_with($path, $prefix)) {
                $path = substr($path, strlen($prefix));
            }
        }

        return $path;
    }
}
