<?php

if ( !defined( 'ABSPATH' ) ) {
    exit;
}
// Exit if accessed directly
function wpsummarize_sanitize_html_input(  $input  ) {
    // Define the allowed HTML tags
    $allowed_html = array(
        'ul'     => array(),
        'ol'     => array(),
        'li'     => array(),
        'p'      => array(),
        'strong' => array(),
        'em'     => array(),
        'b'      => array(),
        'i'      => array(),
        'span'   => array(
            'style' => array(),
        ),
        'a'      => array(
            'href'  => array(),
            'title' => array(),
        ),
        'br'     => array(),
    );
    // Sanitize the input
    $sanitized_input = wp_kses( $input, $allowed_html );
    // Additional sanitization if needed
    $sanitized_input = stripslashes( $sanitized_input );
    return $sanitized_input;
}

function wpsummarize_enqueue_public_css() {
    // Check if the style has already been enqueued
    if ( !wp_style_is( 'wpsummarize-style', 'enqueued' ) ) {
        $summary_theme = "classic";
        if ( is_singular() && $summary_theme != "no_css" ) {
            wp_enqueue_style(
                'wpsummarize-style',
                plugin_dir_url( __DIR__ ) . 'assets/css/wpsummarize_' . $summary_theme . '.css',
                array(),
                WPSUMMARIZE_VERSION
            );
        }
    }
}

add_action( 'wp_enqueue_scripts', 'wpsummarize_enqueue_public_css' );
function wpsummarize_migrate_custom_css() {
    $done = get_option( 'wpsummarize_css_migrated_v2', false );
    if ( $done ) {
        return;
    }
    $custom_css = get_option( 'wpsummarize_custom_css', '' );
    if ( !empty( $custom_css ) ) {
        $updated = str_replace( '.wpsummary_box', '.wpsummarize_box', $custom_css );
        if ( $updated !== $custom_css ) {
            update_option( 'wpsummarize_custom_css', $updated );
        }
    }
    update_option( 'wpsummarize_css_migrated_v2', true );
}

add_action( 'admin_init', 'wpsummarize_migrate_custom_css' );
function wpsummarize_enqueue_custom_css() {
    if ( is_singular() ) {
        $custom_css = get_option( 'wpsummarize_custom_css', '' );
        $custom_css = str_replace( ".wpsummary_box", ".wpsummarize_box", $custom_css );
        if ( !empty( $custom_css ) ) {
            // Enqueue a dummy stylesheet
            wp_register_style( 'wpsummarize-custom-style', false );
            wp_enqueue_style( 'wpsummarize-custom-style' );
            // Add the custom CSS
            wp_add_inline_style( 'wpsummarize-custom-style', $custom_css );
        }
    }
}

add_action( 'wp_enqueue_scripts', 'wpsummarize_enqueue_custom_css' );
function wpsummarize_format_style(  $summary  ) {
    $edited_summary = strip_tags( $summary, "<p><ul><li>" );
    return $edited_summary;
}

function wpsummarize_find_first_block_end_position(  $html  ) {
    // Find the first opening HTML tag, allowing leading whitespace
    if ( !preg_match( '/^\\s*<(\\w+)[\\s>]/s', $html, $m ) ) {
        return false;
    }
    $tag = strtolower( $m[1] );
    // Void elements (self-closing)
    $void = array(
        'br',
        'hr',
        'img',
        'input',
        'meta',
        'link',
        'source',
        'area',
        'col',
        'embed',
        'wbr'
    );
    if ( in_array( $tag, $void, true ) ) {
        $pos = strpos( $html, '>' );
        return ( $pos !== false ? $pos + 1 : false );
    }
    // Track nesting depth for this tag type
    $depth = 0;
    $offset = 0;
    $pattern = '/<(\\/?)\\s*' . preg_quote( $tag, '/' ) . '(?:\\s[^>]*)?\\/?>/i';
    while ( preg_match(
        $pattern,
        $html,
        $m,
        PREG_OFFSET_CAPTURE,
        $offset
    ) ) {
        $full_match = $m[0][0];
        $match_pos = $m[0][1];
        $is_closing = $m[1][0] === '/';
        if ( $is_closing ) {
            $depth--;
            if ( $depth === 0 ) {
                return $match_pos + strlen( $full_match );
            }
        } elseif ( substr( rtrim( $full_match ), -2 ) !== '/>' ) {
            $depth++;
        }
        $offset = $match_pos + strlen( $full_match );
    }
    return false;
}

