<?php

namespace App\Models;

use App\Traits\VisibleToAdmin;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Deposit extends Model
{
    use HasFactory;
    use VisibleToAdmin;

    // This tells the trait how to reach the user who controls visibility
    protected function adminVisibilityRelation(): string
    {
        return 'account.profile.user';
    }

    const STATUS_PENDING = 'pending';
    const STATUS_APPROVED = 'approved';
    const STATUS_REJECTED = 'rejected';

    public function scopeApproved($query)
    {
        return $query->where('status', self::STATUS_APPROVED);
    }

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

    protected $fillable = [
        'account_id',       // the actual account the deposit is for
        'payment_method_id',
        'crypto_wallet_id',
        'user_crypto_balance_id',    // NEW: tracks which user crypto balance was used
        'deposit_type',              // NEW: 'fiat' or 'crypto'
        'idempotency_key',
        'amount',
        'charge',
        'total',
        'file_path',
        'status',
        'meta',
    ];

    protected $cascadeDeletes = [
        'transactions',       // delete all related transactions
        // add other relations if needed in the future
    ];

    protected static function booted()
    {
        static::deleting(function ($deposit) {
            foreach ($deposit->cascadeDeletes as $relationName) {
                try {
                    $relation = $deposit->$relationName();

                    if ($relation instanceof Relation) {
                        // BelongsToMany → detach
                        if ($relation instanceof \Illuminate\Database\Eloquent\Relations\BelongsToMany) {
                            $relation->detach();
                        } else {
                            // HasMany, HasOne, BelongsTo → delete each related model
                            $relation->get()->each(fn($item) => $item->delete());
                        }
                    }
                } catch (\Throwable $e) {
                    // Ignore if relation doesn't exist or fails
                    continue;
                }
            }
        });
    }

    protected $casts = [
        'meta' => 'array',
        'amount' => 'decimal:2',
        'charge' => 'decimal:2',
        'total' => 'decimal:2',
    ];

    protected $attributes = [
        'status' => 'pending',
        'deposit_type' => 'fiat', // default deposit type
    ];

    /**
     * Relationships
     */

    public function account()
    {
        return $this->belongsTo(Account::class);
    }

    public function paymentMethod()
    {
        return $this->belongsTo(PaymentMethod::class, 'payment_method_id');
    }

    public function cryptoWallet()
    {
        return $this->belongsTo(CryptoWallet::class, 'crypto_wallet_id');
    }

    public function userCryptoBalance()
    {
        return $this->belongsTo(AccountCryptoBalance::class, 'user_crypto_balance_id'); // NEW
    }
    public function transactions()
    {
        return $this->hasMany(Transaction::class, 'deposit_id');
    }

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

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

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

    /**
     * Optional helper to get total including charges
     */
    public function totalWithCharge(): float
    {
        return $this->amount + $this->charge;
    }

    /**
     * Scope for crypto deposits
     */
    public function scopeCrypto($query)
    {
        return $query->where('deposit_type', 'crypto');
    }

    /**
     * Scope for fiat deposits
     */
    public function scopeFiat($query)
    {
        return $query->where('deposit_type', 'fiat');
    }

}
