<?php

namespace DiviBooster\DiviBooster\ContactFormModuleConfirmationEmail;

// Constants
const DIVI4_MODULE_SLUG = 'et_pb_contact_form';
const DIVI5_MODULE_SLUG = 'divi/contact-form';

// Divi 4 field slugs (must not change)
const D4_SEND_TOGGLE = 'dbdb_send_confirmation_email';
const D4_FIELD_ID    = 'dbdb_confirmation_field_id';
const D4_SUBJECT     = 'dbdb_confirmation_subject';
const D4_CONTENT     = 'dbdb_confirmation_content';

// Divi 5 attribute slugs (camelCase, prefixed)
const D5_SEND_TOGGLE = 'diviboosterSendConfirmationEmail';
const D5_FIELD_ID    = 'diviboosterConfirmationFieldId';
const D5_SUBJECT     = 'diviboosterConfirmationSubject';
const D5_CONTENT     = 'diviboosterConfirmationContent';

// Bootstrap feature
(function() {
    $feature = new DBDB_ContactForm_Confirmation();
    $feature->init();

    // Divi 5: Register attributes via PHP
    add_filter('divi_module_library_register_module_attrs', __NAMESPACE__ . '\\register_divi5_attrs', 10, 2);

    // Divi 5: Enqueue builder inline JS for mapping + conversion
    add_action('wp_enqueue_scripts', __NAMESPACE__ . '\\enqueue_divi5_script');
})();

class DBDB_ContactForm_Confirmation {
    private $attrs = array();

    public function init() {
        // Admin CSS: suppress legacy VB support warnings for D4 fields
        add_action('admin_head', array($this, 'suppress_vb_support_notices'));
        add_action('wp_head', array($this, 'suppress_vb_support_notices_frontend_builder'));

        // Divi 4: register fields
        add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, array($this, 'add_fields'));

        // Divi 4: per-instance hook attach/detach around module render
        add_filter('et_pb_module_shortcode_attributes', array($this, 'add_email_filter'), 10, 3);
        add_filter('et_pb_contact_form_shortcode_output', array($this, 'remove_email_filter'));

