<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Models\User;

class Advertisement extends Model
{
    use HasFactory;

    protected $table = 'p2p_advertisements';

    protected $fillable = [
        'user_id',
        'type',
        'cryptocurrency',
        'fiat_currency',
        'price_type',
        'fixed_price',
        'margin_percentage',
        'current_price',
        'amount',
        'available_amount',
        'min_limit',
        'max_limit',
        'payment_methods',
        'terms',
        'auto_reply',
        'is_active',
        'expires_at',
    ];

    protected $casts = [
        'fixed_price' => 'decimal:8',
        'margin_percentage' => 'decimal:2',
        'current_price' => 'decimal:8',
        'amount' => 'decimal:8',
        'available_amount' => 'decimal:8',
        'min_limit' => 'decimal:2',
        'max_limit' => 'decimal:2',
        'payment_methods' => 'array',
        'is_active' => 'boolean',
        'expires_at' => 'datetime',
    ];

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

    public function trades()
    {
        return $this->hasMany(Trade::class, 'ad_id');
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('is_active', true)->where('available_amount', '>', 0);
    }

    public function scopeByType($query, $type)
    {
        return $query->where('type', $type);
    }

    public function scopeByCryptocurrency($query, $crypto)
    {
        return $query->where('cryptocurrency', strtoupper($crypto));
    }

    public function scopeByFiatCurrency($query, $fiat)
    {
        return $query->where('fiat_currency', strtoupper($fiat));
    }

    public function scopeByPaymentMethod($query, $method)
    {
        return $query->whereJsonContains('payment_methods', $method);
    }

    // Helper methods
    public function calculateCurrentPrice($marketPrice = null)
    {
        if ($this->price_type === 'fixed') {
            return $this->fixed_price;
        }

        if ($marketPrice && $this->margin_percentage !== null) {
            return $marketPrice * (1 + ($this->margin_percentage / 100));
        }

        return $this->current_price;
    }

    public function canTrade($amount)
    {
        return $this->is_active 
            && $this->available_amount > 0 
            && $amount >= $this->min_limit 
            && $amount <= $this->max_limit;
    }
}