<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;

class ScanTranslations extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'translations:scan {--locale=en}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Scan React files for translation strings and generate messages.php';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $locale = $this->option('locale');
        $path = resource_path('js');
        $files = File::allFiles($path);

        $translations = [];

        foreach ($files as $file) {
            if ($file->getExtension() !== 'jsx' && $file->getExtension() !== 'js')
                continue;

            $content = File::get($file);
            preg_match_all('/t\(["\'](.+?)["\']\)/', $content, $matches);

            foreach ($matches[1] as $text) {
                $key = Str::of($text)
                    ->lower()
                    ->replaceMatches('/[^a-z0-9]+/', '_')
                    ->trim('_')
                    ->toString();
                $translations[$key] = $text;
            }

        }

        $filePath = resource_path("lang/{$locale}/messages.php");
        $existing = File::exists($filePath) ? require $filePath : [];

        $translations = array_merge($translations, $existing);

        $export = "<?php\n\nreturn " . var_export($translations, true) . ";\n";
        File::put($filePath, $export);

        $this->info('Translations scanned and updated for locale: ' . $locale);
    }
}
