<?php
/**
 * Convert absolute-positioned article layout to clean flowing HTML
 * Fixes text/image overlaps and empty shape divs after image removal
 */
$j = json_decode(file_get_contents(__DIR__ . '/../data/articles.json'), 1);
$totalFixed = 0;

function extractNestedContent($html, $openTag) {
    // Find the opening tag
    $tagStart = strpos($html, $openTag);
    if ($tagStart === false) return null;
    
    $contentStart = $tagStart + strlen($openTag);
    $len = strlen($html);
    $depth = 1;
    $pos = $contentStart;
    
    while ($pos < $len && $depth > 0) {
        $nextOpen = strpos($html, '<div', $pos);
        $nextClose = strpos($html, '</div', $pos);
        
        if ($nextClose === false) break;
        
        if ($nextOpen !== false && $nextOpen < $nextClose) {
            $depth++;
            $pos = $nextOpen + 4;
        } else {
            $depth--;
            $pos = $nextClose + 6;
        }
    }
    
    return substr($html, $contentStart, $pos - $contentStart - 6);
}

function extractCanvasChildren($html) {
    // Find canvas opening tag
    if (!preg_match('/<div class="wysiwyg-canvas"[^>]*>/s', $html, $m)) return null;
    $inner = extractNestedContent($html, $m[0]);
    if ($inner === null) return null;
    
    // Parse all direct children (div or picture)
    $items = [];
    $pos = 0;
    $len = strlen($inner);
    
    while ($pos < $len) {
        // Skip whitespace
        if (preg_match('/^\s+/', substr($inner, $pos), $ws)) {
            $pos += strlen($ws[0]);
            continue;
        }
        if ($pos >= $len) break;
        
        $remaining = substr($inner, $pos);
        
        // Match opening tag
        if (!preg_match('/^<(div|picture)\s+[^>]*>/s', $remaining, $tagMatch)) break;
        
        $tagName = $tagMatch[1];
        $tagContent = $tagMatch[0];
        $elementStart = $pos;
        $pos += strlen($tagContent);
        
        if ($tagName === 'picture') {
            // Picture elements don't nest, find </picture>
            $close = strpos($inner, '</picture>', $pos);
            if ($close === false) break;
            $pos = $close + 10;
        } else {
            // Div elements - handle nesting
            $depth = 1;
            while ($depth > 0 && $pos < $len) {
                $nextOpen = strpos($inner, '<div', $pos);
                $nextClose = strpos($inner, '</div', $pos);
                
                if ($nextClose === false) break;
                
                if ($nextOpen !== false && $nextOpen < $nextClose) {
                    $depth++;
                    $pos = $nextOpen + 4;
                } else {
                    $depth--;
                    $pos = $nextClose + 6;
                }
            }
        }
        
        $fullElement = substr($inner, $elementStart, $pos - $elementStart);
        $items[] = $fullElement;
    }
    
    return $items;
}

function parseElement($html) {
    $result = ['raw' => $html];
    
    if (preg_match('/^<(div|picture)\s+id="([^"]*)"\s+style="([^"]*)"[^>]*>/s', $html, $m)) {
        $result['tag'] = $m[1];
        $result['id'] = $m[2];
        $result['style'] = $m[3];
    } else {
        return null;
    }
    
    $style = $result['style'];
    preg_match('/top:\s*(-?\d+)px/i', $style, $tm) && $result['top'] = (int)$tm[1];
    preg_match('/left:\s*(-?\d+)px/i', $style, $lm) && $result['left'] = (int)$lm[1];
    preg_match('/width:\s*(-?\d+)px/i', $style, $wm) && $result['width'] = (int)$wm[1];
    preg_match('/height:\s*(-?\d+)px/i', $style, $hm) && $result['height'] = (int)$hm[1];
    preg_match('/z-index:\s*(\d+)/i', $style, $zm) && $result['zIndex'] = (int)$zm[1];
    
    $tag = $result['tag'];
    $tagLen = strpos($html, '>', strpos($html, '<' . $tag)) + 1;
    $innerStart = $tagLen;
    $closeTag = "</$tag>";
    $innerEnd = strrpos($html, $closeTag);
    $result['inner'] = ($innerEnd !== false) ? substr($html, $innerStart, $innerEnd - $innerStart) : '';
    
    $result['hasImg'] = preg_match('/<img[^>]+>/s', $result['inner']);
    
    $textContent = trim(strip_tags($result['inner'], '<img><a><br><strong><b><em><i><span><ul><ol><li>'));
    $result['isEmpty'] = empty($textContent) && !$result['hasImg'];
    
    if ($result['hasImg']) {
        preg_match('/<img[^>]+src="([^"]+)"/s', $result['inner'], $sm);
        $result['imgSrc'] = $sm[1] ?? '';
        preg_match('/alt="([^"]*)"/s', $result['inner'], $am);
        $result['imgAlt'] = $am[1] ?? '';
        preg_match('/<a[^>]*href="([^"]+)"[^>]*>.*?<img/s', $result['inner'], $hm);
        $result['imgHref'] = $hm[1] ?? '';
    }
    
    return $result;
}

