<?php

namespace Modules\Project\Models;

use App\Services\Upload\UploadService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class ProjectPhoto extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'project_id',
        'image',
        'sort_order',
    ];

    protected $casts = [
        'sort_order' => 'integer',
    ];

    /**
     * Get the project that owns the photo.
     */
    public function project(): BelongsTo
    {
        return $this->belongsTo(Project::class);
    }

    public function setImageAttribute($value): void
    {
        if ($value) {
            if (is_string($value)) {
                $this->attributes['image'] = $value;
            } else {
                $image = UploadService::upload($value, $this->image ?? null, 'projects/photos');
                $this->attributes['image'] = $image;
            }
        } elseif ($this->image ?? false) {
            $this->attributes['image'] = $this->image;
        }
    }

    public function getImageUrlAttribute(): ?string
    {
        return UploadService::url($this->image);
    }
}
