<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * @param string $title
 * @param string $body
 * @param bool   $show_footer Zobrazit patičku „Odesláno přes ElementSell“.
 */
function elementsell_email_template( $title, $body, $show_footer = true ) {

    $title = esc_html( $title );
    $heading = $title !== ''
        ? '<h1 style="margin:0 0 20px; font-size:26px; line-height:1.3;">' . $title . '</h1>'
        : '';
    // $body může už obsahovat bezpečné HTML bloky (tlačítka) z elementsell_format_email_body_with_blocks().
    if ( strpos( (string) $body, '<p' ) === false && strpos( (string) $body, '<a ' ) === false ) {
        $body = wpautop( wp_kses_post( $body ) );
    }

    $footer = $show_footer
        ? '<p style="text-align:center; color:#999; font-size:12px; margin-top:18px;">
                Odesláno přes ElementSell
            </p>'
        : '';

    return '
    <div style="margin:0; padding:0; background:#f4f4f4; font-family:Arial,sans-serif;">
        <div style="max-width:640px; margin:0 auto; padding:30px 16px;">
            <div style="background:#ffffff; border-radius:14px; padding:32px; color:#222;">
                ' . $heading . '
                <div style="font-size:16px; line-height:1.7;">
                    ' . $body . '
                </div>
            </div>
            ' . $footer . '
        </div>
    </div>';
}

/**
 * Převede text upomínky na HTML — odstavce + vložená tlačítka.
 *
 * @param string $body
 * @return string
 */
function elementsell_format_email_body_with_blocks( $body ) {
    $body = trim( (string) $body );

    if ( $body === '' ) {
        return '';
    }

    $chunks = preg_split( '/\n\s*\n/', $body );
    $html   = '';

    foreach ( (array) $chunks as $chunk ) {
        $chunk = trim( $chunk );

        if ( $chunk === '' ) {
            continue;
        }

        if ( strpos( $chunk, '<a ' ) !== false || strpos( $chunk, '<p style=' ) !== false || strpos( $chunk, '<p class=' ) !== false || strpos( $chunk, '<table' ) !== false || strpos( $chunk, 'elementsell-action-email-summary' ) !== false ) {
            $html .= $chunk;
            continue;
        }

        $html .= '<p style="margin:0 0 16px;">' . nl2br( esc_html( $chunk ) ) . '</p>';
    }

    return $html;
}