<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Subscription extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'subscription_id',
        'user_id',
        'plan_id',
        'gateway_subscription_id',
        'gateway_customer_id',
        'gateway_slug',
        'status',
        'payment_status',
        'start_date',
        'end_date',
        'next_billing_date',
        'cancelled_at',
        'billing_cycle_count',
        'max_billing_cycles',
        'amount',
        'currency',
        'billing_interval',
        'billing_frequency',
        'auto_renew',
        'is_trial',
        'trial_ends_at',
        'metadata',
    ];

    protected $casts = [
        'start_date' => 'datetime',
        'end_date' => 'datetime',
        'next_billing_date' => 'datetime',
        'cancelled_at' => 'datetime',
        'trial_ends_at' => 'datetime',
        'auto_renew' => 'boolean',
        'is_trial' => 'boolean',
        'metadata' => 'array',
    ];

    protected $dates = [
        'start_date',
        'end_date',
        'next_billing_date',
        'cancelled_at',
        'trial_ends_at',
    ];

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

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

    public function gateway()
    {
        return $this->belongsTo(PaymentGateway::class, 'gateway_slug', 'slug');
    }

    public function isActive()
    {
        return $this->status === 'active' && $this->end_date > now();
    }

    public function isCancelled()
    {
        return $this->status === 'cancelled';
    }

    public function isExpired()
    {
        return $this->status === 'expired' || ($this->end_date && $this->end_date < now());
    }

    public function isTrial()
    {
        return $this->is_trial && $this->trial_ends_at && $this->trial_ends_at > now();
    }

    public function isWithinBillingCycle()
    {
        return $this->next_billing_date && $this->next_billing_date > now();
    }
}
