<?php

namespace App\Models;

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

class Transaction extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'package_id',
        'server_id',
        'transaction_id', 
        'amount',
        'original_amount',
        'discount_amount',
        'coupon_id',
        'payment_method',
        'status',
        'paypal_data',
        'paypal_order_id',
        'stripe_data',
        'stripe_session_id',
        'ip_address',
        'uuid',
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'original_amount' => 'decimal:2',
        'discount_amount' => 'decimal:2',
        'paypal_data' => 'array',
        'stripe_data' => 'array',
    ];

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

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

    public function server()
    {
        return $this->belongsTo(Server::class);
    }

    public function coupon()
    {
        return $this->belongsTo(Coupon::class);
    }

    public function getRouteKeyName()
    {
        return 'uuid';
    }

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->uuid)) {
                $model->uuid = (string) Str::uuid();
            }
        });
    }

    /**
     * Get the final amount after discounts
     */
    public function getFinalAmountAttribute()
    {
        return $this->amount;
    }

    /**
     * Get the discount percentage if applicable
     */
    public function getDiscountPercentageAttribute()
    {
        if ($this->original_amount && $this->discount_amount) {
            return round(($this->discount_amount / $this->original_amount) * 100, 2);
        }
        return 0;
    }

    /**
     * Check if transaction was paid via Stripe
     */
    public function isPaidViaStripe()
    {
        return $this->payment_method === 'stripe';
    }

    /**
     * Check if transaction was paid via PayPal
     */
    public function isPaidViaPayPal()
    {
        return $this->payment_method === 'paypal';
    }

    /**
     * Get payment method display name
     */
    public function getPaymentMethodDisplayAttribute()
    {
        return match($this->payment_method) {
            'stripe' => 'Credit/Debit Card',
            'paypal' => 'PayPal',
            default => ucfirst($this->payment_method ?? 'Unknown')
        };
    }

    /**
     * Get transaction status badge class for UI
     */
    public function getStatusBadgeClassAttribute()
    {
        return match($this->status) {
            'completed' => 'success',
            'pending' => 'warning',
            'failed', 'cancelled', 'expired' => 'danger',
            'refunded' => 'info',
            default => 'secondary'
        };
    }
}