<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class BackEndBladeExtractController extends Controller
{
    public function index()
    {
        // Get all translation keys from views/admin and save to lang/back.json
        $translation_data = [];
        $files = $this->getBladeFiles(resource_path('views/admin')); // Get all .blade.php files

        foreach ($files as $file) {
            $file_data = file_get_contents($file);
            preg_match_all('/__\((.*?)\)/', $file_data, $matches);
            foreach ($matches[1] as $match) {
                $match = trim($match, "'");
                $match = trim($match, '"');
                $translation_data[$match] = $match; // Use key as value
            }
        }

        file_put_contents(resource_path('lang/back.json'), json_encode($translation_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));

        echo "Successfully Extracted";
    }

    private function getBladeFiles($dir)
    {
        $files = [];
        foreach (scandir($dir) as $file) {
            if ($file === '.' || $file === '..') {
                continue;
            }

            $fullPath = $dir . DIRECTORY_SEPARATOR . $file;

            if (is_dir($fullPath)) {
                // If it's a directory, scan recursively
                $files = array_merge($files, $this->getBladeFiles($fullPath));
            } elseif (is_file($fullPath) && pathinfo($fullPath, PATHINFO_EXTENSION) === 'php') {
                // Only add .php (Blade) files
                $files[] = $fullPath;
            }
        }
        return $files;
    }
}
