<?php

/*
|--------------------------------------------------------------------------
| OwnStore - Build your own online store
| Author: TakfeDev (MKJUEL)
| All Rights Reserved
|--------------------------------------------------------------------------
*/

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

class BuildLangCommand extends Command
{
    protected $signature = 'lang:build';
    protected $description = 'Scan Vue/React and PHP/Blade files to generate lang/en.json automatically';

    public function handle()
    {
        $this->info("------------------------------------------------");
        $this->info("  Marketplace Auto Language Builder");
        $this->info("------------------------------------------------");

        $outputFile = base_path('lang/en.json');
        $translations = [];
        $newCount = 0;

        if (File::exists($outputFile)) {
            $existing = json_decode(File::get($outputFile), true);
            if (is_array($existing)) {
                $translations = $existing;
                $this->info("Loaded " . count($translations) . " existing translations.");
            }
        }

        $jsRegex = '/\bt\(\s*(["\'])(.+?)\1/s';
        
        $phpRegex = '/\b__\(\s*(["\'])(.+?)\1/s';

        $this->info("Scanning React files...");
        $newCount += $this->scanDirectory(base_path('resources/js'), ['js', 'jsx'], $jsRegex, $translations);

        $this->info("Scanning Controllers & Services...");
        $newCount += $this->scanDirectory(base_path('app'), ['php'], $phpRegex, $translations);

        $this->info("Scanning Email & Blade Templates...");
        $newCount += $this->scanDirectory(base_path('resources/views'), ['php'], $phpRegex, $translations);

        ksort($translations);

        if (!File::exists(base_path('lang'))) {
            File::makeDirectory(base_path('lang'), 0755, true);
        }

        $jsonContent = json_encode($translations, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        
        if (File::put($outputFile, $jsonContent)) {
            $this->info("------------------------------------------------");
            $this->info("SUCCESS!");
            $this->info("New keys found: {$newCount}");
            $this->info("Total keys now: " . count($translations));
            $this->info("File saved securely to: lang/en.json");
            $this->info("------------------------------------------------");
        } else {
            $this->error("ERROR: Could not write to {$outputFile}");
        }
    }

    private function scanDirectory($dir, $extensions, $regex, &$translations)
    {
        if (!is_dir($dir)) return 0;

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

        foreach ($iterator as $file) {
            if ($file->isDir()) continue;

            if (in_array($file->getExtension(), $extensions)) {
                $content = file_get_contents($file->getPathname());

                if (preg_match_all($regex, $content, $matches)) {
                    foreach ($matches[2] as $string) {
                        if (!isset($translations[$string])) {
                            $translations[$string] = $string; 
                            $count++;
                        }
                    }
                }
            }
        }

        return $count;
    }
}