<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class CompanySubscription extends Model
{
    protected $fillable = [
        'company_id','max_concurrent_users','session_timeout_minutes',
        'modules_enabled','trial_ends_at','subscription_starts_at',
        'subscription_ends_at','monthly_fee','billing_cycle','notes'
    ];

    protected $casts = [
        'modules_enabled'         => 'array',
        'trial_ends_at'           => 'date',
        'subscription_starts_at'  => 'date',
        'subscription_ends_at'    => 'date',
    ];

    public function company()
    {
        return $this->belongsTo(Company::class);
    }

    public function isExpired(): bool
    {
        if ($this->subscription_ends_at && now()->gt($this->subscription_ends_at)) {
            return true;
        }
        if ($this->trial_ends_at && now()->gt($this->trial_ends_at)
            && !$this->subscription_starts_at) {
            return true;
        }
        return false;
    }

    public function isModuleEnabled(string $module): bool
    {
        if (empty($this->modules_enabled)) return true;
        return in_array($module, $this->modules_enabled);
    }

    public function activeSessions(): int
    {
        return CompanySession::where('company_id', $this->company_id)
            ->where('last_activity', '>=', now()->subMinutes($this->session_timeout_minutes)->timestamp)
            ->count();
    }

    public function canLogin(): bool
    {
        return $this->activeSessions() < $this->max_concurrent_users;
    }
}
