<?php

namespace App\Models;

use App\Models\Concerns\BelongsToUser;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Achat extends Model
{
    use BelongsToUser, HasFactory, SoftDeletes;

    protected $guarded = [];

    protected $casts = [
        'date_achat' => 'date',
        'montant' => 'decimal:0',
        'quantite' => 'integer',
    ];

    public const TYPE_ACHAT = 'achat';
    public const TYPE_RETOUR = 'retour';

    public const STATUT_SOLDE = 'soldé';
    public const STATUT_IMPAYE = 'impayé';

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

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

    public function achatOrigine(): BelongsTo
    {
        return $this->belongsTo(Achat::class, 'achat_origine_id');
    }

    public function retours(): HasMany
    {
        return $this->hasMany(Achat::class, 'achat_origine_id');
    }

    public function isRetour(): bool
    {
        return $this->type === self::TYPE_RETOUR;
    }

    /**
     * Génerons la reference
     */

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