<?php

namespace App\Models;

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

use Database\Factories\CompanySubscriptionFactory;
use App\Services\Payments\PaymentProfileService;
class CompanySubscriptions extends Model
{
    use HasFactory;

    protected $table = 'company_subscriptions';
    
    protected $fillable = 
    [
        'subscription_rate_id',
        'company_id',
        'customer_id', 
        'invoice_no', 
        'mode_of_payment', 
        'duration', 
        'date_subscribed',
        'rate',
        'amount_paid', 
        'discount', 
        'previous_bill', 
        'current_bill', 
        'penalty_charge', 
        'total_paid', 
        'amount_due', 
        'current_month_paid',
        'date_upgraded', 
        'date_renewed', 
        'is_blocked', 
        'is_expired', 
        'balance', 
        'is_monthly_expired',
    ];

    /**
     * Create a new factory instance for the model.
     * 
     * @return Factory 
     */
    protected static function newFactory(): Factory
    {
        return CompanySubscriptionFactory::new();
    }

    /*
        temporary compatibility with payment profiles
        This keeps compatibility if any part of the system still references company_subscriptions.customer_id.
    */
    public function stripeCustomerProfile()
    {
        return $this->belongsTo(PaymentProfile::class, 'customer_id', 'provider_customer_id')
                    ->where('provider', 'stripe');
    }


    /**
     * Automatically triggered after a CompanySubscriptions entry is created.
     *
     * Creates a PaymentProfile entry for the company if none exists yet.
     * This keeps payment records unified, regardless of payment provider.
     */
    protected static function booted(): void
    {
        static::created(function (self $subscription) {
            app(PaymentProfileService::class)
                ->createIfNotExistsFromSubscription($subscription);
        });
    }
}
