<?php

namespace App\Models;

use Illuminate\Support\Str;
use App\Models\Concerns\BelongsToUser;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Deligoez\LaravelModelHashId\Traits\HasHashId;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Client extends Model
{
    use BelongsToUser, HasFactory, SoftDeletes, HasHashId;

    protected $fillable = ['reference', 'nom', 'telephone', 'adresse', 'caution', 'user_id'];

    protected $casts = [
        'caution' => 'decimal:0',
    ];

    public function ventes(): HasMany
    {
        return $this->hasMany(Vente::class);
    }

    public function cautions(): HasMany
    {
        return $this->hasMany(Caution::class);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /** Réference générer automatiquement */

    protected static function booted()
    {
        static::creating(function ($client) {
            if (empty($client->reference)) {
                $client->reference = 'CLI-00' . strtoupper(Str::random(2));
            }
        });
    }
}
