<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Subscription extends Model
{
    protected $fillable = [
        'user_id',
        'package_id',
        'stripe_customer_id',
        'stripe_subscription_id',
        'status',
        'started_at',
        'ends_at',
        'next_billing_date',
        'billing_cycle',
        'trial_days',
        'trial_ends_at',
        'last_driver_count',
        'payment_status',
        'amount_paid',
    ];

    protected $casts = [
        'started_at' => 'datetime',
        'ends_at' => 'datetime',
        'next_billing_date' => 'datetime',
        'trial_ends_at' => 'datetime',
        'last_driver_count' => 'integer',
        'amount_paid' => 'decimal:2',
    ];

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

    public function package()
    {
        return $this->belongsTo(Package::class);
    }

    public function payments()
    {
        return $this->hasMany(Payment::class);
    }

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

    public function isPending()
    {
        return $this->status === 'pending' || $this->payment_status === 'pending';
    }

    /**
     * Check if subscription has Stripe integration
     */
    public function hasStripeIntegration()
    {
        return !empty($this->stripe_customer_id) && !empty($this->stripe_subscription_id);
    }

    /**
     * Get invoice summary for this subscription
     */
    public function getInvoiceSummary()
    {
        $billingService = app(\App\Services\BillingService::class);
        return $billingService->generateInvoiceSummary($this);
    }

    /**
     * Get next billing amount
     */
    public function getNextBillingAmount()
    {
        $billingService = app(\App\Services\BillingService::class);
        $driverCount = $this->user->company->drivers()->count();
        return $billingService->calculateBillingAmount($this->package, $driverCount);
    }

    public function isOnTrial()
    {
        return $this->trial_days > 0 && $this->trial_ends_at && now()->lt($this->trial_ends_at);
    }

    public function isTrialExpired()
    {
        return $this->trial_days > 0 && $this->trial_ends_at && now()->gte($this->trial_ends_at);
    }

    public function hasCardSaved()
    {
        if (!$this->payments()->exists()) {
            return false;
        }

        $lastPayment = $this->payments()->latest()->first();
        $saveOption = $lastPayment?->metadata['save_option'] ?? null;
        return $saveOption === 'save_auto_renew';
    }
}
