<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Carbon\Carbon;

class License extends Model
{
    protected $fillable = [
        'key',
        'name',
        'email',
        'status',
        'expires_at',
        'activated_at',
        'max_devices',
        'current_devices',
        'note',
    ];

    protected $casts = [
        'expires_at' => 'datetime',
        'activated_at' => 'datetime',
        'max_devices' => 'integer',
        'current_devices' => 'integer',
    ];

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

    public function activeDevices(): HasMany
    {
        return $this->deviceLogs()->where('is_active', true);
    }

    public function isExpired(): bool
    {
        return $this->expires_at && Carbon::now()->greaterThan($this->expires_at);
    }

    public function isActive(): bool
    {
        return $this->status === 'active' && !$this->isExpired();
    }

    public function canAddDevice(): bool
    {
        return $this->current_devices < $this->max_devices;
    }

    public function activate(): void
    {
        $this->update([
            'status' => 'active',
            'activated_at' => Carbon::now(),
        ]);
    }

    public function suspend(): void
    {
        $this->update(['status' => 'suspended']);
    }

    public function revoke(): void
    {
        $this->update(['status' => 'revoked']);
    }

    public function reactivate(): void
    {
        $this->update(['status' => 'active']);
    }

    public function incrementDeviceCount(): void
    {
        $this->increment('current_devices');
    }

    public function decrementDeviceCount(): void
    {
        if ($this->current_devices > 0) {
            $this->decrement('current_devices');
        }
    }
}