<?php

namespace App\Models;

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

class vehiculeImage extends Model
{
    use HasFactory;
    use HasFactory;
    protected $fillable = [
        'vehicule_id',
        'images_path'
    ];

    public function vehicule()
    {
        return $this->belongsTo(Vehicule::class);
    }

    public function getImageUrlAttribute()
{
    // Solution universelle
    $basePath = 'storage/';
    $imagePath = $this->images_path;

    // Si le chemin commence déjà par storage/, on ne l'ajoute pas
    if (Str::startsWith($imagePath, $basePath)) {
        return asset($imagePath);
    }

    return asset($basePath . ltrim($imagePath, '/'));
}



protected static function booted()
{
    static::deleting(function ($image) {
        if (!app()->runningInConsole()) {
            $imagePath = $image->images_path;
            if (Storage::disk('public')->exists($imagePath)) {
                Storage::disk('public')->delete($imagePath);
                Log::debug('Auto-suppression fichier', ['path' => $imagePath]);
            }
        }
    });
}
}
