<?php

/**
 * webtrees: online genealogy
 * Copyright (C) 2026 webtrees development team
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

declare(strict_types=1);

namespace Fisharebest\Webtrees\Report;

use Fisharebest\Webtrees\Auth;
use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\MediaFile;
use Fisharebest\Webtrees\Registry;
use Fisharebest\Webtrees\Webtrees;

use function array_map;
use function ceil;
use function count;
use function explode;
use function implode;
use function preg_match;
use function str_replace;
use function stripos;
use function strrpos;
use function substr;
use function substr_count;

class HtmlRenderer extends AbstractRenderer
{
    // Cell padding
    public float $cPadding = 2.0;

    // Cell height ratio
    public float $cellHeightRatio = 1.8;

    // Current horizontal position
    public float $X = 0.0;

    // Current vertical position
    public float $Y = 0.0;

    // Page number counter
    public int $pageN = 1;

    // Store the page width without left and right margins
    // Only needed for PDF reports
    public float $noMarginWidth = 0.0;

    // Last cell height
    public float $lastCellHeight = 0.0;

    // LTR or RTL alignement; "left" on LTR, "right" on RTL
    // Used in <div>
    public string $alignRTL = 'left';

    // LTR or RTL entity
    public string $entityRTL = '&lrm;';

    // Largest Font Height is used by TextBox etc.
    //
    // Use this to calculate the text height.
    // This makes sure that the text fits into the cell/box when different font sizes are used
    public float $largestFontHeight = 0.0;

    // Keep track of the highest Y position
    // Used with Header div / Body div / Footer div / "addpage" / The bottom of the last image etc.
    public float $maxY = 0.0;

    /**
     * @var ReportHtmlFootnote[] Array of elements in the footer notes
     */
    public array $printedfootnotes = [];

    public function setup(): void
    {
        parent::setup();

        // Setting up the correct dimensions if Portrait (default) or Landscape
        if ($this->orientation === 'landscape') {
            $tmpw              = $this->page_width;
            $this->page_width  = $this->page_height;
            $this->page_height = $tmpw;
        }
        // Store the pagewidth without margins
        $this->noMarginWidth = $this->page_width - $this->left_margin - $this->right_margin;
        // If RTL
        if ($this->rtl) {
            $this->alignRTL  = 'right';
            $this->entityRTL = '&rlm;';
        }
        // Change the default HTML font name
        $this->default_font = 'Arial';

        if ($this->show_generated_by) {
            // The default style name for Generated by.... is 'genby'
            $element = new ReportHtmlCell(0.0, 10.0, '', 'C', '', 'genby', 1, ReportBaseElement::CURRENT_POSITION, ReportBaseElement::CURRENT_POSITION, false, 0, '', '', true);
            $element->addText($this->generated_by);
            $element->setUrl(Webtrees::URL);
            $this->footerElements[] = $element;
        }
    }

    public function footnotes(): void
    {
        $this->currentStyle = '';
        if (!empty($this->printedfootnotes)) {
            foreach ($this->printedfootnotes as $element) {
                $element->renderFootnote($this);
            }
        }
    }

    public function run(): void
    {
        echo '<style>';
        echo '#bodydiv { font: 10px sans-serif;}';
        foreach ($this->styles as $class => $style) {
            echo '.', $class, ' { ';
            if ($style['font'] === 'dejavusans') {
                $style['font'] = $this->default_font;
            }
            echo 'font-family: ', $style['font'], '; ';
            echo 'font-size: ', $style['size'], 'pt; ';
            // Case-insensitive
            if (stripos($style['style'], 'B') !== false) {
                echo 'font-weight: bold; ';
            }
            if (stripos($style['style'], 'I') !== false) {
                echo 'font-style: italic; ';
            }
            if (stripos($style['style'], 'U') !== false) {
                echo 'text-decoration: underline; ';
            }
            if (stripos($style['style'], 'D') !== false) {
                echo 'text-decoration: line-through; ';
            }
            echo '}', PHP_EOL;
        }

        //-- header divider
        echo '</style>', PHP_EOL;
        echo '<div id="headermargin" style="position: relative; top: auto; height: ', $this->header_margin, 'pt; width: ', $this->noMarginWidth, 'pt;"></div>';
        echo '<div id="headerdiv" style="position: relative; top: auto; width: ', $this->noMarginWidth, 'pt;">';
        foreach ($this->headerElements as $element) {
            if ($element instanceof ReportBaseElement) {
                $element->render($this);
            } elseif ($element === 'footnotetexts') {
                $this->footnotes();
            } elseif ($element === 'addpage') {
                $this->addPage();
            }
        }
        //-- body
        echo '</div>';
        echo '<script>document.getElementById("headerdiv").style.height="', $this->top_margin - $this->header_margin - 6, 'pt";</script>';
        echo '<div id="bodydiv" style="position: relative; top: auto; width: ', $this->noMarginWidth, 'pt; height: 100%;">';
        $this->Y    = 0;
        $this->maxY = 0;
        foreach ($this->bodyElements as $element) {
            if ($element instanceof ReportBaseElement) {
                $element->render($this);
            } elseif ($element === 'footnotetexts') {
                $this->footnotes();
            } elseif ($element === 'addpage') {
                $this->addPage();
            }
        }
        //-- footer
        echo '</div>';
        echo '<script>document.getElementById("bodydiv").style.height="', $this->maxY, 'pt";</script>';
        echo '<div id="bottommargin" style="position: relative; top: auto; height: ', $this->bottom_margin - $this->footer_margin, 'pt;width:', $this->noMarginWidth, 'pt;"></div>';
        echo '<div id="footerdiv" style="position: relative; top: auto; width: ', $this->noMarginWidth, 'pt;height:auto;">';
        $this->Y    = 0;
        $this->X    = 0;
        $this->maxY = 0;
        foreach ($this->footerElements as $element) {
            if ($element instanceof ReportBaseElement) {
                $element->render($this);
            } elseif ($element === 'footnotetexts') {
                $this->footnotes();
            } elseif ($element === 'addpage') {
                $this->addPage();
            }
        }
        echo '</div>';
        echo '<script>document.getElementById("footerdiv").style.height="', $this->maxY, 'pt";</script>';
        echo '<div id="footermargin" style="position: relative; top: auto; height: ', $this->footer_margin, 'pt;width:', $this->noMarginWidth, 'pt;"></div>';
    }

    public function createCell(float $width, float $height, string $border, string $align, string $bgcolor, string $style, int $ln, float $top, float $left, bool $fill, int $stretch, string $bocolor, string $tcolor, bool $reseth): ReportHtmlCell
    {
        return new ReportHtmlCell($width, $height, $border, $align, $bgcolor, $style, $ln, $top, $left, $fill, $stretch, $bocolor, $tcolor, $reseth);
    }

    public function createTextBox(
        float $width,
        float $height,
        bool $border,
        string $bgcolor,
        bool $newline,
        float $left,
        float $top,
        bool $pagecheck,
        string $style,
        bool $fill,
        bool $padding,
        bool $reseth
    ): ReportHtmlTextBox {
        return new ReportHtmlTextBox($width, $height, $border, $bgcolor, $newline, $left, $top, $pagecheck, $style, $fill, $padding, $reseth);
    }

    public function createText(string $style, string $color): ReportHtmlText
    {
        return new ReportHtmlText($style, $color);
    }

    public function createFootnote(string $style): ReportHtmlFootnote
    {
        return new ReportHtmlFootnote($style);
    }

    public function createImage(
        string $file,
        float $x,
        float $y,
        float $w,
        float $h,
        string $align,
        string $ln,
    ): ReportHtmlImage {
        $mime_type = mime_content_type($file);
        $data      = file_get_contents($file);
        $src = 'data:' . $mime_type . ';base64,' . base64_encode($data);

        return new ReportHtmlImage($file, $x, $y, $w, $h, $align, $ln);
    }

    public function createImageFromObject(
        MediaFile $media_file,
        float $x,
        float $y,
        float $w,
        float $h,
        string $align,
        string $ln
    ): ReportHtmlImage {
        // Send higher-resolution image at the same aspect ratio.
        $add_watermark = Registry::imageFactory()->fileNeedsWatermark($media_file, Auth::user());

        $data = Registry::imageFactory()->mediaFileThumbnail(
            $media_file,
            (int) ($w * 4),
            (int) ($h * 4),
            'crop',
            $add_watermark,
        );

        $src = 'data:' . $media_file->mimeType() . ';base64,' . base64_encode($data);

        return new ReportHtmlImage($src, $x, $y, $w, $h, $align, $ln);
    }

    public function createLine(float $x1, float $y1, float $x2, float $y2): ReportHtmlLine
    {
        return new ReportHtmlLine($x1, $y1, $x2, $y2);
    }

    /**
     * Update the Page Number and set a new Y if max Y is larger - ReportHtml
     */
    public function addPage(): void
    {
        $this->pageN++;

        // Add a little margin to max Y "between pages"
        $this->maxY += 10;

        // If Y is still higher for any reason...
        if ($this->maxY < $this->Y) {
            // ... update max Y
            $this->maxY = $this->Y;
        } else {
            // else update Y so that nothing will be overwritten, like images or cells...
            $this->Y = $this->maxY;
        }
    }

    /**
     * Uppdate max Y to keep track it in case of a pagebreak - ReportHtml
     */
    public function addMaxY(float $y): void
    {
        if ($this->maxY < $y) {
            $this->maxY = $y;
        }
    }

    public function checkFootnote(ReportHtmlFootnote $footnote): ReportHtmlFootnote|false
    {
        $ct  = count($this->printedfootnotes);
        $i   = 0;
        $val = $footnote->getValue();
        while ($i < $ct) {
            if ($this->printedfootnotes[$i]->getValue() === $val) {
                // If this footnote already exists, then set up the numbers for this object
                $footnote->setNum($i + 1);
                $footnote->setAddlink((string) ($i + 1));

                return $this->printedfootnotes[$i];
            }
            $i++;
        }
        // If this Footnote has not been set up yet
        $footnote->setNum($ct + 1);
        $footnote->setAddlink((string) ($ct + 1));
        $this->printedfootnotes[] = $footnote;

        return false;
    }

    public function countLines(string $str): int
    {
        if ($str === '') {
            return 0;
        }

        return substr_count($str, "\n") + 1;
    }

    public function getCurrentStyle(): string
    {
        return $this->currentStyle;
    }

    public function getCurrentStyleHeight(): float
    {
        if (empty($this->currentStyle)) {
            return $this->default_font_size;
        }
        $style = $this->getStyle($this->currentStyle);

        return $style['size'];
    }

    public function getFootnotesHeight(float $cellWidth): float
    {
        $h = 0;
        foreach ($this->printedfootnotes as $element) {
            $h += $element->getFootnoteHeight($this, $cellWidth);
        }

        return $h;
    }

    public function getRemainingWidth(): float
    {
        return $this->noMarginWidth - $this->X;
    }

    public function getStringWidth(string $text): float
    {
        $style = $this->getStyle($this->currentStyle);

        return mb_strlen($text) * $style['size'] / 2;
    }

    public function getTextCellHeight(string $str): float
    {
        // Count the number of lines to calculate the height
        $nl = $this->countLines($str);

        // Calculate the cell height
        return ceil($this->getCurrentStyleHeight() * $this->cellHeightRatio * $nl);
    }

    public function getX(): float
    {
        return $this->X;
    }

    public function getY(): float
    {
        return $this->Y;
    }

    public function pageNo(): int
    {
        return $this->pageN;
    }

    public function setCurrentStyle(string $s): void
    {
        $this->currentStyle = $s;
    }

    public function setX(float $x): void
    {
        $this->X = $x;
    }

    public function setY(float $y): void
    {
        $this->Y = $y;
        if ($this->maxY < $y) {
            $this->maxY = $y;
        }
    }

    public function setXy(float $x, float $y): void
    {
        $this->setX($x);
        $this->setY($y);
    }

    /**
     * @param float $width Width in points the text has to fit into
     */
    public function textWrap(string $str, float $width): string
    {
        $line_width = (int) ($width / ($this->getCurrentStyleHeight() / 2));

        $lines = explode("\n", $str);

        $lines = array_map(fn (string $string): string => $this->utf8WordWrap($string, $line_width), $lines);

        return implode("\n", $lines);
    }

    /**
     * Wrap text, similar to the PHP wordwrap() function.
     */
    private function utf8WordWrap(string $string, int $width): string
    {
        $out = '';
        while ($string) {
            if (mb_strlen($string) <= $width) {
                // Do not wrap any text that is less than the output area.
                $out    .= $string;
                $string = '';
            } else {
                $sub1 = mb_substr($string, 0, $width + 1);
                if (mb_substr($string, mb_strlen($sub1) - 1, 1) === ' ') {
                    // include words that end by a space immediately after the area.
                    $sub = $sub1;
                } else {
                    $sub = mb_substr($string, 0, $width);
                }
                $spacepos = strrpos($sub, ' ');
                if ($spacepos === false) {
                    // No space on the line?
                    $out    .= $sub . "\n";
                    $string = mb_substr($string, mb_strlen($sub));
                } else {
                    // Split at space;
                    $out    .= substr($string, 0, $spacepos) . "\n";
                    $string = substr($string, $spacepos + 1);
                }
            }
        }

        return $out;
    }

    public function write(string $text, string $color = '', bool $useclass = true): void
    {
        $style    = $this->getStyle($this->getCurrentStyle());
        $htmlcode = '<span dir="' . I18N::direction() . '"';
        if ($useclass) {
            $htmlcode .= ' class="' . $style['name'] . '"';
        }
        // Check if Text Color is set and if it’s valid HTML color
        if (preg_match('/#?(..)(..)(..)/', $color)) {
            $htmlcode .= ' style="color:' . $color . ';"';
        }

        $htmlcode .= '>' . $text . '</span>';
        $htmlcode = str_replace([
            "\n",
            '> ',
            ' <',
        ], [
            '<br>',
            '>&nbsp;',
            '&nbsp;<',
        ], $htmlcode);
        echo $htmlcode;
    }
}
