<?php

namespace App\Models;

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

class Transaction extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'seller_id',
        'transaction_type',
        'reference_id',
        'amount',
        'platform_commission',
        'gst_amount',
        'total_amount',
        'currency',
        'payment_gateway',
        'payment_id',
        'order_id',
        'status',
        'payment_method',
        'metadata',
        'failure_reason',
        'payment_started_at',
        'payment_completed_at',
    ];

    protected $casts = [
        'metadata' => 'array',
        'payment_started_at' => 'datetime',
        'payment_completed_at' => 'datetime',
        'amount' => 'decimal:2',
        'platform_commission' => 'decimal:2',
        'gst_amount' => 'decimal:2',
        'total_amount' => 'decimal:2',
    ];

    /**
     * Get metadata attribute with double-encoding fix
     */
    public function getMetadataAttribute($value)
    {
        // If value is null, return empty array
        if (is_null($value)) {
            return [];
        }

        // If it's already an array (via cast), check if it needs further decoding
        // Note: Laravel's cast runs before this accessor if we use the same name 'metadata'
        // But to be safe, we can check the raw value or just handle the result.
        
        // If we access $this->attributes['metadata'], it's the raw JSON string.
        // If we use the cast, it might be a string if it was double encoded.
        
        $decoded = json_decode($value, true);

        // If decoding returned a string, it might have been double encoded.
        if (is_string($decoded)) {
            $secondDecode = json_decode($decoded, true);
            if (is_array($secondDecode)) {
                return $secondDecode;
            }
        }

        return is_array($decoded) ? $decoded : [];
    }

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

    public function seller()
    {
        return $this->belongsTo(Seller::class);
    }

    public function subscription()
    {
        return $this->hasOne(Subscription::class, 'id', 'reference_id')
            ->where('transaction_type', 'subscription');
    }

    public function productPromotion()
    {
        return $this->hasOne(ProductPromotion::class, 'id', 'reference_id')
            ->where('transaction_type', 'promotion');
    }

    // Scopes
    public function scopeByStatus($query, $status)
    {
        return $query->where('status', $status);
    }

    public function scopeByType($query, $type)
    {
        return $query->where('transaction_type', $type);
    }

    public function scopeRecent($query)
    {
        return $query->orderBy('created_at', 'desc');
    }

    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    public function scopeSuccessful($query)
    {
        return $query->where('status', 'success');
    }

    public function scopeFailed($query)
    {
        return $query->where('status', 'failed');
    }

    // Helper Methods
    public function markAsSuccess($paymentId = null, $paymentMethod = null)
    {
        $this->update([
            'status' => 'success',
            'payment_id' => $paymentId ?? $this->payment_id,
            'payment_method' => $paymentMethod ?? $this->payment_method,
            'payment_completed_at' => now(),
        ]);
    }

    public function markAsFailed($reason = null)
    {
        $this->update([
            'status' => 'failed',
            'failure_reason' => $reason,
        ]);
    }

    public function markAsProcessing()
    {
        $this->update([
            'status' => 'processing',
            'payment_started_at' => now(),
        ]);
    }

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

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

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

    public function getStatusBadgeClass(): string
    {
        return match($this->status) {
            'success' => 'bg-success',
            'pending' => 'bg-warning',
            'pending_approval' => 'bg-info',
            'processing' => 'bg-info',
            'failed' => 'bg-danger',
            'cancelled' => 'bg-secondary',
            'refunded' => 'bg-primary',
            default => 'bg-secondary',
        };
    }

    public function getFormattedAmount(): string
    {
        return $this->currency . ' ' . number_format($this->total_amount, 2);
    }
}
