<?php
namespace DiviBooster\DiviBooster\Features\SocialMediaFollowNetworks\CustomImageIcon;

// === Constants ===
const D4_CHILD_SLUG = 'et_pb_social_media_follow_network';
const D5_CHILD_SLUG = 'divi/social-media-follow-network';
const NETWORK_ID    = 'dbdb-custom-image';

// Divi 4 field slugs (must not change)
const D4_IMAGE_FIELD      = 'dbdb_image';
const D4_ICON_TITLE_FIELD = 'dbdb_icon_title';

// Divi 5 attribute slugs (camelCase)
const D5_IMAGE_ATTR      = 'diviboosterImageIcon';
const D5_ICON_TITLE_ATTR = 'diviboosterImageIconTitle';

// === Hook Registration ===
if (function_exists('add_filter')) {
    // Divi 4: add network option and fields
    add_filter('dbdbsmsn_networks', __NAMESPACE__ . '\\d4_add_custom_network');
    add_filter('dbdbsmsn_add_social_media_follow_fields', __NAMESPACE__ . '\\d4_add_image_icon_fields');
    add_filter('dbdbsmsn_network_is_icon_font', __NAMESPACE__ . '\\d4_network_is_icon_font', 10, 2);

    // Divi 4: output filters
    add_filter('et_module_shortcode_output', __NAMESPACE__ . '\\d4_output_styles', 10, 3);
    add_filter('et_module_shortcode_output', __NAMESPACE__ . '\\d4_output_title', 11, 3);

    // Divi 5: PHP attribute registration
    add_filter('divi_module_library_register_module_attrs', __NAMESPACE__ . '\\d5_register_attrs', 10, 2);

    // Divi 5: PHP conversion outline registration (server-side)
    add_filter('divi.moduleLibrary.conversion.moduleConversionOutline', __NAMESPACE__ . '\\d5_register_conversion_outline', 10, 2);

    // Divi 5: front-end block output filter
    add_filter('render_block_' . D5_CHILD_SLUG, __NAMESPACE__ . '\\d5_output_filter', 10, 3);
}

if (function_exists('add_action')) {
    // Divi 5: enqueue builder JS for options injection and conversion mapping
    add_action('divi_visual_builder_assets_before_enqueue_scripts', __NAMESPACE__ . '\\enqueue_divi5_builder_script');
}

// === Network Definition Helper ===
function get_custom_network() {
    return [
        'name'        => 'Image Icon',
        'code'        => '\\e005',
        'color'       => '#58a9de',
        'font-family' => 'ETModules',
    ];
}

// === Divi 4: Add Custom Network to List ===
function d4_add_custom_network($networks) {
    if (!is_array($networks)) {
        $networks = [];
    }
    $networks[NETWORK_ID] = get_custom_network();
    return $networks;
}

// === Divi 4: Add Fields (reuse original implementation) ===
function d4_add_image_icon_fields($fields) {
    if (!is_array($fields)) {
        $fields = [];
    }

    $fields[D4_IMAGE_FIELD] = array(
        'label'              => esc_html__('Image', 'et_builder'),
        'type'               => 'upload',
        'option_category'    => 'basic_option',
        'upload_button_text' => esc_html__('Upload an image', 'et_builder'),
        'choose_text'        => esc_attr__('Choose an Image', 'et_builder'),
        'update_text'        => esc_attr__('Set As Image', 'et_builder'),
        'description'        => esc_html__('Upload an image for your social media network icon.', 'et_builder'),
        'toggle_slug'        => 'main_content',
        'dynamic_content'    => 'image',
        'mobile_options'     => true,
        'hover'              => 'tabs',
        'show_if'            => array(
            'social_network' => NETWORK_ID,
        ),
    );

    $fields[D4_ICON_TITLE_FIELD] = array(
        'label'           => esc_html__('Icon Title', 'et_builder'),
        'type'            => 'text',
        'option_category' => 'basic_option',
        'description'     => esc_html__('This defines the HTML title of the icon, used in the tooltip.', 'et_builder'),
        'toggle_slug'     => 'main_content',
        'dynamic_content' => 'text',
        'show_if'         => array(
            'social_network' => NETWORK_ID,
        ),
    );

    return $fields;
}

// === Divi 4: Mark Network as Non-Font Icon ===
function d4_network_is_icon_font($is_icon_font, $network_id) {
    if ($network_id === NETWORK_ID) {
        return false;
    }
    return $is_icon_font;
}