function wpsummarize_mark_first_block(  $content  ) {
    $post_id = get_the_ID();
    if ( !$post_id ) {
        return $content;
    }
    // Determine insert location (global default)
    $options = get_option( 'wpsummarize_options' );
    $insert_location = ( isset( $options['insert_location'] ) ? $options['insert_location'] : 'after_first_paragraph' );
    if ( $insert_location !== 'after_first_block' ) {
        return $content;
    }
    $blocks = parse_blocks( $content );
    $found = false;
    $new_content = '';
    foreach ( $blocks as $block ) {
        $new_content .= serialize_block( $block );
        if ( !$found && !empty( $block['blockName'] ) ) {
            $new_content .= '<!--wpsummarize_after_first_block-->';
            $found = true;
        }
    }
    return ( $found ? $new_content : $content );
}

add_filter( 'the_content', 'wpsummarize_mark_first_block', 8 );
function wpsummarize_add_to_content(  $content, $summary, $post_id  ) {
    $wpsummarize_options = get_option( 'wpsummarize_options' );
    // Get the insertion location from options
    $insert_location = ( isset( $wpsummarize_options['insert_location'] ) ? $wpsummarize_options['insert_location'] : 'after_first_paragraph' );
    $hide_summary_behind_button = '0';
    $title_before_summary = ( isset( $wpsummarize_options['title_before_summary'] ) ? $wpsummarize_options['title_before_summary'] : '' );
    $summary_theme = ( isset( $wpsummarize_options['summary_theme'] ) ? $wpsummarize_options['summary_theme'] : 'classic' );
    $summary_box = '<div class="wpsummarize_box design-' . $summary_theme . '">';
    // Add the Before Heading HTML code
    $wpsummarize_custom_html_before = get_option( 'wpsummarize_custom_html_before_heading' );
    if ( !empty( $wpsummarize_custom_html_before ) ) {
        $summary_box .= wp_kses_post( $wpsummarize_custom_html_before );
    }
    if ( $hide_summary_behind_button != 1 ) {
        $minimize_summaries = ( isset( $wpsummarize_options['minimize_summaries'] ) ? $wpsummarize_options['minimize_summaries'] : '0' );
        if ( isset( $wpsummarize_post_settings['minimize_summaries'] ) && empty( $wpsummarize_post_settings['use_default_minimize_summaries'] ) ) {
            $minimize_summaries = $wpsummarize_post_settings['minimize_summaries'];
        }
        if ( $minimize_summaries == 1 ) {
            $summary_box .= '<span class="wpsummarize_title">' . $title_before_summary;
            $summary_box .= '<button class="wpsummarize_toggle-btn" onclick="wpsummarize_ToggleContent(this)">
        <span class="wpsummarize_toggle-icon">−</span>
    </button></span>
    
    <div class="wpsummarize_content">
        <div class="wpsummarize_content-inner">';
        }
        if ( $hide_summary_behind_button != 1 && $minimize_summaries != 1 ) {
            $summary_box .= '<span class="wpsummarize_title">' . $title_before_summary . '</span>';
        }
        $summary_box .= wpsummarize_format_style( $summary );
    }
    // Add the After Summary HTML code
    $wpsummarize_custom_html_after = get_option( 'wpsummarize_custom_html_after_summary' );
    if ( !empty( $wpsummarize_custom_html_after ) ) {
        $summary_box .= wp_kses_post( $wpsummarize_custom_html_after );
    }
    if ( $hide_summary_behind_button != 1 && $minimize_summaries == 1 ) {
        $summary_box .= "</div>\r\n    </div>";
    }
    $summary_box .= '</div>';
    // If the insertion method is 'shortcode', return the summary box
    if ( $insert_location === 'manual_shortcode' and $content == "wpsummarize_shortcode_call" ) {
        return $summary_box;
    }
    // Handle different page builders and content structures
    $page_builder_content = wpsummarize_get_page_builder_content( $post_id );
    $content_to_modify = ( $page_builder_content ?: $content );
    // Process blocks if it's a block-based theme or uses Gutenberg
    if ( function_exists( 'wp_is_block_theme' ) && wp_is_block_theme() || function_exists( 'use_block_editor_for_post' ) && use_block_editor_for_post( $post_id ) ) {
        $blocks = parse_blocks( $content_to_modify );
        $content_to_modify = '';
        foreach ( $blocks as $block ) {
            $content_to_modify .= render_block( $block );
        }
    }
    // Insert the custom content based on the specified location
    switch ( $insert_location ) {
        case 'above_content':
            $modified_content = $summary_box . $content_to_modify;
            break;
        case 'below_content':
            $modified_content = $content_to_modify . $summary_box;
            break;
        case 'after_first_paragraph':
            $pos = strpos( $content_to_modify, '</p>' );
            if ( $pos !== false ) {
                $modified_content = substr_replace(
                    $content_to_modify,
                    $summary_box,
                    $pos + 4,
                    0
                );
            } else {
                $modified_content = $content_to_modify . $summary_box;
                // Fallback to appending
            }
            break;
        case 'before_first_heading':
            $pattern = '/<h[1-6][^>]*>/i';
            if ( preg_match(
                $pattern,
                $content_to_modify,
                $matches,
                PREG_OFFSET_CAPTURE
            ) ) {
                $pos = $matches[0][1];
                $modified_content = substr_replace(
                    $content_to_modify,
                    $summary_box,
                    $pos,
                    0
                );
            } else {
                $modified_content = $summary_box . $content_to_modify;
                // Fallback to prepending
            }
            break;
        case 'after_first_block':
            if ( strpos( $content_to_modify, '<!--wpsummarize_after_first_block-->' ) !== false ) {
                $modified_content = str_replace( '<!--wpsummarize_after_first_block-->', $summary_box, $content_to_modify );
            } else {
                // Fallback for classic editor
                $pos = strpos( $content_to_modify, '</p>' );
                if ( $pos !== false ) {
                    $modified_content = substr_replace(
                        $content_to_modify,
                        $summary_box,
                        $pos + 4,
                        0
                    );
                } else {
                    $modified_content = $summary_box . $content_to_modify;
                }
            }
            break;
        default:
            $modified_content = $content_to_modify;
    }
    return $modified_content;
}

