<?php

namespace App\Models;

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

class License extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'license_key', 'user_id', 'product_id', 'order_id', 'order_item_id',
        'type', 'status', 'max_activations', 'activations_count', 'max_domains',
        'activated_at', 'expires_at', 'suspended_at', 'revoked_at', 'revoke_reason',
        'secret_key', 'checksum', 'is_trial', 'trial_days', 'is_subscription',
        'subscription_id', 'next_billing_at', 'notes', 'meta',
    ];

    protected $casts = [
        'is_trial' => 'boolean',
        'is_subscription' => 'boolean',
        'activated_at' => 'datetime',
        'expires_at' => 'datetime',
        'suspended_at' => 'datetime',
        'revoked_at' => 'datetime',
        'next_billing_at' => 'datetime',
        'meta' => 'array',
    ];

    protected $hidden = ['secret_key', 'checksum'];

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

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    public function activations()
    {
        return $this->hasMany(LicenseActivation::class);
    }

    public function activeActivations()
    {
        return $this->hasMany(LicenseActivation::class)->where('status', 'active');
    }

    public function downloads()
    {
        return $this->hasMany(Download::class);
    }

    /** Returns "Extended" for premium types, "Regular" for standard types */
    public function getDisplayType(): string
    {
        return $this->type === 'unlimited' ? 'Extended' : 'Regular';
    }

    public function isExtended(): bool
    {
        return $this->getDisplayType() === 'Extended';
    }

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

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

    public function hasActivationSlots(): bool
    {
        return $this->activations_count < $this->max_activations;
    }

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

    public function scopeExpiring($query, int $days = 30)
    {
        return $query->where('status', 'active')
            ->whereNotNull('expires_at')
            ->whereBetween('expires_at', [now(), now()->addDays($days)]);
    }
}
