<?php

namespace App\Models;

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

class LedgerTransaction extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'type',
        'description',
        'amount',
        'currency',
        'status',
        'details',
    ];

    protected $casts = [
        'amount' => 'decimal:8',
        'details' => 'array',
    ];

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

    // Relationship with ledger entries
    public function ledgerEntries()
    {
        return $this->hasMany(LedgerEntry::class);
    }

    // Scope for completed transactions
    public function scopeCompleted($query)
    {
        return $query->where('status', 'completed');
    }

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

    // Scope for transactions by type
    public function scopeOfType($query, $type)
    {
        return $query->where('type', $type);
    }

    // Scope for transactions by user
    public function scopeForUser($query, $userId)
    {
        return $query->where('user_id', $userId);
    }

    // Scope for transactions by currency
    public function scopeForCurrency($query, $currency)
    {
        return $query->where('currency', $currency);
    }

    // Create a new transaction
    public static function createTransaction($userId, $type, $amount, $currency, $description, $details = [])
    {
        return self::create([
            'user_id' => $userId,
            'type' => $type,
            'amount' => $amount,
            'currency' => $currency,
            'description' => $description,
            'details' => $details,
            'status' => 'completed', // Default to completed
        ]);
    }

    // Create debit entry
    public function createDebitEntry($accountId, $amount, $description)
    {
        return LedgerEntry::create([
            'ledger_transaction_id' => $this->id,
            'account_id' => $accountId,
            'entry_type' => 'debit',
            'amount' => $amount,
            'currency' => $this->currency,
            'description' => $description,
        ]);
    }

    // Create credit entry
    public function createCreditEntry($accountId, $amount, $description)
    {
        return LedgerEntry::create([
            'ledger_transaction_id' => $this->id,
            'account_id' => $accountId,
            'entry_type' => 'credit',
            'amount' => $amount,
            'currency' => $this->currency,
            'description' => $description,
        ]);
    }
}