<?php

/* Titan © TakfeDev (MKJUEL). All Rights. */

namespace App\Http\Controllers\Api\Admin;

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

class LanguageController extends Controller
{
    public function index()
    {
        return response()->json(Language::all());
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string',
            'code' => 'required|string|unique:languages,code|max:5',
            'is_rtl' => 'boolean'
        ]);

        $lang = Language::create([
            'name' => $request->name,
            'code' => strtolower($request->code),
            'is_default' => false,
            'is_rtl' => $request->is_rtl ?? false
        ]);

        $path = lang_path("{$lang->code}.json");
        if (!File::exists(lang_path())) {
            File::makeDirectory(lang_path());
        }
        
        if (!File::exists($path)) {
            File::put($path, '{}');
        }

        return response()->json(['message' => 'Language added successfully']);
    }

    public function setDefault(Language $language)
    {
        Language::query()->update(['is_default' => false]);
        $language->update(['is_default' => true]);
        
        Cache::forget('default_locale');

        return response()->json(['message' => 'Default language updated']);
    }

    public function getTranslations($code)
    {
        $path = lang_path("{$code}.json");
        if (!File::exists($path)) {
            return response()->json(['content' => '{}']);
        }
        return response()->json(['content' => File::get($path)]);
    }

    public function updateTranslations(Request $request, $code)
    {
        $request->validate(['content' => 'required|json']);
        $path = lang_path("{$code}.json");
        File::put($path, $request->content);
        return response()->json(['message' => 'Translations saved successfully']);
    }
    
    public function destroy(Language $language)
    {
        if ($language->is_default) {
            return response()->json(['message' => 'Cannot delete default language'], 422);
        }
        $language->delete();
        return response()->json(['message' => 'Language deleted']);
    }
}