<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;


class Setting extends Model
{
    use HasFactory;

    protected $fillable = [
        'key',
        'value_ar',
        'value_en',
        'last_updated_by_admin_id',
    ];

    protected $casts = [
        'value_ar' => 'array',
        'value_en' => 'array',
    ];

    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('splash_screens_ar');
        $this->addMediaCollection('splash_screens_en');
    }

    /**
     * Get the admin who last updated the setting.
     */
    public function lastUpdatedByAdmin(): BelongsTo
    {
        return $this->belongsTo(Admin::class, 'last_updated_by_admin_id');
    }

    public static function boot()
    {
        parent::boot();

        static::saving(function ($model) {
            if (auth('admin')->check()) { // Check if a user is authenticated
                $model->last_updated_by_admin_id = auth('admin')->id();
            }
        });

        static::deleted(function ($model) {
            // delete all cache starting with 'settings::'
            \Illuminate\Support\Facades\Cache::forget('settings::splash_screens::en');
            \Illuminate\Support\Facades\Cache::forget('settings::splash_screens::ar');
        });
        static::saved(function ($model) {
            \Illuminate\Support\Facades\Cache::forget('settings::splash_screens::en');
            \Illuminate\Support\Facades\Cache::forget('settings::splash_screens::ar');
        });
    }
}
