<?php
/**
 * SmoothTOC - Table of Contents Generator
 *
 * @package SmoothTOC
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

/**
 * Generate Table of Contents HTML for given content.
 *
 * @param string $content The post content.
 * @param bool   $manual  If true, only return TOC (for shortcode).
 * @return string Modified content with TOC or just TOC HTML.
 */
function smoothtoc_generate_toc($content, $manual = false) {
    if (empty($content)) {
        return '';
    }

    $headings = get_option('smoothtoc_headings', 'h2,h3');
    $headings = explode(',', $headings);
    $headings = array_map('trim', $headings);

    $pattern = '/<(' . implode('|', $headings) . ')[^>]*>(.*?)<\/\1>/i';
    preg_match_all($pattern, $content, $matches, PREG_SET_ORDER);

    if (empty($matches)) {
        return '';
    }

    $toc = '';
    $counter = 0;

    foreach ($matches as $match) {
        $counter++;
        $id = 'smoothtoc-' . $counter;
        $title = wp_strip_all_tags($match[2]);
        $level = substr($match[1], 1);
        
        // Add ID to the heading in the content
        $content = str_replace(
            $match[0],
            '<' . esc_attr($match[1]) . ' id="' . esc_attr($id) . '">' . wp_kses_post($match[2]) . '</' . esc_attr($match[1]) . '>',
            $content
        );
        
        // Add to TOC
        $toc .= '<li class="smoothtoc-level-' . esc_attr($level) . '"><a href="#' . esc_attr($id) . '">' . esc_html($title) . '</a></li>';
    }

    $toc_title = sanitize_text_field(get_option('smoothtoc_title', __('Table of Contents', 'smooth-toc')));
    $position = in_array(get_option('smoothtoc_position', 'top'), array('top', 'after_first'), true) ? get_option('smoothtoc_position', 'top') : 'top';
    $bg_color = sanitize_hex_color(get_option('smoothtoc_bg_color', '#f9f9f9'));
    $text_color = sanitize_hex_color(get_option('smoothtoc_text_color', '#333'));
    $font_size = absint(get_option('smoothtoc_font_size', 14));
    $width = absint(get_option('smoothtoc_width', ''));

    $style = '';
    if (!empty($bg_color)) {
        $style .= 'background-color: ' . esc_attr($bg_color) . ';';
    }
    if (!empty($text_color)) {
        $style .= 'color: ' . esc_attr($text_color) . ';';
    }
    if (!empty($font_size)) {
        $style .= 'font-size: ' . esc_attr($font_size) . 'px;';
    }
    if (!empty($width)) {
        $style .= 'width: ' . esc_attr($width) . 'px;';
    }

    $toc = '<div class="smoothtoc-wrapper" style="' . esc_attr($style) . '">' .
           '<strong class="smoothtoc-title">' . esc_html($toc_title) . '</strong>' .
           '<div class="smoothtoc-toggle" onclick="smoothtoc_toggle_list(this)">' . esc_html__('Toggle TOC', 'smooth-toc') . '</div>' .
           '<ul class="smoothtoc-list" style="' . (!empty($text_color) ? 'color: ' . esc_attr($text_color) . ';' : '') . '">' . $toc . '</ul>' .
           '</div>';

    if ($manual) {
        return $toc;
    }

    if ($position === 'top') {
        return $toc . $content;
    } else {
        // Insert after first paragraph
        $parts = preg_split('/(<\/p>)/', $content, 2, PREG_SPLIT_DELIM_CAPTURE);
        if (count($parts) > 1) {
            return $parts[0] . $parts[1] . $toc . $parts[2];
        }
        return $toc . $content;
    }
}

/**
 * Shortcode handler for [smooth_toc].
 *
 * @return string The generated table of contents.
 */
function smoothtoc_shortcode() {
    global $post;
    if (empty($post)) {
        return '';
    }
    $content = $post->post_content;
    $toc = smoothtoc_generate_toc($content, true);
    return $toc;
}
add_shortcode('smooth_toc', 'smoothtoc_shortcode');

/**
 * Filter the content to automatically insert the TOC.
 *
 * @param string $content The post content.
 * @return string The modified content.
 */
function smoothtoc_content_filter($content) {
    global $post;
    if (empty($post) || !empty(get_post_meta($post->ID, '_smoothtoc_disabled', true))) {
        return $content;
    }

    // Don't add TOC if shortcode is present
    if (strpos($content, '[smooth_toc') !== false) {
        return $content;
    }

    return smoothtoc_generate_toc($content);
}
add_filter('the_content', 'smoothtoc_content_filter');

// End of file
