<?php

namespace WPT\Cf7Divi\Divi5\Modules\ContactForm7Module\ContactForm7ModuleTraits;

if ( !defined( 'ABSPATH' ) ) {
    die( 'Direct access forbidden.' );
}

use ET\Builder\Packages\Module\Module;
use ET\Builder\FrontEnd\BlockParser\BlockParserStore;
use WPT\Cf7Divi\Divi5\Modules\ContactForm7Module\ContactForm7Module;

trait RenderCallbackTrait
{
    /**
     * Render callback
     */
    public static function render_callback(
        $attrs,
        $content,
        $block,
        $elements
    ) {
        $loader = wpt_divi_contact_form7_container();

        wp_enqueue_script(
            'wpt-cf7-divi',
            $loader['plugin_url'] . '/js/cf7/script.js',
            ['contact-form-7'],
            $loader['plugin_version']
        );
    

        $renderedHtml = self::render_contact_form7( [
            'id'			  => $attrs['contactForm7']['advanced']['desktop']['value']['id'],
        ] );

        $parent = BlockParserStore::get_parent( $block->parsed_block['id'], $block->parsed_block['storeInstance'] );

        return Module::render(
            [
                // FE only.
                'orderIndex'		  => $block->parsed_block['orderIndex'],
                'storeInstance'	   => $block->parsed_block['storeInstance'],

                // VB equivalent.
                'attrs'			   => $attrs,
                'elements'			=> $elements,
                'id'				  => $block->parsed_block['id'],
                'name'				=> $block->block_type->name,
                'classnamesFunction'  => [ContactForm7Module::class, 'module_classnames'],
                'moduleCategory'	  => $block->block_type->category,
                'stylesComponent'	 => [ContactForm7Module::class, 'module_styles'],
                'scriptDataComponent' => [ContactForm7Module::class, 'module_script_data'],
                'parentAttrs'		 => $parent->attrs ?? [],
                'parentId'			=> $parent->id ?? '',
                'parentName'		  => $parent->blockName ?? '',
                'children'			=> $elements->style_components(
                    [
                        'attrName' => 'module',
                    ]
                ) 
                . sprintf('<div class="et_pb_module_inner"><div class="d5-wpt-divi-contact-form7">%s</div></div>', $renderedHtml)				,
            ]
        );
    }

    /*
     * Render the gravity form based on the ID
     */
    public static function render_contact_form7( $args )
    {
        if(!$args['id'] || 'cf7-0' == $args['id']){
            return 'Please select a Contact Form 7 entity';
        }

        $form_id = str_replace('cf7-', '', $args['id']);

        $shortcode = sprintf(
            '[contact-form-7 id="%s"/]',
            $form_id
        );

        return do_shortcode($shortcode);
    }
}
