<?php

defined( 'ABSPATH' ) || exit;

use EmailCraft\App\DTO\ContentDTO;
use EmailCraft\App\Repositories\TemplateRepository;
use EmailCraft\App\Repositories\TemplateTypeRepository;
use EmailCraft\App\Helpers\SmartTag;
use EmailCraft\WpMVC\View\View;
use EmailCraft\WpMVC\App;
use EmailCraft\DI\Container;

function emailcraft():App {
    return App::$instance;
}

function emailcraft_config( string $config_key ) {
    return emailcraft()::$config->get( $config_key );
}

function emailcraft_app_config( string $config_key ) {
    return emailcraft_config( "app.{$config_key}" );
}

function emailcraft_version() {
    return emailcraft_app_config( 'version' );
}

function emailcraft_container():Container {
    return emailcraft()::$container;
}

/**
 * @template T of object
 * @param class-string<T> $class
 * @return T
 */
function emailcraft_singleton( string $class ) {
    return emailcraft_container()->get( $class );
}

function emailcraft_url( string $url = '' ) {
    return emailcraft()->get_url( $url );
}

function emailcraft_dir( string $dir = '' ) {
    return emailcraft()->get_dir( $dir );
}

function emailcraft_get_email_content( $dto ): string {
    $repository = emailcraft_singleton( TemplateRepository::class );

    $template = $repository->get_template( $dto->get_integration(), $dto->get_template_type() );

    if ( empty( $template->post_id ) ) {
        return false;
    }

    $settings = get_post_meta( $template->post_id, '_emailcraft_settings', true );
    $content  = do_blocks( $template->post_content );

    $dto->set_content( $content )->set_settings( $settings );

    return emailcraft_process_email_content( $dto );
}

function emailcraft_process_email_content( ContentDTO $dto ): string {
    $smart_tag = emailcraft_singleton( SmartTag::class );
    $content   = View::get(
        'email', [
            'content'  => $smart_tag->process( $dto ),
            'settings' => $dto->get_settings(),
        ]
    );

    return apply_filters( 'emailcraft_email_template', $content, $dto );
}

function emailcraft_get_email_headers( array $default_headers = [] ) {
    $headers = array_merge(
        $default_headers, [
            'Content-Type: text/html; charset=UTF-8',
        ] 
    );

    return apply_filters( 'emailcraft_email_headers', $headers );
}

function emailcraft_get_email_template_type_by_post_id( int $post_id ) {
    $repository = emailcraft_singleton( TemplateTypeRepository::class );
    return $repository->get_by_post_id( $post_id );
}