// === Shared: Generate Per-Instance CSS for Image Icon ===
function generate_image_icon_css($order_class, $image_url, $hover_image_url = '') {
    $order_class = trim((string) $order_class);
    if ($order_class === '' || $image_url === '') {
        return '';
    }

    $base_selector  = '.' . esc_attr($order_class) . '.et-social-' . esc_attr(NETWORK_ID) . ' a';
    $before_selector = '.' . esc_attr($order_class) . '.et-social-' . esc_attr(NETWORK_ID) . ' a:before';
    $hover_selector  = '.' . esc_attr($order_class) . '.et-social-' . esc_attr(NETWORK_ID) . ' a:hover';

    $css  = '<style type="text/css">';
    $css .= $base_selector . '{background-image:url("' . esc_url($image_url) . '");background-size:contain;background-repeat:no-repeat;background-position:center;}';
    // Hide font icon but keep layout
    $css .= $before_selector . '{content:"a";visibility:hidden;}';

    if ($hover_image_url !== '') {
        $css .= $hover_selector . '{background-image:url("' . esc_url($hover_image_url) . '");}';
    }

    $css .= '</style>';
    return $css;
}

// === Shared: Extract Order Class from HTML ===
function extract_order_class_from_html($html, $prefix) {
    if (!is_string($html) || $html === '') {
        return '';
    }
    if (!preg_match('/class="([^"]+)"/i', $html, $m)) {
        return '';
    }
    $classes = preg_split('/\s+/', $m[1], -1, PREG_SPLIT_NO_EMPTY);
    foreach ($classes as $cls) {
        if (strpos($cls, $prefix) === 0) {
            return $cls;
        }
    }
    return '';
}

// === Divi 4: Output Styles ===
function d4_output_styles($output, $render_slug, $module) {
    if (!is_string($output) || $render_slug !== D4_CHILD_SLUG || !isset($module->props) || !is_array($module->props)) {
        return $output;
    }

    $props          = $module->props;
    $social_network = isset($props['social_network']) ? $props['social_network'] : '';
    if ($social_network !== NETWORK_ID) {
        return $output;
    }

    $image_value = isset($props[D4_IMAGE_FIELD]) ? $props[D4_IMAGE_FIELD] : '';
    if ($image_value === '') {
        return $output;
    }

    // Normal and hover values: Divi stores hover in prop with __hover suffix when hover enabled
    $image_normal = $image_value;
    $image_hover  = '';

    if (isset($props[D4_IMAGE_FIELD . '__hover_enabled']) && $props[D4_IMAGE_FIELD . '__hover_enabled'] === 'on|hover') {
        if (!empty($props[D4_IMAGE_FIELD . '__hover'])) {
            $image_hover = $props[D4_IMAGE_FIELD . '__hover'];
        }
    }

    // Use ET_Builder_Element::set_style when available (Divi 4)
    if (class_exists('ET_Builder_Element')) {
        \ET_Builder_Element::set_style(
            $render_slug,
            array(
                'selector'    => '%%order_class%%.et-social-' . NETWORK_ID . ' a',
                'declaration' => "background-image:url('" . esc_html($image_normal) . "');background-size:contain;background-repeat:no-repeat;background-position:center;",
            )
        );
        \ET_Builder_Element::set_style(
            $render_slug,
            array(
                'selector'    => '%%order_class%%.et-social-' . NETWORK_ID . ' a:before',
                'declaration' => 'content:"a";visibility:hidden;',
            )
        );
        if ($image_hover !== '') {
            \ET_Builder_Element::set_style(
                $render_slug,
                array(
                    'selector'    => '%%order_class%%.et-social-' . NETWORK_ID . ' a:hover',
                    'declaration' => "background-image:url('" . esc_html($image_hover) . "');",
                )
            );
        }
    } else {
        // Fallback: prepend inline CSS using extracted order class
        $order_class = extract_order_class_from_html($output, D4_CHILD_SLUG . '_');
        if ($order_class) {
            $css    = generate_image_icon_css($order_class, $image_normal, $image_hover);
            $output = $css . $output;
        }
    }

    return $output;
}

