<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Language;
use Illuminate\Support\Facades\File;

class LanguageSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $languages = [
            [
                'name' => 'English',
                'code' => 'en',
                'is_rtl' => false,
                'is_default' => true,
            ],
            [
                'name' => 'বাংলা (Bangla)',
                'code' => 'bn',
                'is_rtl' => false,
                'is_default' => false,
            ],
            [
                'name' => 'العربية (Arabic)',
                'code' => 'ar',
                'is_rtl' => true, // Arabic is Right-to-Left
                'is_default' => false,
            ],
            [
                'name' => '中文 (Chinese)',
                'code' => 'zh',
                'is_rtl' => false,
                'is_default' => false,
            ],
        ];

        // 1. Ensure lang directory exists
        if (!File::exists(base_path('lang'))) {
            File::makeDirectory(base_path('lang'), 0755, true);
        }

        foreach ($languages as $lang) {
            // 2. Insert or Update Database
            Language::updateOrCreate(
                ['code' => $lang['code']],
                $lang
            );

            // 3. Create JSON file if it doesn't exist
            $path = base_path("lang/{$lang['code']}.json");
            if (!File::exists($path)) {
                File::put($path, json_encode([], JSON_PRETTY_PRINT));
            }
        }

        // Clear Cache to reflect changes in Header immediately
        \Illuminate\Support\Facades\Cache::forget('active_languages');
    }
}