<?php

namespace App\Models;

use App\Models\Concerns\BelongsToUser;
use Deligoez\LaravelModelHashId\Traits\HasHashId;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Produit extends Model
{
    use BelongsToUser, HasFactory, SoftDeletes, HasHashId, LogsActivity;

    protected $guarded = [];

    protected $appends = ['hash_id'];

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

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

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

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

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

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

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

    public function magasins(): BelongsToMany
    {
        return $this->belongsToMany(Magasin::class, 'stock')
            ->withPivot('quantite', 'seuil_alerte')
            ->withTimestamps();
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['reference', 'designation', 'prix', 'prix_vente', 'fournisseur_id'])
            ->logOnlyDirty();
    }

    /**
     * Générer la référence du produit lors de la création
     */

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