<?php

namespace App\Models;

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

class Transaction extends Model
{
    use HasFactory;

    protected $fillable = [
        'invoice_number',
        'reference',
        'merchant_ref',
        'customer_email',
        'customer_phone',
        'customer_name',
        'product_id',
        'product_name',
        'product_code',
        'customer_data',
        'base_price',
        'margin_amount',
        'product_price',
        'payment_fee',
        'total_amount',
        'status',
        'payment_status',
        'payment_method',
        'payment_name',
        'checkout_url',
        'payment_instructions',
        'paid_at',
        'expired_at',
        'trx_id',
        'provider_response',
        'provider_note',
        'provider_status',
        'provider_sn',
    ];

    protected $casts = [
        'paid_at' => 'datetime',
        'expired_at' => 'datetime',
        'base_price' => 'decimal:2',
        'margin_amount' => 'decimal:2',
        'product_price' => 'decimal:2',
        'payment_fee' => 'decimal:2',
        'total_amount' => 'decimal:2',
        'payment_instructions' => 'array',
    ];

    /**
     * Get the product
     */
    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    /**
     * Check if transaction is expired
     */
    public function isExpired()
    {
        return $this->expired_at && $this->expired_at->isPast();
    }

    /**
     * Check if transaction can be processed
     */
    public function canProcess()
    {
        return $this->payment_status === 'PAID' && 
               in_array($this->status, ['pending', 'paid']);
    }

    /**
     * Get status badge color
     */
    public function getStatusBadgeAttribute()
    {
        $colors = [
            'pending' => 'bg-yellow-500',
            'paid' => 'bg-blue-500',
            'processing' => 'bg-blue-500',
            'success' => 'bg-green-500',
            'failed' => 'bg-red-500',
            'refund' => 'bg-purple-500',
            'expired' => 'bg-gray-500',
        ];

        return $colors[$this->status] ?? 'bg-gray-500';
    }

    /**
     * Get payment status badge color
     */
    public function getPaymentStatusBadgeAttribute()
    {
        $colors = [
            'UNPAID' => 'bg-yellow-500',
            'PAID' => 'bg-green-500',
            'EXPIRED' => 'bg-red-500',
            'FAILED' => 'bg-red-500',
        ];

        return $colors[$this->payment_status] ?? 'bg-gray-500';
    }

    /**
     * Get profit amount (margin)
     */
    public function getProfitAttribute()
    {
        return $this->margin_amount;
    }

    /**
     * Get net amount (after payment fee)
     */
    public function getNetAmountAttribute()
    {
        return $this->total_amount - $this->payment_fee;
    }
}
