<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
use App\Models\Admin;

class Receipt extends Model
{
    use HasFactory;

    protected $fillable = [
        'receipt_number',
        'user_name',
        'user_email',
        'amount',
        'cryptocurrency',
        'wallet_address',
        'transaction_type',
        'template_type',
        'transaction_hash',
        'fee_amount',
        'fee_currency',
        'network',
        'status',
        'notes',
        'transaction_date',
        'created_by'
    ];

    protected $casts = [
        'transaction_date' => 'datetime',
        'amount' => 'decimal:8',
        'fee_amount' => 'decimal:8'
    ];

    /**
     * Generate a unique receipt number
     */
    public static function generateReceiptNumber($templateType)
    {
        $prefix = match($templateType) {
            'bybit' => 'BB',
            'binance' => 'BN',
            'coinbase' => 'CB',
            default => 'RC'
        };

        $timestamp = now()->format('YmdHis');
        $random = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);

        return $prefix . $timestamp . $random;
    }

    /**
     * Get the admin who created this receipt
     */
    public function creator()
    {
        return $this->belongsTo(Admin::class, 'created_by');
    }

    /**
     * Format amount with cryptocurrency symbol
     */
    public function getFormattedAmountAttribute()
    {
        return number_format((float)$this->amount, 8) . ' ' . strtoupper($this->cryptocurrency);
    }

    /**
     * Format fee amount
     */
    public function getFormattedFeeAttribute()
    {
        if ($this->fee_amount > 0) {
            return number_format((float)$this->fee_amount, 8) . ' ' . strtoupper($this->fee_currency ?: $this->cryptocurrency);
        }
        return '0.00000000 ' . strtoupper($this->cryptocurrency);
    }
}
