<?php

namespace App\Models;

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

class Subscription extends Model
{
    protected $fillable = [
        'organization_id', 'plan', 'status', 'amount', 'billing_cycle',
        'trial_ends_at', 'current_period_start', 'current_period_end',
        'cancelled_at', 'notes',
    ];

    protected function casts(): array
    {
        return [
            'trial_ends_at'        => 'datetime',
            'current_period_start' => 'datetime',
            'current_period_end'   => 'datetime',
            'cancelled_at'         => 'datetime',
            'amount'               => 'decimal:2',
        ];
    }

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

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

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

    /**
     * Check whether this subscription has passed its end date and, if so,
     * update its status to 'expired' in the database. Returns true when
     * the subscription was just expired.
     */
    public function expireIfNeeded(): bool
    {
        if ($this->status === 'trial' && $this->trial_ends_at?->isPast()) {
            $this->update(['status' => 'expired']);
            $this->status = 'expired';
            return true;
        }

        if ($this->status === 'active' && $this->current_period_end?->isPast()) {
            $this->update(['status' => 'expired']);
            $this->status = 'expired';
            return true;
        }

        return false;
    }

    /**
     * Returns true when the subscription is currently granting access
     * (status is active/trial and has not passed its end date).
     */
    public function isCurrentlyActive(): bool
    {
        if ($this->status === 'trial') {
            return !$this->trial_ends_at || $this->trial_ends_at->isFuture();
        }

        if ($this->status === 'active') {
            return !$this->current_period_end || $this->current_period_end->isFuture();
        }

        return false;
    }
}
