Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
336 / 336
100.00% covered (success)
100.00%
19 / 19
CRAP
100.00% covered (success)
100.00%
1 / 1
TemplateVisualComponentRenderer
100.00% covered (success)
100.00%
335 / 335
100.00% covered (success)
100.00%
19 / 19
63
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 companyLogo
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
1
 relatedTable
100.00% covered (success)
100.00%
38 / 38
100.00% covered (success)
100.00%
1 / 1
7
 resolveColumnLabel
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
10
 resolveColumnAlign
100.00% covered (success)
100.00%
13 / 13
100.00% covered (success)
100.00%
1 / 1
3
 renderRelatedTableRows
100.00% covered (success)
100.00%
18 / 18
100.00% covered (success)
100.00%
1 / 1
6
 formatItemCellValue
100.00% covered (success)
100.00%
38 / 38
100.00% covered (success)
100.00%
1 / 1
12
 formatItemNameCell
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 qrCode
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
1
 barcode
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
1
 bankTransferQr
100.00% covered (success)
100.00%
34 / 34
100.00% covered (success)
100.00%
1 / 1
2
 verificationBadge
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
1
 chartSparkline
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
4
 pageBreak
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 statusBadge
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
2
 formatCurrency
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
3
 renderFinancialSummaryFooter
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
1
 renderSparklinePolyline
100.00% covered (success)
100.00%
19 / 19
100.00% covered (success)
100.00%
1 / 1
3
 renderSparklineBars
