<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class TranslationCheckerCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'i18n:check-json {--l|locale= : The source of truth locale}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Uses one JSON file as the source of truth to check other lang files against.';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $masterLocale = 'en';
        if (!empty($this->option('locale'))) {
            $masterLocale = trim($this->option('locale'));
        }

        $langDir = base_path('lang');
        $langFiles = scandir($langDir);
        $bigCount = count($langFiles);
        for ($i = 0; $i < $bigCount; $i++) {
            if (! preg_match('/.*\.json$/', $langFiles[$i]) || "{$masterLocale}.json" === $langFiles[$i]) {
                unset($langFiles[$i]);
            }
        }

        $langFilesCount = count($langFiles);
        $this->info("Checking {$langFilesCount} file(s) against {$masterLocale}...");

        $masterLocaleTranslations = translations(base_path("lang/{$masterLocale}.json"));

        foreach ($langFiles as $localeFile) {
            $otherLocaleTranslations = translations(base_path("lang/{$localeFile}"));
            $counts = 0;
            $mergedTranslations = $this->recursiveMergeArray($masterLocaleTranslations, $otherLocaleTranslations, $counts);
            file_put_contents(base_path("lang/{$localeFile}"), json_encode($mergedTranslations, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
            $this->info("{$localeFile} had {$counts} missing translations.");
        }

        return Command::SUCCESS;
    }

    public function recursiveMergeArray(array $firstArray, array $secondArray, int &$counts)
    {
        $mergedArray = $secondArray;
        foreach ($firstArray as $key => $value) {
            if (is_array($value)) {
                if (!array_key_exists($key, $secondArray)) {
                    $mergedArray[$key] = $value;
                } else {
                    $subDiff = $this->recursiveMergeArray($value, $secondArray[$key], $counts);
                    if (!empty($subDiff)) {
                        $mergedArray[$key] = $subDiff;
                    }
                }
            } else {
                if (!array_key_exists($key, $secondArray)) {
                    $counts++;
                    $mergedArray[$key] = $value;
                }
            }
        }

        return $mergedArray;
    }
}