        // Divi 5: per-instance hook attach/detach around block render
        add_filter('render_block_data', array($this, 'divi5_pre_render_block'), 10, 3);
        add_filter('render_block', array($this, 'divi5_post_render_block'), 10, 3);
    }

    public function suppress_vb_support_notices() {
        echo '<style>#et-fb-dbdb_confirmation_subject + .et-fb-no-vb-support-warning, #et-fb-dbdb_confirmation_content + .et-fb-no-vb-support-warning, #et-fb-dbdb_confirmation_field_id + .et-fb-no-vb-support-warning { display: none !important; }</style>';
    }

    public function suppress_vb_support_notices_frontend_builder() {
        if (function_exists('et_core_is_fb_enabled') && \et_core_is_fb_enabled()) {
            $this->suppress_vb_support_notices();
        }
    }

    public function add_fields($fields) {
        if (!is_array($fields)) {
            return $fields;
        }

        $fields[D4_SEND_TOGGLE] = array(
            'label'           => esc_html__('Send Confirmation Email', 'divi-booster'),
            'type'            => 'yes_no_button',
            'option_category' => 'configuration',
            'options'         => array(
                'on'  => esc_html__('Yes', 'et_builder'),
                'off' => esc_html__('No', 'et_builder'),
            ),
            'default'         => 'off',
            'tab_slug'        => 'general',
            'toggle_slug'     => 'email',
            'description'     => esc_html__('Send a confirmation email to the submitter when a message is submitted.', 'divi-booster'),
        );

        $fields[D4_FIELD_ID] = array(
            'label'           => esc_html__('Email Field ID', 'divi-booster'),
            'type'            => 'text',
            'option_category' => 'configuration',
            'default'         => 'Email',
            'tab_slug'        => 'general',
            'toggle_slug'     => 'email',
            'description'     => esc_html__('The ID of the email field in the contact form.', 'divi-booster'),
            'show_if'         => array(
                D4_SEND_TOGGLE => 'on',
            ),
        );

        $fields[D4_SUBJECT] = array(
            'label'           => esc_html__('Confirmation Email Subject', 'divi-booster'),
            'type'            => 'text',
            'option_category' => 'configuration',
            'default'         => 'We have received your contact form submission',
            'tab_slug'        => 'general',
            'toggle_slug'     => 'email',
            'description'     => esc_html__('Subject for the confirmation email.', 'divi-booster'),
            'show_if'         => array(
                D4_SEND_TOGGLE => 'on',
            ),
        );

        $fields[D4_CONTENT] = array(
            'label'           => esc_html__('Confirmation Email Content', 'divi-booster'),
            'type'            => 'tiny_mce',
            'option_category' => 'configuration',
            'default'         => 'Thank you for your submission! We will get back to you soon.',
            'tab_slug'        => 'general',
            'toggle_slug'     => 'email',
            'description'     => esc_html__('Enter the message content for the confirmation email. Like the main message pattern field, you can include the values of contact form fields using following format, <strong>%%field_id%%</strong>. For example if you want to include the field with id = <strong>phone</strong> and field with id = <strong>message</strong>, then you can use the following pattern: <strong>You entered message %%message%% and phone number %%phone%%</strong>.', 'divi-booster'),
            'show_if'         => array(
                D4_SEND_TOGGLE => 'on',
            ),
        );

        return $fields;
    }

    public function add_email_filter($props, $attrs, $slug) {
        if ($slug === DIVI4_MODULE_SLUG) {
            $this->attrs = $attrs;
            if (isset($attrs[D4_SEND_TOGGLE]) && $attrs[D4_SEND_TOGGLE] === 'on') {
                add_action('et_pb_contact_form_submit', array($this, 'send_confirmation_email'), 10, 3);
            }
        }
        return $props;
    }

    public function remove_email_filter($output) {
        remove_action('et_pb_contact_form_submit', array($this, 'send_confirmation_email'));
        return $output;
    }

    // Divi 5: before a block renders, attach submit handler for this instance if enabled
    public function divi5_pre_render_block($parsed_block, $source_block, $parent_block) {
        if (!is_array($parsed_block) || !isset($parsed_block['blockName']) || $parsed_block['blockName'] !== DIVI5_MODULE_SLUG) {
            return $parsed_block;
        }

        $attrs = isset($parsed_block['attrs']) && is_array($parsed_block['attrs']) ? $parsed_block['attrs'] : array();
        $enabled = $this->d5_get_attr_value($attrs, D5_SEND_TOGGLE, 'off');
        if ($enabled === 'on') {
            // Normalize to D4-style attrs for reuse in send handler
            $this->attrs = array(
                D4_SEND_TOGGLE => 'on',
                D4_FIELD_ID    => $this->d5_get_attr_value($attrs, D5_FIELD_ID, 'Email'),
                D4_SUBJECT     => $this->d5_get_attr_value($attrs, D5_SUBJECT, 'We have received your contact form submission'),
                D4_CONTENT     => $this->d5_get_attr_value($attrs, D5_CONTENT, ''),
            );
            add_action('et_pb_contact_form_submit', array($this, 'send_confirmation_email'), 10, 3);
        }
        return $parsed_block;
    }

    // Divi 5: after a block renders, detach submit handler
    public function divi5_post_render_block($block_content, $parsed_block, $instance) {
        if (isset($parsed_block['blockName']) && $parsed_block['blockName'] === DIVI5_MODULE_SLUG) {
            remove_action('et_pb_contact_form_submit', array($this, 'send_confirmation_email'));
        }
        return $block_content;
    }

    public function send_confirmation_email($processed_fields_values, $et_contact_error, $contact_form_info) {
        if (true === $et_contact_error) {
            return;
        }

        $email_field_id = isset($this->attrs[D4_FIELD_ID]) ? $this->attrs[D4_FIELD_ID] : 'Email';
        $email_field_id = strtolower($email_field_id);
        if (isset($processed_fields_values[$email_field_id]['value'])) {
            $email   = $processed_fields_values[$email_field_id]['value'];
            $subject = isset($this->attrs[D4_SUBJECT]) ? $this->attrs[D4_SUBJECT] : 'We have received your contact form submission';
            $content = $this->email_content(empty($this->attrs[D4_CONTENT]) ? '' : $this->attrs[D4_CONTENT], $processed_fields_values);

            if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
                wp_mail($email, $subject, $content, $this->email_headers());
            }
        }
    }

    public function email_headers() {
        return $this->email_content_type_header_text_html_without_charset();
    }

    public function email_content_type_header_text_html_without_charset() {
        return 'Content-Type: text/html';
    }

    public function email_content($message, $processed_fields_values) {
        if (empty($message)) {
            $message = $this->default_email_content();
        }

        $message = urldecode($message);

        if (substr($message, 0, 4) === '</p>') {
            $message = substr($message, 4);
        }
        if (substr($message, -3) === '<p>') {
            $message = substr($message, 0, -3);
        }

        foreach ($processed_fields_values as $key => $value) {
            $message = str_ireplace("%%{$key}%%", wp_strip_all_tags(isset($value['value']) ? $value['value'] : ''), $message);
        }

        return $message;
    }

    public function default_email_content() {
        return 'Thank you for your submission! We will get back to you soon.';
    }

    private function d5_get_attr_value($attrs, $slug, $default = '') {
        if (!isset($attrs[$slug]) || !is_array($attrs[$slug])) {
            return $default;
        }
        // D5 format: [ 'desktop' => [ 'value' => '...' ] ]
        if (isset($attrs[$slug]['desktop']['value'])) {
            return $attrs[$slug]['desktop']['value'];
        }
        return $default;
    }
}

