<?php

namespace App\Models;

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

class Gallery extends Model
{
    use HasFactory;

    protected $table = 'gallery';

    protected $fillable = [
        'category_id',
        'title',
        'image_path',
        'sort_order',
    ];

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    protected static function booted(): void
    {
        static::deleted(function (Gallery $item) {
            self::deleteStorageFile($item->image_path);
        });

        static::updating(function (Gallery $item) {
            if ($item->isDirty('image_path')) {
                self::deleteStorageFile($item->getOriginal('image_path'));
            }
        });
    }

    private static function deleteStorageFile(?string $path): void
    {
        if ($path && ! str_starts_with($path, 'http')) {
            Storage::disk('public')->delete($path);
        }
    }
}
