<?php

namespace App\Models;

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

class Payment extends Model
{
    use HasFactory;

    protected $table = 'payments';

     protected $fillable = [
        'payment_number',
        'user_id',
        'subscription_id',
        'amount',
        'tax_amount',
        'total_amount',
        'currency',
        'payment_method',
        'payment_type',
        'status',
        'transaction_id',
        'paid_at',
        'billing_period_start',
        'billing_period_end',
        'receipt_url',
        'receipt_sent_at',
        'refunded_amount',
        'refunded_at',
        'refund_reason',
        'stripe_payment_intent_id',
        'stripe_charge_id',
        'stripe_invoice_id',
        'stripe_refund_id',
        'metadata',
        'notes',
    ];

    protected $casts = [
        'amount'               => 'decimal:2',
        'tax_amount'           => 'decimal:2',
        'total_amount'         => 'decimal:2',
        'refunded_amount'      => 'decimal:2',

        'paid_at'              => 'datetime',
        'billing_period_start' => 'datetime',
        'billing_period_end'   => 'datetime',
        'receipt_sent_at'      => 'datetime',
        'refunded_at'          => 'datetime',

        'metadata'             => 'array',
    ];


    protected static function booted()
    {
        static::creating(function ($payment) {
            if (empty($payment->payment_number)) {
                $payment->payment_number = 'PAY-' . strtoupper(Str::random(10));
            }
        });
    }

    /*
    |--------------------------------------------------------------------------
    | Relationships
    |--------------------------------------------------------------------------
    */

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