<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\File;

class Language extends Model
{
    protected $fillable = [
        'name',
        'native_name',
        'code',
        'is_default',
        'is_active',
        'direction',
        'flag',
        'order',
    ];

    protected $casts = [
        'is_default' => 'boolean',
        'is_active' => 'boolean',
        'order' => 'integer',
    ];

    public function translations()
    {
        return $this->hasMany(Translation::class, 'language_code', 'code');
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeDefault($query)
    {
        return $query->where('is_default', true);
    }

    public function scopeOrdered($query)
    {
        return $query->orderBy('order');
    }

    public function isRTL()
    {
        return $this->direction === 'rtl';
    }

    public function isLTR()
    {
        return $this->direction === 'ltr';
    }

    public function getDirectionAttribute($value)
    {
        return $value ?: 'ltr';
    }

    public function getTranslationsAttribute()
    {
        $translations = [];
        $langPath = resource_path("lang/{$this->code}");

        if (File::exists($langPath)) {
            $files = File::files($langPath);
            foreach ($files as $file) {
                $group = pathinfo($file, PATHINFO_FILENAME);
                $translations[$group] = require $file;
            }
        }

        return $translations;
    }

    public function updateTranslations(array $translations)
    {
        $langPath = resource_path("lang/{$this->code}");

        if (! File::exists($langPath)) {
            File::makeDirectory($langPath, 0755, true);
        }

        foreach ($translations as $group => $items) {
            $content = "<?php\n\nreturn ".var_export($items, true).";\n";
            File::put("{$langPath}/{$group}.php", $content);
        }
    }
}