function wpsummarize_get_page_builder_content(  $post_id  ) {
    // Elementor
    if ( did_action( 'elementor/loaded' ) && function_exists( '\\Elementor\\Plugin::instance' ) ) {
        $document = \Elementor\Plugin::instance()->documents->get( $post_id );
        if ( $document && $document->is_built_with_elementor() ) {
            return $document->get_content();
        }
    }
    // Divi
    if ( function_exists( 'et_builder_init_global_settings' ) && function_exists( 'et_pb_is_pagebuilder_used' ) && et_pb_is_pagebuilder_used( $post_id ) ) {
        return do_shortcode( get_post_field( 'post_content', $post_id ) );
    }
    // Oxygen
    if ( function_exists( 'ct_template_output' ) ) {
        $oxygen_content = get_post_meta( $post_id, 'ct_builder_json', true );
        if ( $oxygen_content ) {
            return do_shortcode( wpsummarize_oxygen_render_json_for_content( $oxygen_content ) );
        }
    }
    // WPBakery Page Builder
    // Don't pre-render here. WPBakery has its own the_content pipeline; reconstructing the
    // content and running do_shortcode() on it discards the original $content we received
    // from the filter and causes WPBakery's later passes to relocate the summary box.
    // We confirm the post is actually built with WPBakery via the _wpb_vc_js_status meta
    // (just function_exists('vc_is_inline') is true for any site with WPBakery active).
    if ( function_exists( 'vc_is_inline' ) && get_post_meta( $post_id, '_wpb_vc_js_status', true ) === 'true' ) {
        return false;
    }
    // Beaver Builder
    if ( class_exists( 'FLBuilderModel' ) && method_exists( 'FLBuilderModel', 'is_builder_enabled' ) && FLBuilderModel::is_builder_enabled( $post_id ) ) {
        return FLBuilder::render_content_by_id( $post_id );
    }
    // Avada (Fusion Builder)
    if ( function_exists( 'fusion_is_builder_enabled' ) && function_exists( 'fusion_builder_get_content' ) && fusion_is_builder_enabled( $post_id ) ) {
        return do_shortcode( fusion_builder_get_content( $post_id ) );
    }
    // SiteOrigin Page Builder
    if ( class_exists( 'SiteOrigin_Panels' ) && function_exists( 'siteorigin_panels_render' ) ) {
        $panels_data = get_post_meta( $post_id, 'panels_data', true );
        if ( $panels_data ) {
            return siteorigin_panels_render( $post_id, false, $panels_data );
        }
    }
    // Thrive Architect
    if ( function_exists( 'tve_get_post_meta' ) ) {
        $tve_content = tve_get_post_meta( $post_id, 'tve_updated_post' );
        if ( $tve_content ) {
            return do_shortcode( $tve_content );
        }
    }
    // OptimizePress 3
    if ( function_exists( 'op3_get_page_data' ) ) {
        $op3_data = op3_get_page_data( $post_id );
        if ( $op3_data ) {
            return do_shortcode( op3_get_rendered_content( $post_id ) );
        }
    }
    // Brizy
    if ( class_exists( 'Brizy_Editor_Post' ) && method_exists( 'Brizy_Editor_Post', 'get' ) ) {
        $brizy_post = Brizy_Editor_Post::get( $post_id );
        if ( $brizy_post && $brizy_post->uses_editor() ) {
            return do_shortcode( $brizy_post->get_compiled_html() );
        }
    }
    return '';
    // Return empty string if no page builder content is found
}

