<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Setting extends Model
{
    use HasFactory;
    use SoftDeletes;

    const VALID_TYPES = [
        'text' => 'متنی',
        'image' => 'عکس',
        'video' => 'ویدئو',
    ];

    protected $guarded = [
        'id',
        'created_at',
        'updated_at',
    ];

    protected $appends = [];

    protected $with = [];

    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope('order', function (Builder $builder): void {
            $builder->orderByDesc('created_at');
        });
    }

    protected function value(): Attribute
    {
        return Attribute::make(get: function ($value) {
            // If the setting type is a media file, return the full URL.
            if (in_array($this->type, ['image', 'video', 'audio'])) {
                return url($value);
            }
            // If the setting type is JSON, process and return an array of image URLs or other values.
            if ($this->type === 'json') {
                $itemsArray = json_decode($value, true);
                $processedItems = [];

                // Ensure $items_array is a valid, non-empty array.
                if (is_array($itemsArray) && ! empty($itemsArray)) {
                    foreach ($itemsArray as $item) {
                        // If the item contains an 'image' key, generate the full URL and add it to the processed items.
                        if (isset($item['image'])) {
                            $processedItems[] = url($item['image']);
                        }
                        // If item does not contain image and is an array return it directly.
                        elseif (is_array($item)) {
                            return $item;
                        }
                        // Otherwise, add the item itself to the processed items (assuming it's a simple value).
                        else {
                            $processedItems[] = $item;
                        }
                    }
                }

                return $processedItems;
            }

            // For all other setting types, return the value as is.
            return $value;
        });
    }
}