// === Divi 4: Output Icon Title ===
function d4_output_title($output, $render_slug, $module) {
    if (!is_string($output) || $render_slug !== D4_CHILD_SLUG || !isset($module->props) || !is_array($module->props)) {
        return $output;
    }

    $props          = $module->props;
    $social_network = isset($props['social_network']) ? $props['social_network'] : '';
    if ($social_network !== NETWORK_ID) {
        return $output;
    }

    $title = isset($props[D4_ICON_TITLE_FIELD]) ? trim((string) $props[D4_ICON_TITLE_FIELD]) : '';
    if ($title === '') {
        return $output;
    }

    // Replace or add title attribute on the main <a> element for this child
    $escaped_title = esc_attr($title);

    // Try to target the first anchor in this markup
    if (preg_match('/<a\s+[^>]*>/i', $output, $m, PREG_OFFSET_CAPTURE)) {
        $anchor      = $m[0][0];
        $anchor_pos  = $m[0][1];
        $new_anchor  = $anchor;
        if (preg_match('/\stitle=(["\"]).*?\1/i', $anchor)) {
            $new_anchor = preg_replace('/\stitle=(["\"]).*?\1/i', ' title="' . $escaped_title . '"', $anchor);
        } else {
            $new_anchor = rtrim($anchor, '>') . ' title="' . $escaped_title . '">';
        }
        $output = substr($output, 0, $anchor_pos) . $new_anchor . substr($output, $anchor_pos + strlen($anchor));
    }

    return $output;
}

// === Divi 5: Attribute Definitions (PHP) ===
function get_d5_image_attr_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'diviboosterImageIconField' => [
                        'groupSlug'   => 'contentNetwork',
                        'attrName'    => D5_IMAGE_ATTR,
                        'label'       => __('Image', 'et_builder'),
                        'description' => __('Upload an image for your social media network icon.', 'et_builder'),
                        'features'    => [
                            'hover'      => true,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'content',
                        ],
                        'render'      => true,
                        'priority'    => 40,
                        'component'   => [
                            'type' => 'field',
                            'name' => 'divi/upload',
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => '' ] ],
                    ],
                ],
            ],
        ],
    ];
}

function get_d5_icon_title_attr_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'diviboosterImageIconTitleField' => [
                        'groupSlug'   => 'contentNetwork',
                        'attrName'    => D5_ICON_TITLE_ATTR,
                        'label'       => __('Icon Title', 'et_builder'),
                        'description' => __('This defines the HTML title of the icon, used in the tooltip.', 'et_builder'),
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'content',
                        ],
                        'render'      => true,
                        'priority'    => 41,
                        'component'   => [
                            'type' => 'field',
                            'name' => 'divi/text',
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => '' ] ],
                    ],
                ],
            ],
        ],
    ];
}


function d5_register_attrs($attrs, $args) {
    if (($args['name'] ?? '') !== D5_CHILD_SLUG) {
        return $attrs;
    }
    $attrs[D5_IMAGE_ATTR]      = get_d5_image_attr_definition();
    $attrs[D5_ICON_TITLE_ATTR] = get_d5_icon_title_attr_definition();
    return $attrs;
}

// Also register via Gutenberg block metadata to mirror background-blur's reliability
function d5_register_attribute_via_block_metadata($settings) {
    $module_name       = $settings['name'] ?? '';
    $module_attributes = $settings['attributes'] ?? false;
    if ($module_name !== D5_CHILD_SLUG) {
        return $settings;
    }
    if (!$module_attributes || !is_array($module_attributes)) {
        return $settings;
    }
    $settings['attributes'][D5_IMAGE_ATTR]      = get_d5_image_attr_definition();
    $settings['attributes'][D5_ICON_TITLE_ATTR] = get_d5_icon_title_attr_definition();
    return $settings;
}

// === Divi 5: Conversion Outline (PHP version) ===
function d5_register_conversion_outline($conversion_outline, $module_name) {
    if ($module_name !== D5_CHILD_SLUG) {
        return $conversion_outline;
    }

    if (!isset($conversion_outline['module']) || !is_array($conversion_outline['module'])) {
        $conversion_outline['module'] = array();
    }

    // Map Divi 4 fields to Divi 5 attributes
    $conversion_outline['module']['social_network']           = 'socialNetwork.innerContent.*.title';
    $conversion_outline['module'][D4_IMAGE_FIELD]             = D5_IMAGE_ATTR . '.*';
    $conversion_outline['module'][D4_ICON_TITLE_FIELD]        = D5_ICON_TITLE_ATTR . '.*';

    return $conversion_outline;
}

