<?php

namespace App\Models;

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

class Subscription extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'plan',
        'status',
        'paystack_reference',
        'paystack_transaction_id',
        'amount',
        'currency',
        'starts_at',
        'expires_at',
        'gateway_response',
    ];

    protected function casts(): array
    {
        return [
            'starts_at'        => 'datetime',
            'expires_at'       => 'datetime',
            'amount'           => 'decimal:2',
            'gateway_response' => 'array',
        ];
    }

    // ─────────────────────────────────────────
    // RELATIONSHIPS
    // ─────────────────────────────────────────

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

    // ─────────────────────────────────────────
    // HELPERS
    // ─────────────────────────────────────────

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

    public function getPlanLabelAttribute(): string
    {
        return match ($this->plan) {
            'pro'      => 'Pro',
            'business' => 'Business',
            default    => ucfirst($this->plan),
        };
    }

    public function getDaysRemainingAttribute(): int
    {
        if (! $this->expires_at) return 0;
        return max(0, (int) now()->diffInDays($this->expires_at, false));
    }
}
