<?php

namespace App\Modules\Admin\Tenancy\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Subscription extends Model
{
    public const STATUS_TRIAL = 'trial';

    public const STATUS_ACTIVE = 'active';

    public const STATUS_GRACE_PERIOD = 'grace_period';

    public const STATUS_EXPIRED = 'expired';

    public const STATUS_CANCELLED = 'cancelled';

    protected $fillable = [
        'tenant_id',
        'plan_id',
        'status',
        'starts_at',
        'ends_at',
        'trial_ends_at',
        'grace_ends_at',
    ];

    protected $casts = [
        'starts_at' => 'datetime',
        'ends_at' => 'datetime',
        'trial_ends_at' => 'datetime',
        'grace_ends_at' => 'datetime',
    ];

    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }

    public function plan(): BelongsTo
    {
        return $this->belongsTo(Plan::class);
    }

    public function scopeActive(Builder $query): Builder
    {
        return $query->whereIn('status', [
            self::STATUS_TRIAL,
            self::STATUS_ACTIVE,
            self::STATUS_GRACE_PERIOD,
        ]);
    }

    public function isExpired(): bool
    {
        if ($this->status === self::STATUS_EXPIRED || $this->status === self::STATUS_CANCELLED) {
            return true;
        }

        if ($this->status === self::STATUS_GRACE_PERIOD) {
            return $this->grace_ends_at !== null && $this->grace_ends_at->isPast();
        }

        return false;
    }
}
