<?php

namespace App\Models;

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

class Server extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'project_id',
        'provider',
        'provider_id',
        'name',
        'region',
        'plan',
        'image',
        'status',
        'suspended_at',
        'ip_address',
        'password',
        'price_hourly_toman',
    ];

    /**
     * ✅ تبدیل فیلدها به Carbon
     */
    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'suspended_at' => 'datetime', // ✅ اضافه شد
    ];

    // ==================== Relations ====================

    public function user()
    {
        return $this->belongsTo(User::class);
    }
    
    public function project()
    {
        return $this->belongsTo(Project::class);
    }

    public function bandwidthUsages()
    {
        return $this->hasMany(BandwidthUsage::class);
    }

    public function ips()
    {
        return $this->hasMany(ServerIp::class);
    }

    // ==================== Helper Methods ====================

    /**
     * آیا سرور معلق شده؟
     */
    public function isSuspended(): bool
    {
        return $this->status === 'suspended';
    }

    /**
     * تعداد ساعت از زمان معلق شدن
     */
    public function getHoursSinceSuspension(): int
    {
        if (!$this->suspended_at) {
            return 0;
        }

        return (int) $this->suspended_at->diffInHours(now());
    }

    /**
     * آیا سرور باید حذف بشه؟ (بعد از 12 ساعت)
     */
    public function shouldBeDeleted(): bool
    {
        return $this->isSuspended() && $this->getHoursSinceSuspension() >= 12;
    }

    /**
     * دریافت Badge Color برای وضعیت
     */
public function getStatusBadgeColor(): string
{
    $colors = [
        'active' => 'success',
        'running' => 'success',
        'creating' => 'info',
        'suspended' => 'warning',
        'stopped' => 'secondary',
        'off' => 'secondary',
        'deleted' => 'danger',
    ];

    return $colors[$this->status] ?? 'secondary';
}

public function getStatusLabel(): string
{
    $labels = [
        'active' => 'فعال',
        'running' => 'در حال اجرا',
        'creating' => 'در حال ساخت',
        'suspended' => 'معلق',
        'stopped' => 'متوقف',
        'off' => 'خاموش',
        'deleted' => 'حذف شده',
    ];

    return $labels[$this->status] ?? $this->status;
    }
}