<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Language;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;

class LanguageController extends Controller
{
    public function index()
    {
        $languages = Language::all();

        return view('admin.languages.index', compact('languages'));
    }

    public function create()
    {
        return view('admin.languages.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:50',
            'native_name' => 'required|string|max:50',
            'code' => 'required|string|max:5|unique:languages',
            'flag' => 'nullable|string|max:10',
            'is_default' => 'boolean',
            'is_active' => 'boolean',
        ]);

        // Set default values for boolean fields if not present
        $validated['is_default'] = $request->has('is_default') ? true : false;
        $validated['is_active'] = $request->has('is_active') ? true : false;

        if ($validated['is_default']) {
            Language::where('is_default', true)->update(['is_default' => false]);
        }

        // Create new language
        $language = new Language();
        $language->name = $validated['name'];
        $language->native_name = $validated['native_name'];
        $language->code = $validated['code'];
        $language->flag = $validated['flag'];
        $language->is_default = $validated['is_default'];
        $language->is_active = $validated['is_active'];
        $language->direction = $validated['code'] === 'ar' ? 'rtl' : 'ltr';
        $language->save();

        // Create language directory and files
        $langPath = resource_path("lang/{$language->code}");
        if (! File::exists($langPath)) {
            File::makeDirectory($langPath, 0755, true);
        }

        return redirect()->route('admin.languages.index')
            ->with('success', __('admin.language_created_successfully'));
    }

    public function edit(Language $language)
    {
        return view('admin.languages.edit', compact('language'));
    }

    public function update(Request $request, Language $language)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:50',
            'native_name' => 'required|string|max:50',
            'code' => 'required|string|max:5|unique:languages,code,'.$language->id,
            'flag' => 'nullable|string|max:10',
            'is_default' => 'boolean',
            'is_active' => 'boolean',
        ]);

        // Set default values for boolean fields if not present
        $validated['is_default'] = $request->has('is_default') ? true : false;
        $validated['is_active'] = $request->has('is_active') ? true : false;

        if ($validated['is_default'] && ! $language->is_default) {
            Language::where('is_default', true)->update(['is_default' => false]);
        }

        // Update language
        $language->name = $validated['name'];
        $language->native_name = $validated['native_name'];
        $language->code = $validated['code'];
        $language->flag = $validated['flag'];
        $language->is_default = $validated['is_default'];
        $language->is_active = $validated['is_active'];
        $language->direction = $validated['code'] === 'ar' ? 'rtl' : 'ltr';
        $language->save();

        return redirect()->route('admin.languages.index')
            ->with('success', __('admin.language_updated_successfully'));
    }

    public function destroy(Language $language)
    {
        if ($language->is_default) {
            return redirect()->route('admin.languages.index')
                ->with('error', __('admin.cannot_delete_default_language'));
        }

        // Delete language files
        $langPath = resource_path("lang/{$language->code}");
        if (File::exists($langPath)) {
            File::deleteDirectory($langPath);
        }

        $language->delete();

        return redirect()->route('admin.languages.index')
            ->with('success', __('admin.language_deleted_successfully'));
    }

    public function translations(Language $language)
    {
        $translations = $language->translations;

        return view('admin.languages.translations', compact('language', 'translations'));
    }

    public function updateTranslations(Request $request, Language $language)
    {
        $translations = $request->except('_token');
        $language->updateTranslations($translations);

        return redirect()->route('admin.languages.translations', $language)
            ->with('success', __('admin.translations_updated_successfully'));
    }

    public function setDefault(Language $language)
    {
        Language::where('is_default', true)->update(['is_default' => false]);
        $language->update(['is_default' => true]);

        return redirect()->route('admin.languages.index')
            ->with('success', __('admin.default_language_updated'));
    }

    public function toggleActive(Language $language)
    {
        if ($language->is_default) {
            return redirect()->route('admin.languages.index')
                ->with('error', __('admin.cannot_deactivate_default_language'));
        }

        $language->update(['is_active' => ! $language->is_active]);

        return redirect()->route('admin.languages.index')
            ->with('success', __('admin.language_status_updated'));
    }

    /**
     * تغییر زبان برنامه
     */
    public function switchLanguage($locale)
    {
        $language = \App\Models\Language::where('code', $locale)->first();
        if (! $language) {
            if (request()->ajax()) {
                return response()->json(['success' => false, 'message' => 'زبان مورد نظر یافت نشد.']);
            }

            return redirect()->back()->with('error', 'زبان مورد نظر یافت نشد.');
        }
        session()->put('locale', $locale);
        app()->setLocale($locale);
        if (request()->ajax()) {
            return response()->json(['success' => true]);
        }

        return redirect()->back();
    }
}
