<?php

namespace App\Http\Controllers\Admin;

use App\DataTables\Admin\LanguageDataTable;
use App\DataTables\Admin\SystemLanguageDataTable;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\LanguageRequest;
use App\Models\FlagIcon;
use App\Models\Language;
use App\Models\MovieLanguage;
use App\Repositories\Interfaces\Admin\LanguageInterface;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\App;

class LanguageController extends Controller
{
    protected $languages;

    public function __construct(LanguageInterface $languages)
    {
        $this->languages = $languages;
    }

    public function index(LanguageDataTable $dataTable)
    {
        return $dataTable->render('admin.language.index');
    }

    public function add()
    {
        return view('admin.language.add');
    }

    public function store(LanguageRequest $request)
    {
        if (isDemoMode()) {
            $data = [
                'status'    => 'error',
                'message'   => 'This action is disabled in demo mode.',
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        $this->languages->store($request->all());
        $data = [
            'status'    => 'success',
            'message'   => __('movie_language_added_successfully'),
            'title'     => __('success'),
            'is_reload' => true,
        ];
        return response()->json($data);
    }

    public function status(Request $request)
    {
        if (isDemoMode()) {
            $data = [
                'status'    => 'error',
                'message'   => 'This action is disabled in demo mode.',
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        MovieLanguage::where('id', $request->id)->update(['status' => $request->status]);
        $data = [
            'status'    => 'success',
            'message'   => __('movie_language_status_update_successfully'),
            'title'     => __('success'),
            'is_reload' => false,
        ];
        return response()->json($data);
    }

    public function edit($id)
    {
        $data['language'] = MovieLanguage::where('id', $id)->first();
        return view('admin.language.edit', $data);
    }

    public function update(LanguageRequest $request, $id)
    {
        if (isDemoMode()) {
            $data = [
                'status'    => 'error',
                'message'   => 'This action is disabled in demo mode.',
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        $this->languages->update($request->all(), $id);
        $data = [
            'status'    => 'success',
            'message'   => __('category_update_successfully'),
            'title'     => __('success'),
            'is_reload' => true,
        ];
        return response()->json($data);
    }

    public function delete($id)
    {
        if (isDemoMode()) {
            $data = [
                'status'    => 'error',
                'message'   => 'This action is disabled in demo mode.',
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        if(!auth()->user()->can('admin.language.delete')){
            $data = [
                'status'    => 'error',
                'message'   => __('you_are_not_authorized_to_perform_this_action'),
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        $languageDelete = MovieLanguage::where('id', $id)->delete();
        if ($languageDelete) {
            $data = [
                'title'  => __('Success'),
                'status'  => true,
                'message' => __('movie_language_delete_successfully'),
                'is_reload' => true,
            ];
            return $data;
        }
        return false;
    }

    public function systemLanguage(SystemLanguageDataTable $dataTable)
    {
        try {

            return $dataTable->render('admin.settings.language.index');
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    public function systemLanguageAdd()
    {
        $data = [
            'flags' => FlagIcon::get(),
        ];

        return view('admin.settings.language.add', $data);
    }

    public function systemLanguageStore(Request $request)
    {
        if (isDemoMode()) {
            $data = [
                'status'    => 'error',
                'message'   => 'This action is disabled in demo mode.',
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        $this->languages->systemLanguageStore($request->all());
        $data = [
            'status'    => 'success',
            'message'   => __('language_added_successfully'),
            'title'     => __('success'),
            'is_reload' => true,
        ];
        return response()->json($data);
    }
    public function systemLanguageUpdate(Request $request)
    {
        if (isDemoMode()) {
            $data = [
                'status'    => 'error',
                'message'   => 'This action is disabled in demo mode.',
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        $this->languages->systemLanguageUpdate($request->all());
        $data = [
            'status'    => 'success',
            'message'   => __('language_updated_successfully'),
            'title'     => __('success'),
            'is_reload' => true,
        ];
        return response()->json($data);
    }

     public function systemLanguageEdit($id)
    {
        $data['flags'] = FlagIcon::get();
        $data['language'] = Language::where('id', $id)->first();
        return view('admin.settings.language.edit', $data);
    }


    public function statusChange(Request $request)
    {
        if (isDemoMode()) {
            $data = [
                'status'    => 'error',
                'message'   => 'This action is disabled in demo mode.',
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        Language::where('id', $request->id)->update(['status' => $request->status]);
        $data = [
            'status'    => 'success',
            'message'   => __('language_status_update_successfully'),
            'title'     => __('success'),
            'is_reload' => false,
        ];
        return response()->json($data);
    }

    public function languageDelete($id)
    {
        if (isDemoMode()) {
            $data = [
                'status'    => 'error',
                'message'   => 'This action is disabled in demo mode.',
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        // Get the language row
        $language = Language::find($id);

        if ($language) {
            // Store the path to the JSON file before deleting
            $file_path = base_path("lang/{$language->locale}.json");

            // Delete the DB record
            $languageDelete = $language->delete();

            if ($languageDelete) {
                // Delete the JSON file if it exists
                if (File::exists($file_path)) {
                    File::delete($file_path);
                }

                return [
                    'title'     => __('Success'),
                    'status'    => true,
                    'message'   => __('language_delete_successfully'),
                    'is_reload' => true,
                ];
            }
        }

        return false;
    }

    public function translationPage(Request $request, $id)
    {
        $language     = Language::where('id', $id)->first();
        $file         = base_path('lang/' . $language->locale . '.json');
        if (! file_exists($file)) {
            $en_file = base_path('lang/en.json');
            copy($en_file, $file);
        }

        $translations = json_decode(file_get_contents($file), true);

        if ($request->q) {
            $translations = array_filter($translations, function ($key) use ($request) {
                return str_contains($key, $request->q);
            }, ARRAY_FILTER_USE_KEY);
        }

        $data         = [
            'language'     => $language,
            'languages'    => Language::where('status', 'active')->get(),
            'translations' => $translations,
            'search_query' => $request->q,
        ];

        return view('admin.settings.language.translation', $data);
    }


    public function translationDelete($id, $key)
    {
        if (isDemoMode()) {
            $data = [
                'status'    => 'error',
                'message'   => 'This action is disabled in demo mode.',
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        try {
            $language = Language::find($id);
            $data = file_get_contents(base_path('lang/') . $language->locale . '.json');
            $json_arr = json_decode($data, true);
            unset($json_arr[$key]);
            file_put_contents(base_path('lang/' . $language->locale . '.json'), json_encode($json_arr));
            return [
                'title'     => __('Success'),
                'status'    => true,
                'message'   => __('translation_delete_successfully'),
                'is_reload' => true,
            ];
        } catch (\Throwable $e) {
            if (config('app.debug')) {
                dd($e->getMessage());
            }
            return redirect()->back()->with('success_message', $e->getMessage());
        }
    }

    public function updateTranslations(Request $request, $language)
    {
        if (isDemoMode()) {
            $data = [
                'status'    => 'error',
                'message'   => 'This action is disabled in demo mode.',
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        try {
            // Decode request data
            $translations     = json_decode($request->translations, true);
            $keys             = array_column(json_decode(trim($request->keys), true), 'value');
            $values           = array_column($translations, 'value');
            $translation_keys = array_combine($keys, $values);
            // Load existing translations
            $language         = Language::find($language);
            $path             = base_path('lang/' . $language->locale . '.json');
            $old_values       = json_decode(file_get_contents($path), true);
            // Merge new translations with existing ones
            foreach ($translation_keys as $key => $value) {
                $old_values[$key] = $value; // Overwrite or add new key-value pair
            }
            // Write updated translations back to JSON file
            file_put_contents($path, json_encode($old_values, JSON_PRETTY_PRINT));

            return response()->json([
                'success' => __('update_successful'),
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'error' => $e->getMessage(),
            ]);
        }
    }

    public function findMissingKeys($id)
    {
        if (isDemoMode()) {
            $data = [
                'status'    => 'error',
                'message'   => 'This action is disabled in demo mode.',
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        $result = $this->languages->findMissingKeys($id);
        session()->flash('toastr_success', 'missing_keyword_added_successfully!');
        return redirect()->back();
    }

    public function scanAndStore($id)
    {
        if (isDemoMode()) {
            $data = [
                'status'    => 'error',
                'message'   => 'This action is disabled in demo mode.',
                'title'     => __('error'),
                'is_reload' => false,
            ];
            return response()->json($data);
        }
        $result = $this->languages->scanAndStore($id);
        session()->flash('toastr_success', 'lang_scan_and_store_successfully!');
        return redirect()->back();
    }

    public function changeLanguage(string $lang)
    {
        $lang = trim($lang);
        if ($lang === '' || ! Language::where('status', 1)->where('locale', $lang)->exists()) {
            return redirect()->back()->with('error', __('invalid_request'));
        }

        session(['locale' => $lang]);
        App::setLocale($lang);

        return redirect()->to(url()->previous() ?: route('home'));
    }
}
