<?php

namespace App\Models;

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

class Transaction extends Model {
    use HasFactory;

    protected $guarded = ['id'];

    protected $casts = [
        'details' => 'object',
        'data' => 'object',
        'date' => 'datetime',
    ];

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

    public function coin() {
        return $this->belongsTo(Coin::class);
    }

    protected function shortHash(): Attribute {
        return Attribute::make(
            get: fn() => shorten_id($this->hash)
        );
    }

    protected function fromCoin(): Attribute {
        return Attribute::make(fn() => Coin::find($this->details?->from_coin));
    }

    protected function toCoin(): Attribute {
        return Attribute::make(fn() => Coin::find($this->details?->to_coin));
    }

    protected function fullAmount(): Attribute {
        return Attribute::make(get: fn() => $this->direction == 'credit' ? '+' . $this->amount : '-' . $this->amount);
    }

    protected function totalAmount(): Attribute {
        return Attribute::make(get: fn() => number_format($this->amount, 4) . ' ' . $this->coin->symbol);
    }

    protected function shortAddress(): Attribute {
        return Attribute::make(fn() => shorten_address($this->details->receiver ?? $this->details->sender));
    }

    public function isCredit() {
        return $this->direction == 'credit';
    }

    public function isDebit() {
        return $this->direction == 'debit';
    }

    public static function perDay() {
        $transactions = static::selectRaw('DATE(created_at) as date, COUNT(*) as count')
            ->groupBy('date')
            ->orderBy('date', 'ASC')
            ->get()
            ->pluck('count', 'date')
            ->toArray();

        return $transactions;
    }

    public function fullNetworkFee(): Attribute {
        return Attribute::make(fn() => number_format($this->network_fee, 4) . ' ' . $this->coin->network_coin->symbol);
    }
}
