<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class RangeDoi extends Model
{
    use HasFactory;

    protected $table = 'm_range_dois';

    protected $fillable = [
        'name',
        'min_days',
        'max_days',
        'color_code',
        'description',
        'is_active',
        'delete_flag',
        'created_by',
        'updated_by',
        'created_at',
        'updated_at',
    ];

    protected $casts = [
        'min_days' => 'decimal:2',
        'max_days' => 'decimal:2',
        'is_active' => 'boolean',
        'delete_flag' => 'boolean',
    ];

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function modificator()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    // Scope for active ranges
    public function scopeActive($query)
    {
        return $query->where('is_active', true)->where('delete_flag', false);
    }

    // Check if a DOI value falls within this range
    public function isInRange($doiValue)
    {
        return $doiValue >= $this->min_days && $doiValue <= $this->max_days;
    }

    // Get range display text
    public function getRangeDisplayAttribute()
    {
        if ($this->max_days == 999999) {
            return "{$this->min_days}+ days";
        }
        return "{$this->min_days} - {$this->max_days} days";
    }

    // Get color badge HTML
    public function getColorBadgeAttribute()
    {
        $color = $this->color_code ?? '#6c757d';
        return "<span class=\"badge\" style=\"background-color: {$color}; color: white;\">{$this->name}</span>";
    }

    // Static method to get DOI category for a value
    public static function getDoiCategory($doiValue)
    {
        $range = static::active()
            ->where('min_days', '<=', $doiValue)
            ->where('max_days', '>=', $doiValue)
            ->first();

        return $range ? $range->name : 'Unknown';
    }

    // Static method to get DOI color for a value
    public static function getDoiColor($doiValue)
    {
        $range = static::active()
            ->where('min_days', '<=', $doiValue)
            ->where('max_days', '>=', $doiValue)
            ->first();

        return $range ? $range->color_code : '#6c757d';
    }
}