<?php

namespace App\Models;

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

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

    const SALE_TYPES = [
        ['name' => 'Vente avec ordonnance', 'code' => 'prescription_sale', 'description' => 'Vente de médicaments nécessitant une prescription médicale', 'status' => true],
        ['name' => 'Vente sans ordonnance', 'code' => 'otc_sale', 'description' => 'Vente de médicaments en vente libre (OTC)', 'status' => true],
        ['name' => 'Vente en gros', 'code' => 'wholesale', 'description' => 'Vente de grandes quantités', 'status' => true],
    ];

    protected $guarded = [];

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

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

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

    // Scopes
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order')->orderBy('name');
    }

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

    // Helper methods
    public function isActive(): bool
    {
        return $this->status === self::STATUS_ACTIVE;
    }

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

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

        return $code;
    }

    // Accessors
    public function getStatusBadgeAttribute(): string
    {
        if ($this->status) {
            return '<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>';
        }

        return '<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>';
    }

    public function getIconHtmlAttribute(): string
    {
        return '<i class="ph '.$this->icon.'" style="color: '.$this->color.';"></i>';
    }
}
