<?php

defined( 'ABSPATH' ) || exit;

use EmailCraft\App\DTO\ContentDTO;
use EmailCraft\WpMVC\Enqueue\Enqueue;

if ( 'post.php' === $hook_suffix && 'emailcraft' === get_current_screen()->post_type ) {
    if ( SCRIPT_DEBUG && is_file( emailcraft_dir( 'assets/blocks/runtime.js' ) ) ) {
        Enqueue::script( 'emailcraft-blocks-runtime', 'blocks/runtime' );
    }
    Enqueue::script( 'emailcraft-builder', 'build/js/builder' );
    Enqueue::style( 'emailcraft-builder', 'build/css/builder' );

    $social_icons_url   = [];
    $icons_dir          = emailcraft_dir( 'assets/images/social-icons' );
    $icons_dir_contents = scandir( $icons_dir );
    $icons_url          = emailcraft_url( 'assets/images/social-icons' );

    foreach ( $icons_dir_contents as $icon ) {
        if ( is_file( $icons_dir . '/' . $icon ) ) {
            $social_icons_url[] = $icons_url . '/' . $icon;
        }
    }

    $template_type = (array) emailcraft_get_email_template_type_by_post_id( get_the_ID() );
    $content_dto   = ( new ContentDTO )->set_integration( $template_type['integration'] )->set_template_type( $template_type['template_type'] );

    wp_localize_script(
        'emailcraft-builder', 'emailcraft_builder', [
            'smart_tags'    => [
                'categories' => EmailCraft\App\Helpers\SmartTag::get_categories( $content_dto ),
                'tags'       => array_map(
                    function( $tag ) {
                        unset( $tag['data_callback'] );
                        return $tag;
                    }, EmailCraft\App\Helpers\SmartTag::get_tags( $content_dto )
                )
            ],
            'social_icons'  => $social_icons_url,
            'template_type' => [
                'integration'   => $template_type['integration'] ?? '',
                'template_type' => $template_type['template_type'] ?? '',
            ],
            'assets_url'    => emailcraft_url( 'assets' )
        ]
    );
}

if ( $hook_suffix === 'toplevel_page_emailcraft' ) {
    if ( SCRIPT_DEBUG && is_file( emailcraft_dir( 'assets/build/runtime.js' ) ) ) {  
        Enqueue::script( 'emailcraft-dashbaord-runtime', 'build/runtime' );
    }
    Enqueue::script( 'emailcraft-dashboard', 'build/js/dashboard' );
    Enqueue::style( 'emailcraft-dashboard', 'build/css/dashboard', ['wp-components'] );
    Enqueue::style( 'emailcraft-dashboard-style', 'build/css/style-dashboard' );

    wp_localize_script(
        'emailcraft-dashboard', 'emailcraft_admin', [
            'templates'  => emailcraft_config( 'templates' ),
            'assets_url' => emailcraft_url( 'assets' )
        ]
    );
}
