<?php

declare(strict_types=1);

namespace PpPhp\Core\DataOps\Formats;

use PpPhp\Core\DataOps\ExportFormat;

/**
 * Shared body for the Office formats: Word and Excel both open a styled HTML
 * <table> perfectly well, which keeps the export dependency-free. Subclasses
 * only declare their identity.
 */
abstract class HtmlTableFormat implements ExportFormat
{
    public function write(array $rows, array $columns, array $meta): void
    {
        $caption = (string) ($meta['caption'] ?? '');
        $brand   = (string) ($meta['brand'] ?? '');
        $title   = $brand !== '' ? $brand . ' — ' . $caption : $caption;
        $cols    = max(1, count($columns));

        echo '<html><head><meta charset="utf-8"><style>'
            . 'th{background:#eef2f7;font-weight:bold;text-align:left}'
            . 'td,th{border:1px solid #cbd5e1;padding:4px 8px}'
            . '</style></head><body>';

        echo '<table border="0"><tr><td colspan="' . $cols . '" style="font-size:15pt;font-weight:bold;border:0;padding:2px 0">'
            . htmlspecialchars($title) . '</td></tr>';
        echo '<tr><td colspan="' . $cols . '" style="color:#666;border:0;padding:0 0 6px">'
            . count($rows) . ' record(s) · ' . htmlspecialchars((string) ($meta['generatedAt'] ?? date('M j, Y g:i a')))
            . '</td></tr></table>';

        echo '<table border="1" style="border-collapse:collapse">';
        if (($meta['includeHeaders'] ?? true) !== false) {
            echo '<tr>';
            foreach ($columns as $label) echo '<th>' . htmlspecialchars((string) $label) . '</th>';
            echo '</tr>';
        }
        foreach ($rows as $r) {
            echo '<tr>';
            foreach (array_keys($columns) as $c) echo '<td>' . htmlspecialchars((string) ($r[$c] ?? '')) . '</td>';
            echo '</tr>';
        }
        echo '</table></body></html>';
    }
}
