<?php

namespace App\Models;

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

class Transaction extends Model
{
    use HasFactory;

    protected $fillable = [
        'code',
        'user_id',
        'user2_id',
        'type',
        'amount',
        'memo',
        'confirmed',
        'data',
        'payment_gateway',
        'gateway_reference',
        'gateway_status',
        'gateway_response',
        'proof_of_payment'
    ];

    protected $casts = [
        'amount' => 'decimal:2',
        'confirmed' => 'boolean',
        'data' => 'array',
        'gateway_response' => 'array',
        'proof_of_payment' => 'string'
    ];

    /**
     * User who made the transaction
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Payment gateway used
     */
    public function paymentGateway()
    {
        return $this->belongsTo(PaymentGateway::class, 'payment_gateway', 'name');
    }

    /**
     * Payment logs for this transaction
     */
    public function logs()
    {
        return $this->hasMany(PaymentLog::class);
    }

    /**
     * Scope for successful payments
     */
    public function scopeSuccessful($query)
    {
        return $query->where('gateway_status', 'success')->where('confirmed', true);
    }

    /**
     * Scope for pending payments
     */
    public function scopePending($query)
    {
        return $query->where('gateway_status', 'pending');
    }

    /**
     * Scope for failed payments
     */
    public function scopeFailed($query)
    {
        return $query->where('gateway_status', 'failed');
    }

    /**
     * Check if payment is successful
     */
    public function isSuccessful()
    {
        return $this->gateway_status === 'success' && $this->confirmed;
    }

    /**
     * Check if payment is pending
     */
    public function isPending()
    {
        return $this->gateway_status === 'pending';
    }

    /**
     * Mark transaction as successful
     */
    public function markAsSuccessful($gatewayResponse = null)
    {
        $this->update([
            'gateway_status' => 'success',
            'confirmed' => true,
            'gateway_response' => $gatewayResponse
        ]);
    }

    /**
     * Mark transaction as failed
     */
    public function markAsFailed($gatewayResponse = null)
    {
        $this->update([
            'gateway_status' => 'failed',
            'confirmed' => false,
            'gateway_response' => $gatewayResponse
        ]);
    }
}

