<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class Contact extends Model implements HasMedia
{
    use HasFactory;
    use InteractsWithMedia;

    protected $fillable = [
        'title', 'subtitle', 'address', 'phone', 
        'whatsapp', 'email', 'working_hours', 
        'google_maps_embed', 'image', 'seo', 'is_active',
        'created_by', 'updated_by',
    ];

    // PENTING: Biar kolom JSON bisa dibaca array
    protected $casts = [
        'seo' => 'array',
    ];

    // Relasi Audit
    public function creator() { return $this->belongsTo(User::class, 'created_by'); }
    public function editor() { return $this->belongsTo(User::class, 'updated_by'); }

    // Logic Otomatis
    protected static function booted()
    {
        static::creating(function ($model) {
            if (Auth::check()) {
                $model->created_by = Auth::id();
                $model->updated_by = Auth::id();
            }
        });

        static::updating(function ($model) {
            if (Auth::check()) {
                $model->updated_by = Auth::id();
            }
        });
    }

    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('images')
            ->useDisk('public')
            ->singleFile();
    }

    public function getImageUrlAttribute(): string
    {
        if ($this->getFirstMediaUrl('images')) {
            return $this->getFirstMediaUrl('images');
        }

        if (!empty($this->image)) {
            return asset('storage/' . ltrim($this->image, '/'));
        }

        return asset('images/default.png');
    }
}