<?php

namespace App\Models;

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

class Transaction extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'transaction_id',
        'order_id',
        'gateway_transaction_id',
        'gateway_order_id',
        'gateway_payment_id',
        'gateway_signature',
        'user_id',
        'entity_type',
        'entity_id',
        'gateway_slug',
        'payment_method_slug',
        'amount',
        'currency',
        'gateway_fee',
        'platform_fee',
        'status',
        'payment_status',
        'refund_status',
        'gateway_response',
        'metadata',
        'paid_at',
        'captured_at',
        'refunded_at',
    ];

    protected $casts = [
        'gateway_response' => 'array',
        'metadata' => 'array',
        'paid_at' => 'datetime',
        'captured_at' => 'datetime',
        'refunded_at' => 'datetime',
    ];

    protected $dates = [
        'paid_at',
        'captured_at',
        'refunded_at',
    ];

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

    public function gateway()
    {
        return $this->belongsTo(PaymentGateway::class, 'gateway_slug', 'slug');
    }

    public function paymentMethod()
    {
        return $this->belongsTo(PaymentMethod::class, 'payment_method_slug', 'slug');
    }

    public function isSuccessful()
    {
        return $this->status === 'success';
    }

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

    public function isFailed()
    {
        return $this->status === 'failed';
    }

    public function isRefunded()
    {
        return $this->refund_status === 'full' || $this->refund_status === 'partial';
    }

    public function canBeRefunded()
    {
        return $this->isSuccessful() && !$this->isRefunded();
    }

    public function getTotalAmount()
    {
        return $this->amount + $this->gateway_fee + $this->platform_fee;
    }

    public function getNetAmount()
    {
        return $this->amount - $this->gateway_fee - $this->platform_fee;
    }
}