// === Divi 5: Front-End Block Output ===
function d5_output_filter($block_content, $parsed_block, $block) {
    if (!is_string($block_content)) {
        return $block_content;
    }

    $attrs         = $parsed_block['attrs'] ?? array();
    $social_attr   = $attrs['socialNetwork']['innerContent']['desktop']['value'] ?? array();
    $network_title = $social_attr['title'] ?? '';
    if ($network_title !== NETWORK_ID) {
        return $block_content;
    }

    // Image values
    $image_attr = $attrs[D5_IMAGE_ATTR]['desktop']['value'] ?? ($attrs[D5_IMAGE_ATTR]['value'] ?? '');
    $image_hover_attr = $attrs[D5_IMAGE_ATTR]['hover']['value'] ?? '';

    $image_normal = is_string($image_attr) ? $image_attr : '';
    $image_hover  = is_string($image_hover_attr) ? $image_hover_attr : '';

    if ($image_normal === '') {
        return $block_content;
    }

    // Icon title
    $icon_title_attr = $attrs[D5_ICON_TITLE_ATTR]['desktop']['value'] ?? ($attrs[D5_ICON_TITLE_ATTR]['value'] ?? '');
    $icon_title      = is_string($icon_title_attr) ? trim($icon_title_attr) : '';

    // Extract order class for this child
    $order_class = extract_order_class_from_html($block_content, 'et_pb_social_media_follow_network_');
    if ($order_class) {
        $css           = generate_image_icon_css($order_class, $image_normal, $image_hover);
        $block_content = $css . $block_content;
    }

    if ($icon_title !== '') {
        $escaped_title = esc_attr($icon_title);
        if (preg_match('/<a\s+[^>]*>/i', $block_content, $m, PREG_OFFSET_CAPTURE)) {
            $anchor     = $m[0][0];
            $anchor_pos = $m[0][1];
            $new_anchor = $anchor;
            if (preg_match('/\stitle=(["\"]).*?\1/i', $anchor)) {
                $new_anchor = preg_replace('/\stitle=(["\"]).*?\1/i', ' title="' . $escaped_title . '"', $anchor);
            } else {
                $new_anchor = rtrim($anchor, '>') . ' title="' . $escaped_title . '">';
            }
            $block_content = substr($block_content, 0, $anchor_pos) . $new_anchor . substr($block_content, $anchor_pos + strlen($anchor));
        }
    }

    return $block_content;
}

// === Divi 5: Builder JS (network injection, attributes, conversion mapping) ===
function enqueue_divi5_builder_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('divibooster-d5-sfnetworks-custom-image-icon');

    $network      = get_custom_network();
    $network_json = wp_json_encode([
        NETWORK_ID => [
            'label'      => $network['name'],
            'background' => $network['color'],
        ],
    ]);

    $image_def_json      = wp_json_encode(get_d5_image_attr_definition());
    $icon_title_def_json = wp_json_encode(get_d5_icon_title_attr_definition());

    $d5_slug          = wp_json_encode(D5_CHILD_SLUG);
    $d5_image_attr    = wp_json_encode(D5_IMAGE_ATTR);
    $d5_icon_title    = wp_json_encode(D5_ICON_TITLE_ATTR);
    
    $d4_image_field   = wp_json_encode(D4_IMAGE_FIELD);
    $d4_icon_title    = wp_json_encode(D4_ICON_TITLE_FIELD);
    $network_id_json  = wp_json_encode(NETWORK_ID);

    $inline = <<<JS
