<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Export;

/**
 * Browsers do not understand mPDF's `cmyk(c,m,y,k)` color notation, so the
 * print-sheet templates render as black/transparent when shown in a normal
 * HTML preview. This best-effort converter rewrites every `cmyk(...)` value
 * (in both `style="…"` declarations and `bgcolor="…"` attributes) into an
 * approximate `rgb(...)`, which is good enough for an on-screen preview.
 */
final class CmykToRgb
{
    public static function convert(string $html): string
    {
        return preg_replace_callback(
            '/cmyk\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)/i',
            static function (array $m): string {
                [$c, $mg, $y, $k] = [(float) $m[1] / 100, (float) $m[2] / 100, (float) $m[3] / 100, (float) $m[4] / 100];

                $r = (int) round(255 * (1 - $c) * (1 - $k));
                $g = (int) round(255 * (1 - $mg) * (1 - $k));
                $b = (int) round(255 * (1 - $y) * (1 - $k));

                return \sprintf('rgb(%d, %d, %d)', $r, $g, $b);
            },
            $html
        );
    }
}
