<?php

namespace App\Models;

use App\Models\Client;
use App\Models\Concerns\BelongsToUser;
use App\Models\Vente;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class Creance extends Model
{
    use BelongsToUser, HasFactory;
    protected $guarded = [];

    public function client(): BelongsTo
    {
        return $this->belongsTo(Client::class);
    }

    public function vente(): BelongsTo
    {
        return $this->belongsTo(Vente::class);
    }

    /**
     * Générer la référence de la creance lors de la création
     */
    protected static function booted()
    {
        static::creating(function ($creance) {
            if (empty($creance->reference)) {
                $creance->reference = 'CRE-00' . strtoupper(Str::random(2));
            }
        });
    }
}
