<?php

namespace App\Models;

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

class Dispute extends Model
{
    use HasFactory;

    protected $fillable = [
        'ticket_number',
        'order_id',
        'user_id',
        'seller_id',
        'type',
        'subject',
        'description',
        'status',
        'priority',
        'refund_amount',
        'resolution_notes',
        'assigned_to',
        'resolved_by',
        'resolved_at',
    ];

    protected $casts = [
        'refund_amount' => 'decimal:2',
        'resolved_at' => 'datetime',
    ];

    protected static function boot()
    {
        parent::boot();
        
        static::creating(function ($dispute) {
            if (empty($dispute->ticket_number)) {
                $dispute->ticket_number = 'DIS' . strtoupper(uniqid());
            }
        });
    }

    public function order()
    {
        return $this->belongsTo(Order::class);
    }

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

    public function seller()
    {
        return $this->belongsTo(Seller::class);
    }

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

    /**
     * Alias pour assignedAgent - compatibilité avec les vues
     */
    public function assignedTo()
    {
        return $this->belongsTo(User::class, 'assigned_to');
    }

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

    /**
     * Alias pour resolvedByUser - compatibilité avec les vues
     */
    public function resolvedBy()
    {
        return $this->belongsTo(User::class, 'resolved_by');
    }

    public function messages()
    {
        return $this->hasMany(DisputeMessage::class);
    }

    public function scopeOpen($query)
    {
        return $query->whereIn('status', ['open', 'in_progress', 'waiting_response']);
    }

    public function scopeClosed($query)
    {
        return $query->whereIn('status', ['resolved', 'rejected', 'refunded', 'closed']);
    }

    public function isOpen()
    {
        return in_array($this->status, ['open', 'in_progress', 'waiting_response']);
    }

    public function resolve($resolvedBy, $notes, $refundAmount = null)
    {
        $this->update([
            'status' => $refundAmount ? 'refunded' : 'resolved',
            'resolved_by' => $resolvedBy,
            'resolved_at' => now(),
            'resolution_notes' => $notes,
            'refund_amount' => $refundAmount,
        ]);

        if ($refundAmount) {
            $this->processRefund($refundAmount);
        }
    }

    public function reject($resolvedBy, $reason)
    {
        $this->update([
            'status' => 'rejected',
            'resolved_by' => $resolvedBy,
            'resolved_at' => now(),
            'resolution_notes' => $reason,
        ]);
    }

    protected function processRefund($amount)
    {
        $wallet = $this->user->wallet;
        if ($wallet) {
            $wallet->credit($amount, 'refund', "Remboursement litige #{$this->ticket_number}");
        }
    }

    public function addMessage($userId, $message, $attachments = [], $isInternal = false)
    {
        return $this->messages()->create([
            'user_id' => $userId,
            'message' => $message,
            'attachments' => $attachments,
            'is_internal' => $isInternal,
        ]);
    }
}
