<?php

namespace WPDesk\Library\WPEmail;

use Exception;
use Pelago\Emogrifier\CssInliner;
use Pelago\Emogrifier\HtmlProcessor\CssToAttributeConverter;
use Pelago\Emogrifier\HtmlProcessor\HtmlPruner;
use Psr\Log\LoggerInterface;
use WPDesk\View\Renderer\Renderer;

class Template {

    /**
     * @var LoggerInterface
     */
    private LoggerInterface $logger;

    /**
     * @var Renderer
     */
    private Renderer $renderer;

    /**
     * @var array
     */
    private array $template_attributes;

    public function __construct( LoggerInterface $logger, Renderer $renderer, array $template_attributes ) {
        $this->logger              = $logger;
        $this->renderer            = $renderer;
        $this->template_attributes = wp_parse_args( $template_attributes, $this->get_default_template_attributes() );
    }

    public function get_body( string $content ): string {
        $output = $this->renderer->render( 'html/email-header', $this->template_attributes );
        $output .= $this->renderer->render( 'html/email-content', [ 'content' => $content ] );
        $output .= $this->renderer->render( 'html/email-footer', [ 'footer' => $this->template_attributes['footer'] ] );

        return $this->css_inline( $output );
    }

    /**
     * @param string $content
     *
     * @return mixed|string
     */
    public function css_inline( string $content ): string {
        $styles = $this->renderer->render( 'html/email-styles', $this->template_attributes );

        return $this->convert_css( $content, $styles );
    }

    public function get_default_template_attributes(): array {
        return [
            'heading' => '',
            'logo'    => '',
            'footer'  => '',
            'primary' => '#d15291',
            'text'    => '#303030',
            'bg'      => '#f9f9f9',
            'body'    => '#ffffff',
        ];
    }

    public function convert_css( string $content, string $styles = '' ): string {
        if ( class_exists( 'DOMDocument' ) ) {
            try {
                $css_inliner  = CssInliner::fromHtml( $content )->inlineCss( $styles );
                $dom_document = $css_inliner->getDomDocument();
                HtmlPruner::fromDomDocument( $dom_document )->removeElementsWithDisplayNone();
                $content = CssToAttributeConverter::fromDomDocument( $dom_document )->convertCssToVisualAttributes()->render();
            } catch ( Exception $e ) {
                $this->logger->debug( $e->getMessage() );

                return $content;
            }
        } else {
            $content = '<style>' . strip_tags( $styles ) . '</style>' . $content;
        }

        return $content;
    }

}