#!/usr/bin/env php
<?php

/*
 * This script installs custom fonts for the PDF generator.
 *
 * It is recommended to run this script after adding new fonts to the resources/fonts folder.
 * Only have to add the TTF file to the resources/fonts folder and update the $customFonts array below.
 *
 * Run this script from the project root folder: php bin/install-fonts.php
 */

require_once dirname(__DIR__) . '/vendor/autoload.php';

use Dealerdirect\Agreements\DataObjects\Font;
use Dealerdirect\Agreements\Pdf\Generator;

$resourcesFolder = dirname(__DIR__) . '/resources';

$customFonts = [
    new Font('ARegular', 'normal', "$resourcesFolder/fonts/Regular-Regular.ttf"),
    new Font('ARegular', 'bold', "$resourcesFolder/fonts/Regular-Bold.ttf"),
    new Font('Roboto', 'normal', "$resourcesFolder/fonts/Roboto-Regular.ttf"),
    new Font('Bree Serif', 'normal', "$resourcesFolder/fonts/BreeSerif-Regular.ttf"),
];

$printMessage = false;
$domPdf = Generator::applyOptionsToPdf(new Dompdf\Dompdf(), $resourcesFolder);
$fontMetrics = $domPdf->getFontMetrics();

foreach ($customFonts as $font) {
    if (!$fontMetrics->getFont($font->family, $font->weight)) {
        echo sprintf("Registering font: %-10s - %s\n", $font->family, $font->weight);

        $font->register($fontMetrics);
        $printMessage = true;
    }
}

$fontMetrics->saveFontFamilies();

// Fix for absolute paths in installed-fonts.json
$installedFonts = json_decode(file_get_contents($fontMetrics->getUserFontsFilePath()), true);
foreach ($installedFonts as $family => $weights) {
    foreach ($weights as $weight => $path) {
        if (0 === strpos($path, $resourcesFolder)) {
            $installedFonts[$family][$weight] = str_replace("$resourcesFolder/fonts/", '', $path);
        }
    }
}

file_put_contents($fontMetrics->getUserFontsFilePath(), json_encode($installedFonts, JSON_PRETTY_PRINT));

if ($printMessage) {
    echo "Fonts installed successfully\n";
}
