<?php

declare(strict_types=1);

$pluginDir = dirname(__DIR__);
$vendorDir = $pluginDir . '/vendor';
$autoload = $vendorDir . '/autoload.php';
$tcpdfFontDir = $vendorDir . '/tecnickcom/tcpdf/fonts';
$sourceDir = $pluginDir . '/resources/fonts/arial';
$tmpDir = $pluginDir . '/.font-build';

function cmt_log(string $message): void {
    echo '[TCPDF] ' . $message . PHP_EOL;
}

function cmt_fail(string $message): void {
    fwrite(STDERR, '[TCPDF] ' . $message . PHP_EOL);
    exit(1);
}

function cmt_rename_dir_if_exists(string $from, string $to): void {
    if (is_dir($from) && !is_dir($to)) {
        if (!@rename($from, $to)) {
            cmt_fail('Could not rename font directory: ' . $from . ' -> ' . $to);
        }
        cmt_log('Renamed font directory: ' . basename($from) . ' -> ' . basename($to));
    }
}

function cmt_find_font_file(string $sourceDir, array $candidates): ?string {
    foreach ($candidates as $candidate) {
        $path = $sourceDir . '/' . $candidate;
        if (is_file($path)) {
            return $path;
        }
    }

    $files = glob($sourceDir . '/*') ?: [];
    foreach ($files as $file) {
        if (!is_file($file)) {
            continue;
        }

        $name = strtolower(basename($file));
        foreach ($candidates as $candidate) {
            if ($name === strtolower($candidate)) {
                return $file;
            }
        }
    }

    return null;
}

function cmt_delete_generated_font(string $fontDir, string $fontName): void {
    foreach (array(
        $fontName . '.php',
        $fontName . '.z',
        $fontName . '.ctg.z',
    ) as $file) {
        $path = $fontDir . '/' . $file;
        if (is_file($path) && !@unlink($path)) {
            cmt_fail('Could not remove old generated font file: ' . $path);
        }
    }
}

cmt_rename_dir_if_exists($tcpdfFontDir . '/ae_fonts_2.0', $tcpdfFontDir . '/ae_fonts_2_0');
cmt_rename_dir_if_exists($tcpdfFontDir . '/dejavu-fonts-ttf-2.33', $tcpdfFontDir . '/dejavu-fonts-ttf-2_33');
cmt_rename_dir_if_exists($tcpdfFontDir . '/dejavu-fonts-ttf-2.34', $tcpdfFontDir . '/dejavu-fonts-ttf-2_34');

if (!is_file($autoload)) {
    cmt_fail('Composer autoload not found: ' . $autoload);
}

require_once $autoload;

if (!class_exists('TCPDF_FONTS')) {
    cmt_fail('TCPDF_FONTS class not available. TCPDF installation is incomplete.');
}

if (!is_dir($sourceDir)) {
    cmt_fail('Arial source directory missing: ' . $sourceDir);
}

if (!is_dir($tcpdfFontDir)) {
    cmt_fail('TCPDF font directory missing: ' . $tcpdfFontDir);
}

if (!is_writable($tcpdfFontDir)) {
    cmt_fail('TCPDF font directory is not writable: ' . $tcpdfFontDir);
}

if (!is_dir($tmpDir) && !@mkdir($tmpDir, 0775, true)) {
    cmt_fail('Could not create temporary font build directory: ' . $tmpDir);
}

$fonts = array(
    'arial' => array('arial.ttf', 'Arial.ttf', 'ARIAL.TTF'),
    'arialb' => array('arialb.ttf', 'arialbd.ttf', 'Arial Bold.ttf', 'ARIALB.TTF', 'ARIALBD.TTF'),
    'ariali' => array('ariali.ttf', 'Arial Italic.ttf', 'ARIALI.TTF'),
    'arialbi' => array('arialbi.ttf', 'arialz.ttf', 'Arial Bold Italic.ttf', 'ARIALBI.TTF', 'ARIALZ.TTF'),
);

foreach ($fonts as $targetName => $candidates) {
    $sourceFile = cmt_find_font_file($sourceDir, $candidates);
    if ($sourceFile === null) {
        cmt_fail('Missing Arial font file for ' . $targetName . ' in ' . $sourceDir . '. Expected one of: ' . implode(', ', $candidates));
    }

    $buildFile = $tmpDir . '/' . $targetName . '.ttf';
    if (!@copy($sourceFile, $buildFile)) {
        cmt_fail('Could not copy font file for build: ' . $sourceFile . ' -> ' . $buildFile);
    }

    cmt_delete_generated_font($tcpdfFontDir, $targetName);

    $fontName = TCPDF_FONTS::addTTFfont(
        $buildFile,
        'TrueTypeUnicode',
        '',
        96,
        $tcpdfFontDir . '/'
    );

    if ($fontName === false) {
        cmt_fail('Could not generate TCPDF font definition for: ' . $sourceFile);
    }

    if ($fontName !== $targetName) {
        cmt_fail('Generated unexpected font name "' . $fontName . '" for target "' . $targetName . '".');
    }

    @unlink($buildFile);
    cmt_log('Installed Arial font variant: ' . $targetName);
}

@rmdir($tmpDir);
cmt_log('Arial TCPDF fonts installed into: ' . $tcpdfFontDir);