// Helper function for Oxygen
function wpsummarize_oxygen_render_json_for_content(  $json  ) {
    $content = '';
    $data = json_decode( $json, true );
    if ( is_array( $data ) ) {
        foreach ( $data as $element ) {
            if ( !empty( $element['children'] ) ) {
                $content .= wpsummarize_oxygen_render_json_for_content( wp_json_encode( $element['children'] ) );
            } elseif ( !empty( $element['options']['ct_content'] ) ) {
                $content .= $element['options']['ct_content'];
            }
        }
    }
    return $content;
}

// Hook to modify the content.
// Default priority is 10. For posts built with WPBakery, we run later (priority 20)
// so WPBakery's shortcode rendering at priority 11 has already finished. Otherwise
// inserting at priority 10 lands the summary inside raw vc_row shortcode source, and
// WPBakery's pipeline ends up placing the summary at the bottom of the rendered post.
add_action( 'wp', function () {
    $priority = 10;
    $post_id = get_the_ID();
    if ( $post_id && function_exists( 'vc_is_inline' ) && get_post_meta( $post_id, '_wpb_vc_js_status', true ) === 'true' ) {
        $priority = 20;
    }
    add_filter( 'the_content', 'wpsummarize_insert_summary', $priority );
} );
function wpsummarize_is_translated_post(  $post_id  ) {
    // WPML
    if ( function_exists( 'wpml_get_language_information' ) ) {
        $language_details = apply_filters( 'wpml_element_language_details', null, array(
            'element_id'   => $post_id,
            'element_type' => 'post_post',
        ) );
        return !empty( $language_details->source_language_code );
    }
    // TranslatePress
    if ( class_exists( 'TRP_Translate_Press' ) ) {
        // TranslatePress translates content dynamically
        return false;
    }
    // MultilingualPress
    if ( class_exists( 'MultilingualPress\\Framework\\Api\\Translation' ) ) {
        $original_blog = get_post_meta( $post_id, 'mlp_original_blog', true );
        $original_content = get_post_meta( $post_id, 'mlp_original_content', true );
        return !empty( $original_blog ) && !empty( $original_content );
    }
    return false;
}