(function(){
  var hooks = window.vendor && window.vendor.wp && window.vendor.wp.hooks;
  if (!hooks) return;
  var addFilter = hooks.addFilter;
  var lodash = window.lodash || {};
    var customNetworks = {$network_json};

    // Inject custom attributes and visibility in builder
    addFilter('divi.moduleLibrary.moduleAttributes', 'divibooster.customImage.attrs', function(attributes, metadata){
            if (!metadata || metadata.name !== {$d5_slug}) return attributes;
            var imageDef = {$image_def_json};
            var titleDef = {$icon_title_def_json};
            

        try {
            var getNetworkTitle = function(attrs){
                try {
                    return attrs && attrs.socialNetwork && attrs.socialNetwork.innerContent &&
                                 attrs.socialNetwork.innerContent.desktop &&
                                 attrs.socialNetwork.innerContent.desktop.value &&
                                 attrs.socialNetwork.innerContent.desktop.value.title || '';
                } catch(e){ return ''; }
            };
            var imageItem = imageDef.settings.innerContent.items.diviboosterImageIconField;
            if (imageItem) imageItem.visible = function(ctx){ return getNetworkTitle(ctx.attrs || {}) === {$network_id_json}; };
                    var titleItem = titleDef.settings.innerContent.items.diviboosterImageIconTitleField;
                    if (titleItem) titleItem.visible = function(ctx){ return getNetworkTitle(ctx.attrs || {}) === {$network_id_json}; };
                    
        } catch(e){}

        attributes[{$d5_image_attr}]      = imageDef;
        attributes[{$d5_icon_title}]      = titleDef;
        
        return attributes;
    });

  // JS-side conversion outline (for builder)
  addFilter('divi.moduleLibrary.conversion.moduleConversionOutline', 'divibooster', function(outline, name){
    if (name !== {$d5_slug}) return outline;
    if (!outline.module) outline.module = {};
    outline.module['social_network'] = 'socialNetwork.innerContent.*.title';
    outline.module[{$d4_image_field}] = {$d5_image_attr} + '.*';
    outline.module[{$d4_icon_title}]  = {$d5_icon_title} + '.*';
    return outline;
  });

  // Inject Image Icon option + patch onChange (prototype strategy)
  (function(){
    var attempts = 0;
    var maxAttempts = 100;

    function injectOptionsIntoGroups(groups){
      try {
        var path = ["contentNetwork", "component", "props", "fields", "socialNetworkTitle", "component", "props", "options"];
        var current = groups;
        for (var i=0;i<path.length;i++){
          if (current && current[path[i]]) {
            current = current[path[i]];
          } else {
            return;
          }
        }
        Object.assign(current, customNetworks);
      } catch(e){}
    }

    function patchModule(module){
      if (!module || module._diviBoosterCustomImagePatched) return;
      module._diviBoosterCustomImagePatched = true;

      if (module.settings && typeof module.settings.content === 'function') {
        var originalContent = module.settings.content;
        module.settings.content = function(args){
          var result = originalContent(args);
          if (args && args.groupConfiguration) {
            injectOptionsIntoGroups(args.groupConfiguration);
          }
          return result;
        };
      }

      try {
        var callbacks = module.callbacks;
        if (callbacks && callbacks.content && callbacks.content.contentNetwork &&
            callbacks.content.contentNetwork.fields &&
            callbacks.content.contentNetwork.fields.socialNetworkTitle) {
          var field = callbacks.content.contentNetwork.fields.socialNetworkTitle;
          var originalOnChange = field.onChange;
          var isExecuting = false;
          field.onChange = function(e){
            if (isExecuting) return;
            isExecuting = true;
            var inputValue = e && e.inputValue ? e.inputValue : null;
            var network = inputValue ? customNetworks[inputValue] : null;
            if (network) {
              Object.prototype[inputValue] = network;
            }
            var result;
            try {
              if (typeof originalOnChange === 'function') {
                result = originalOnChange.call(this, e);
              }
            } catch(err) {
            } finally {
              if (network) {
                delete Object.prototype[inputValue];
              }
              isExecuting = false;
            }
            return result;
          };
        }
      } catch(err){}
    }

    var interval = setInterval(function(){
      attempts++;
      if (attempts > maxAttempts) {
        clearInterval(interval);
        return;
      }
      if (window.divi && window.divi.moduleLibrary) {
        clearInterval(interval);
        var hooks2 = window.wp && window.wp.hooks ? window.wp.hooks : (window.vendor && window.vendor.wp && window.vendor.wp.hooks ? window.vendor.wp.hooks : null);
        if (hooks2) {
          hooks2.addFilter('divi.moduleLibrary.moduleSettings.groups', 'divibooster', function(groups, metadata){
            if (metadata && metadata.name === {$d5_slug}) {
              injectOptionsIntoGroups(groups);
            }
            return groups;
          });
        }

        var patchAttempts = 0;
        var patchInterval = setInterval(function(){
          patchAttempts++;
          if (patchAttempts > 40) {
            clearInterval(patchInterval);
            return;
          }
          if (window.divi && window.divi.moduleLibrary && window.divi.moduleLibrary.moduleMapping) {
            var module = window.divi.moduleLibrary.moduleMapping[{$d5_slug}];
            if (module) {
              clearInterval(patchInterval);
              patchModule(module);
              return;
            }
          }
          if (window.wp && window.wp.data) {
            var libStore = window.wp.data.select('divi/module-library');
            if (libStore && typeof libStore.getModule === 'function') {
              var module2 = libStore.getModule({$d5_slug});
              if (module2) {
                clearInterval(patchInterval);
                patchModule(module2);
                return;
              }
            }
          }
        }, 500);
      }
    }, 100);
  })();
})();
JS;

    \dbdb_enqueue_inline_script_if_dependencies_available($handle, $inline, array('lodash', array('divi-vendor-wp-hooks', 'wp-hooks')));
}

// Created at 1765506743.