100.00% covered (success)
100.00%
24 / 24
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3declare(strict_types=1);
4
5/** @license For full copyright and license information, please see the LICENSE.md file. */
6
7namespace App\Core\Template\Application\Service;
8
9defined('AMMONLY_APP') || exit('Direct script access is forbidden.');
10
11/**
12 * Renders visual HTML and inline SVG components for email and PDF document templates.
13 *
14 * Provides branding logos, line-item data tables, QR codes, barcodes,
15 * bank transfer snippets, verification badges, and sparkline charts.
16 *
17 * @package App\Core\Template\Application\Service
18 */
19final readonly class TemplateVisualComponentRenderer
20{
21    private const string TABLE_CELL_STYLE = 'overflow: hidden; word-break: break-word; box-sizing: border-box;">';
22
23    /**
24     * TemplateVisualComponentRenderer constructor.
25     *
26     * @param (callable(float|int|string|null, string): string)|null $currencyFormatter Optional currency formatter.
27     */
28    public function __construct(private mixed $currencyFormatter = null)
29    {
30    }
31
32    /**
33     * Renders responsive inline SVG / HTML company brand logo.
34     *
35     * @param int    $maxWidth  Maximum width in pixels.
36     * @param int    $maxHeight Maximum height in pixels.
37     * @param string $alt       Alternative accessibility text.
38     * @return string HTML/SVG logo markup.
39     */
40    public function companyLogo(int $maxWidth = 180, int $maxHeight = 60, string $alt = 'Company Logo'): string
41    {
42        $safeAlt = htmlspecialchars($alt, ENT_QUOTES, 'UTF-8');
43
44        return sprintf(
45            '<div class="template-logo-box" style="display:inline-block;max-width:%dpx;max-height:%dpx;">'
46            . '<svg width="%d" height="%d" viewBox="0 0 180 50" fill="none" xmlns="http://www.w3.org/2000/svg" '
47            . 'aria-label="%s">'
48            . '<rect width="180" height="50" rx="6" fill="#0f172a"/>'
49            . '<circle cx="28" cy="25" r="14" fill="#3b82f6"/>'
50            . '<path d="M22 25L26 29L34 21" stroke="#ffffff" stroke-width="3" stroke-linecap="round"/>'
51            . '<text x="52" y="32" font-family="sans-serif" font-size="20" font-weight="bold" fill="#ffffff">'
52            . 'AMMONLY</text></svg></div>',
53            $maxWidth,
54            $maxHeight,
55            $maxWidth,
56            $maxHeight,
57            $safeAlt
58        );
59    }
60
61    /**
62     * Generates styled HTML table for related line items or child entities.
63     *
64     * @param string               $relationName Relation or dataset name.
65     * @param array<int, string>   $columns      Column keys to display.
66     * @param array<string, mixed> $options      Display options (title, show_total).
67     * @return string Rendered HTML table markup.
68     */
69    public function relatedTable(string $relationName, array $columns = [], array $options = []): string
70    {
71        $title = (string)($options['title'] ?? ucfirst(str_replace('_', ' ', $relationName)));
72        $showTotal = (bool)($options['show_total'] ?? false);
73        $showFin = (bool)($options['show_financial_summary'] ?? false);
74        $currency = htmlspecialchars((string)($options['currency'] ?? 'PLN'), ENT_QUOTES, 'UTF-8');
75
76        $html = '<div class="template-table-wrapper" style="margin: 15px 0; width: 100%; max-width: 100%;">';
77        if ($title !== '') {
78            $html .= '<h4 style="margin: 0 0 8px 0; font-size: 11pt; color: #1e293b;">'
79                . htmlspecialchars($title, ENT_QUOTES, 'UTF-8') . '</h4>';
80        }
81
82        $html .= '<table class="template-data-table" style="width: 100%; max-width: 100%; table-layout: fixed; '
83            . 'border-collapse: collapse; font-size: 10pt; box-sizing: border-box;">'
84            . '<thead><tr style="background-color: #f1f5f9; border-bottom: 2px solid #cbd5e1;">';
85
86        foreach ($columns as $col) {
87            $colLabel = $this->resolveColumnLabel($col);
88            $align = $this->resolveColumnAlign($col);
89            $html .= '<th style="padding: 6px 10px; text-align: ' . $align . '; color: #475569; font-weight: 600; '
90                . self::TABLE_CELL_STYLE
91                . htmlspecialchars($colLabel, ENT_QUOTES, 'UTF-8') . '</th>';
92        }
93        $html .= '</tr></thead><tbody>';
94
95        $rawItems = $options['items'] ?? [];
96        if (is_array($rawItems) && $rawItems !== []) {
97            $html .= $this->renderRelatedTableRows($rawItems, $columns, $currency);
98        } else {
99            $html .= '<tr><td colspan="' . max(1, count($columns))
100                . '" style="padding: 10px; text-align: center; color: #64748b; font-style: italic; '
101                . self::TABLE_CELL_STYLE
102                . 'No related items to display'
103                . '</td></tr>';
104        }
105        $html .= '</tbody>';
106
107        if ($showFin) {
108            $html .= $this->renderFinancialSummaryFooter($columns, $currency);
109        } elseif ($showTotal) {
110            $html .= '<tfoot><tr style="border-top: 2px solid #cbd5e1; font-weight: bold; background: #f8fafc;">'
111                . '<td colspan="' . max(1, count($columns) - 1) . '" style="padding: 8px 10px; text-align: right; '
112                . self::TABLE_CELL_STYLE
113                . 'Total:</td><td style="padding: 8px 10px; text-align: right; '
114                . self::TABLE_CELL_STYLE
115                . '0.00</td></tr></tfoot>';
116        }
117        $html .= '</table></div>';
118
119        return $html;
120    }
121
122    /**
123     * Resolves human-readable column label.
124     */
125    private function resolveColumnLabel(string $col): string
126    {
127        return match ($col) {
128            'name', 'item_name'                     => 'Pozycja / Nazwa',
129            'quantity', 'qty'                       => 'Ilość',
130            'price_net', 'unit_price'               => 'Cena netto',
131            'discount', 'discount_percent'          => 'Rabat',
132            'amount_net', 'net_amount'              => 'Wartość netto',
133            'vat_rate', 'tax_percent'               => 'VAT',
134            'amount_vat', 'tax_amount'              => 'Kwota VAT',
135            'amount_gross', 'gross_amount'          => 'Wartość brutto',
136            default                                 => ucfirst(str_replace('_', ' ', $col)),
137        };
138    }
139
140    /**
141     * Resolves column text alignment.
142     */
143    private function resolveColumnAlign(string $col): string
144    {
145        if (in_array($col, ['quantity', 'qty', 'vat_rate', 'tax_percent'], true)) {
146            return 'center';
147        }
148        if (in_array(
149            $col,
150            [
151                'price_net', 'unit_price', 'discount', 'discount_percent',
152                'amount_net', 'net_amount', 'amount_vat', 'tax_amount',
153                'amount_gross', 'gross_amount',
154            ],
155            true
156        )) {
157            return 'right';
158        }
159        return 'left';
160    }
161
162    /**
163     * Renders table rows for related line items.
164     *
165     * @param array<int, array<string, mixed>> $items
166     * @param array<int, string>               $columns
167     */
168    private function renderRelatedTableRows(array $items, array $columns, string $currency): string
169    {
170        $html = '';
171        $currentGroup = null;
172
173        foreach ($items as $idx => $item) {
174            $groupName = trim((string)($item['group_name'] ?? ''));
175            if ($groupName !== '' && $groupName !== $currentGroup) {
176                $currentGroup = $groupName;
177                $html .= '<tr style="background:#e2e8f0;font-weight:bold;color:#1e293b;">'
178                    . '<td colspan="' . count($columns) . '" style="padding:5px 10px;' . self::TABLE_CELL_STYLE
179                    . htmlspecialchars($groupName, ENT_QUOTES, 'UTF-8') . '</td></tr>';
180            }
181
182            $bg = $idx % 2 === 0 ? '#ffffff' : '#f8fafc';
183            $html .= '<tr style="background:' . $bg . ';border-bottom:1px solid #e2e8f0;">';
184
185            foreach ($columns as $col) {
186                $align = $this->resolveColumnAlign($col);
187                $formattedVal = $this->formatItemCellValue($item, $col, $currency);
188                $html .= '<td style="padding:6px 10px;text-align:' . $align . ';' . self::TABLE_CELL_STYLE
189                    . $formattedVal . '</td>';
190            }
191
192            $html .= '</tr>';
193        }
194
195        return $html;
196    }
197
198    /**
199     * Formats individual cell value for line item.
200     *
201     * @param array<string, mixed> $item Item row.
202     * @param string               $col  Column key.
203     * @param string               $currency Currency code.
204     */
205    private function formatItemCellValue(array $item, string $col, string $currency): string
206    {
207        return match ($col) {
208            'name', 'item_name' => $this->formatItemNameCell($item),
209            'quantity', 'qty' => number_format((float)($item['quantity'] ?? 1), 2, ',', ' ')
210                . (!empty($item['unit']) ? ' ' . htmlspecialchars((string)$item['unit'], ENT_QUOTES, 'UTF-8') : ''),
211            'price_net', 'unit_price' => number_format(
212                (float)($item['unit_price'] ?? ($item['price_net'] ?? 0)),
213                2,
214                ',',
215                ' '
216            ) . ' ' . $currency,
217            'discount', 'discount_percent' => (float)($item['discount_percent'] ?? 0) > 0
218                ? number_format((float)$item['discount_percent'], 2, ',', ' ') . '%'
219                : '-',
220            'amount_net', 'net_amount' => number_format(
221                (float)($item['net_amount'] ?? ($item['amount_net'] ?? 0)),
222                2,
223                ',',
224                ' '
225            ) . ' ' . $currency,
226            'vat_rate', 'tax_percent' => htmlspecialchars(
227                rtrim(rtrim((string)($item['tax_percent'] ?? ($item['vat_rate'] ?? '23')), '0'), '.') . '%',
228                ENT_QUOTES,
229                'UTF-8'
230            ),
231            'amount_vat', 'tax_amount' => number_format(
232                (float)($item['tax_amount'] ?? ($item['amount_vat'] ?? 0)),
233                2,
234                ',',
235                ' '
236            ) . ' ' . $currency,
237            'amount_gross', 'gross_amount' => '<strong>' . number_format(
238                (float)($item['gross_amount'] ?? ($item['amount_gross'] ?? 0)),
239                2,
240                ',',
241                ' '
242            ) . ' ' . $currency . '</strong>',
243            default => htmlspecialchars((string)($item[$col] ?? '-'), ENT_QUOTES, 'UTF-8'),
244        };
245    }
246
247    /**
248     * Formats name cell with optional comment or SKU.
249     *
250     * @param array<string, mixed> $item Item data.
251     */
252    private function formatItemNameCell(array $item): string
253    {
254        $name = htmlspecialchars((string)($item['item_name'] ?? ($item['name'] ?? 'Pozycja')), ENT_QUOTES, 'UTF-8');
255        if (!empty($item['comment'])) {
256            $name .= '<br><span style="font-size:8pt;color:#64748b;">'
257                . htmlspecialchars((string)$item['comment'], ENT_QUOTES, 'UTF-8') . '</span>';
258        }
259        return $name;
260    }
261
262    /**
263     * Generates lightweight vector SVG QR Code representation.
264     *
265     * @param string $data Data string to encode.
266     * @param int    $size Pixel dimension of the code square.
267     * @return string SVG QR code markup.
268     */
269    public function qrCode(string $data, int $size = 120): string
270    {
271        $safeData = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
272
273        return sprintf(
274            '<div class="template-qr-box" style="display:inline-block;width:%dpx;height:%dpx;padding:4px;'
275            . 'background:#ffffff;border:1px solid #e2e8f0;border-radius:4px;" title="%s">'
276            . '<svg width="%d" height="%d" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">'
277            . '<rect x="10" y="10" width="30" height="30" stroke="#0f172a" stroke-width="6" fill="none"/>'
278            . '<rect x="18" y="18" width="14" height="14" fill="#0f172a"/>'
279            . '<rect x="60" y="10" width="30" height="30" stroke="#0f172a" stroke-width="6" fill="none"/>'
280            . '<rect x="68" y="18" width="14" height="14" fill="#0f172a"/>'
281            . '<rect x="10" y="60" width="30" height="30" stroke="#0f172a" stroke-width="6" fill="none"/>'
282            . '<rect x="18" y="68" width="14" height="14" fill="#0f172a"/>'
283            . '<rect x="50" y="50" width="10" height="10" fill="#3b82f6"/>'
284            . '<rect x="70" y="70" width="15" height="15" fill="#0f172a"/>'
285            . '</svg></div>',
286            $size,
287            $size,
288            $safeData,
289            $size - 8,
290            $size - 8
291        );
292    }
293
294    /**
295     * Generates vector barcode representation.
296     *
297     * @param string $code Numeric or alphanumeric code string.
298     * @param string $type Barcode specification (e.g. C128).
299     * @return string SVG Barcode markup.
300     */
301    public function barcode(string $code, string $type = 'C128'): string
302    {
303        $safeCode = htmlspecialchars($code, ENT_QUOTES, 'UTF-8');
304        $safeType = htmlspecialchars($type, ENT_QUOTES, 'UTF-8');
305
306        return sprintf(
307            '<div class="template-barcode-box" data-barcode-type="%s" style="display:inline-block;text-align:center;">'
308            . '<svg width="160" height="42" viewBox="0 0 160 42" xmlns="http://www.w3.org/2000/svg">'
309            . '<rect x="4" y="2" width="4" height="36" fill="#000000"/>'
310            . '<rect x="12" y="2" width="2" height="36" fill="#000000"/>'
311            . '<rect x="18" y="2" width="6" height="36" fill="#000000"/>'
312            . '<rect x="28" y="2" width="2" height="36" fill="#000000"/>'
313            . '<rect x="34" y="2" width="4" height="36" fill="#000000"/>'
314            . '<rect x="44" y="2" width="6" height="36" fill="#000000"/>'
315            . '<rect x="54" y="2" width="2" height="36" fill="#000000"/>'
316            . '<rect x="60" y="2" width="4" height="36" fill="#000000"/>'
317            . '<rect x="70" y="2" width="6" height="36" fill="#000000"/>'
318            . '<rect x="80" y="2" width="2" height="36" fill="#000000"/>'
319            . '<rect x="86" y="2" width="4" height="36" fill="#000000"/>'
320            . '<rect x="96" y="2" width="6" height="36" fill="#000000"/>'
321            . '<rect x="108" y="2" width="4" height="36" fill="#000000"/>'
322            . '<rect x="116" y="2" width="2" height="36" fill="#000000"/>'
323            . '<rect x="124" y="2" width="6" height="36" fill="#000000"/>'
324            . '<rect x="136" y="2" width="4" height="36" fill="#000000"/>'
325            . '<rect x="146" y="2" width="4" height="36" fill="#000000"/>'
326            . '</svg>'
327            . '<div style="font-family:monospace;font-size:8pt;color:#334155;letter-spacing:2px;">%s</div></div>',
328            $safeType,
329            $safeCode
330        );
331    }
332
333    /**
334     * Generates Polish standard ZBP / EPC-QR bank transfer barcode snippet with details.
335     *
336     * @param string           $account   Bank account number (IBAN / 26 digits).
337     * @param string           $recipient Recipient business name.
338     * @param float|int|string $amount    Transfer amount in currency units.
339     * @param string           $title     Payment title / reference.
340     * @param string           $currency  Currency code (default PLN).
341     * @return string Rendered HTML bank transfer block.
342     */
343    public function bankTransferQr(
344        string $account,
345        string $recipient,
346        float|int|string $amount,
347        string $title,
348        string $currency = 'PLN'
349    ): string {
350        $cleanAccount = preg_replace('/[^0-9A-Za-z]/', '', $account) ?? '';
351        $amountFloat = is_numeric($amount) ? (float)$amount : 0.0;
352        $amountInGrosze = (int)round($amountFloat * 100);
353
354        $qrPayload = sprintf(
355            '||%s|%06d|%s|%s|||',
356            $cleanAccount,
357            $amountInGrosze,
358            mb_substr(trim($recipient), 0, 70),
359            mb_substr(trim($title), 0, 140)
360        );
361
362        $safeAccount = htmlspecialchars(chunk_split($cleanAccount, 4, ' '), ENT_QUOTES, 'UTF-8');
363        $safeRecipient = htmlspecialchars($recipient, ENT_QUOTES, 'UTF-8');
364        $safeTitle = htmlspecialchars($title, ENT_QUOTES, 'UTF-8');
365        $formattedAmount = $this->formatCurrency($amountFloat, $currency);
366
367        return sprintf(
368            '<div class="bank-transfer-qr-box" style="border:1px solid #cbd5e1;background:#f8fafc;'
369            . 'border-radius:6px;padding:12px;margin:12px 0;width:100%%;box-sizing:border-box;">'
370            . '<table style="width:100%%;border-collapse:collapse;"><tr>'
371            . '<td style="width:110px;vertical-align:top;padding-right:12px;">'
372            . '%s</td>'
373            . '<td style="vertical-align:top;font-size:9pt;line-height:1.4;color:#1e293b;">'
374            . '<strong style="font-size:10pt;color:#0f172a;display:block;margin-bottom:4px;">'
375            . 'Fast Payment QR Code</strong>'
376            . '<div><span style="color:#64748b;">Account:</span> <strong>%s</strong></div>'
377            . '<div><span style="color:#64748b;">Recipient:</span> %s</div>'
378            . '<div><span style="color:#64748b;">Title:</span> %s</div>'
379            . '<div><span style="color:#64748b;">Amount:</span> <strong style="color:#2563eb;">%s</strong></div>'
380            . '</td></tr></table></div>',
381            $this->qrCode($qrPayload, 100),
382            $safeAccount,
383            $safeRecipient,
384            $safeTitle,
385            $formattedAmount
386        );
387    }
388
389    /**
390     * Generates a digital verification badge with cryptographic SHA-256 hash.
391     *
392     * @param string      $hash    Cryptographic document verification hash.
393     * @param string|null $baseUrl Optional verification URL root.
394     * @return string Rendered HTML verification badge.
395     */
396    public function verificationBadge(string $hash, ?string $baseUrl = null): string
397    {
398        $root = $baseUrl ?? 'https://app-admin.ammonly.com';
399        $verifyUrl = rtrim($root, '/') . '/verify/' . urlencode($hash);
400        $safeHash = htmlspecialchars($hash, ENT_QUOTES, 'UTF-8');
401        $shortHash = mb_substr($safeHash, 0, 16) . '...';
402
403        return sprintf(
404            '<div class="pdf-verification-badge" style="border:1px solid #10b981;background:#ecfdf5;'
405            . 'border-radius:6px;padding:8px 12px;margin:12px 0;display:inline-block;font-size:8.5pt;">'
406            . '<table style="border-collapse:collapse;"><tr>'
407            . '<td style="vertical-align:middle;padding-right:10px;">%s</td>'
408            . '<td style="vertical-align:middle;line-height:1.3;color:#065f46;">'
409            . '<strong style="color:#047857;font-size:9pt;display:block;">'
410            . 'Document Authenticity Certificate</strong>'
411            . '<div>SHA-256: <code style="background:#d1fae5;padding:1px 4px;border-radius:3px;">%s</code></div>'
412            . '<div style="margin-top:2px;"><a href="%s" style="color:#059669;text-decoration:none;'
413            . 'font-weight:600;">Verify online &rarr;</a></div>'
414            . '</td></tr></table></div>',
415            $this->qrCode($verifyUrl, 54),
416            $shortHash,
417            htmlspecialchars($verifyUrl, ENT_QUOTES, 'UTF-8')
418        );
419    }
420
421    /**
422     * Generates inline vector SVG sparkline chart (bar or line) without external JS.
423     *
424     * @param array<int, float|int> $values Numeric data series.
425     * @param string                $type   Chart format: 'bar' or 'line'.
426     * @param int                   $width  SVG width in pixels.
427     * @param int                   $height SVG height in pixels.
428     * @param string                $color  Primary chart fill/stroke color.
429     * @return string Inline SVG chart markup.
430     */
431    public function chartSparkline(
432        array $values,
433        string $type = 'bar',
434        int $width = 120,
435        int $height = 32,
436        string $color = '#2563eb'
437    ): string {
438        if ($values === []) {
439            $values = [10, 25, 40, 30, 50, 65, 80];
440        }
441
442        $min = min($values);
443        $max = max($values);
444        $range = ($max - $min) > 0 ? ($max - $min) : 1.0;
445        $count = count($values);
446        $safeColor = htmlspecialchars($color, ENT_QUOTES, 'UTF-8');
447
448        if ($type === 'line') {
449            return $this->renderSparklinePolyline($values, $min, $range, $count, $width, $height, $safeColor);
450        }
451
452        return $this->renderSparklineBars($values, $min, $range, $count, $width, $height, $safeColor);
453    }
454
455    /**
456     * Emits clean CSS page break markup for PDF rendering engines.
457     *
458     * @return string Page-break HTML snippet.
459     */
460    public function pageBreak(): string
461    {
462        return '<div class="pdf-page-break" style="page-break-after: always; break-after: page;"></div>';
463    }
464
465    /**
466     * Renders standard status badge tag.
467     *
468     * @param string|int|null $status Status key code.
469     * @param string          $label  Optional display label.
470     * @return string HTML status badge markup.
471     */
472    public function statusBadge(string|int|null $status, string $label = ''): string
473    {
474        $statusStr = (string)($status ?? 'default');
475        $displayLabel = $label !== '' ? $label : ucfirst($statusStr);
476
477        $colorMap = [
478            'active'    => '#10b981',
479            'closed'    => '#64748b',
480            'pending'   => '#f59e0b',
481            'urgent'    => '#ef4444',
482            'in_prog'   => '#3b82f6',
483            'completed' => '#10b981',
484        ];
485
486        $bgColor = $colorMap[strtolower($statusStr)] ?? '#64748b';
487
488        return sprintf(
489            '<span class="template-status-badge" style="display:inline-block;padding:2px 8px;'
490            . 'font-size:8pt;font-weight:600;color:#ffffff;background-color:%s;border-radius:4px;">%s</span>',
491            $bgColor,
492            htmlspecialchars($displayLabel, ENT_QUOTES, 'UTF-8')
493        );
494    }
495
496    /**
497     * Formats currency with internal fallback if formatter not provided.
498     */
499    private function formatCurrency(float|int|string|null $amount, string $currency): string
500    {
501        if ($this->currencyFormatter !== null) {
502            return ($this->currencyFormatter)($amount, $currency);
503        }
504
505        $val = is_numeric($amount) ? (float)$amount : 0.0;
506        return number_format($val, 2, ',', ' ') . ' ' . $currency;
507    }
508
509    /**
510     * Renders financial summary footer for related table.
511     *
512     * @param array<int, string> $columns  Column definitions.
513     * @param string             $currency Currency string.
514     * @return string Rendered footer HTML.
515     */
516    private function renderFinancialSummaryFooter(array $columns, string $currency): string
517    {
518        $colspan = max(1, count($columns) - 1);
519        $currExport = var_export($currency, true);
520
521        return '<tfoot>'
522            . '<tr style="border-top: 2px solid #cbd5e1; background: #f8fafc;">'
523            . '<td colspan="' . $colspan . '" style="padding: 6px 10px; text-align: right; color: #64748b; '
524            . self::TABLE_CELL_STYLE
525            . 'Total Net:</td>'
526            . '<td style="padding: 6px 10px; text-align: right; font-weight: 600; '
527            . self::TABLE_CELL_STYLE
528            . '{{ record.amount_net|default(\'0,00\')|format_currency(' . $currExport . ') }}</td>'
529            . '</tr>'
530            . '<tr style="background: #f8fafc;">'
531            . '<td colspan="' . $colspan . '" style="padding: 6px 10px; text-align: right; color: #64748b; '
532            . self::TABLE_CELL_STYLE
533            . 'Tax Amount:</td>'
534            . '<td style="padding: 6px 10px; text-align: right; font-weight: 600; '
535            . self::TABLE_CELL_STYLE
536            . '{{ record.amount_vat|default(\'0,00\')|format_currency(' . $currExport . ') }}</td>'
537            . '</tr>'
538            . '<tr style="border-top: 2px solid #0f172a; font-weight: bold; background: #f1f5f9;">'
539            . '<td colspan="' . $colspan . '" style="padding: 8px 10px; text-align: right; color: #0f172a; '
540            . self::TABLE_CELL_STYLE
541            . 'Total Gross (Due):</td>'
542            . '<td style="padding: 8px 10px; text-align: right; color: #2563eb; font-size: 11pt; '
543            . self::TABLE_CELL_STYLE
544            . '{{ record.amount_gross|default(\'0,00\')|format_currency(' . $currExport . ') }}</td>'
545            . '</tr></tfoot>';
546    }
547
548    /**
549     * Renders SVG polyline for sparkline chart.
550     */
551    private function renderSparklinePolyline(
552        array $values,
553        float|int $min,
554        float|int $range,
555        int $count,
556        int $width,
557        int $height,
558        string $safeColor
559    ): string {
560        $points = [];
561        $step = $count > 1 ? ($width - 8) / ($count - 1) : 0;
562        foreach (array_values($values) as $i => $val) {
563            $x = 4 + ($i * $step);
564            $normalized = ($val - $min) / $range;
565            $y = ($height - 4) - ($normalized * ($height - 8));
566            $points[] = sprintf('%.1f,%.1f', $x, $y);
567        }
568
569        return sprintf(
570            '<svg class="template-sparkline" width="%d" height="%d" viewBox="0 0 %d %d" '
571            . 'xmlns="http://www.w3.org/2000/svg" style="vertical-align:middle;">'
572            . '<polyline fill="none" stroke="%s" stroke-width="2" stroke-linecap="round" '
573            . 'stroke-linejoin="round" points="%s"/></svg>',
574            $width,
575            $height,
576            $width,
577            $height,
578            $safeColor,
579            implode(' ', $points)
580        );
581    }
582
583    /**
584     * Renders SVG rect bars for sparkline chart.
585     */
586    private function renderSparklineBars(
587        array $values,
588        float|int $min,
589        float|int $range,
590        int $count,
591        int $width,
592        int $height,
593        string $safeColor
594    ): string {
595        $barWidth = max(2, (int)floor(($width - ($count * 2)) / $count));
596        $bars = '';
597        foreach (array_values($values) as $i => $val) {
598            $x = $i * ($barWidth + 2) + 2;
599            $normalized = ($val - $min) / $range;
600            $barHeight = max(2, (int)round($normalized * ($height - 4)));
601            $y = $height - $barHeight;
602            $bars .= sprintf(
603                '<rect x="%d" y="%d" width="%d" height="%d" fill="%s" rx="1"/>',
604                $x,
605                $y,
606                $barWidth,
607                $barHeight,
608                $safeColor
609            );
610        }
611
612        return sprintf(
613            '<svg class="template-sparkline" width="%d" height="%d" viewBox="0 0 %d %d" '
614            . 'xmlns="http://www.w3.org/2000/svg" style="vertical-align:middle;">%s</svg>',
615            $width,
616            $height,
617            $width,
618            $height,
619            $bars
620        );
621    }
622}