add_filter(
    'pll_copy_post_metas',
    function ( $metas, $sync ) {
        $exclude = ['_wpsummarize_summary_set', '_wpsummarize_summary_set_manual', '_wpsummarize_post_settings'];
        return array_diff( $metas, $exclude );
    },
    10,
    2
);
add_filter(
    'pll_translate_post_meta',
    function (
        $value,
        $key,
        $language,
        $from,
        $to
    ) {
        if ( in_array( $key, ['_wpsummarize_summary_set', '_wpsummarize_summary_set_manual', '_wpsummarize_post_settings'] ) ) {
            return false;
            // prevent copy
        }
        return $value;
    },
    10,
    5
);
function wpsummarize_insert_summary(  $content  ) {
    $post_id = get_the_ID();
    static $processed_posts = array();
    $wpsummarize_is_timber = class_exists( 'Timber\\Post' );
    $wpsummarize_is_raw_blocks = $wpsummarize_is_timber && strpos( $content, '<!-- wp:' ) !== false;
    if ( isset( $processed_posts[$post_id] ) && $content != "wpsummarize_shortcode_call" && !$wpsummarize_is_raw_blocks ) {
        return $content;
    }
    if ( !did_action( 'loop_start' ) && $content != "wpsummarize_shortcode_call" ) {
        return $content;
    }
    // Check if we're on a singular post and in the main query
    if ( !is_singular() || !is_main_query() ) {
        return $content;
    }
    if ( $content !== "wpsummarize_shortcode_call" && strlen( wp_strip_all_tags( trim( $content ) ) ) < 40 ) {
        return $content;
    }
    // Check if there's a summary in wp_postmeta
    $summary = get_post_meta( $post_id, '_wpsummarize_summary_set', true );
    if ( empty( $summary ) ) {
        return $content;
    }
    // Get plugin options
    $options = get_option( 'wpsummarize_options', array() );
    // Check if summaries are globally hidden
    if ( isset( $options['hide_all_summaries'] ) && $options['hide_all_summaries'] == 1 ) {
        return $content;
    }
    // Check if the current post type is enabled for summaries
    $current_post_type = get_post_type( $post_id );
    $enabled_post_types = ( isset( $options['wpsummarize_post_types_enabled'] ) ? $options['wpsummarize_post_types_enabled'] : array() );
    if ( !in_array( $current_post_type, $enabled_post_types ) ) {
        return $content;
    }
    if ( $content != "wpsummarize_shortcode_call" && (!$wpsummarize_is_timber || $wpsummarize_is_raw_blocks) ) {
        $processed_posts[$post_id] = true;
    }
    // If all checks pass, insert the summary
    return wpsummarize_add_to_content( $content, $summary, $post_id );
}

// Shortcode handler
function wpsummarize_shortcode(  $atts  ) {
    $post_id = get_the_ID();
    // Determine the effective insert location (global + per-post override)
    $options = get_option( 'wpsummarize_options', array() );
    $insert_location = ( isset( $options['insert_location'] ) ? $options['insert_location'] : 'after_first_paragraph' );
    // Only render via shortcode if the user actually chose manual_shortcode.
    if ( $insert_location !== 'manual_shortcode' ) {
        return '';
    }
    $shortcode = wpsummarize_insert_summary( "wpsummarize_shortcode_call" );
    if ( !empty( $shortcode ) && $shortcode !== "wpsummarize_shortcode_call" ) {
        return $shortcode;
    }
    return '';
}

