<?php

namespace App\Repositories\Admin;

use App\Models\Category;
use App\Models\Language;
use App\Models\MovieLanguage;
use App\Repositories\Interfaces\Admin\LanguageInterface;
use Carbon\Carbon;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Artisan;

class LanguageRepository implements LanguageInterface
{
    public function all()
    {
        return Category::get();
    }

    public function store($request)
    {
        try {
            $data = [
                'name' => $request['name'],
                'description' => $request['description'],
                'status' => $request['status'],
                'slug' => Str::slug($request['name']),
                'created_at' => Carbon::now(),
                'updated_at' => Carbon::now(),
            ];
            return MovieLanguage::create($data);
        } catch (\Exception $e) {
            return false;
        }
    }

    public function update($request, $id)
    {
        try {
            $data = [
                'name' => $request['name'],
                'description' => $request['description'],
                'status' => $request['status'],
                'slug' => Str::slug($request['name']),
                'updated_at' => Carbon::now(),
            ];
            return MovieLanguage::where('id', $id)->update($data);
        } catch (\Exception $e) {
            return false;
        }
    }

    public function systemLanguageStore($request)
    {
        $data = [
            'name' => $request['name'],
            'flag' => $request['flag'],
            'status' => $request['status']
        ];
        // Create or update the language by 'locale'
        $language = Language::updateOrCreate(
            ['locale' => $request['locale']], // search condition
            $data // values to update or insert
        );

        $base_path = base_path("lang/{$language->locale}.json");

        if (!File::exists($base_path)) {
            $translation_keys = file_get_contents(base_path('lang/en.json'));
            file_put_contents($base_path, $translation_keys);
        }

        return $language;
    }
    public function systemLanguageUpdate($request)
    {
        $data = [
            'name' => $request['name'],
            'flag' => $request['flag'],
            'status' => $request['status']
        ];

        // Create or update the language by 'locale'
        $language = Language::updateOrCreate(
            ['locale' => $request['locale']], // search condition
            $data // values to update or insert
        );

        $base_path = base_path("lang/{$language->locale}.json");

        if (!File::exists($base_path)) {
            $translation_keys = file_get_contents(base_path('lang/en.json'));
            file_put_contents($base_path, $translation_keys);
        }

        return $language;
    }

    public function findMissingKeys($id)
    {
        try {
             // Find the language by ID
             $language = Language::findOrFail($id);
             $enJsonFile = File::get(base_path('lang/en.json'));
             $bnJsonFilePath = base_path('lang/') . $language->locale . '.json';
             $enTranslations = json_decode($enJsonFile, true);
             $bnTranslations = File::exists($bnJsonFilePath) ? json_decode(File::get($bnJsonFilePath), true) : [];
             $missingKeys = array_diff_key($enTranslations, $bnTranslations);
             foreach ($missingKeys as $key => $value) {
                 if (preg_match('/\\\\u[0-9A-Fa-f]{4}/', $value)) {
                     // Convert Unicode escape sequences to actual Unicode characters
                     $value = json_decode('"'.$value.'"');
                 }
                 $bnTranslations[$key] = $value;
             }
              // Save updated bn.json file
             File::put($bnJsonFilePath, json_encode($bnTranslations, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
              // Clear all cached data
             Artisan::call('cache:clear');
             Artisan::call('config:clear');
             Artisan::call('view:clear');
            return true;
        } catch (\Exception $e) {
            // Handle exceptions
            return $e->getMessage();

        }
    }

     public function scanAndStore($id)
    {
        try {
            $language = Language::findOrFail($id);
            $exitCode = Artisan::call('translation:scan');
            // Check if the command ran successfully
            if ($exitCode !== 0) {
                throw new \Exception('Langscanner command failed');
            }
            Artisan::call('all:clear');
            return true;
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }
}
