<?php

namespace App\Models;

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

class ChatMessage extends Model
{
    use HasFactory;

    protected $fillable = [
        'sender_id',
        'receiver_id',
        'ad_id',
        'message',
        'message_type',
        'attachment_url',
        'attachment_type',
        'read_at',
        'deleted_by_sender',
        'deleted_by_receiver',
    ];

    protected $dispatchesEvents = [
        'created' => \App\Events\MessageSent::class,
    ];

    protected $casts = [
        'read_at' => 'datetime',
        'deleted_by_sender' => 'boolean',
        'deleted_by_receiver' => 'boolean',
    ];

    // Relationships
    public function sender()
    {
        return $this->belongsTo(User::class, 'sender_id');
    }

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

    public function ad()
    {
        return $this->belongsTo(Ad::class);
    }

    // Scopes
    public function scopeBetweenUsers($query, $senderId, $receiverId)
    {
        return $query->where(function($q) use ($senderId, $receiverId) {
            $q->where('sender_id', $senderId)
              ->where('receiver_id', $receiverId);
        })->orWhere(function($q) use ($senderId, $receiverId) {
            $q->where('sender_id', $receiverId)
              ->where('receiver_id', $senderId);
        });
    }

    public function scopeForUser($query, $userId)
    {
        return $query->where(function($q) use ($userId) {
            $q->where('sender_id', $userId)
              ->where('deleted_by_sender', false);
        })->orWhere(function($q) use ($userId) {
            $q->where('receiver_id', $userId)
              ->where('deleted_by_receiver', false);
        });
    }

    public function scopeUnread($query, $userId)
    {
        return $query->where('receiver_id', $userId)
                     ->whereNull('read_at')
                     ->where('deleted_by_receiver', false);
    }

    // Accessors
    public function getIsReadAttribute()
    {
        return !is_null($this->read_at);
    }

    public function getCanDeleteAttribute()
    {
        // Message can be deleted if it's not older than 24 hours
        return $this->created_at->diffInHours(now()) <= 24;
    }
}
