<?php

namespace DZ\ImageShield;

use XF;
use XF\Util\File;

class TemplateHelper
{
    public static function getCurrentImage($html): ?string
    {
        $signature = XF::options()->dzImageShield_signature;
        if (($signature['type'] ?? '') !== 'image') {
            return null;
        }

        $file = Shield::getOverlayImagePath();
        if (!File::abstractedPathExists($file)) {
            return null;
        }

        $imageData = static::getImageEncoded($file);
        if ($imageData === null) {
            return null;
        }

        return $imageData;
    }

    public static function getImageEncoded(string $path): ?string
    {
        $tempFile = File::copyAbstractedPathToTempFile($path);
        $contents = file_get_contents($tempFile);
        if ($contents === false) {
            return null;
        }

        return 'data:image/png;base64,' . base64_encode($contents);
    }

    /**
     * Get list of available fonts from the fonts directory.
     * 
     * @return array<string, string> Array of font path => font name
     */
    public static function getAvailableFonts(): array
    {
        $fontsDir = XF::getAddOnDirectory() . '/DZ/ImageShield/fonts';
        $fonts = ['' => (string) XF::phrase('dz_imageshield_default_font')];

        if (!is_dir($fontsDir)) {
            return $fonts;
        }

        $files = @scandir($fontsDir);
        if ($files === false) {
            return $fonts;
        }

        foreach ($files as $file) {
            if ($file === '.' || $file === '..') {
                continue;
            }

            $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
            if (in_array($ext, ['ttf', 'otf', 'woff', 'woff2'], true)) {
                $fullPath = $fontsDir . '/' . $file;
                $fontName = pathinfo($file, PATHINFO_FILENAME);
                $fonts[$fullPath] = $fontName;
            }
        }

        return $fonts;
    }
}