// ===== Divi 5: Attribute registration (PHP) =====
function register_divi5_attrs($module_attrs, $filter_args) {
    if (($filter_args['name'] ?? '') !== DIVI5_MODULE_SLUG) {
        return $module_attrs;
    }

    foreach (get_divi5_attribute_definitions() as $slug => $def) {
        $module_attrs[$slug] = $def;
    }
    return $module_attrs;
}

function get_divi5_attribute_definitions() {
    $group = 'contentEmail';
    return array(
        D5_SEND_TOGGLE => array(
            'type'     => 'object',
            'settings' => array(
                'innerContent' => array(
                    'groupType' => 'group-items',
                    'items'     => array(
                        'diviboosterSendConfirmationEmailToggle' => array(
                            'groupSlug'   => $group,
                            'attrName'    => D5_SEND_TOGGLE,
                            'label'       => esc_html__('Send Confirmation Email', 'divi-booster'),
                            'description' => esc_html__('Send a confirmation email to the submitter when a message is submitted.', 'divi-booster'),
                            'features'    => array(
                                'hover'      => false,
                                'sticky'     => false,
                                'responsive' => false,
                                'preset'     => 'content',
                            ),
                            'render'   => true,
                            'priority' => 5,
                            'component' => array(
                                'type' => 'field',
                                'name' => 'divi/toggle',
                            ),
                            'defaultAttr' => array('desktop' => array('value' => 'off')),
                        ),
                    ),
                ),
            ),
        ),
        D5_FIELD_ID => array(
            'type'     => 'object',
            'settings' => array(
                'innerContent' => array(
                    'groupType' => 'group-items',
                    'items'     => array(
                        'diviboosterConfirmationFieldIdField' => array(
                            'groupSlug'   => $group,
                            'attrName'    => D5_FIELD_ID,
                            'label'       => esc_html__('Email Field ID', 'divi-booster'),
                            'description' => esc_html__('The ID of the email field in the contact form.', 'divi-booster'),
                            'features'    => array(
                                'hover'      => false,
                                'sticky'     => false,
                                'responsive' => false,
                                'preset'     => 'content',
                            ),
                            'render'   => true,
                            'priority' => 6,
                            'component' => array(
                                'type' => 'field',
                                'name' => 'divi/text',
                            ),
                            'defaultAttr' => array('desktop' => array('value' => 'Email')),
                        ),
                    ),
                ),
            ),
        ),
        D5_SUBJECT => array(
            'type'     => 'object',
            'settings' => array(
                'innerContent' => array(
                    'groupType' => 'group-items',
                    'items'     => array(
                        'diviboosterConfirmationSubjectField' => array(
                            'groupSlug'   => $group,
                            'attrName'    => D5_SUBJECT,
                            'label'       => esc_html__('Confirmation Email Subject', 'divi-booster'),
                            'description' => esc_html__('Subject for the confirmation email.', 'divi-booster'),
                            'features'    => array(
                                'hover'      => false,
                                'sticky'     => false,
                                'responsive' => false,
                                'preset'     => 'content',
                            ),
                            'render'   => true,
                            'priority' => 7,
                            'component' => array(
                                'type' => 'field',
                                'name' => 'divi/text',
                            ),
                            'defaultAttr' => array('desktop' => array('value' => 'We have received your contact form submission')),
                        ),
                    ),
                ),
            ),
        ),
        D5_CONTENT => array(
            'type'     => 'object',
            'settings' => array(
                'innerContent' => array(
                    'groupType' => 'group-items',
                    'items'     => array(
                        'diviboosterConfirmationContentField' => array(
                            'groupSlug'   => $group,
                            'attrName'    => D5_CONTENT,
                            'label'       => esc_html__('Confirmation Email Content', 'divi-booster'),
                            'description' => wp_kses_post(__('Enter the message content for the confirmation email. Like the main message pattern field, you can include the values of contact form fields using following format, <strong>%%field_id%%</strong>. For example if you want to include the field with id = <strong>phone</strong> and field with id = <strong>message</strong>, then you can use the following pattern: <strong>You entered message %%message%% and phone number %%phone%%</strong>.', 'divi-booster')),
                            'features'    => array(
                                'hover'      => false,
                                'sticky'     => false,
                                'responsive' => false,
                                'preset'     => 'content',
                            ),
                            'render'   => true,
                            'priority' => 8,
                            'component' => array(
                                'type' => 'field',
                                'name' => 'divi/textarea',
                            ),
                            'defaultAttr' => array('desktop' => array('value' => 'Thank you for your submission! We will get back to you soon.')),
                        ),
                    ),
                ),
            ),
        ),
    );
}

