<?php

namespace App\Models;

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

class Dispute extends Model
{
    use HasFactory;

    protected $table = 'p2p_disputes';

    protected $fillable = [
        'trade_id',
        'complainant_id',
        'respondent_id',
        'reason',
        'description',
        'evidence',
        'status',
        'resolution',
        'admin_notes',
        'refund_percentage',
        'resolved_by',
        'resolved_at',
    ];

    protected $casts = [
        'evidence' => 'array',
        'refund_percentage' => 'decimal:2',
        'resolved_at' => 'datetime',
    ];

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

    public function complainant()
    {
        return $this->belongsTo(User::class, 'complainant_id');
    }

    public function respondent()
    {
        return $this->belongsTo(User::class, 'respondent_id');
    }

    public function resolver()
    {
        return $this->belongsTo(User::class, 'resolved_by');
    }

    // Scopes
    public function scopeOpen($query)
    {
        return $query->where('status', 'open');
    }

    public function scopeResolved($query)
    {
        return $query->where('status', 'resolved');
    }

    public function scopeForUser($query, $userId)
    {
        return $query->where('complainant_id', $userId)->orWhere('respondent_id', $userId);
    }

    // Helper methods
    public function canResolve($userId)
    {
        return User::find($userId)->is_admin && $this->status === 'open';
    }
}