<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Subscription extends Model
{
    protected $fillable = [
        'user_id',
        'package_name',
        'price',
        'starts_at',
        'expires_at',
        'status',
    ];

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

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

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

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

    public function isTrialExpired(): bool
    {
        return $this->status === 'trial'
            && $this->expires_at !== null
            && $this->expires_at->isPast();
    }

    public function canAccess(): bool
    {
        if ($this->status === 'active') {
            return true;
        }
        if ($this->status === 'trial' && !$this->isTrialExpired()) {
            return true;
        }
        return false;
    }

    public function trialDaysRemaining(): int
    {
        if ($this->status !== 'trial' || $this->expires_at === null) {
            return 0;
        }
        $remaining = (int) now()->diffInDays($this->expires_at, false);
        return max(0, $remaining);
    }
}