// ===== Divi 5: Inline JS for mapping + conversion =====
function enqueue_divi5_script() {
    if ((!function_exists('et_builder_d5_enabled') || !\et_builder_d5_enabled()) || (!function_exists('et_core_is_fb_enabled') || !\et_core_is_fb_enabled())) {
        return;
    }
    $handle = sanitize_title('divi-booster-' . DIVI5_MODULE_SLUG . '-confirmation-email');
    \dbdb_enqueue_inline_script_if_dependencies_available($handle, get_inline_js(), array('lodash', array('divi-vendor-wp-hooks', 'wp-hooks')));
}

function get_inline_js() {
    $defs = array();
    foreach (get_divi5_attribute_definitions() as $slug => $def) {
        $defs[$slug] = $def;
    }
    $defs_json           = wp_json_encode($defs);
    $divi5_slug_json     = wp_json_encode(DIVI5_MODULE_SLUG);
    $divi4_slug_json     = wp_json_encode(DIVI4_MODULE_SLUG);
    $d5_send_toggle_json = wp_json_encode(D5_SEND_TOGGLE);
    $d5_field_id_json    = wp_json_encode(D5_FIELD_ID);
    $d5_subject_json     = wp_json_encode(D5_SUBJECT);
    $d5_content_json     = wp_json_encode(D5_CONTENT);

    $d4_send_toggle_json = wp_json_encode(D4_SEND_TOGGLE);
    $d4_field_id_json    = wp_json_encode(D4_FIELD_ID);
    $d4_subject_json     = wp_json_encode(D4_SUBJECT);
    $d4_content_json     = wp_json_encode(D4_CONTENT);

    return <<<JS
(function(){
  const slug = {$divi5_slug_json};
  const defs = {$defs_json};
  const mapAttrs = [{$d5_send_toggle_json}, {$d5_field_id_json}, {$d5_subject_json}, {$d5_content_json}];
  const d4Slugs = [{$d4_send_toggle_json}, {$d4_field_id_json}, {$d4_subject_json}, {$d4_content_json}];

  // Register attributes in module mapping
  window.vendor.wp.hooks.addFilter('divi.moduleLibrary.moduleMapping', 'divi', modules => {
    const path = [slug, 'metadata', 'attributes'];
    const { set, get, has, forEach } = window.lodash;
    const target = get(modules, path) ? get(modules, path) : set(modules, path, {});
    if (has(modules, path)) {
      forEach(mapAttrs, key => { target[key] = defs[key]; });
    }
    return modules;
  });

  // Conversion: D4 -> D5
  window.vendor.wp.hooks.addFilter('divi.moduleLibrary.conversion.moduleConversionOutline', 'divi', (conversionOutline, name) => {
    if (name !== {$divi4_slug_json}) return conversionOutline;
    const pairs = [
      [{$d4_send_toggle_json}, {$d5_send_toggle_json}],
      [{$d4_field_id_json}, {$d5_field_id_json}],
      [{$d4_subject_json}, {$d5_subject_json}],
      [{$d4_content_json}, {$d5_content_json}],
    ];
    pairs.forEach(([oldKey, newKey]) => { conversionOutline.module[oldKey] = newKey + '.*'; });
    return conversionOutline;
  });

    // Visibility: show dependent fields (Field ID, Subject, Content) only when confirmation toggle is ON
    window.vendor.wp.hooks.addFilter('divi.moduleLibrary.moduleAttributes.divi.contact-form', 'divi', (attributes) => {
        const toggleSlug = {$d5_send_toggle_json};
        const dependentSlugs = [{$d5_field_id_json}, {$d5_subject_json}, {$d5_content_json}];
        const isToggleOn = (attrs) => {
            const v = attrs?.[toggleSlug];
            if (!v) return false;
            // Possible value shapes
            if (v.desktop?.value) return v.desktop.value === 'on';
            if (v.value) return v.value === 'on';
            return false;
        };
        dependentSlugs.forEach(dep => {
            const items = attributes?.[dep]?.settings?.innerContent?.items;
            if (!items) return;
            Object.keys(items).forEach(key => {
                // Assign / override visible callback
                items[key].visible = ({ attrs }) => isToggleOn(attrs);
            });
        });
        return attributes;
    });
})();
JS;
}

// === Divi 5: PHP conversion outline registration ===
function dbdb_register_divi5_confirmation_email_conversion( $conversion_outline, $module_name ) {
    if ( DIVI5_MODULE_SLUG !== $module_name ) {
        return $conversion_outline;
    }
    if ( ! isset( $conversion_outline['module'] ) || ! is_array( $conversion_outline['module'] ) ) {
        $conversion_outline['module'] = array();
    }
    $conversion_outline['module'][ D4_SEND_TOGGLE ] = D5_SEND_TOGGLE . '.*';
    $conversion_outline['module'][ D4_FIELD_ID ]    = D5_FIELD_ID . '.*';
    $conversion_outline['module'][ D4_SUBJECT ]     = D5_SUBJECT . '.*';
    $conversion_outline['module'][ D4_CONTENT ]     = D5_CONTENT . '.*';
    return $conversion_outline;
}
add_filter( 'divi.moduleLibrary.conversion.moduleConversionOutline', __NAMESPACE__ . '\\dbdb_register_divi5_confirmation_email_conversion', 10, 2 );

// Created at 1762819162

