<?php
defined( 'ABSPATH' ) || exit;

class Jalpi_Element_Form extends Jalpi_Element {
    public static function type(): string { return 'form'; }

    public function render( array $node, Jalpi_Renderer $renderer ): string {
        $id      = sanitize_html_class( $node['id'] ?? '' );
        $content = $node['content'] ?? [];
        $styles  = $node['styles']  ?? [];
        $plugin  = sanitize_key( $content['plugin']  ?? '' );
        $form_id = absint( $content['form_id'] ?? 0 );
        $a       = $renderer->get_css_attrs( $node );

        if ( ! $plugin || ! $form_id ) {
            return '<div class="jalpi-el jalpi-form-placeholder jalpi-' . esc_attr( $id ) . '">'
                 . '<p>' . esc_html__( 'No form selected. Choose a plugin and form in the Content tab.', 'jalpi-page-builder' ) . '</p>'
                 . '</div>';
        }

        if ( ! class_exists( 'Jalpi_Forms' ) ) {
            return '';
        }

        $form_html = Jalpi_Forms::render( $plugin, $form_id );

        if ( '' === $form_html ) {
            $label = Jalpi_Forms::PLUGIN_LABELS[ $plugin ] ?? $plugin;
            return '<div class="jalpi-el jalpi-form-placeholder jalpi-' . esc_attr( $id ) . '">'
                 // translators: 1: plugin/form name, 2: numeric form ID
                 . '<p>' . sprintf( esc_html__( '%1$s is not active or form #%2$d could not be found.', 'jalpi-page-builder' ), esc_html( $label ), $form_id ) . '</p>'
                 . '</div>';
        }

        $renderer->add_css( '.jalpi-el.jalpi-form.jalpi-' . $id . '{display:block;' . $renderer->styles_to_css( $styles ) . '}' );

        return '<div class="jalpi-el jalpi-form jalpi-' . esc_attr( $id ) . $a['extra_cls'] . '"' . $a['id_attr'] . '>'
             . $form_html
             . '</div>';
    }
}
