<?php

namespace App\Models;

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

class Subscription extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'package_id',
        'package_name',
        'amount',
        'interval',
        'auto_renew',
        'status',
        'stripe_customer_id',
        'stripe_subscription_id',
        'stripe_session_id',
        'activated_at',
        'cancelled_at',
        'expires_at',
        // Legacy fields
        'gateway_provider',
        'gateway_subscription_id',
        'plan_name',
        'currency',
        'current_period_start',
        'current_period_end',
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'auto_renew' => 'boolean',
        'activated_at' => 'datetime',
        'cancelled_at' => 'datetime',
        'expires_at' => 'datetime',
        'current_period_start' => 'datetime',
        'current_period_end' => 'datetime',
    ];

    /**
     * User who owns this subscription.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Transactions related to this subscription.
     */
    public function transactions()
    {
        return $this->hasMany(Transaction::class);
    }
    
    /**
     * Invoices related to this subscription.
     */
    public function invoices()
    {
        return $this->hasMany(Invoice::class);
    }

    /**
     * Check if subscription is active.
     */
    public function isActive(): bool
    {
        return $this->status === 'active' && 
               $this->current_period_end->isFuture();
    }

    /**
     * Cancel subscription.
     */
    public function cancel()
    {
        $this->update([
            'status' => 'cancelled',
            'cancelled_at' => now(),
        ]);
    }

    /**
     * Reactivate subscription.
     */
    public function reactivate()
    {
        $this->update([
            'status' => 'active',
            'cancelled_at' => null,
        ]);
    }
}
