<?php
/*
desenvolvedor: luciano donizeti
mania de script: www.maniadescript.com.br
whatsapp 43998240911
*/

/**
 * Utilidades para desenhar textos dentro dos cards sem cortar conteúdo.
 * Faz ajuste automático por redução de fonte e quebra em múltiplas linhas.
 */
if (!function_exists('card_text_bbox')) {
    function card_text_bbox(string $font, int $size, string $text): array {
        if (function_exists('imagettfbbox') && is_file($font)) {
            $bbox = @imagettfbbox($size, 0, $font, $text === '' ? ' ' : $text);
            if (is_array($bbox)) return $bbox;
        }
        $fw = function_exists('imagefontwidth') ? imagefontwidth(5) : 8;
        $fh = function_exists('imagefontheight') ? imagefontheight(5) : 12;
        $w = $fw * strlen($text);
        $h = $fh;
        return [0, 0, $w, 0, $w, -$h, 0, -$h];
    }

    function card_text_width(string $font, int $size, string $text): int {
        $bbox = card_text_bbox($font, $size, $text);
        return (int)ceil(abs($bbox[2] - $bbox[0]));
    }

    function card_text_height(string $font, int $size, string $text = 'Ag'): int {
        $bbox = card_text_bbox($font, $size, $text);
        return max(1, (int)ceil(abs($bbox[1] - $bbox[7])));
    }

    function card_text_chars(string $text): array {
        if (function_exists('preg_split')) {
            $chars = @preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY);
            if (is_array($chars) && !empty($chars)) return $chars;
        }
        return str_split($text);
    }

    function card_split_long_word(string $word, string $font, int $size, int $maxWidth): array {
        $parts = [];
        $current = '';
        foreach (card_text_chars($word) as $ch) {
            $test = $current . $ch;
            if ($current !== '' && card_text_width($font, $size, $test) > $maxWidth) {
                $parts[] = $current;
                $current = $ch;
            } else {
                $current = $test;
            }
        }
        if ($current !== '') $parts[] = $current;
        return $parts ?: [$word];
    }

    function card_wrap_text(string $text, string $font, int $size, int $maxWidth): array {
        $text = trim(preg_replace('/\s+/u', ' ', (string)$text));
        if ($text === '') return [''];
        if ($maxWidth <= 0) return [$text];

        $words = preg_split('/\s+/u', $text, -1, PREG_SPLIT_NO_EMPTY);
        $lines = [];
        $line = '';

        foreach ($words as $word) {
            $test = $line === '' ? $word : $line . ' ' . $word;
            if (card_text_width($font, $size, $test) <= $maxWidth) {
                $line = $test;
                continue;
            }

            if ($line !== '') {
                $lines[] = $line;
                $line = '';
            }

            if (card_text_width($font, $size, $word) <= $maxWidth) {
                $line = $word;
            } else {
                $chunks = card_split_long_word($word, $font, $size, $maxWidth);
                $last = array_pop($chunks);
                foreach ($chunks as $chunk) $lines[] = $chunk;
                $line = $last ?? '';
            }
        }

        if ($line !== '') $lines[] = $line;
        return $lines ?: [$text];
    }

    function card_fit_text_lines(string $text, string $font, int $startSize, int $minSize, int $maxWidth, int $maxHeight, int $lineGap = 2): array {
        $startSize = max(1, $startSize);
        $minSize = max(1, min($minSize, $startSize));
        $maxWidth = max(1, $maxWidth);
        $maxHeight = max(1, $maxHeight);
        $lineGap = max(0, $lineGap);

        for ($size = $startSize; $size >= $minSize; $size--) {
            $lines = card_wrap_text($text, $font, $size, $maxWidth);
            $lineHeight = card_text_height($font, $size);
            $totalHeight = count($lines) * $lineHeight + max(0, count($lines) - 1) * $lineGap;
            if ($totalHeight <= $maxHeight) {
                return [$lines, $size, $lineHeight, $totalHeight, $lineGap];
            }
        }

        $lines = card_wrap_text($text, $font, $minSize, $maxWidth);
        $lineHeight = card_text_height($font, $minSize);
        $gap = 0;
        $totalHeight = count($lines) * $lineHeight;
        return [$lines, $minSize, $lineHeight, $totalHeight, $gap];
    }

    function card_draw_text_block($im, string $text, int $x, int $y, int $maxWidth, int $maxHeight, $color, string $font, int $startSize, string $align = 'center', int $minSize = 8, int $lineGap = 2): int {
        [$lines, $size, $lineHeight, $totalHeight, $gap] = card_fit_text_lines($text, $font, $startSize, $minSize, $maxWidth, $maxHeight, $lineGap);
        $cursorY = $y;

        foreach ($lines as $line) {
            if (function_exists('imagettftext') && is_file($font)) {
                $bbox = card_text_bbox($font, $size, $line);
                $lineWidth = (int)ceil(abs($bbox[2] - $bbox[0]));
                if ($align === 'right') {
                    $drawX = $x + $maxWidth - $lineWidth - $bbox[0];
                } elseif ($align === 'left') {
                    $drawX = $x - $bbox[0];
                } else {
                    $drawX = $x + (($maxWidth - $lineWidth) / 2) - $bbox[0];
                }
                $baseline = $cursorY - $bbox[7];
                @imagettftext($im, $size, 0, (int)round($drawX), (int)round($baseline), $color, $font, $line);
            } else {
                $fw = (function_exists('imagefontwidth') ? imagefontwidth(5) : 8) * strlen($line);
                if ($align === 'right') $drawX = $x + $maxWidth - $fw;
                elseif ($align === 'left') $drawX = $x;
                else $drawX = $x + (($maxWidth - $fw) / 2);
                imagestring($im, 5, (int)round($drawX), (int)$cursorY, $line, $color);
            }
            $cursorY += $lineHeight + $gap;
        }

        return (int)ceil($totalHeight);
    }
}
