<?php

namespace App\Traits;

use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;

trait HasUniqueSlug
{
    protected static function initializeHasUniqueSlug()
    {
        static::creating(function (Model $model) {
            if (empty($model->slug) && !empty($model->slugSource)) {
                $baseSlug = Str::slug($model->{$model->slugSource});
                $slug = $baseSlug;

                $query = static::query()->where('slug', 'LIKE', $baseSlug . '%');
                if ($model->getKey()) {
                    $query->where($model->getKeyName(), '!=', $model->getKey());
                }

                $existingSlugs = $query->pluck('slug')->toArray();

                if (in_array($baseSlug, $existingSlugs)) {
                    $i = 1;
                    while (in_array($baseSlug . '-' . $i, $existingSlugs)) {
                        $i++;
                    }
                    $slug = $baseSlug . '-' . $i;
                }

                $model->slug = $slug;
            }
        });
    }
}