foreach ($j as &$a) {
    $orig = $a['content'];
    
    if (strpos($a['content'], 'wysiwyg-canvas') === false) continue;
    
    // Find wrapper opening tag
    if (!preg_match('/<div class="wysiwyg-canvas-wrapper"[^>]*>/s', $a['content'], $wrapMatch)) continue;
    $wrapperStart = $wrapMatch[0];
    $wrapperInner = extractNestedContent($a['content'], $wrapperStart);
    if ($wrapperInner === null) continue;
    
    // Now find the canvas inside the wrapper
    $canvasStart = '<div class="wysiwyg-canvas"';
    $canvasPos = strpos($wrapperInner, $canvasStart);
    if ($canvasPos === false) continue;
    
    $canvasTag = substr($wrapperInner, $canvasPos, strpos($wrapperInner, '>', $canvasPos) - $canvasPos + 1);
    $canvasInner = extractNestedContent($wrapperInner, $canvasTag);
    if ($canvasInner === null) continue;
    
    // Rebuild the wrapper inner without canvas, then put clean content
    $beforeCanvas = substr($wrapperInner, 0, $canvasPos);
    
    $children = extractCanvasChildren($a['content']);
    if ($children === null || empty($children)) continue;
    
    $items = [];
    foreach ($children as $childHtml) {
        $parsed = parseElement($childHtml);
        if ($parsed === null) continue;
        if ($parsed['isEmpty']) continue;
        
        if ($parsed['hasImg']) {
            $items[] = [
                'top' => $parsed['top'] ?? 0,
                'type' => 'image',
                'src' => $parsed['imgSrc'],
                'alt' => $parsed['imgAlt'],
                'href' => $parsed['imgHref'],
                'width' => $parsed['width'] ?? 0,
            ];
        } else {
            $text = $parsed['inner'];
            $text = preg_replace('/(<br\s*\/?>\s*){3,}/s', '<br><br>', $text);
            $items[] = [
                'top' => $parsed['top'] ?? 0,
                'type' => 'text',
                'html' => trim($text),
            ];
        }
    }
    
    if (empty($items)) {
        $clean = '<div class="article-clean-content"><p>İçerik bulunamadı.</p></div>';
    } else {
        usort($items, function($a, $b) { return $a['top'] - $b['top']; });
        
        $clean = '<div class="article-clean-content">';
        foreach ($items as $item) {
            if ($item['type'] === 'image') {
                $style = ($item['width'] > 0 && $item['width'] <= 600) ? ' style="max-width:' . $item['width'] . 'px;"' : '';
                $img = '<img src="' . htmlspecialchars($item['src']) . '" alt="' . htmlspecialchars($item['alt']) . '" loading="lazy"' . $style . '>';
                if ($item['href']) {
                    $img = '<a href="' . htmlspecialchars($item['href']) . '" target="_blank" rel="noopener">' . $img . '</a>';
                }
                $clean .= '<div class="article-image-block">' . $img . '</div>';
            } else {
                $html = $item['html'];
                if (!preg_match('/^<(p|div|h[1-6]|ul|ol|li|table|span)/', $html)) {
                    $html = '<p>' . $html . '</p>';
                }
                $clean .= '<div class="article-text-block">' . $html . '</div>';
            }
        }
        $clean .= '</div>';
    }
    
    // Replace the entire wrapper content
    $fullWrapper = substr($a['content'], strpos($a['content'], $wrapperStart), strlen($wrapperStart) + strlen($wrapperInner) + 6);
    $a['content'] = str_replace($fullWrapper, $clean, $a['content']);
    
    if ($a['content'] !== $orig) {
        echo "Fixed: {$a['title']}\n";
        $totalFixed++;
    }
}

file_put_contents(__DIR__ . '/../data/articles.json', json_encode($j, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
echo "\nTotal articles reformatted: $totalFixed\n";
