<?php

namespace App\Models;

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

class Subscription extends Model
{
    protected $fillable = [
        'tenant_id', 'plan_id', 'status', 'starts_at',
        'current_period_ends_at', 'grace_ends_at', 'gateway',
        'paddle_subscription_id', 'expiry_notified', 'is_demo',
        'cancelled_at', 'mrr_iqd',
    ];

    protected function casts(): array
    {
        return [
            'starts_at' => 'datetime',
            'current_period_ends_at' => 'datetime',
            'grace_ends_at' => 'datetime',
            'expiry_notified' => 'array',
            'cancelled_at' => 'datetime',
            'is_demo' => 'boolean',
        ];
    }

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

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

    public function onTrial(): bool
    {
        return $this->status === 'trialing'
            && $this->current_period_ends_at->isFuture();
    }

    public function isActive(): bool
    {
        return in_array($this->status, ['trialing', 'active'], true)
            && $this->current_period_ends_at->isFuture();
    }

    public function inGrace(): bool
    {
        return $this->status === 'grace'
            && $this->grace_ends_at?->isFuture();
    }

    /** Trial/active days remaining, never negative. */
    public function daysLeft(): int
    {
        return max(0, (int) now()->diffInDays($this->current_period_ends_at, false));
    }
}
