<?php
function fixTranslationFile($filePath) {
    echo "Processing: $filePath\n";
    
    $content = file_get_contents($filePath);
    if ($content === false) {
        echo "ERROR: Could not read file\n";
        return false;
    }
    
    echo "Original size: " . strlen($content) . " bytes\n";
    $lines = explode("\n", $content);
    echo "Total lines: " . count($lines) . "\n";
    
    $outputLines = array();
    $insideArray = false;
    
    foreach ($lines as $lineNum => $line) {
        $trimmed = trim($line);
        
        // Detect the start of the return array
        if (!$insideArray && $trimmed === 'return [') {
            $insideArray = true;
            $outputLines[] = $line;
            continue;
        }
        
        if (!$insideArray) {
            // Before the array: keep everything (php tag, comments, blank lines)
            $outputLines[] = $line;
            continue;
        }
        
        // Inside the array:
        
        // Skip premature ]; closings
        if ($trimmed === '];') {
            echo "  Skipping premature ]; at line " . ($lineNum + 1) . "\n";
            continue;
        }
        
        // Skip ?> tags
        if ($trimmed === '?>' || $trimmed === '? >') {
            echo "  Skipping ?> at line " . ($lineNum + 1) . "\n";
            continue;
        }
        
        // Keep everything else
        $outputLines[] = $line;
    }
    
    // Add the single final ];
    $outputLines[] = '];';
    
    $newContent = implode("\n", $outputLines);
    
    // Clean up excessive blank lines
    $newContent = preg_replace('/\n{4,}/', "\n\n", $newContent);
    $newContent = rtrim($newContent) . "\n";
    
    echo "New size: " . strlen($newContent) . " bytes\n";
    
    // Write fixed content
    file_put_contents($filePath, $newContent);
    echo "File written successfully!\n\n";
    return true;
}

fixTranslationFile('includes/translations/ar.php');
fixTranslationFile('includes/translations/en.php');
echo "Done!\n";
