<?php
$dir = 'c:\xampp\htdocs\inveetaire\app\views\public\identity\sections';
$filesModified = 0;
$sectionsMigrated = 0;

foreach (glob("$dir/*.php") as $file) {
    $content = file_get_contents($file);
    
    // Pattern to match the header block precisely
    $pattern = '/<div class="([^"]+)">\s*(?:<span class="([^"]+)">([^<]+)<\/span>\s*)?<h2 class="text-2xl <\?= \$style\[\'fontSerif\'\] \?> font-bold <\?= \$style\[\'textColor\'\] \?>">([^<]+)<\/h2>\s*<div class="w-12 h-0.5 bg-amber-400\/40 mx-auto"><\/div>\s*<\/div>/is';
    
    $newContent = preg_replace_callback($pattern, function($matches) use (&$sectionsMigrated) {
        $sectionsMigrated++;
        
        $headerClass = $matches[1];
        $emojiClass = isset($matches[2]) && trim($matches[2]) !== '' ? $matches[2] : '';
        $emoji = isset($matches[3]) ? trim($matches[3]) : '';
        $title = trim($matches[4]);
        
        $php = "<?php\n";
        if ($headerClass !== 'text-center space-y-2') {
            $php .= "    \$headerClass = '" . addslashes($headerClass) . "';\n";
        }
        if ($emoji !== '') {
            $php .= "    \$headerEmoji = '" . addslashes($emoji) . "';\n";
            if ($emojiClass !== 'text-3xl') {
                if (strpos($emojiClass, '<\?=') !== false) {
                    $emojiClass = str_replace('<\?= ', '{', $emojiClass);
                    $emojiClass = str_replace(' \?>', '}', $emojiClass);
                    $php .= "    \$headerEmojiClass = \"$emojiClass\";\n";
                } else {
                    $php .= "    \$headerEmojiClass = '" . addslashes($emojiClass) . "';\n";
                }
            }
        } else {
            $php .= "    \$headerEmoji = null;\n";
        }
        
        $php .= "    \$headerTitle = '" . addslashes($title) . "';\n";
        $php .= "    require __DIR__ . '/../partials/section_header.php';\n";
        
        // Reset vars so they don't leak to next sections
        $php .= "    unset(\$headerClass, \$headerEmoji, \$headerEmojiClass, \$headerTitle);\n";
        $php .= "?>";
        
        return $php;
    }, $content);
    
    if ($newContent !== $content) {
        // Fix any mangled PHP tags that were bypassed
        $newContent = str_replace('<\?=', '<?=', $newContent);
        $newContent = str_replace('\?>', '?>', $newContent);
        file_put_contents($file, $newContent);
        $filesModified++;
    }
}

echo "Files modified: $filesModified\n";
echo "Sections migrated: $sectionsMigrated\n";
