<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

/**
 * PaymentMethod model
 * 
 * This model represents the payment methods in the application.
 * It is used to store the payment methods and their associated data.
 */
class PaymentMethod extends Model
{
    const STATUS_ACTIVE = 1;
    const STATUS_INACTIVE = 0;

    const PAYMENT_METHODS = [
        ['name' => 'Espèces', 'code' => 'cash', 'description' => 'Le client paie en espèces', 'status' => true],
        ['name' => 'Dette', 'code' => 'debt', 'description' => 'Le client enregisté peut payer par dette', 'status' => true],
        ['name' => 'Mobile Money', 'code' => 'mobile_money', 'description' => 'Le client paie par mobile money', 'status' => true],
        ['name' => 'Virement bancaire', 'code' => 'bank_transfer', 'description' => 'Le client paie par virement bancaire', 'status' => false],
        ['name' => 'Chèque', 'code' => 'check', 'description' => 'Le client paie par chèque', 'status' => false],
    ];

    protected $guarded = [];

    public function getRouteKeyName()
    {
        return 'code';
    }

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

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

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('status', true);
    }

    public static function generateUniqueCode($name)
    {
        $code = Str::slug($name);
        $count = 1;
        while (PaymentMethod::where('code', $code)->exists()) {
            $code = $code . '-' . $count;
            $count++;
        }

        return $code;
    }

    // Accessors
    public function getStatusBadgeAttribute()
    {
        return match ($this->status) {
            true => '<span class="inline-block px-3 py-1 border border-green-500 bg-green-100 text-xs font-medium rounded text-green-700 text-center min-w-30"> <i class="ph ph-check-circle mr-1"></i>Actif</span>',
            false => '<span class="inline-block px-3 py-1 border border-red-500 bg-red-100 text-xs font-medium rounded text-red-700 text-center min-w-30"> <i class="ph ph-x-circle mr-1"></i>Inactif</span>',
            default => '<span class="inline-block px-3 py-1 border border-gray-500 bg-gray-100 text-xs font-medium rounded text-gray-700 text-center min-w-30"> <i class="ph ph-clock mr-1"></i>Inconnu</span>'
        };
    }

    public function getIconHtmlAttribute()
    {
        return "<i class=\"{$this->icon}\"></i>";
    }

    // Helpers
    public function isActive(): bool
    {
        return $this->status === true;
    }

    public function isInactive(): bool
    {
        return $this->status === false;
    }
}
