<?php

namespace App\Models;

use App\Models\BaseModel;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Cache;

class Setting extends BaseModel
{
    protected $table = 'settings';

    protected $fillable = [
        'name',
        'timezone',
        'updated_by',
        'created_at',
        'updated_at',
    ];

    public $timestamps = true;

    protected $casts = [
        'updated_by' => 'integer',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    /* ============================================================
     * Relationships (optional)
     * ============================================================
     */

    public function updater(): BelongsTo
    {
        // Change Admin::class to your actual user model if needed
        return $this->belongsTo(Admin::class, 'updated_by');
    }

    /* ============================================================
     * Singleton helpers (1-row settings table)
     * ============================================================
     */

    /**
     * Get the singleton settings row.
     * - If missing, creates id=1.
     */
    public static function singleton(): self
    {
        return static::query()->first() ?? static::query()->create([
            // set safe defaults if you want
            'name'     => 'App',
            'timezone' => config('app.timezone', 'UTC'),
        ]);
    }

    /**
     * CI-compatible: getSettings()
     * Returns the settings model (single row).
     */
    public static function getSettings(): self
    {
        return static::singleton();
    }

    /**
     * CI-compatible: updateSettings($data)
     * Updates the singleton row and returns bool.
     */
    public static function updateSettings(array $data): bool
    {
        $settings = static::singleton();
        return $settings->fill($data)->save();
    }

    /* ============================================================
     * Performance: cached settings (optional)
     * ============================================================
     */

    public static function cached(int $ttlSeconds = 300): self
    {
        return Cache::remember('app_settings_singleton', $ttlSeconds, function () {
            return static::singleton();
        });
    }

    public static function clearCache(): void
    {
        Cache::forget('app_settings_singleton');
    }

    protected static function booted(): void
    {
        static::saved(fn () => static::clearCache());
        static::deleted(fn () => static::clearCache());
    }

    /* ============================================================
     * Optional validation helper
     * ============================================================
     */

    public static function rules(bool $updating = false): array
    {
        return [
            'name'      => ['nullable', 'string', 'max:255'],
            'timezone'  => ['nullable', 'string', 'max:80'], // validate against a list if you want
            'updated_by'=> ['nullable', 'integer'],
        ];
    }
}