<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Storage;

class AdImage extends Model
{
    use HasFactory, SoftDeletes;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'ad_id',
        'image_url',
        'image_path',
        'image_name',
        'image_size',
        'image_type',
        'is_primary',
        'sort_order',
        'alt_text',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'is_primary' => 'boolean',
        'image_size' => 'integer',
        'sort_order' => 'integer',
    ];

    /**
     * Get the ad that owns the image.
     */
    public function ad()
    {
        return $this->belongsTo(Ad::class);
    }

    /**
     * Accessor for 'url' attribute.
     * Returns image_url if present, otherwise generates full URL from image_path.
     */
    public function getUrlAttribute()
    {
        if (!empty($this->image_url)) {
            return $this->image_url;
        }

        if (!empty($this->image_path)) {
            return Storage::disk('public')->url($this->image_path);
        }

        return asset('images/placeholder.jpg'); // Fallback placeholder
    }

    /**
     * Scope a query to only include primary images.
     */
    public function scopePrimary($query)
    {
        return $query->where('is_primary', true);
    }

    /**
     * Scope a query to order by sort order.
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order', 'asc');
    }
}