add_shortcode( 'wpsummarize', 'wpsummarize_shortcode' );
function wpsummarize_enqueue_minimize_summaries() {
    global $post;
    if ( is_singular() ) {
        $wpsummarize_options = get_option( 'wpsummarize_options' );
        $wpsummarize_post_settings_serialized = get_post_meta( $post->ID, '_wpsummarize_post_settings', true );
        $wpsummarize_post_settings = maybe_unserialize( $wpsummarize_post_settings_serialized );
        $minimize_summaries = ( isset( $wpsummarize_options['minimize_summaries'] ) ? $wpsummarize_options['minimize_summaries'] : '0' );
        if ( isset( $wpsummarize_post_settings['minimize_summaries'] ) && empty( $wpsummarize_post_settings['use_default_minimize_summaries'] ) ) {
            $minimize_summaries = $wpsummarize_post_settings['minimize_summaries'];
        }
        $hide_summary_behind_button = ( isset( $wpsummarize_options['hide_summary_behind_button'] ) ? $wpsummarize_options['hide_summary_behind_button'] : '0' );
        if ( isset( $wpsummarize_post_settings['hide_summary_behind_button'] ) && empty( $wpsummarize_post_settings['use_default_hide_summary_behind_button'] ) ) {
            $hide_summary_behind_button = $wpsummarize_post_settings['hide_summary_behind_button'];
        }
        if ( $minimize_summaries == 1 && $hide_summary_behind_button != 1 ) {
            wp_enqueue_script(
                'wpsummarize-minimize-summaries',
                plugin_dir_url( __DIR__ ) . 'assets/js/wpsummarize-minimize-summaries.js',
                array(),
                WPSUMMARIZE_VERSION,
                true
            );
            wp_localize_script( 'wpsummarize-public-script', 'wpSummarize', array(
                'ajax_url' => admin_url( 'admin-ajax.php' ),
                'nonce'    => wp_create_nonce( 'wpsummarize_nonce' ),
                'post_id'  => $post->ID,
            ) );
            wp_enqueue_style(
                'wpsummarize-minimize-summaries-css',
                plugin_dir_url( __DIR__ ) . 'assets/css/wpsummarize_minimize_summaries.css',
                array(),
                WPSUMMARIZE_VERSION
            );
        }
    }
}

add_action( 'wp_enqueue_scripts', 'wpsummarize_enqueue_minimize_summaries' );
// 3. AJAX handler to fetch the summary (remains the same)
function wpsummarize_get_summary() {
    check_ajax_referer( 'wpsummarize_nonce', 'nonce' );
    $post_id = ( isset( $_POST['post_id'] ) ? intval( $_POST['post_id'] ) : 0 );
    if ( !$post_id ) {
        wp_send_json_error( 'Invalid post ID' );
    }
    $summary = get_post_meta( $post_id, '_wpsummarize_summary_set', true );
    if ( empty( $summary ) ) {
        wp_send_json_error( 'No summary available' );
    }
    $summary_box = wpsummarize_format_style( $summary );
    wp_send_json_success( $summary_box );
}

add_action( 'wp_ajax_wpsummarize_get_summary', 'wpsummarize_get_summary' );
add_action( 'wp_ajax_nopriv_wpsummarize_get_summary', 'wpsummarize_get_summary' );
add_action( 'wp', function () {
    $post_id = get_the_ID();
    $is_wpbakery = $post_id && function_exists( 'vc_is_inline' ) && get_post_meta( $post_id, '_wpb_vc_js_status', true ) === 'true';
    if ( $is_wpbakery ) {
        // Uncode/WPBakery does NOT pass the real body through the_content
        // (it uses get_the_content internally). Hook Uncode's final assembled
        // single-post output instead. Late priority so all rendering is done.
        add_filter( 'uncode_single_content_final_output', 'wpsummarize_insert_summary_uncode', 50 );
    } else {
        add_filter( 'the_content', 'wpsummarize_insert_summary', 10 );
    }
} );
/**
 * Adapter for Uncode's final single-content output filter.
 * Undocumented hook - defensively take only the content string and
 * fall back to returning it untouched on any unexpected condition.
 */
function wpsummarize_insert_summary_uncode(  $content  ) {
    // Only the main singular view; never alter anything else.
    if ( !is_singular() || !is_main_query() || !is_string( $content ) || $content === '' ) {
        return $content;
    }
    return wpsummarize_insert_summary( $content );
}
