<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Arr;

class AppSetting extends Model
{
    protected $table = 'app_settings'; //
    
    // Menggunakan guarded kosong agar semua field bisa diisi
    protected $guarded = []; //[cite: 3]

    // Memastikan accessor logo_url otomatis ikut terkirim saat model dipanggil via API
    protected $appends = [
        'logo_url'
    ];

    protected $casts = [
        'brand_logo' => 'array', //[cite: 3]
        'is_online_store_open' => 'boolean', //[cite: 3]
    ];

    /**
     * Accessor untuk logo_url.
     * Menggantikan getBrandLogoUrlAttribute agar output JSON menjadi "logo_url"
     * sesuai dengan yang ditangkap oleh frontend Next.js.
     */
    public function getLogoUrlAttribute()
    {
        $path = null;

        // Perbaikan: Gunakan Arr::first() untuk mengambil value path, 
        // bukan array_key_first() yang justru mengambil index angka (0).
        if (is_array($this->brand_logo) && !empty($this->brand_logo)) {
            $path = Arr::first($this->brand_logo);
        } else {
            $path = $this->brand_logo;
        }

        // Cek apakah file fisik benar-benar ada di storage
        if ($path && Storage::disk('public')->exists($path)) {
            return Storage::url($path);
        }
        
        // Fallback jika logo belum diset atau file hilang
        return asset('images/default-logo.png'); //[cite: 3]
    }

    public static function getSetting()
    {
        return Cache::rememberForever('app_setting', function () { //[cite: 3]
            return self::first() ?? self::create([
                'brand_name' => 'SISTEM DISTRIBUSI P-LINK', //[cite: 3]
                'admin_whatsapp' => '628xxxxxxxx', //[cite: 3]
                'is_online_store_open' => true, //[cite: 3]
                'whatsapp_format' => "Halo Admin P-LINK, saya mau pesan:\n{items}\n\nTotal: {total}\nNama: {customer}\nAlamat: {address}\n\nLokasi Pengiriman:\n{location}", //[cite: 3]
            ]);
        });
    }
    
    protected static function booted()
    {
        static::saved(function () {
            Cache::forget('app_setting'); //[cite: 3]
        });
    }
}