<?php

namespace App\Models;

use App\Models\Client;
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;
use Illuminate\Support\Str;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class Caution extends Model
{
    use BelongsToUser, HasFactory, SoftDeletes, LogsActivity;

    protected $guarded = [];

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

    public const STATUT_ACTIVE = 'active';
    public const STATUT_RESTITUEE = 'remboursée';
    // public const STATUT_ANNULEE = 'annulée';
    public const STATUT_DETTE = 'endeté';
    public const STATUT_PARTIEL = 'partiellement utilisée';
    public const STATUT_EPUISE = 'solde epuisé';

    /**
     * Libellé lisible du statut pour affichage (PDF, exports).
     */
    public static function libelleStatut(?string $statut): string
    {
        return match ($statut) {
            self::STATUT_ACTIVE => 'Active',
            self::STATUT_RESTITUEE => 'Remboursée',
            self::STATUT_DETTE => 'Endetté',
            self::STATUT_PARTIEL => 'Partiellement utilisée',
            self::STATUT_EPUISE => 'Solde épuisé',
            default => $statut ?? '—',
        };
    }

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

    public function isActive(): bool
    {
        return $this->statut === self::STATUT_ACTIVE;
    }

    public function isRestituee(): bool
    {
        return $this->statut === self::STATUT_RESTITUEE;
    }

    public function isAnnulee(): bool
    {
        return $this->statut === self::STATUT_ANNULEE;
    }

    public function isDette(): bool
    {
        return $this->statut === self::STATUT_DETTE;
    }

    public function isPartiel(): bool
    {
        return $this->statut === self::STATUT_PARTIEL;
    }

    public function isEpuise(): bool
    {
        return $this->statut === self::STATUT_EPUISE;
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logOnly(['reference', 'client_id', 'montant', 'statut', 'date_depot', 'date_restitution'])
            ->logOnlyDirty();
    }

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