<?php
namespace Domain\Newsletter;

class NewsletterPreviewRenderer
{
    public function render(array $articles, array $settings, ?array $template, string $dates = ''): string
    {
        $out = '<div style="border-bottom: 1px solid #ccc;">';
        $out .= !empty($settings['newsletter_header'])
            ? (string)$settings['newsletter_header']
            : '<p style="text-align: center;">--- brak zdefiniowanego naglowka ---</p>';
        $out .= '</div>';

        $out .= '<div style="border-bottom: 1px solid #ccc; padding: 10px 0 0 0;">';

        if (is_array($template) && !empty($template)) {
            $out .= '<div style="padding: 10px; background: #F1F1F1; margin-bottom: 10px">';
            $out .= (string)($template['text'] ?? '');
            $out .= '</div>';
        }

        if (is_array($articles) && !empty($articles)) {
            foreach ($articles as $article) {
                $articleId = (int)($article['id'] ?? 0);
                $title = (string)($article['language']['title'] ?? '');
                $seoLink = trim((string)($article['language']['seo_link'] ?? ''));
                $url = $seoLink !== '' ? $seoLink : ('a-' . $articleId . '-' . \Shared\Helpers\Helpers::seo($title));
                $entry = !empty($article['language']['entry'])
                    ? (string)$article['language']['entry']
                    : (string)($article['language']['text'] ?? '');

                $out .= '<div style="padding: 10px; background: #F1F1F1; margin-bottom: 10px">';
                $out .= '<a href="http://' . htmlspecialchars((string)($_SERVER['SERVER_NAME'] ?? ''), ENT_QUOTES, 'UTF-8') . '/'
                    . htmlspecialchars($url, ENT_QUOTES, 'UTF-8')
                    . '" title="' . htmlspecialchars($title, ENT_QUOTES, 'UTF-8')
                    . '" style="margin-bottom: 10px; display: block; font-size: 14px; color: #5b7fb1; font-weight: 600;">'
                    . htmlspecialchars($title, ENT_QUOTES, 'UTF-8')
                    . '</a>';
                $out .= '<div>' . $entry . '</div>';
                $out .= '<div style="clear: both;"></div>';
                $out .= '</div>';
            }
        } elseif (trim($dates) !== '') {
            $out .= '<div style="padding: 10px; background: #F1F1F1; margin-bottom: 10px; text-align: center;">';
            $out .= '--- brak artykulow w danym okresie ---';
            $out .= '</div>';
        }

        $out .= '</div>';

        $out .= '<div style="border-bottom: 1px solid #ccc; padding: 10px 0 0 0;">';
        $out .= !empty($settings['newsletter_footer'])
            ? (string)$settings['newsletter_footer']
            : '<p style="text-align: center;">--- brak zdefiniowanej stopki ---</p>';
        $out .= '</div>';

        return $out;
    }
}
