<?php
/**
 * Fix Common Translation Mess - Cleanup Script
 * This script fixes the double-translation issues caused by automated replacement
 */

require_once '../bootstrap/env.php';

echo "<h2>Fixing Common Translation Mess</h2>";

// Function to clean up a file
function cleanupTranslationsInFile($filePath) {
    if (!file_exists($filePath)) {
        return false;
    }
    
    $content = file_get_contents($filePath);
    $originalContent = $content;
    
    // Fix double-nested translation calls
    $patterns = [
        // Fix: __('key', '<?= __('key', 'Default') ?>') → __('key', 'Default')
        '/__(\'([^\']+)\', \'<\?= __\(\1, \'([^\']+)\'\) \?\>\')/' => '__(\'\1\', \'\2\')',
        '/__(\"([^\"]+)\", \"<\?= __(\\\\1, \"([^\"]+)\") \?\>\")/' => '__(\"\1\", \"\3\")',
        
        // Fix mixed quote patterns
        '/__(\'([^\']+)\', \'<\?= __\(\"([^\"]+)\", \"([^\"]+)\"\) \?\>\')/' => '__(\'\1\', \'\3\')',
        '/__(\"([^\"]+)\", \"<\?= __(\'([^\']+)\', \'([^\']+)\') \?\>\")/' => '__(\"\1\", \"\3\")',
    ];
    
    foreach ($patterns as $pattern => $replacement) {
        $content = preg_replace($pattern, $replacement, $content);
    }
    
    // Additional cleanup for specific malformed patterns
    $cleanups = [
        // Remove extra PHP opening tags inside strings
        '\'\<?= __(' => '\'<?= __(',
        '\"\<?= __(' => '"<?= __(',
        'All\') ?\>\'' => 'All\'',
        'Active\') ?\>\'' => 'Active\'',
        'Inactive\') ?\>\'' => 'Inactive\'',
        'All\") ?\>"' => 'All"',
        'Active\") ?\>"' => 'Active"',
        'Inactive\") ?\>"' => 'Inactive"',
    ];
    
    foreach ($cleanups as $search => $replace) {
        $content = str_replace($search, $replace, $content);
    }
    
    if ($content !== $originalContent) {
        file_put_contents($filePath, $content);
        return true;
    }
    
    return false;
}

$viewsDir = __DIR__ . '/../app/Views';
$cleanedFiles = [];

// Function to recursively scan directories
function scanViews($dir, &$files) {
    $items = scandir($dir);
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        
        $path = $dir . '/' . $item;
        if (is_dir($path)) {
            scanViews($path, $files);
        } elseif (pathinfo($item, PATHINFO_EXTENSION) === 'php') {
            $files[] = $path;
        }
    }
}

$viewFiles = [];
scanViews($viewsDir, $viewFiles);

echo "<h3>Cleaning Up View Files:</h3>";

foreach ($viewFiles as $file) {
    $relativePath = str_replace($viewsDir . '/', '', $file);
    
    if (cleanupTranslationsInFile($file)) {
        $cleanedFiles[] = $relativePath;
        echo "<p>🧹 Cleaned: $relativePath</p>";
    } else {
        echo "<p>✅ OK: $relativePath</p>";
    }
}

echo "<hr>";
echo "<h3>Summary:</h3>";
echo "<p><strong>🧹 Cleaned " . count($cleanedFiles) . " files</strong></p>";

if (!empty($cleanedFiles)) {
    echo "<details><summary>Cleaned Files:</summary><ul>";
    foreach ($cleanedFiles as $file) {
        echo "<li>$file</li>";
    }
    echo "</ul></details>";
}

echo "<h3>Manual Check Recommended:</h3>";
echo "<p>Please manually review these common patterns and fix if needed:</p>";
echo "<ul>";
echo "<li><code>&lt;?= __('common.key', 'Default') ?&gt;</code> ✅ Good</li>";
echo "<li><code>&lt;?= __('common.key', '&lt;?= __('common.key', 'Default') ?&gt;') ?&gt;</code> ❌ Bad (nested)</li>";
echo "<li><code>'All'</code> → <code>&lt;?= __('common.all', 'All') ?&gt;</code> ✅ Good</li>";
echo "</ul>";

echo "<p><strong>Cleanup completed! Check your views for proper translation syntax.</strong></p>";
echo "<p><a href='/samanta_crm/languages'>Manage Translations</a> | ";
echo "<a href='/samanta_crm/users'>Test Users Page</a></p>";
?>
