<?php

namespace App\Models;

use App\Models\Concerns\BelongsToUser;
use App\Models\Vente;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Paiement extends Model
{
    use BelongsToUser, HasFactory, LogsActivity;

    protected $guarded = [];

    protected $casts = [
        'montant' => 'decimal:0',
        'date_paiement' => 'date',
    ];

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

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['reference', 'vente_id', 'montant_paye', 'mode_paiement', 'date_paiement'])
            ->logOnlyDirty();
    }

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