<?php

namespace App\Models;

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

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

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

    protected $casts = [
        'disabled' => 'boolean',
    ];

    public function responsable(): HasOne
    {
        return $this->hasOne(User::class, 'magasin_id');
    }

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

    public function transfertsOrigine(): HasMany
    {
        return $this->hasMany(Transfert::class, 'magasin_origine_id');
    }

    public function transfertsDestination(): HasMany
    {
        return $this->hasMany(Transfert::class, 'magasin_destination_id');
    }

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

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

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

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

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

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

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

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

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