<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class LocalizationSetting extends Model
{
    protected $fillable = [
        'timezone',
        'start_week',
        'default_currency',
        'date_format',
        'time_format',
        'locale',
    ];

    /**
     * Get the localization settings (singleton)
     */
    public static function getSettings(): self
    {
        try {
            return static::firstOrCreate([], [
                'timezone' => config('app.timezone', 'UTC'),
                'start_week' => 'monday',
                'default_currency' => 'USD',
                'date_format' => 'MM/DD/YYYY',
                'time_format' => '12',
                'locale' => config('app.locale', 'en'),
            ]);
        } catch (\Illuminate\Database\QueryException $e) {
            // If table doesn't exist, create it
            if (str_contains($e->getMessage(), "doesn't exist")) {
                \Artisan::call('migrate', [
                    '--force' => true,
                    '--path' => 'database/migrations/2025_12_23_145310_create_localization_settings_table.php',
                ]);

                return static::firstOrCreate([], [
                    'timezone' => config('app.timezone', 'UTC'),
                    'start_week' => 'monday',
                    'default_currency' => 'USD',
                    'date_format' => 'MM/DD/YYYY',
                    'time_format' => '12',
                    'locale' => config('app.locale', 'en'),
                ]);
            }
            throw $e;
        }
    }
}
