<?php
namespace App\Helpers;

class ContentCleaner {

    public static function clean($html) {
        if (empty($html)) return '';

        $html = self::stripWysiwyg($html);
        $html = self::cleanElements($html);
        $html = self::normalizeWhitespace($html);

        return trim($html);
    }

    private static function stripWysiwyg($html) {
        // Remove empty shape containers
        $html = preg_replace('/<div[^>]*id="wb_Shape\d+"[^>]*>\s*<\/div>/i', '', $html);

        // Strip wrapper and canvas containers but keep inner HTML
        $html = preg_replace('/<div[^>]*class="wysiwyg-canvas-wrapper"[^>]*>\s*<div[^>]*class="wysiwyg-canvas"[^>]*>(.*?)<\/div>\s*<\/div>/is', '$1', $html);

        // Remove all inline position/dimension styles
        $html = preg_replace(
            '/\s+style="[^"]*(?:position:\s*absolute|left:\s*\d+|top:\s*\d+|width:\s*\d+|height:\s*\d+|z-index:\s*\d+)[^"]*"/i',
            '',
            $html
        );

        // Remove any remaining style attributes that slipped through
        $html = preg_replace('/\s+style="[^"]*"/i', '', $html);

        // Remove wb_* id attributes (they're meaningless now)
        $html = preg_replace('/\s+id="wb_\w+"/i', '', $html);

        return $html;
    }

