<?php

/**
 * Find all translation strings in PHP files that are not in en.json
 */

echo "=== FINDING MISSING TRANSLATION STRINGS ===\n\n";

// Load current en.json
$enFile = 'resources/lang/en.json';
$existing = json_decode(file_get_contents($enFile), true);
echo "Current en.json has " . count($existing) . " keys\n\n";

// Find all PHP files in app directory
$phpFiles = [];
$directories = ['app/Http/Controllers', 'app/Http/Livewire', 'app/Models', 'app'];

foreach ($directories as $dir) {
    if (!is_dir($dir)) continue;

    $iterator = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir)
    );

    foreach ($iterator as $file) {
        if ($file->isFile() && $file->getExtension() === 'php') {
            $phpFiles[] = $file->getPathname();
        }
    }
}

echo "Scanning " . count($phpFiles) . " PHP files...\n\n";

// Find all translation calls
$foundStrings = [];
$patterns = [
    '/__\([\'"]([^\'"]+)[\'"]\)/',           // __('string')
    '/trans\([\'"]([^\'"]+)[\'"]\)/',       // trans('string')
    '/@lang\([\'"]([^\'"]+)[\'"]\)/',       // @lang('string')
];

foreach ($phpFiles as $file) {
    $content = file_get_contents($file);

    foreach ($patterns as $pattern) {
        if (preg_match_all($pattern, $content, $matches)) {
            foreach ($matches[1] as $string) {
                // Skip if it's a variable or complex expression
                if (strpos($string, '$') !== false) continue;
                if (strpos($string, '.') === 0) continue; // Starts with dot

                $foundStrings[$string] = [
                    'file' => str_replace(getcwd() . '/', '', $file),
                    'string' => $string
                ];
            }
        }
    }
}

echo "Found " . count($foundStrings) . " unique translation strings in PHP files\n\n";

// Find missing strings
$missing = [];
foreach ($foundStrings as $string => $info) {
    if (!isset($existing[$string])) {
        $missing[$string] = $info;
    }
}

echo "Missing from en.json: " . count($missing) . " strings\n";
echo str_repeat('=', 80) . "\n\n";

if (count($missing) > 0) {
    echo "Missing translation strings:\n";
    echo str_repeat('-', 80) . "\n";

    foreach ($missing as $string => $info) {
        echo sprintf("%-50s (from %s)\n", $string, $info['file']);
    }

    echo "\n" . str_repeat('=', 80) . "\n\n";
    echo "Would you like to add these to en.json? (y/n): ";

    $handle = fopen("php://stdin", "r");
    $line = fgets($handle);
    fclose($handle);

    if (trim($line) === 'y' || trim($line) === 'yes') {
        // Add missing strings to en.json
        foreach ($missing as $string => $info) {
            $existing[$string] = $string; // Use the string itself as the value
        }

        // Sort alphabetically
        ksort($existing);

        // Save to file
        file_put_contents(
            $enFile,
            json_encode($existing, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL
        );

        echo "\n✓ Added " . count($missing) . " new keys to en.json\n";
        echo "✓ Total keys in en.json: " . count($existing) . "\n\n";

        echo "Next steps:\n";
        echo "1. Review the new keys in en.json and edit values if needed\n";
        echo "2. Run: ./translate-new-keys.sh\n";
        echo "3. Clear cache: php artisan config:clear && php artisan cache:clear\n";
    } else {
        echo "\nNo changes made.\n";

        // Save list to file for review
        $output = "Missing translation strings:\n\n";
        foreach ($missing as $string => $info) {
            $output .= sprintf("%-50s (from %s)\n", $string, $info['file']);
        }
        file_put_contents('/tmp/missing-translations.txt', $output);
        echo "List saved to: /tmp/missing-translations.txt\n";
    }
} else {
    echo "✓ All translation strings in PHP files are already in en.json!\n";
}
