<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class BillingHistory extends Model
{
    use HasFactory;

    protected $table = 'billing_history';

    protected $fillable = [
        'user_id',
        'subscription_id',
        'payment_method_id',
        'invoice_number',
        'billing_date',
        'amount',
        'currency',
        'status',
        'plan_name',
        'billing_period',
        'invoice_url',
        'pdf_url',
        'payment_gateway',
        'gateway_transaction_id',
        'notes',
    ];

    protected $casts = [
        'billing_date' => 'date',
        'amount' => 'decimal:2',
    ];

    /**
     * Boot the model
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($billing) {
            if (empty($billing->invoice_number)) {
                $billing->invoice_number = 'INV-' . strtoupper(Str::random(8)) . '-' . now()->format('Ymd');
            }
        });
    }

    /**
     * Get the user who owns this billing record
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the subscription for this billing record
     */
    public function subscription(): BelongsTo
    {
        return $this->belongsTo(Subscription::class);
    }

    /**
     * Get the payment method used for this billing
     */
    public function paymentMethod(): BelongsTo
    {
        return $this->belongsTo(PaymentMethod::class);
    }
}
