<?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\SoftDeletes;

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

    protected $fillable = [
        'reference',
        'client_id',
        'produit_id',
        'magasin_id',
        'quantite',
        'montant',
        'mode_paiement',
        'statut_paiement',
        'montant_paye',
        'date_vente',
        'user_id',
    ];

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

    public const STATUT_PAYE = 'paye';
    public const STATUT_PARTIELLEMENT = 'partiellement';
    public const STATUT_EN_ATTENTE = 'en_attente';

    public function getMontantRestantAttribute(): float
    {
        return max(0, (float) $this->montant - (float) $this->montant_paye);
    }

    public function isPaye(): bool
    {
        return $this->statut_paiement === self::STATUT_PAYE;
    }

    public function isPartiellementPaye(): bool
    {
        return $this->statut_paiement === self::STATUT_PARTIELLEMENT;
    }

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

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

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