    private static function cleanElements($html) {
        // Remove picture tags, keep inner img
        $html = preg_replace('/<picture[^>]*>/i', '', $html);
        $html = preg_replace('/<\/picture>/i', '', $html);

        // Remove srcset attributes
        $html = preg_replace('/\s+srcset="[^"]*"/i', '', $html);

        // Remove all leftover id attributes (Image3, Picture4, etc.)
        $html = preg_replace('/\s+id="[^"]*"/i', '', $html);

        // Remove empty divs
        $html = preg_replace('/<div[^>]*>\s*<\/div>/i', '', $html);

        // Remove empty wrapper divs — keep inner content
        $html = preg_replace('/<div[^>]*>\s*(<(p|img|table|ul|ol|h[1-6])[^>]*>.*?<\/\2>)\s*<\/div>/is', '$1', $html);
        // Second pass for remaining content divs (a, strong, b, em, span)
        $html = preg_replace('/<div[^>]*>\s*(<(a|strong|b|em|span)[^>]*>.*?<\/\2>)\s*<\/div>/is', '$1', $html);

        // Convert spans that contain text (not already inside p) to paragraphs
        $html = preg_replace('/<span[^>]*>(.*?)<\/span>/is', '<p>$1</p>', $html);

        // Remove Facebook support messages and links
        $html = preg_replace('/Bize destek olmak için\s*/i', '', $html);
        $html = preg_replace('/Facebook sayfamızı beğenirmisiniz\.\s*/i', '', $html);
        $html = preg_replace('/<a\s+[^>]*href="[^"]*facebook\.com[^"]*"[^>]*>.*?<\/a>/is', '', $html);

        // Remove 100-free promotional images and their potential anchor wrappers
        $html = preg_replace('/(?:<a[^>]*>\s*)?<img[^>]*src="[^"]*100-free[^"]*"[^>]*>(?:\s*<\/a>)?/is', '', $html);
        $html = preg_replace('/<img[^>]*src="[^"]*(facebook|fb-logo|fb_icon)[^"]*"[^>]*>/i', '', $html);

        // Reduce multiple <br> tags to a single <br> to eliminate huge gaps
        $html = preg_replace('/(<br\s*\/?>\s*){2,}/i', "<br>", $html);

        // Remove leading/trailing <br> inside paragraphs
        $html = preg_replace('/<p[^>]*>\s*<br\s*\/?>/i', '<p>', $html);
        $html = preg_replace('/<br\s*\/?>\s*<\/p>/i', '</p>', $html);

        // Clean up empty paragraphs, divs, spans (including those with only &nbsp;, spaces, or a leftover dot)
        // Do this in a loop to catch nested empty tags
        do {
            $oldHtml = $html;
            $html = preg_replace('/<(span|strong|b|em|i)[^>]*>(\s|&nbsp;|&#160;|<br\s*\/?>|\.|\,)*<\/\1>/iu', '', $html);
            $html = preg_replace('/<(p|div|h[1-6])[^>]*>(\s|&nbsp;|&#160;|<br\s*\/?>|\.|\,)*<\/\1>/iu', '', $html);
        } while ($oldHtml !== $html);

        // Remove standalone dots or commas left between tags
        $html = preg_replace('/>\s*[\.,]\s*</', '><', $html);

        // Collapse consecutive P tags nicely
        $html = preg_replace('/<\/p>\s*<p>/is', "</p>\n<p>", $html);

        // Replace download button images with a nice icon link
        $html = preg_replace_callback('/<a\s+([^>]*)>\s*<img[^>]*src="[^"]*download[^"]*"[^>]*>\s*<\/a>/i', function($m) {
            $attrs = $m[1];
            $href = '';
            if (preg_match('/href="([^"]+)"/i', $attrs, $h)) {
                $href = $h[1];
            }
            $target = '';
            if (preg_match('/target="([^"]+)"/i', $attrs, $t)) {
                $target = ' target="' . $t[1] . '"';
            }
            $title = '';
            if (preg_match('/title="([^"]+)"/i', $attrs, $t)) {
                $title = htmlspecialchars($t[1]);
            }
            return '<a href="' . htmlspecialchars($href) . '"' . $target . ' rel="noopener" class="dl-btn"><span class="dl-icon">⬇</span><span class="dl-text">' . ($title ?: 'İndir') . '</span></a>';
        }, $html);

        // Replace malformed material icon download links (common in some pages like oki_resetter)
        $html = preg_replace_callback('/<a\s+([^>]*)>(?:\s*<div[^>]*>)?\s*<i[^>]*class="[^"]*material-icons[^"]*"[^>]*>.*?<\/i>(?:\s*<\/div>)?(?:\s*<\/a>)?/is', function($m) {
            $attrs = $m[1];
            $href = '';
            if (preg_match('/href="([^"]+)"/i', $attrs, $h)) {
                $href = $h[1];
            }
            $target = '';
            if (preg_match('/target="([^"]+)"/i', $attrs, $t)) {
                $target = ' target="' . $t[1] . '"';
            }
            $title = '';
            if (preg_match('/title="([^"]+)"/i', $attrs, $t)) {
                $title = htmlspecialchars($t[1]);
            }
            return '<a href="' . htmlspecialchars($href) . '"' . $target . ' rel="noopener" class="dl-btn"><span class="dl-icon">⬇</span><span class="dl-text">' . ($title ?: 'İndir') . '</span></a>';
        }, $html);

        // Optimize images: add responsive sizing + lazy loading
        $html = preg_replace_callback('/<img\s+([^>]*)>/i', function($m) {
            $attrs = $m[1];
            if (!preg_match('/\bloading\s*=/i', $attrs)) {
                $attrs .= ' loading="lazy"';
            }
            return '<img ' . $attrs . ' class="detail-img">';
        }, $html);

        // Wrap bare images (not already in a figure) for better layout
        $html = preg_replace('/<img([^>]+)>(?!\s*<\/a>)/i', '<figure class="img-wrap"><img$1></figure>', $html);

        // Unwrap figures from paragraphs so they become direct children of the grid
        $html = preg_replace('/<p[^>]*>\s*(<figure class="img-wrap">.*?<\/figure>)\s*<\/p>/is', '$1', $html);

        // Remove any remaining empty wrapper divs (non-nested case)
        $html = preg_replace('/<div[^>]*>\s*<\/div>/i', '', $html);
        // Remove divs that only contain whitespace or linebreaks
        $html = preg_replace('/<div[^>]*>(\s*|&nbsp;)<\/div>/i', '', $html);

        return $html;
    }

    private static function normalizeWhitespace($html) {
        $html = preg_replace('/\n{3,}/', "\n\n", $html);
        $html = preg_replace('/[ \t]+/', ' ', $html);
        return $html;
    }
}
